问:
"EACCES: permission denied" when running npm install by jenkins and using docker agent
i've created a simple nodejs project containing a Jenkinsfile with this content:

```<code>pipeline {
  agent { docker { image 'node:12-alpine' } }
  stages {
    stage('build') {
      steps {
        sh 'npm install'
      }
    }
    stage('test') {
      steps {
        sh 'npm run test'
      }
    }
  }
}
</code>```

jenkins service is running by its own user named "jenkins", i've added that user to docker user group due to previous permission issues (permission denied while trying to connect to the Docker daemon) and i already have docker plugin installed in jenkins.

but when i run the build job, i get the following error and the build fails

```<code>EACCES: permission denied, mkdir '/.npm'
</code>```

if i use

```<code>agent any
</code>```

in the Jenkinsfile, i don't get the mentioned error. but i want to use docker agents.

why is this happening? am i missing something ?

答:
The user can't write in the default cache directory, you can overwrite it using this environment variable at the beginning of your pipeline :</p>
```<code>environment {
    NPM_CONFIG_CACHE = "${WORKSPACE}/.npm"
}
</code>```

Body:
i've created a simple nodejs project containing a Jenkinsfile with this content:

pipeline {
  agent { docker { image 'node:12-alpine' } }
  stages {
    stage('build') {
      steps {
        sh 'npm install'
      }
    }
    stage('test') {
      steps {
        sh 'npm run test'
      }
    }
  }
}

jenkins service is running by its own user named "jenkins", i've added that user to docker user group due to previous permission issues (permission denied while trying to connect to the Docker daemon) and i already have docker plugin installed in jenkins.

but when i run the build job, i get the following error and the build fails

EACCES: permission denied, mkdir '/.npm'

if i use

agent any

in the Jenkinsfile, i don't get the mentioned error. but i want to use docker agents.

why is this happening? am i missing something ?

Body:
The user can't write in the default cache directory, you can overwrite it using this environment variable at the beginning of your pipeline :

environment {
    NPM_CONFIG_CACHE = "${WORKSPACE}/.npm"
}


来源: stackexchange

问:
Default arguments in a function when using decorators
I cannot really tell how to use *args and **kwargs when combined with decorators and default arguments. Let me give you a MWE.

```<code>def outer(f):
    def inner(*args, **kwargs):
        print("args:", args)
        print("kwargs:", kwargs)

    return inner

@outer
def simple(x, y):
    pass
</code>```

Running the simple function passing arguments in a different format. So:

Running:

```<code>simple(10, 20)

args: (10, 20)
kwargs: {}
</code>```

Running:

```<code>simple(x=10, y=20)

args: ()
kwargs: {'x': 10, 'y': 20}
</code>```

Running:

```<code>simple(10, y=20)

args: (10,)
kwargs: {'y': 20}
</code>```

All of these seem to be expected. What I cannot understand is if I define the simple function with a default value something like:

```<code>@outer
def simple(x, y=100):
    pass

</code>```

If I then run simple(10) I would have expected the outcome to be:

```<code>args: (10,)
kwargs: {'y': 100}
</code>```

but I get

```<code>args: (10,)
kwargs: {}
</code>```

instead. Probably my understanding is not that good, so how could I achieve the expected result?

答:
In this case **kwargs is not about the function signature, it's about how you called it.
And your call

simple(10)
```
<p>have only specified one positional argument.</p>
<p>Decorator (wrapper) knows nothing about the function and its default arguments.
It just passes the arguments it received further.</p>
<pre class="lang-py prettyprint-override"><code>simple(*(10,), **{})
</code>```

If you want to do some excercise and write decorator that is informed about the defaults of a function it is wrapping, I suggest to take a look at inspect.signature().

ContentLicense: CC BY-SA 4.0

Body:
I cannot really tell how to use *args and **kwargs when combined with decorators and default arguments. Let me give you a MWE.

def outer(f):
    def inner(*args, **kwargs):
        print("args:", args)
        print("kwargs:", kwargs)

    return inner

@outer
def simple(x, y):
    pass

Running the simple function passing arguments in a different format. So:

Running:

simple(10, 20)

args: (10, 20)
kwargs: {}

Running:

simple(x=10, y=20)

args: ()
kwargs: {'x': 10, 'y': 20}

Running:

simple(10, y=20)

args: (10,)
kwargs: {'y': 20}

All of these seem to be expected. What I cannot understand is if I define the simple function with a default value something like:

@outer
def simple(x, y=100):
    pass

If I then run simple(10) I would have expected the outcome to be:

args: (10,)
kwargs: {'y': 100}

but I get

args: (10,)
kwargs: {}

instead. Probably my understanding is not that good, so how could I achieve the expected result?

Body:
In this case **kwargs is not about the function signature, it's about how you called it.
And your call

simple(10)

have only specified one positional argument.

Decorator (wrapper) knows nothing about the function and its default arguments.
It just passes the arguments it received further.

simple(*(10,), **{})

If you want to do some excercise and write decorator that is informed about the defaults of a function it is wrapping, I suggest to take a look at inspect.signature().


问:
Navigating without the navigation prop - typescript typings
I'm trying to include React Navigation 6.x into a React Native project with Redux and therefore need to be able to access the navigator from outside components.

I'm following this guide (Navigating without the navigation prop) and have essentially the same code as in their example, which functionally works fine:

import { createNavigationContainerRef } from '@react-navigation/native';

export const navigationRef = createNavigationContainerRef()

export function navigate(name, params) {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}
```
<p>However I'm also using Typescript.</p>
<p>React Navigation also have a guide on integrating Typescript (Type checking with TypeScript) which shows how to type the navigation ref itself, which works also fine:</p>
```export const navigationRef = createNavigationContainerRef<RootStackParamList>();
```
<p>There is no example for typing the <code>navigate</code> function though, and I haven't been able to get anything to work.</p>
<p>I thought the solution would be to copy the typing for the <code>navigationRef.navigate()</code> method (defined here) and simply apply it to the wrapper function:</p>
```// navigationRef.navigate() typing...
//
// navigate<RouteName extends keyof ParamList>(
//   ...args: undefined extends ParamList[RouteName]
//     ? [screen: RouteName] | [screen: RouteName, params: ParamList[RouteName]]
//     : [screen: RouteName, params: ParamList[RouteName]]
// ): void;

type ParamList = RootStackParamList;
type Navigate = <RouteName extends keyof ParamList>(
  ...args: undefined extends ParamList[RouteName]
    ? [screen: RouteName] | [screen: RouteName, params: ParamList[RouteName]]
    : [screen: RouteName, params: ParamList[RouteName]]
) => void;

export const navigate: Navigate = (name, params) => {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}

// or...

export const navigate: typeof navigationRef.navigate = (name, params) => {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}
```
<p>That unfortunately gives the following error:</p>
```Argument of type '[(undefined extends RootStackParamList[RouteName] ? [screen: RouteName] | [screen: RouteName, params: RootStackParamList[RouteName]] : [screen: ...])[0], (undefined extends RootStackParamList[RouteName] ? [screen: ...] | [screen: ...] : [screen: ...])[1]]' is not assignable to parameter of type 'undefined extends RootStackParamList[(undefined extends RootStackParamList[RouteName] ? [screen: RouteName] | [screen: RouteName, params: RootStackParamList[RouteName]] : [screen: ...])[0]] ? [screen: ...] | [screen: ...] : [screen: ...]'.ts(2345)
```

答:
You can reuse the type of navigationRef.navigate

```<code>export const navigate: typeof navigationRef.navigate = (name, params) => {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}
</code>```

Body:
I'm trying to include React Navigation 6.x into a React Native project with Redux and therefore need to be able to access the navigator from outside components.

I'm following this guide (Navigating without the navigation prop) and have essentially the same code as in their example, which functionally works fine:

import { createNavigationContainerRef } from '@react-navigation/native';

export const navigationRef = createNavigationContainerRef()

export function navigate(name, params) {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}

However I'm also using Typescript.

React Navigation also have a guide on integrating Typescript (Type checking with TypeScript) which shows how to type the navigation ref itself, which works also fine:

export const navigationRef = createNavigationContainerRef<RootStackParamList>();

There is no example for typing the navigate function though, and I haven't been able to get anything to work.

I thought the solution would be to copy the typing for the navigationRef.navigate() method (defined here) and simply apply it to the wrapper function:

// navigationRef.navigate() typing...
//
// navigate<RouteName extends keyof ParamList>(
//   ...args: undefined extends ParamList[RouteName]
//     ? [screen: RouteName] | [screen: RouteName, params: ParamList[RouteName]]
//     : [screen: RouteName, params: ParamList[RouteName]]
// ): void;

type ParamList = RootStackParamList;
type Navigate = <RouteName extends keyof ParamList>(
  ...args: undefined extends ParamList[RouteName]
    ? [screen: RouteName] | [screen: RouteName, params: ParamList[RouteName]]
    : [screen: RouteName, params: ParamList[RouteName]]
) => void;

export const navigate: Navigate = (name, params) => {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}

// or...

export const navigate: typeof navigationRef.navigate = (name, params) => {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}

That unfortunately gives the following error:

Argument of type '[(undefined extends RootStackParamList[RouteName] ? [screen: RouteName] | [screen: RouteName, params: RootStackParamList[RouteName]] : [screen: ...])[0], (undefined extends RootStackParamList[RouteName] ? [screen: ...] | [screen: ...] : [screen: ...])[1]]' is not assignable to parameter of type 'undefined extends RootStackParamList[(undefined extends RootStackParamList[RouteName] ? [screen: RouteName] | [screen: RouteName, params: RootStackParamList[RouteName]] : [screen: ...])[0]] ? [screen: ...] | [screen: ...] : [screen: ...]'.ts(2345)

Body:
You can reuse the type of navigationRef.navigate

export const navigate: typeof navigationRef.navigate = (name, params) => {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}


问:
Convert lists of model objects to pandas dataframe based on the values of each object
I have a number of lists of objects of this class:

```<code>from typing import List,Optional
from pydantic import BaseModel

class Concept(BaseModel):
  text: str
  type: str

class ClassObject(BaseModel):
  question_text: str
  question_entity: Optional[List[Concept]]
  answer_text: str
  answer_entity: Optional[List[Concept]]
</code>```

The lists:

```<code>answers1 = [
ClassObject(question_text='Question 1', question_entity=[Concept(text='Concept 1',type='Type 1')], answer_text='Answer 1', answer_entity=[Concept(text='Concept 2',type='Type 1'),Concept(text='Concept 3',type='Type 2')]),
ClassObject(question_text='Question 2', question_entity=[], answer_text=' ', answer_entity=[]),
ClassObject(question_text='Question 3', question_entity=[Concept(text='Concept 1',type='Type 1')], answer_text='Answer 3', answer_entity=[])
]

 answers2 = [
ClassObject(question_text='Question 1', question_entity=[], answer_text='Answer 1', answer_entity=[Concept(text='Concept 2',type='Type 1'),Concept(text='Concept 3',type='Type 2')]),
ClassObject(question_text='Question 2', question_entity=[], answer_text='Answer 2', answer_entity=[]),
ClassObject(question_text='Question 3', question_entity=[Concept(text='Concept 1',type='Type 1')], answer_text='Answer 3', answer_entity=[Concept(text='Concept 1',type='Type 1')])
]
</code>```

I would like to convert this to a pandas dataframe by taking the values from question_text as columns and the answer_entity as row value. Example for column 1 with column name question_text= 'Question 1'

```<code>  Question 1
0 Concept(text='Concept 2',type='Type 1')
1 Concept(text='Concept 2',type='Type 1'),Concept(text='Concept 3',type='Type 2')
</code>```

Any idea on how to achieve this?
I have tried playing with the DataFrame function but it doesn't cover my question.

```<code> df = pd.DataFrame([t.__dict__ for t in answers1])
</code>```

答:
Is it what you expect:</p>
```<code>df = pd.json_normalize({t.question_text: t.answer_entity for t in answers1})
print(df)

# Output
                                          Question 1 Question 2 Question 3
0  [text='Concept 2' type='Type 1', text='Concept...         []         []
</code>```

Body:
I have a number of lists of objects of this class:

from typing import List,Optional
from pydantic import BaseModel

class Concept(BaseModel):
  text: str
  type: str

class ClassObject(BaseModel):
  question_text: str
  question_entity: Optional[List[Concept]]
  answer_text: str
  answer_entity: Optional[List[Concept]]

The lists:

answers1 = [
ClassObject(question_text='Question 1', question_entity=[Concept(text='Concept 1',type='Type 1')], answer_text='Answer 1', answer_entity=[Concept(text='Concept 2',type='Type 1'),Concept(text='Concept 3',type='Type 2')]),
ClassObject(question_text='Question 2', question_entity=[], answer_text=' ', answer_entity=[]),
ClassObject(question_text='Question 3', question_entity=[Concept(text='Concept 1',type='Type 1')], answer_text='Answer 3', answer_entity=[])
]

 answers2 = [
ClassObject(question_text='Question 1', question_entity=[], answer_text='Answer 1', answer_entity=[Concept(text='Concept 2',type='Type 1'),Concept(text='Concept 3',type='Type 2')]),
ClassObject(question_text='Question 2', question_entity=[], answer_text='Answer 2', answer_entity=[]),
ClassObject(question_text='Question 3', question_entity=[Concept(text='Concept 1',type='Type 1')], answer_text='Answer 3', answer_entity=[Concept(text='Concept 1',type='Type 1')])
]

I would like to convert this to a pandas dataframe by taking the values from question_text as columns and the answer_entity as row value. Example for column 1 with column name question_text= 'Question 1'

  Question 1
0 Concept(text='Concept 2',type='Type 1')
1 Concept(text='Concept 2',type='Type 1'),Concept(text='Concept 3',type='Type 2')

Any idea on how to achieve this?
I have tried playing with the DataFrame function but it doesn't cover my question.

 df = pd.DataFrame([t.__dict__ for t in answers1])

Body:
Is it what you expect:

df = pd.json_normalize({t.question_text: t.answer_entity for t in answers1})
print(df)

# Output
                                          Question 1 Question 2 Question 3
0  [text='Concept 2' type='Type 1', text='Concept...         []         []


问:
PHP pass variable through for loop into link
i would like to pass a variable through a for loop into a link such that the loaded page passes information about the correct link. right now my code seems to be storing the last variable in the for loop and passing that onto the link. it means that the generated table in the link always references the final piece.

the code is:

```<code>    <?php foreach($result as $key => $result) :?>
    <?php session_regenerate_id(); $_SESSION['id'] = $result['id']; ?>
    <tr>
    <td><?php echo $result['id'] ?></td>
    <td><?php echo $result['date'] ?></td>
    <td><?php echo $result['name'] ?></td>
    <td><div class="btn-group" data-toggle="buttons"><a href="cpt.php?id=$_SESSION['id']" target="_blank" class="btn btn-warning btn-xs" rel="noopener">More details</a></div></td>
    </tr>
    <?php endforeach;?>
</code>```

The point is the link should display more information about the id that the user clicks on. However it only ever shows data of the last id. I think this is because the $_session['id'] is just storing the final loop.

答:
You are overwriting the $result variable in your loop:

```<code><?php foreach($result as $key => $result) :?>
</code>```

Do something like this instead:

```<code><?php foreach($result as $key => $value) :?>
</code>```

Then in your link you should be able to do:

```<code><a href="cpt.php?id=<?php echo $value['id'] ?>"
</code>```

I don't see any reason to be using session in this loop, I would advise removing that. You certainly don't want to be regenerating the session ID inside of a loop that displays chunks of html.

Body:
i would like to pass a variable through a for loop into a link such that the loaded page passes information about the correct link. right now my code seems to be storing the last variable in the for loop and passing that onto the link. it means that the generated table in the link always references the final piece.

the code is:

    <?php foreach($result as $key => $result) :?>
    <?php session_regenerate_id(); $_SESSION['id'] = $result['id']; ?>

    <?php echo $result['id'] ?>
    <?php echo $result['date'] ?>
    <?php echo $result['name'] ?>

More details

    <?php endforeach;?>

The point is the link should display more information about the id that the user clicks on. However it only ever shows data of the last id. I think this is because the $_session['id'] is just storing the final loop.

Body:
You are overwriting the $result variable in your loop:

<?php foreach($result as $key => $result) :?>

Do something like this instead:

<?php foreach($result as $key => $value) :?>

Then in your link you should be able to do:

<a href="cpt.php?id=<?php echo $value['id'] ?>"

I don't see any reason to be using session in this loop, I would advise removing that. You certainly don't want to be regenerating the session ID inside of a loop that displays chunks of html.


问:
How does static field initialization work in C#?
Should static field initialization be completed before constructor is called?

The following program provides output that seems incorrect to me.

```<code>new A()
_A == null
static A()
new A()
_A == A
</code>```

The code:

```<code>public class A
{
    public static string _A = (new A()).I();

    public A()
    {
        Console.WriteLine("new A()");
        if (_A == null)
            Console.WriteLine("_A == null");
        else
            Console.WriteLine("_A == " + _A);
    }

    static A()
    {
        Console.WriteLine("static A()");
    }

    public string I()
    {
        return "A";
    }
}

class Program
{
    static void Main(string[] args)
    {
       var a = new A();
    }
}
</code>```

答:
Yes, static fields initialization should complete before constructor is called. But you put compiler in the unnormal situation and it just can't obey this rule.

This is interesting trick, but it's not gonna happen in normal application.

ContentLicense: CC BY-SA 2.5

Body:
Should static field initialization be completed before constructor is called?

The following program provides output that seems incorrect to me.

new A()
_A == null
static A()
new A()
_A == A

The code:

public class A
{
    public static string _A = (new A()).I();

    public A()
    {
        Console.WriteLine("new A()");
        if (_A == null)
            Console.WriteLine("_A == null");
        else
            Console.WriteLine("_A == " + _A);
    }

    static A()
    {
        Console.WriteLine("static A()");
    }

    public string I()
    {
        return "A";
    }
}

class Program
{
    static void Main(string[] args)
    {
       var a = new A();
    }
}

OwnerDisplayName: XOR


问:
How to prevent css grid elements from making a black line when overflowed from the container?
I'm trying to create a semicircle as a container of a grid having a lot of elements.

.circle {
  /* this is for sqaures */
  display: grid;
  grid-template-columns: repeat(auto-fit, 25px);
  grid-template-rows: repeat(auto-fit, 25px);
  /* overflow: hidden; */
  height: 40vh;
  width: 80vh;
  background-color: white;
  margin: 0px auto;
  margin-top: 10vh;
  border-radius: 40vh 40vh 0px 0px;
}

.squares {
  border: 1px solid black;
}```

image

But when the grid elements overflow the semicircle which is its container then they make a black line in the bottom. How to prevent it and make the grid continue in the vertical direction.

Also, I need the boxes to be square only and the width of the grid should be as it is but height may vary.

答:
Just add the following to the .circle selector:

```<code>  grid-auto-flow: row;
  grid-auto-rows: 25px;
</code>```

You can also check it here:
https://codepen.io/serazoltan/pen/bGYRqjg

Body:
I'm trying to create a semicircle as a container of a grid having a lot of elements.

.circle {
  /* this is for sqaures */
  display: grid;
  grid-template-columns: repeat(auto-fit, 25px);
  grid-template-rows: repeat(auto-fit, 25px);
  /* overflow: hidden; */
  height: 40vh;
  width: 80vh;
  background-color: white;
  margin: 0px auto;
  margin-top: 10vh;
  border-radius: 40vh 40vh 0px 0px;
}

.squares {
  border: 1px solid black;
}

image

But when the grid elements overflow the semicircle which is its container then they make a black line in the bottom. How to prevent it and make the grid continue in the vertical direction.

Also, I need the boxes to be square only and the width of the grid should be as it is but height may vary.

Body:
Just add the following to the .circle selector:

  grid-auto-flow: row;
  grid-auto-rows: 25px;

You can also check it here:
https://codepen.io/serazoltan/pen/bGYRqjg


问:
Why is my sort function sorting a different array I did not ask for?
I want to copy an array and sort it. However, when I copy the array and sort it, it seems to sort both arrays. Does anyone know why this is?

```<code>var arr1 = [-1, 2, 0, -2];
var arr2 = [];
arr2 = arr1;
arr2.sort(function(a, b){return a - b});
console.log(arr1);
console.log(arr2);
/*
Expected result:
arr1 = [-1, 2, 0, -2]
arr2 = [-2, -1, 0, 2]

Actual result:
arr1 = [-2, -1, 0, 2]
arr2 = [-2, -1, 0, 2]
*/
</code>```

I don't know why this is, so it might make a difference that I'm using the p5.js library. I don't know if this matters however. I should also note that I don't know how the sorting algorithm works and I just looked up how to sort numbers on google.

答:
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. Thats why your parent array (arr1) is modified rather the child array (arr2). But if you dont want that to happen replace the following,</p>
```<code>arr2 = arr1.slice();
</code>```

Body:
I want to copy an array and sort it. However, when I copy the array and sort it, it seems to sort both arrays. Does anyone know why this is?

var arr1 = [-1, 2, 0, -2];
var arr2 = [];
arr2 = arr1;
arr2.sort(function(a, b){return a - b});
console.log(arr1);
console.log(arr2);
/*
Expected result:
arr1 = [-1, 2, 0, -2]
arr2 = [-2, -1, 0, 2]

Actual result:
arr1 = [-2, -1, 0, 2]
arr2 = [-2, -1, 0, 2]
*/

I don't know why this is, so it might make a difference that I'm using the p5.js library. I don't know if this matters however. I should also note that I don't know how the sorting algorithm works and I just looked up how to sort numbers on google.

Body:
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. Thats why your parent array (arr1) is modified rather the child array (arr2). But if you dont want that to happen replace the following,

arr2 = arr1.slice();


问:
What exactly is buffer (last parameter) in io.Copybuffer(...)?
I understand it's handy in reusing a buffer rather than allocating every time hen using io.Copy. However, having printed its value several times, I get all zeros and the size of my buffer never changes. I tried to set the size to 8 and 1.

On a related note, to what value should I set my buffer size?

答:
io.CopyBuffer() documents that:

```<code>func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)
</code>```

CopyBuffer is identical to Copy except that it stages through the provided buffer (if one is required) rather than allocating a temporary one. If buf is nil, one is allocated; otherwise if it has zero length, CopyBuffer panics.

If either src implements WriterTo or dst implements ReaderFrom, buf will not be used to perform the copy.

So io.CopyBuffer() copies data (bytes) from src to dst. The source is an io.Reader and the destination is an io.Writer. These interfaces allow you to read and write slices of bytes ([]byte).

In the general case to do the copying, we need a slice to read into from the source, which we can write into the destination. So io.CopyBuffer() needs a buffer. The buf param allows you to pass a byte slice if you already have one, and if you do so, that buffer will be used to do the job, so no new slice have to be allocated (which would be thrown away at the end of the operation).

What size should it be? The bigger the better, but no bigger is needed than the data you want to copy. Obviously bigger requires more memory, so there's a trade-off. Typically a few KB is a good compromise.

Note that as documented, if the source implements io.WriterTo or the destination implements io.ReaderFrom, those interfaces allow to read /
write without having to pass a slice, so in that case the buffer you pass will not be used. Like in this example:

```<code>srcData := []byte{1, 2, 3, 4, 5, 6, 7}
src := bytes.NewBuffer(srcData)
dst := &bytes.Buffer{}
buf := make([]byte, 10)

io.CopyBuffer(dst, src, buf)

fmt.Println(srcData)
fmt.Println(dst.Bytes())
fmt.Println(buf)
</code>```

Which outputs (try it on the Go Playground):

```<code>[1 2 3 4 5 6 7]
[1 2 3 4 5 6 7]
[0 0 0 0 0 0 0 0 0 0]
</code>```

Since we used bytes.Buffer as the source and destination (and since it implements both io.ReaderFrom and io.WriterTo), the buffer is not used.

Let's construct a source and destination that does not implement these interfaces, so we can test if / how our passed buffer is used.

For this, I will embed *bytes.Buffer in a struct, but specify a WriteTo and ReadFrom fields, so those methods will not get promoted from the embedded bytes.Buffer:

```<code>srcData := []byte{1, 2, 3, 4, 5, 6, 7}
src := struct {
    WriteTo int // "disable" WriteTo method
    *bytes.Buffer
}{0, bytes.NewBuffer(srcData)}

dst := struct {
    ReadFrom int // "disable" ReadFrom method
    *bytes.Buffer
}{0, &bytes.Buffer{}}

buf := make([]byte, 10)

io.CopyBuffer(dst, src, buf)

fmt.Println(srcData)
fmt.Println(dst.Bytes())
fmt.Println(buf)
</code>```

This will output (try it on the Go Playground):

```<code>[1 2 3 4 5 6 7]
[1 2 3 4 5 6 7]
[1 2 3 4 5 6 7 0 0 0]
</code>```

As you can see, the data from the source was read into the buffer, which then was written to the destination.

Note that you may pass a buffer smaller than the data to be copied, in which case reading / writing will be done in several iterations. In such cases, the data in the buffer may hold only the last iteration, and may only hold partial data (if the copied size is not an integer multiplication of the buffer size). It also depends on how the Read() method is implemented on the source, as Read() is not required to read the full slice passed to it.

Also note that io.CopyBuffer() does not document that the data written to the passed buffer is retained, it may get cleared / zeroed. Although this clearing is not implemented for performance reasons, but you should not count on it holding valid data after io.CopyBuffer() returns.

Body:
io.CopyBuffer() documents that:

func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)

CopyBuffer is identical to Copy except that it stages through the provided buffer (if one is required) rather than allocating a temporary one. If buf is nil, one is allocated; otherwise if it has zero length, CopyBuffer panics.

If either src implements WriterTo or dst implements ReaderFrom, buf will not be used to perform the copy.

So io.CopyBuffer() copies data (bytes) from src to dst. The source is an io.Reader and the destination is an io.Writer. These interfaces allow you to read and write slices of bytes ([]byte).

In the general case to do the copying, we need a slice to read into from the source, which we can write into the destination. So io.CopyBuffer() needs a buffer. The buf param allows you to pass a byte slice if you already have one, and if you do so, that buffer will be used to do the job, so no new slice have to be allocated (which would be thrown away at the end of the operation).

What size should it be? The bigger the better, but no bigger is needed than the data you want to copy. Obviously bigger requires more memory, so there's a trade-off. Typically a few KB is a good compromise.

Note that as documented, if the source implements io.WriterTo or the destination implements io.ReaderFrom, those interfaces allow to read /
write without having to pass a slice, so in that case the buffer you pass will not be used. Like in this example:

srcData := []byte{1, 2, 3, 4, 5, 6, 7}
src := bytes.NewBuffer(srcData)
dst := &bytes.Buffer{}
buf := make([]byte, 10)

io.CopyBuffer(dst, src, buf)

fmt.Println(srcData)
fmt.Println(dst.Bytes())
fmt.Println(buf)

Which outputs (try it on the Go Playground):

[1 2 3 4 5 6 7]
[1 2 3 4 5 6 7]
[0 0 0 0 0 0 0 0 0 0]

Since we used bytes.Buffer as the source and destination (and since it implements both io.ReaderFrom and io.WriterTo), the buffer is not used.

Let's construct a source and destination that does not implement these interfaces, so we can test if / how our passed buffer is used.

For this, I will embed *bytes.Buffer in a struct, but specify a WriteTo and ReadFrom fields, so those methods will not get promoted from the embedded bytes.Buffer:

srcData := []byte{1, 2, 3, 4, 5, 6, 7}
src := struct {
    WriteTo int // "disable" WriteTo method
    *bytes.Buffer
}{0, bytes.NewBuffer(srcData)}

dst := struct {
    ReadFrom int // "disable" ReadFrom method
    *bytes.Buffer
}{0, &bytes.Buffer{}}

buf := make([]byte, 10)

io.CopyBuffer(dst, src, buf)

fmt.Println(srcData)
fmt.Println(dst.Bytes())
fmt.Println(buf)

This will output (try it on the Go Playground):

[1 2 3 4 5 6 7]
[1 2 3 4 5 6 7]
[1 2 3 4 5 6 7 0 0 0]

As you can see, the data from the source was read into the buffer, which then was written to the destination.

Note that you may pass a buffer smaller than the data to be copied, in which case reading / writing will be done in several iterations. In such cases, the data in the buffer may hold only the last iteration, and may only hold partial data (if the copied size is not an integer multiplication of the buffer size). It also depends on how the Read() method is implemented on the source, as Read() is not required to read the full slice passed to it.

Also note that io.CopyBuffer() does not document that the data written to the passed buffer is retained, it may get cleared / zeroed. Although this clearing is not implemented for performance reasons, but you should not count on it holding valid data after io.CopyBuffer() returns.


问:
Why can't if and else statements be on separate lines in R
Why is it that when using an if else statement in R, the "else" cannot be on a new line unless the whole statement is nested within another form of statement, loop or function?

For example, the below code does not work:

```<code>x <- 5

if(x<10){
  print("x<10")
}
else{
  print("x>9")
}

</code>```

However if we put the whole thing within a loop so that it is indented, suddenly it works fine

```<code>for(i in 1:1){
  x <- 5

  if(x<10){
    print("x<10")
  }
  else{
    print("x>9")
  }
}
</code>```

I understand that R wants you to write them like below:

```<code>x <- 5

if(x<10){
  print("x<10")
}else{
  print("x>9")
}
</code>```

But I don't like how that looks and also want to understand why this syntax / style is only a requirement when the statement is not nested within something else.

Thanks!

答:
This has nothing to do with enforcing a style, but to do with how the R parser works. In essence, when your if clause is syntactically complete with a newline at the end of its closing bracket, the console thinks you are done with that instruction, and waits for its next instruction. But an else clause has to be part of the same instruction. If the next instruction starts with an else, the R parser doesn't know what the else is referring to.

Let's demonstrate this for clarity. If you paste the following code into the console:

x <- 5

if(x<10){
print("x<10")
}
```
<p>Then you will see this:</p>
<pre class="lang-r prettyprint-override"><code>> x <- 5
>
> if(x<10){
+   print("x<10")
+ }
[1] "x<10"
>
</code>```

Notice that if a line of code is syntactically complete, R will run the code, then print the console marker > at the start of the next line. If a newline symbol is present in the pasted code, but the code is syntactically incomplete, the console places a + at the start of each line, indicating that the R parser needs more input before it has syntactically complete code to run.

But if you run your example code, look what happens:

> if(x<10){
+   print("x<10")
+ }
[1] "x<10"
> else{
Error: unexpected 'else' in "else"
>   print("x>9")
[1] "x>9"
> }
Error: unexpected '}' in "}"
```
<p>Your <code>if</code> statement with its associated brackets was a syntactically complete element, so R ran the code. It printed out <code>[1] "x<10"</code> as expected, then waited for its next instruction. However, its next instruction was <code>else {</code>, and the R parser knows that <em>no</em> syntactically correct R code can <em>start</em> with an <em>else</em>. R can't go back in time and undo what it did in the <code>if</code> clause just because you <em>subsequently</em> write an <code>else</code> clause.</p>
<p>So, this has nothing to do with enforcing a style. You simply need a way of saying to R "I'm not done yet" after an <code>if</code> clause. There are various ways to do this. For example, your code would be fine inside a function, or a loop, or brackets. These are just ways of saying to the R parser : "don't run the code yet, I'm not done."</p>
<pre class="lang-r prettyprint-override"><code>x <- 5

{

if(x<10){
  print("x<10")
}
else{
  print("x>9")
}

}
#> [1] "x<10"
</code>```

Created on 2022-02-11 by the reprex package (v2.0.1)

Body:
Why is it that when using an if else statement in R, the "else" cannot be on a new line unless the whole statement is nested within another form of statement, loop or function?

For example, the below code does not work:

x <- 5

if(x<10){
  print("x<10")
}
else{
  print("x>9")
}

However if we put the whole thing within a loop so that it is indented, suddenly it works fine

for(i in 1:1){
  x <- 5

  if(x<10){
    print("x<10")
  }
  else{
    print("x>9")
  }
}

I understand that R wants you to write them like below:

x <- 5

if(x<10){
  print("x<10")
}else{
  print("x>9")
}

But I don't like how that looks and also want to understand why this syntax / style is only a requirement when the statement is not nested within something else.

Thanks!

Body:
This has nothing to do with enforcing a style, but to do with how the R parser works. In essence, when your if clause is syntactically complete with a newline at the end of its closing bracket, the console thinks you are done with that instruction, and waits for its next instruction. But an else clause has to be part of the same instruction. If the next instruction starts with an else, the R parser doesn't know what the else is referring to.

Let's demonstrate this for clarity. If you paste the following code into the console:

x <- 5

if(x<10){
print("x<10")
}

Then you will see this:

> x <- 5
>
> if(x<10){
+   print("x<10")
+ }
[1] "x<10"
>

Notice that if a line of code is syntactically complete, R will run the code, then print the console marker > at the start of the next line. If a newline symbol is present in the pasted code, but the code is syntactically incomplete, the console places a + at the start of each line, indicating that the R parser needs more input before it has syntactically complete code to run.

But if you run your example code, look what happens:

> if(x<10){
+   print("x<10")
+ }
[1] "x<10"
> else{
Error: unexpected 'else' in "else"
>   print("x>9")
[1] "x>9"
> }
Error: unexpected '}' in "}"

Your if statement with its associated brackets was a syntactically complete element, so R ran the code. It printed out [1] "x<10" as expected, then waited for its next instruction. However, its next instruction was else {, and the R parser knows that no syntactically correct R code can start with an else. R can't go back in time and undo what it did in the if clause just because you subsequently write an else clause.

So, this has nothing to do with enforcing a style. You simply need a way of saying to R "I'm not done yet" after an if clause. There are various ways to do this. For example, your code would be fine inside a function, or a loop, or brackets. These are just ways of saying to the R parser : "don't run the code yet, I'm not done."

x <- 5

{

if(x<10){
  print("x<10")
}
else{
  print("x>9")
}

}
#> [1] "x<10"

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
Frequently repeated try/except in Python
Firstly, I'm not sure if my approach is proper, so I'm open to a variety of suggestions.

If try/except statements are frequently repeated in code, are there any good ways to shorten them or avoid fully writing them out?

```<code>try:
    # Do similar thing
    os.remove('/my/file')
except OSError, e:
    # Same exception handing
    pass

try:
    # Do similar thing
    os.chmod('/other/file', 0700)
except OSError, e:
    #Same exception handling
    pass
</code>```

For example, for one line actions you could define a exception handling wrapper and then pass a lambda function:

```<code>def may_exist(func):
    "Work with file which you are not sure if exists."""
    try:
        func()
    except OSError, e:
        # Same exception handling
        pass

may_exist(lambda: os.remove('/my/file'))
may_exist(lambda: os.chmod('/other/file', 0700))
</code>```

Does this 'solution' just make things less clear? Should I just fully write out all the try/except statements?

答:
I think your generic solution is ok, but I wouldn't use those lambdas at the bottom. I'd recommend passing the function and arguments like this</p>

```<code>def may_exist(func, *args):
    "Work with file which you are not sure if exists."""
    try:
        func(args)
    except OSError, e:
        # Same exception handling
        pass

may_exist(os.remove, '/my/file')
may_exist(os.chmod, '/other/file', '0700')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Firstly, I'm not sure if my approach is proper, so I'm open to a variety of suggestions.

If try/except statements are frequently repeated in code, are there any good ways to shorten them or avoid fully writing them out?

try:
    # Do similar thing
    os.remove('/my/file')
except OSError, e:
    # Same exception handing
    pass

try:
    # Do similar thing
    os.chmod('/other/file', 0700)
except OSError, e:
    #Same exception handling
    pass

For example, for one line actions you could define a exception handling wrapper and then pass a lambda function:

def may_exist(func):
    "Work with file which you are not sure if exists."""
    try:
        func()
    except OSError, e:
        # Same exception handling
        pass

may_exist(lambda: os.remove('/my/file'))
may_exist(lambda: os.chmod('/other/file', 0700))

Does this 'solution' just make things less clear? Should I just fully write out all the try/except statements?

Body:
I think your generic solution is ok, but I wouldn't use those lambdas at the bottom. I'd recommend passing the function and arguments like this

def may_exist(func, *args):
    "Work with file which you are not sure if exists."""
    try:
        func(args)
    except OSError, e:
        # Same exception handling
        pass

may_exist(os.remove, '/my/file')
may_exist(os.chmod, '/other/file', '0700')


问:
Input from the use in a try/except block

List item

i want to let the user type 1 , 2 or quit otherwise i want to put him to type again one of them. everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level. also its a hangman game. tanks

Sloved!!

import sys
while True:

difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower()
try:

```<code>         if difficulty == '1':
            print('Easy game mode is set!')
         elif difficulty =='2':
            print('Hard game mode is set!')
         elif difficulty =='quit':
            print('Sheeeeeeeeeeeeeeesh')

      except:
         continue
      if difficulty == '1' or difficulty =='2':
         break
      elif difficulty == 'quit':
         sys.exit('byeeeee')
         break
    #elif difficulty
      else:
         print('invalid ')
</code>```

答:
try: and except: is probably not what you want to use here because you won't get a ValueError and thus the except does not execute. Maybe try something like:

```<code>while True:
    difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
    if difficulty == '1':
        print('Easy game mode is set!')
        break
    elif difficulty =='2':
        print('Hard game mode is set!')
        break
    elif difficulty =='QUIT':
        print('bye')
        break
    else:
        print("you can only choose 1, 2, or quit.")
</code>```

It breaks the loop when the correct input is given, and keeps looping otherwise.

If you would LIKE to have a ValueError when they enter a wrong input you can use raise like so:

```<code>while True:
    difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
    if difficulty == '1':
        print('Easy game mode is set!')
        break
    elif difficulty =='2':
        print('Hard game mode is set!')
        break
    elif difficulty =='QUIT':
        print('bye')
        break
    else:
        print("you can only choose 1, 2, or quit.")
        raise ValueError #notice the additional line here
</code>```

Body:
List item

i want to let the user type 1 , 2 or quit otherwise i want to put him to type again one of them. everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level. also its a hangman game. tanks

Sloved!!

import sys
while True:

difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower()
try:

         if difficulty == '1':
            print('Easy game mode is set!')
         elif difficulty =='2':
            print('Hard game mode is set!')
         elif difficulty =='quit':
            print('Sheeeeeeeeeeeeeeesh')

      except:
         continue
      if difficulty == '1' or difficulty =='2':
         break
      elif difficulty == 'quit':
         sys.exit('byeeeee')
         break
    #elif difficulty
      else:
         print('invalid ')

Body:
try: and except: is probably not what you want to use here because you won't get a ValueError and thus the except does not execute. Maybe try something like:

while True:
    difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
    if difficulty == '1':
        print('Easy game mode is set!')
        break
    elif difficulty =='2':
        print('Hard game mode is set!')
        break
    elif difficulty =='QUIT':
        print('bye')
        break
    else:
        print("you can only choose 1, 2, or quit.")

It breaks the loop when the correct input is given, and keeps looping otherwise.

If you would LIKE to have a ValueError when they enter a wrong input you can use raise like so:

while True:
    difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
    if difficulty == '1':
        print('Easy game mode is set!')
        break
    elif difficulty =='2':
        print('Hard game mode is set!')
        break
    elif difficulty =='QUIT':
        print('bye')
        break
    else:
        print("you can only choose 1, 2, or quit.")
        raise ValueError #notice the additional line here


问:
PHP 7.2 Warning count(): Parameter must be an array or an object that implements Countable
i've a problem with Wordpress. This is the error message: PHP 7.2 Warning count(): Parameter must be an array or an object that implements Countable /web/htdocs/www.firenzeflowershow.com/home/wp-content/themes/wpex-elegant/functions/meta/init.php on line 750</p>
```<code>> elseif ( is_array( $meta_box['pages'] ) && count( $meta_box['pages']
> === 1  ))             $type = is_string( end( $meta_box['pages'] ) ) ? end( $meta_box['pages'] ) : false;
</code>```

答:
Try:

```<code>elseif ( is_array( $meta_box['pages'] ) && count( $meta_box['pages'] )
=== 1)             $type = is_string( end( $meta_box['pages'] ) ) ? end( $meta_box['pages'] ) : false;
</code>```

Your code did not work because === 1 was inside the count() function call: count($meta_box['pages'] === 1), and a comparison returns a bool. Here, I have changed it to count($meta_box['pages']) === 1 which gets the number of elements in the array, and checks if it returns 1.

Body:
i've a problem with Wordpress. This is the error message: PHP 7.2 Warning count(): Parameter must be an array or an object that implements Countable /web/htdocs/www.firenzeflowershow.com/home/wp-content/themes/wpex-elegant/functions/meta/init.php on line 750

> elseif ( is_array( $meta_box['pages'] ) && count( $meta_box['pages']
> === 1  ))             $type = is_string( end( $meta_box['pages'] ) ) ? end( $meta_box['pages'] ) : false;

Body:
Try:

elseif ( is_array( $meta_box['pages'] ) && count( $meta_box['pages'] )
=== 1)             $type = is_string( end( $meta_box['pages'] ) ) ? end( $meta_box['pages'] ) : false;

Your code did not work because === 1 was inside the count() function call: count($meta_box['pages'] === 1), and a comparison returns a bool. Here, I have changed it to count($meta_box['pages']) === 1 which gets the number of elements in the array, and checks if it returns 1.


问:
Define new parameter based on several responses in long dataset in R
I have a dataset with multiple lines per patient with the following structure:

```<code> A tibble: 15 x 3
   SubjectNo Question Answer
       <dbl>    <dbl>  <dbl>
 1         1        1      0
 2         1        2      1
 3         1        3      0
 4         1        4      1
 5         1        5      0
 6         2        1      1
 7         2        2      1
 8         2        3      0
 9         2        4      0
10         2        5      1
11         3        1      1
12         3        2      0
13         3        3      0
14         3        4      0
15         3        5      1
</code>```

The structure is identical per patient, so each patient has an input for all 5 questions. The answers can only be 0 or 1.
I want to create a new parameter per unique subject number which is based on the order of the "Answer" parameter.

Example:
if "Answer" is 00001, then new parameter is "combination 1"
if "Answer" is 00011, then new parameter is "combination 2" ect.

I have a basic idea about grouping the data by Subject number and then using an ifelse formula, but I did not succeed putting it into a working code.

答:
We may do a group by SubjectNo, paste the elements in 'Answer' to a single string, and use match to get the index after sorting

```<code>library(dplyr)
library(stringr)
df1 %>%
 group_by(SubjectNo) %>%
 mutate(new = as.numeric(str_c(Answer, collapse = ""))) %>%
 ungroup %>%
 mutate(new = match(new, sort(unique(new))))
</code>```

data

```<code>df1 <- structure(list(SubjectNo = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 3L), Question = c(1L, 2L, 3L, 4L, 5L,
1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), Answer = c(0L, 1L, 0L,
1L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 1L)), class = "data.frame",
 row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",

"14", "15"))
</code>```

Body:
I have a dataset with multiple lines per patient with the following structure:

 A tibble: 15 x 3
   SubjectNo Question Answer
       <dbl>    <dbl>  <dbl>
 1         1        1      0
 2         1        2      1
 3         1        3      0
 4         1        4      1
 5         1        5      0
 6         2        1      1
 7         2        2      1
 8         2        3      0
 9         2        4      0
10         2        5      1
11         3        1      1
12         3        2      0
13         3        3      0
14         3        4      0
15         3        5      1

The structure is identical per patient, so each patient has an input for all 5 questions. The answers can only be 0 or 1.
I want to create a new parameter per unique subject number which is based on the order of the "Answer" parameter.

Example:
if "Answer" is 00001, then new parameter is "combination 1"
if "Answer" is 00011, then new parameter is "combination 2" ect.

I have a basic idea about grouping the data by Subject number and then using an ifelse formula, but I did not succeed putting it into a working code.

Body:
We may do a group by SubjectNo, paste the elements in 'Answer' to a single string, and use match to get the index after sorting

library(dplyr)
library(stringr)
df1 %>%
 group_by(SubjectNo) %>%
 mutate(new = as.numeric(str_c(Answer, collapse = ""))) %>%
 ungroup %>%
 mutate(new = match(new, sort(unique(new))))

data

df1 <- structure(list(SubjectNo = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 3L), Question = c(1L, 2L, 3L, 4L, 5L,
1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), Answer = c(0L, 1L, 0L,
1L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 1L)), class = "data.frame",
 row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",

"14", "15"))


问:
Simple substraction on PHP (Arithmetic Operators)
I need some help with this simple substraction:

```<code>$savings = ($newprice - $newvalue);
</code>```

$newprice and $newvalue are values like 120.00 and 40.00

The problem is that the result is shown as 80 , without the .00 (dot00) at the end.

I will like to keep the values on the same format (a dot plus double cero at the end); what I need to change or include to that code ?

Thanks in advance

答:
Check into this function:</p>

```<code>number_format();
</code>```

Body:
I need some help with this simple substraction:

$savings = ($newprice - $newvalue);

$newprice and $newvalue are values like 120.00 and 40.00

The problem is that the result is shown as 80 , without the .00 (dot00) at the end.

I will like to keep the values on the same format (a dot plus double cero at the end); what I need to change or include to that code ?

Thanks in advance

Body:
Check into this function:

number_format();


问:
Binary XML file line #1: invalid drawable tag vector
I have an app that runs perfectly on most devices. However, I'm getting a FATAL exception whenever I try to run my application on devices with API < 21.

Here is the log:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aceinteract.sleak/com.aceinteract.sleak.activity.LoginRegisterActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class EditText
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$700(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class EditText
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:710)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:846)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.aceinteract.sleak.activity.LoginRegisterActivity.onCreate(LoginRegisterActivity.kt:21)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$700(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_person_accent_24dp.xml from drawable resource ID #0x7f07006f
at android.content.res.Resources.loadDrawable(Resources.java:2842)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.TextView.<init>(TextView.java:1023)
at android.widget.EditText.<init>(EditText.java:76)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:64)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:60)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:112)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1016)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1073)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$WrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:280)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:681)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:846)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.aceinteract.sleak.activity.LoginRegisterActivity.onCreate(LoginRegisterActivity.kt:21)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$700(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag vector
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:917)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:858)
at android.content.res.Resources.loadDrawable(Resources.java:2839)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.TextView.<init>(TextView.java:1023)
at android.widget.EditText.<init>(EditText.java:76)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:64)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:60)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:112)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1016)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1073)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$WrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:280)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:681)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:846)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.aceinteract.sleak.activity.LoginRegisterActivity.onCreate(LoginRegisterActivity.kt:21)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$700(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
</code>```

Here is the layout XML

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/layout_register"
    android:visibility="gone"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <EditText
        android:id="@+id/edit_register_full_name"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:drawableEnd="@drawable/ic_person_accent_24dp"
        android:padding="20dp"
        android:layout_width="0dp"
        android:hint="@string/hint_full_name"
        android:singleLine="true"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:drawableRight="@drawable/ic_person_accent_24dp" />

    <EditText
        android:id="@+id/edit_register_email"
        app:layout_constraintTop_toBottomOf="@id/edit_register_full_name"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:drawableEnd="@drawable/ic_email_accent_24dp"
        android:padding="20dp"
        android:layout_width="0dp"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:layout_height="wrap_content"
        android:drawableRight="@drawable/ic_email_accent_24dp" />

    <EditText
        android:id="@+id/edit_register_password"
        app:layout_constraintTop_toBottomOf="@id/edit_register_email"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:drawableEnd="@drawable/ic_vpn_key_accent_24dp"
        android:padding="20dp"
        android:inputType="textPassword"
        android:layout_width="0dp"
        android:hint="@string/hint_password"
        android:layout_height="wrap_content"
        android:drawableRight="@drawable/ic_vpn_key_accent_24dp" />

    <CheckBox
        android:id="@+id/check_register_show_password"
        android:text="@string/desc_show_password"
        android:layout_marginTop="10dp"
        app:layout_constraintTop_toBottomOf="@id/edit_register_password"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>
</code>```

And the gradle file:

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.aceinteract.sleak"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildToolsVersion '27.0.2'
}

androidExtensions {
    experimental = true
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.0.2'
    implementation 'com.android.support:design:27.0.2'
    implementation 'com.android.support:customtabs:27.0.2'
    implementation 'com.android.support:support-vector-drawable:27.0.2'
    implementation 'com.android.support:support-v4:27.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:animated-vector-drawable:27.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.android.support:cardview-v7:27.0.2'
    implementation 'com.android.support:gridlayout-v7:27.0.2'
    implementation 'com.android.support:recyclerview-v7:27.0.2'
    implementation 'com.android.support:design:27.0.2'
    implementation 'com.android.support:palette-v7:27.0.2'
    implementation 'com.google.code.gson:gson:2.8.0'
    implementation 'com.mikhaellopez:circularimageview:3.0.2'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'uk.co.chrisjenx:calligraphy:2.2.0'
}
</code>```

I have tried changing to AppComaptEditText, but it still just gives the same error.

Thanks in advance :)

答:
Only need to Change

android:drawableTop -  app:drawableTopCompat,

android:drawableBottom - app:drawableBottomCompat,

android:drawableLeft - app:drawableLeftCompat,

android:drawableRight - app:drawableRightCompat.

Body:
I have an app that runs perfectly on most devices. However, I'm getting a FATAL exception whenever I try to run my application on devices with API < 21.

Here is the log:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aceinteract.sleak/com.aceinteract.sleak.activity.LoginRegisterActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class EditText
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$700(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class EditText
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:710)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:846)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.aceinteract.sleak.activity.LoginRegisterActivity.onCreate(LoginRegisterActivity.kt:21)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$700(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_person_accent_24dp.xml from drawable resource ID #0x7f07006f
at android.content.res.Resources.loadDrawable(Resources.java:2842)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.TextView.<init>(TextView.java:1023)
at android.widget.EditText.<init>(EditText.java:76)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:64)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:60)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:112)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1016)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1073)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$WrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:280)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:681)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:846)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.aceinteract.sleak.activity.LoginRegisterActivity.onCreate(LoginRegisterActivity.kt:21)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$700(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag vector
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:917)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:858)
at android.content.res.Resources.loadDrawable(Resources.java:2839)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.TextView.<init>(TextView.java:1023)
at android.widget.EditText.<init>(EditText.java:76)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:64)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:60)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:112)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1016)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1073)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$WrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:280)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:681)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:846)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.aceinteract.sleak.activity.LoginRegisterActivity.onCreate(LoginRegisterActivity.kt:21)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$700(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)

Here is the layout XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/layout_register"
    android:visibility="gone"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <EditText
        android:id="@+id/edit_register_full_name"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:drawableEnd="@drawable/ic_person_accent_24dp"
        android:padding="20dp"
        android:layout_width="0dp"
        android:hint="@string/hint_full_name"
        android:singleLine="true"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:drawableRight="@drawable/ic_person_accent_24dp" />

    <EditText
        android:id="@+id/edit_register_email"
        app:layout_constraintTop_toBottomOf="@id/edit_register_full_name"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:drawableEnd="@drawable/ic_email_accent_24dp"
        android:padding="20dp"
        android:layout_width="0dp"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:layout_height="wrap_content"
        android:drawableRight="@drawable/ic_email_accent_24dp" />

    <EditText
        android:id="@+id/edit_register_password"
        app:layout_constraintTop_toBottomOf="@id/edit_register_email"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:drawableEnd="@drawable/ic_vpn_key_accent_24dp"
        android:padding="20dp"
        android:inputType="textPassword"
        android:layout_width="0dp"
        android:hint="@string/hint_password"
        android:layout_height="wrap_content"
        android:drawableRight="@drawable/ic_vpn_key_accent_24dp" />

    <CheckBox
        android:id="@+id/check_register_show_password"
        android:text="@string/desc_show_password"
        android:layout_marginTop="10dp"
        app:layout_constraintTop_toBottomOf="@id/edit_register_password"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>

And the gradle file:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.aceinteract.sleak"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildToolsVersion '27.0.2'
}

androidExtensions {
    experimental = true
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.0.2'
    implementation 'com.android.support:design:27.0.2'
    implementation 'com.android.support:customtabs:27.0.2'
    implementation 'com.android.support:support-vector-drawable:27.0.2'
    implementation 'com.android.support:support-v4:27.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:animated-vector-drawable:27.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.android.support:cardview-v7:27.0.2'
    implementation 'com.android.support:gridlayout-v7:27.0.2'
    implementation 'com.android.support:recyclerview-v7:27.0.2'
    implementation 'com.android.support:design:27.0.2'
    implementation 'com.android.support:palette-v7:27.0.2'
    implementation 'com.google.code.gson:gson:2.8.0'
    implementation 'com.mikhaellopez:circularimageview:3.0.2'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'uk.co.chrisjenx:calligraphy:2.2.0'
}

I have tried changing to AppComaptEditText, but it still just gives the same error.

Thanks in advance :)


问:
how to confirm a correlation between features?
I have data showing the price to lease different cars.
i have created a matrix to show the correlations between each of the elements involved but i do not trust it. in my experience the correlations it is showing should not be. the blp (the cost to fully purchase the car) should be the most important factor, however im getting seats and engine volume. (engine volume i can understand, but seats?)
perhaps the problem may be how i scaled my data.

correlation matrix image

```<code>from matplotlib import pyplot
import pandas as pd
import numpy

from sklearn import *

def scale_this_data(data, col_names):

    print("scalling data now")
    new_df = pd.DataFrame(columns = col_names)
    for col in data.columns:
        wanted_col = False
        for the_col in col_names:
            if the_col == col:
                wanted_col = True
        if wanted_col == True:
            np_arr = data[col].values
            np_arr = np_arr.reshape(-1, 1)
            min_max_scaler = preprocessing.MinMaxScaler()

            np_arr = min_max_scaler.fit_transform(np_arr)

            #for n in range(len(data[col])):
            old = data[col].iloc[3]
            data[col] = np_arr
            print(str(data[col].iloc[3])+ "   this   became    this    = "+ str(data[col]))
    return data

Path = "new_ratebook.csv"
col_names = ['Net Rental2','Doors2', 'Seats2', 'BHP2', 'Eng CC2', 'CO22',  'blp2']
data = pd.read_csv(Path , dtype = str , index_col=False, low_memory=False)

data = scale_this_data(data, col_names)
data.to_csv("scaleddata.csv")

correlations = data.corr()
fig = pyplot.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(correlations, vmin=0, vmax=1)
fig.colorbar(cax)
ticks = np.arange(0,7,1)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xticklabels(col_names)
ax.set_yticklabels(col_names)
pyplot.savefig('correlations.png')
pyplot.show()
</code>```

question, how do i confirm to myself the the correlation is correct

答:
You can confirm it with various ways. Some are the following:

Verify that data are correct.

Take some of your data (reduce the length of your data frame).

Calculate it by hand (good way to convince one's self), calculator, excel or an online correlation coefficient calculator like the Pearson Correlation Coefficient Calculator from google results.

By the way, correlation does not imply effect/causality (link, archived).

Body:
I have data showing the price to lease different cars.
i have created a matrix to show the correlations between each of the elements involved but i do not trust it. in my experience the correlations it is showing should not be. the blp (the cost to fully purchase the car) should be the most important factor, however im getting seats and engine volume. (engine volume i can understand, but seats?)
perhaps the problem may be how i scaled my data.

correlation matrix image

from matplotlib import pyplot
import pandas as pd
import numpy

from sklearn import *

def scale_this_data(data, col_names):

    print("scalling data now")
    new_df = pd.DataFrame(columns = col_names)
    for col in data.columns:
        wanted_col = False
        for the_col in col_names:
            if the_col == col:
                wanted_col = True
        if wanted_col == True:
            np_arr = data[col].values
            np_arr = np_arr.reshape(-1, 1)
            min_max_scaler = preprocessing.MinMaxScaler()

            np_arr = min_max_scaler.fit_transform(np_arr)

            #for n in range(len(data[col])):
            old = data[col].iloc[3]
            data[col] = np_arr
            print(str(data[col].iloc[3])+ "   this   became    this    = "+ str(data[col]))
    return data

Path = "new_ratebook.csv"
col_names = ['Net Rental2','Doors2', 'Seats2', 'BHP2', 'Eng CC2', 'CO22',  'blp2']
data = pd.read_csv(Path , dtype = str , index_col=False, low_memory=False)

data = scale_this_data(data, col_names)
data.to_csv("scaleddata.csv")

correlations = data.corr()
fig = pyplot.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(correlations, vmin=0, vmax=1)
fig.colorbar(cax)
ticks = np.arange(0,7,1)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xticklabels(col_names)
ax.set_yticklabels(col_names)
pyplot.savefig('correlations.png')
pyplot.show()

question, how do i confirm to myself the the correlation is correct


问:
c# to vb conversion issues - Is this line correct?
I am trying to convert this line to vb.net:

using var scorer = new YoloScorer<YoloCocoP5Model>("Assets/Weights/yolov5s.onnx");
```
<p>I converted it like this (renaming also scorer to my scorer, and correcting the path):</p>
<pre class="lang-vb prettyprint-override"><code>Dim myscorer As New Yolov5Net.Scorer.YoloScorer(Of Yolov5Net.Scorer.Models.YoloCocoP5Model)("Assets/Weights/best.onnx")
</code>```

Visual studio is not complaining, so I assume that the conversion is correct, but unfortunately its also not returning anything later in the code, so its not working properly. This line is the only one I am still not sure at the moment. What is the anotation <xxx>(...)?

答:
My first suggestion would be to import Yolov5Net.Scorer and Yolov5Net.Scorer.Models since C# is doing the same indicated by the lack of fully qualified namespaces.

My second suggestion would be to use a Using declaration like what C# is doing:

Using myscorer As New YoloScorer(Of YoloCocoP5Model)("Assets/Weights/best.onnx")
    ' do something with myscorer
End Using
```

Body:
I am trying to convert this line to vb.net:

using var scorer = new YoloScorer<YoloCocoP5Model>("Assets/Weights/yolov5s.onnx");

I converted it like this (renaming also scorer to my scorer, and correcting the path):

Dim myscorer As New Yolov5Net.Scorer.YoloScorer(Of Yolov5Net.Scorer.Models.YoloCocoP5Model)("Assets/Weights/best.onnx")

Visual studio is not complaining, so I assume that the conversion is correct, but unfortunately its also not returning anything later in the code, so its not working properly. This line is the only one I am still not sure at the moment. What is the anotation <xxx>(...)?


问:
Formatting a UITextField for credit card input like (xxxx xxxx xxxx xxxx)
I want to format a UITextField for entering a credit card number into such that it only allows digits to be entered and automatically inserts spaces so that the number is formatted like so:

```<code>XXXX XXXX XXXX XXXX
</code>```

How can I do this?

答:
You can use StringPatternFormatter pod:

```<code>pod 'StringPatternFormatter'
</code>```

The UITextField need to implement the following method from UITextFieldDelegate:

import StringPatternFormatter

...

textField.delegate = self

...

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else {
        return true
    }

    let lastText = (text as NSString).replacingCharacters(in: range, with: string) as String

    textField.text = lastText.format("nnnn nnnn nnnn nnnn", oldString: text)
    return false
}
```

Body:
I want to format a UITextField for entering a credit card number into such that it only allows digits to be entered and automatically inserts spaces so that the number is formatted like so:

XXXX XXXX XXXX XXXX

How can I do this?

Body:
You can use StringPatternFormatter pod:

pod 'StringPatternFormatter'

The UITextField need to implement the following method from UITextFieldDelegate:

import StringPatternFormatter

...

textField.delegate = self

...

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else {
        return true
    }

    let lastText = (text as NSString).replacingCharacters(in: range, with: string) as String

    textField.text = lastText.format("nnnn nnnn nnnn nnnn", oldString: text)
    return false
}


问:
DevExtreme DataGrid react-testing-library
Cannot test datagrid component

Here is example.
https://codesandbox.io/s/g921o?file=/src/components/Home.js

Please check test console. screen.debug() doesn't return dom with dataSource of data grid.
How to test data grid with simple array or with CustomStore.

答:
In my case this way helped, but then there is a problem of how to get updated number of rows if some action happened...

```<code>it("We are doing test1", async () => {
    render(<Home />);
    const rows =  await screen.findAllByText(/Test\d/);
    console.log(rows);
});
</code>```

HERE they answer why the regular way doesn't work for their components...

Body:
In my case this way helped, but then there is a problem of how to get updated number of rows if some action happened...

it("We are doing test1", async () => {
    render(<Home />);
    const rows =  await screen.findAllByText(/Test\d/);
    console.log(rows);
});

HERE they answer why the regular way doesn't work for their components...


问:
Output of this javascript and the reason
```<code>function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();
</code>```

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

答:
Closures

The return statement in that function saves i. So when var i = 0; is only called var ctr = getCtr();. Then ctr becomes the returned function:

```<code>function () {
       console.log(++i)
   }
</code>```

and the variable ctr has i in the scope of the outer function, getCtr() and the return function is in the scope of getCtr() as well.

Body:
function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

Body:
Closures

The return statement in that function saves i. So when var i = 0; is only called var ctr = getCtr();. Then ctr becomes the returned function:

function () {
       console.log(++i)
   }

and the variable ctr has i in the scope of the outer function, getCtr() and the return function is in the scope of getCtr() as well.


问:
I want to get input value without id
In this code, I want to get input value by javascript, How can I do?
Thanks.</p>
```<code><div id='my-id' class='my-class'>
    <div>
        <input type='text'>
    </div>
</div>
</code>```

答:
Easiest way is querySelector

```<code>document.querySelector("#my-id input")
</code>```

Old way is getElementsByTagName

```<code>document.getElementsByTagName("input")[0];
document.getElementById("my-id").getElementsByTagName("input")[0];
</code>```

If your element is in a form, you can go old school with

```<code>document.forms[0].elements[0]
</code>```

Title: I want to get input value without id

Body:
In this code, I want to get input value by javascript, How can I do?
Thanks.

        <input type='text'>

Body:
Easiest way is querySelector

document.querySelector("#my-id input")

Old way is getElementsByTagName

document.getElementsByTagName("input")[0];
document.getElementById("my-id").getElementsByTagName("input")[0];

If your element is in a form, you can go old school with

document.forms[0].elements[0]


问:
Pandas replace value in column with key in dictionary
I'm trying to replace each value of a column in my pandas df with dict key if the value == the value of the dictionary:

Example dic: {'The Name of the Rose': '9780544176560'}

Example df:

```<code>ISBN, link
9780544176560, https://link
</code>```

Code:

```<code>df['ISBN'] = df['ISBN'].astype(str)
for k,v in dic.items():
    for x in df['ISBN']:
        x = str(x)
        if x == v:
            print(True)
            x = k
</code>```

It prints True every time, and if I print x I get the correct titles, but then when I print the df it returns numbers like nothing changed. I also tried replace but nothing changed

答:
You should use map, but you're building your dictionary the wrong way.

As ISBN are unique, they can be used as key. A book title could not be unique though:

```<code>dic = {'The Name of the Rose': '9780544176560'}
df = pd.DataFrame({'ISBN': [9780544176560],
                   'link': ['https://link']})

# invert the dictionary if needed
# but the best it to build it directly with ISBN as key
dic = {isbn:title for title,isbn in dic.items()}
# {'9780544176560': 'The Name of the Rose'}

# map the Title from the ISBN
df['Title'] = df['ISBN'].astype(str).map(dic)
</code>```

output:

```<code>            ISBN          link                 Title
0  9780544176560  https://link  The Name of the Rose
</code>```

Body:
I'm trying to replace each value of a column in my pandas df with dict key if the value == the value of the dictionary:

Example dic: {'The Name of the Rose': '9780544176560'}

Example df:

ISBN, link
9780544176560, https://link

Code:

df['ISBN'] = df['ISBN'].astype(str)
for k,v in dic.items():
    for x in df['ISBN']:
        x = str(x)
        if x == v:
            print(True)
            x = k

It prints True every time, and if I print x I get the correct titles, but then when I print the df it returns numbers like nothing changed. I also tried replace but nothing changed

Body:
You should use map, but you're building your dictionary the wrong way.

As ISBN are unique, they can be used as key. A book title could not be unique though:

dic = {'The Name of the Rose': '9780544176560'}
df = pd.DataFrame({'ISBN': [9780544176560],
                   'link': ['https://link']})

# invert the dictionary if needed
# but the best it to build it directly with ISBN as key
dic = {isbn:title for title,isbn in dic.items()}
# {'9780544176560': 'The Name of the Rose'}

# map the Title from the ISBN
df['Title'] = df['ISBN'].astype(str).map(dic)

output:

            ISBN          link                 Title
0  9780544176560  https://link  The Name of the Rose


Title: I want to get input value without id

Body: document.getElementsByTagName('input')[0].value


问:
Kafka Connect won't pick up custom connector
I am trying to use kafka connect in a docker container with a custom connector (PROGRESS_DATADIRECT_JDBC_OE_ALL.jar) to connect to an openedge database.

I have put the JAR file in the plugin path (usr/share/java) but it won't load as a connector.

```<code>COPY Openedge/PROGRESS_DATADIRECT_JDBC_OE_ALL.jar /usr/share/java/progress
</code>```

I can load another (standard) connector by putting it in the plugin path. This works

```<code>COPY confluentinc-kafka-connect-jdbc-10.3.2 /usr/share/java/confluentinc-kafka-connect-jdbc-10.3.2
</code>```

A little lost on how to move forward and I'm very new to kafka. My main sources of information are
openedge to kafka streaming and How to use Kafka connect

答:
JDBC Drivers are not Connect plugins, nor are they connectors themselves.

You'd need to set the JVM CLASSPATH environment variable for detecting JDBC Drivers, as with any Java process.

The instructions on the linked site suggest you should copy the JDBC Drivers into the directory for the existing Confluent JDBC connector. While you could use a Docker COPY command, the better way would be to use confluent-hub install

Body:
I am trying to use kafka connect in a docker container with a custom connector (PROGRESS_DATADIRECT_JDBC_OE_ALL.jar) to connect to an openedge database.

I have put the JAR file in the plugin path (usr/share/java) but it won't load as a connector.

COPY Openedge/PROGRESS_DATADIRECT_JDBC_OE_ALL.jar /usr/share/java/progress

I can load another (standard) connector by putting it in the plugin path. This works

COPY confluentinc-kafka-connect-jdbc-10.3.2 /usr/share/java/confluentinc-kafka-connect-jdbc-10.3.2

A little lost on how to move forward and I'm very new to kafka. My main sources of information are
openedge to kafka streaming and How to use Kafka connect