问:
Space between textview and drawable icon
I'm facing problems with the position of an icon. I've set that icon as drawableLeft of a TextView, this is working fine but, if I set the TextView's gravity to center_horizontal, then a padding space appears between the icon and the text. The code is as follows:

```<code><TextView
    style="@style/BaseText.White.Bold"
    android:gravity="center_horizontal"
    android:drawableStart="@drawable/ic_text"
    android:drawableLeft="@drawable/ic_text"
    android:text="@string/text"
    android:layout_marginBottom="@dimen/margin_small"
    android:layout_marginRight="@dimen/margin_big"
    android:layout_marginLeft="@dimen/margin_big"
    android:padding="0dp"
    android:drawablePadding="0dp"/>
</code>```

What do I have to do to ensure that the icon is shown at the text's left side but horizontally centered?
I've make two screenshots to show you the difference when adding or removing the icon's gravity.
When the textview's gravity is not set, the result is as follows:

But, when the gravity is added, then a padding appears between the text and the icon:

Thanks in advance

答:
Only add android:drawablePadding="10dp" field in your text view refer the coad</p>

```<code> <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add New Address"
        android:textAppearance="@style/Title"
        android:id="@+id/tvAddNewAddress"
        android:drawablePadding="20dp"
        android:layout_weight="1"
        android:padding="5dp"
        android:textColor="@color/colorAccent"
        android:drawableStart="@android:drawable/arrow_down_float"
        />
</code>```

Body:
I'm facing problems with the position of an icon. I've set that icon as drawableLeft of a TextView, this is working fine but, if I set the TextView's gravity to center_horizontal, then a padding space appears between the icon and the text. The code is as follows:

<TextView
    style="@style/BaseText.White.Bold"
    android:gravity="center_horizontal"
    android:drawableStart="@drawable/ic_text"
    android:drawableLeft="@drawable/ic_text"
    android:text="@string/text"
    android:layout_marginBottom="@dimen/margin_small"
    android:layout_marginRight="@dimen/margin_big"
    android:layout_marginLeft="@dimen/margin_big"
    android:padding="0dp"
    android:drawablePadding="0dp"/>

What do I have to do to ensure that the icon is shown at the text's left side but horizontally centered?
I've make two screenshots to show you the difference when adding or removing the icon's gravity.
When the textview's gravity is not set, the result is as follows:

But, when the gravity is added, then a padding appears between the text and the icon:

Thanks in advance

Body:
Only add android:drawablePadding="10dp" field in your text view refer the coad

 <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add New Address"
        android:textAppearance="@style/Title"
        android:id="@+id/tvAddNewAddress"
        android:drawablePadding="20dp"
        android:layout_weight="1"
        android:padding="5dp"
        android:textColor="@color/colorAccent"
        android:drawableStart="@android:drawable/arrow_down_float"
        />


来源: stackexchange

问:
Cloud Spanner - Insert or Update and Increment DML?
Is there a way to use DML to "insert or (update and increment)" rows in Google Cloud Spanner?

This doesn't work:

```<code>INSERT INTO table (key, value) VALUES ('ABC', 1)
       ON DUPLICATE KEY UPDATE value = value + 1
# Syntax error: Unexpected keyword ON
</code>```

答:
As per the documentation Data Manipulation Language syntax informs:

If the statement attempts to insert a duplicate row, as determined by the primary key, then the entire statement fails.

So, it's not possible to insert using this type of function that you are trying, unfortunately.

I would recommend you to take a look at this documentation - Inserting, updating, and deleting data using Data Manipulation Language - to get more information, on using DML with Cloud Spanner.

Let me know if the information helped you!

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to use DML to "insert or (update and increment)" rows in Google Cloud Spanner?

This doesn't work:

INSERT INTO table (key, value) VALUES ('ABC', 1)
       ON DUPLICATE KEY UPDATE value = value + 1
# Syntax error: Unexpected keyword ON


问:
data.table frollmean very slow
I'm trying to calculate the rolling mean of a column in a large data.table (~30M rows) aggregated by two other columns.
The rolling mean should include only the preceding N row values, not the row value itself.
For this purpose, i had to define my own rolling mean function based on frollmean function. (N=3)
Applying the function to the column is really really slow, rendering it rather useless.

Here is sample data:

```<code>require(data.table)
DT <- data.table(ID=c('A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C')
               , value_type =c('type 1', 'type 1','type 2','type 1','type 2','type 2','type 1','type 1','type 2','type 1','type 1','type 1')
               , value=c(1,4,7,2,3,5,1,6,8,2,2,3))
    DT
         ID value_type value
     1:  A     type 1     1
     2:  A     type 1     4
     3:  A     type 2     7
     4:  A     type 1     2
     5:  A     type 2     3
     6:  A     type 2     5
     7:  B     type 1     1
     8:  B     type 1     6
     9:  B     type 2     8
    10:  C     type 1     2
    11:  C     type 1     2
    12:  C     type 1     3

#this is the customised rolling function
lrollmean<-function(x){

  head(frollmean(c(NA,NA,NA,x), n = 3, fill = NA, algo ="exact", align="right", na.rm = TRUE)[-(1:2)], -1)

}

> DT[, roll_mean := lrollmean(value), by=.(ID, value_type)]
> DT
    ID value_type value roll_mean
 1:  A     type 1     1       NaN
 2:  A     type 1     4       1.0
 3:  A     type 2     7       NaN
 4:  A     type 1     2       2.5
 5:  A     type 2     3       7.0
 6:  A     type 2     5       5.0
 7:  B     type 1     1       NaN
 8:  B     type 1     6       1.0
 9:  B     type 2     8       NaN
10:  C     type 1     2       NaN
11:  C     type 1     2       2.0
12:  C     type 1     3       2.0
</code>```

This operation takes more than 30 minutes! I've got a reasonable machine which ample RAM, and I feel the long time of the operation has something to do with my code rather than the machine.

答:
Can you try and see if its fast enough:

```<code>n <- 3L
DT[, roll_mean := {
        v <- if (.N - n >= 1L) c(seq.int(n), rep(n, .N-n)) else seq.int(min(n, .N))
        shift(frollmean(value, v, adaptive=TRUE))
    }, .(ID, value_type)]
</code>```

But if you have a large number of small groups, you can try:

```<code>setorder(DT[, rn := .I], ID, value_type)
rid <- DT[, rowid(ID, value_type)]

DT[, roll_mean := shift(frollmean(value, n))]

ix <- DT[rid==3L, which=TRUE]
set(DT, ix, "roll_mean", DT[, shift(frollmean(value, n - 1L))][ix])

ix <- DT[rid==2L, which=TRUE]
set(DT, ix, "roll_mean", DT[, shift(value)][ix])

DT[rid==1L, roll_mean := NA_real_]
setorder(DT, rn)[]
</code>```

Title: data.table frollmean very slow

Body:
I'm trying to calculate the rolling mean of a column in a large data.table (~30M rows) aggregated by two other columns.
The rolling mean should include only the preceding N row values, not the row value itself.
For this purpose, i had to define my own rolling mean function based on frollmean function. (N=3)
Applying the function to the column is really really slow, rendering it rather useless.

Here is sample data:

require(data.table)
DT <- data.table(ID=c('A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C')
               , value_type =c('type 1', 'type 1','type 2','type 1','type 2','type 2','type 1','type 1','type 2','type 1','type 1','type 1')
               , value=c(1,4,7,2,3,5,1,6,8,2,2,3))
    DT
         ID value_type value
     1:  A     type 1     1
     2:  A     type 1     4
     3:  A     type 2     7
     4:  A     type 1     2
     5:  A     type 2     3
     6:  A     type 2     5
     7:  B     type 1     1
     8:  B     type 1     6
     9:  B     type 2     8
    10:  C     type 1     2
    11:  C     type 1     2
    12:  C     type 1     3

#this is the customised rolling function
lrollmean<-function(x){

  head(frollmean(c(NA,NA,NA,x), n = 3, fill = NA, algo ="exact", align="right", na.rm = TRUE)[-(1:2)], -1)

}

> DT[, roll_mean := lrollmean(value), by=.(ID, value_type)]
> DT
    ID value_type value roll_mean
 1:  A     type 1     1       NaN
 2:  A     type 1     4       1.0
 3:  A     type 2     7       NaN
 4:  A     type 1     2       2.5
 5:  A     type 2     3       7.0
 6:  A     type 2     5       5.0
 7:  B     type 1     1       NaN
 8:  B     type 1     6       1.0
 9:  B     type 2     8       NaN
10:  C     type 1     2       NaN
11:  C     type 1     2       2.0
12:  C     type 1     3       2.0

This operation takes more than 30 minutes! I've got a reasonable machine which ample RAM, and I feel the long time of the operation has something to do with my code rather than the machine.

Body:
Can you try and see if its fast enough:

n <- 3L
DT[, roll_mean := {
        v <- if (.N - n >= 1L) c(seq.int(n), rep(n, .N-n)) else seq.int(min(n, .N))
        shift(frollmean(value, v, adaptive=TRUE))
    }, .(ID, value_type)]

But if you have a large number of small groups, you can try:

setorder(DT[, rn := .I], ID, value_type)
rid <- DT[, rowid(ID, value_type)]

DT[, roll_mean := shift(frollmean(value, n))]

ix <- DT[rid==3L, which=TRUE]
set(DT, ix, "roll_mean", DT[, shift(frollmean(value, n - 1L))][ix])

ix <- DT[rid==2L, which=TRUE]
set(DT, ix, "roll_mean", DT[, shift(value)][ix])

DT[rid==1L, roll_mean := NA_real_]
setorder(DT, rn)[]


问:
Confusion about IE9's automatic Document Mode behavior
I'm experiencing a very strange behavior in IE - gasp, right? - regarding Document Mode.

Normally the browser picks this based on doctype and so on, but two separate, untampered-with installations of the same exact version of IE - 9.0.8112.16421 - choose different Document Mode when visiting the same URL. One machine chooses IE9 standards mode, the other chooses IE7 standards.

Anyone have an idea why this might happen?

答: The typical explanation here is that you have different settings for CompatView on the two machines. On the Tools menu, choose "Compatibility View Settings." If they're the same, look in the page's Context Menu > Properties and see if the page is being treated as originating in a different Zone on one of the computers.</p>

ContentLicense: CC BY-SA 3.0


问:
What is the most efficient way to copy some properties from an object in JavaScript?
Say, I have an object:

```<code>const user = {_id: 1234, firstName: 'John', lastName: 'Smith'}
</code>```

I want to create another object without the _id key:

```<code>const newUser = {firstName: 'John', lastName: 'Smith'}
</code>```

I am using this:

```<code>const newUser = Object.assign({}, {firstName: user.firstName, lastName: user.lastName})
</code>```

Is there a better way to do this?

答:
Go through the object keys, put the wanted property keys in an array and use the Array.prototype.includes() to copy only these into the new object.

const account = {
  id: 123456,
  firstname: "John",
  lastname: "Doe",
  login: "john123",
  site_admin: false,
  blog: "https://opensource.dancingbear/",
  email: "john123@example.com",
  bio: "John ❤ Open Source",
  created_at: "2001-01-01T01:30:18Z",
  updated_at: "2020-02-16T21:09:14Z"
};

function selectSomeProperties(account) {
return Object.keys(account).reduce(function(obj, k) {
    if (["id", "email", "created_at"].includes(k)) {
        obj[k] = account[k];
    }
    return obj;
  }, {});
}
const selectedProperties = selectSomeProperties(account);
console.log(JSON.stringify(selectedProperties))```
</div>
</div>
</p>

<p>The result:</p>

```{"id":123456,"email":"john123@example.com","created_at":"2001-01-01T01:30:18Z"}
```

Body:
Say, I have an object:

const user = {_id: 1234, firstName: 'John', lastName: 'Smith'}

I want to create another object without the _id key:

const newUser = {firstName: 'John', lastName: 'Smith'}

I am using this:

const newUser = Object.assign({}, {firstName: user.firstName, lastName: user.lastName})

Is there a better way to do this?

Body:
Go through the object keys, put the wanted property keys in an array and use the Array.prototype.includes() to copy only these into the new object.

const account = {
  id: 123456,
  firstname: "John",
  lastname: "Doe",
  login: "john123",
  site_admin: false,
  blog: "https://opensource.dancingbear/",
  email: "john123@example.com",
  bio: "John ❤ Open Source",
  created_at: "2001-01-01T01:30:18Z",
  updated_at: "2020-02-16T21:09:14Z"
};

function selectSomeProperties(account) {
return Object.keys(account).reduce(function(obj, k) {
    if (["id", "email", "created_at"].includes(k)) {
        obj[k] = account[k];
    }
    return obj;
  }, {});
}
const selectedProperties = selectSomeProperties(account);
console.log(JSON.stringify(selectedProperties))

The result:

{"id":123456,"email":"john123@example.com","created_at":"2001-01-01T01:30:18Z"}


问:
Python3: Counting occurrence of characters in a nested dict
I'm currently working on a small piece of code and I seem to have run into a roadblock. I was wondering if it's possible to find the most common occurrence of a character that follows a specific group of characters?

For example, say I have the following sentence:

"fishies are super neat, a fish is a good pet. also, fishing is for dads."

How would could I determine, for example, the most common character that occurs after the fragment "fish"?

In this specific example, doing it by hand, I get something like this:

{"i": 2, " ": 1}

Currently, I have this chunk of code written to grab the "fish" portion of the word:

```<code>b = Class(n, 'file.txt')
ngrams = [b.file[i:i+n] for i in range(len(b.file)-1)]
</code>```

this will break up all of the text into chunks of 4 like so: ['fish', 'ishi', 'shie', 'hies', 'ies ', 'es a'.....]

My goal is to combine these two thoughts so that I can print something that looks like the following:

{'fish' : {'i':2, ' ':1} ..... }

I also currently have a defaultdict defined in __init__ like so: self.counts=defaultdict(lambda: defaultdict(int))

This is the closest I can get to achieving my desired solution, although I am unsure how to grab the individual characters that follow and how to count those characters:

b.counts = {i : { j : 5 for j in ngrams } for i in ngrams }

5 is merely a placeholder so I could see what printed. j in ngrams was also a placeholder to see what printed. Any input or ideas from anyone would be greatly appreciated!

答:
```<code>import re

raw_string = "fishies are super neat, a fish is a good pet. also, fishing is for dads."

key =  ['fish', 'ishi', 'shie', 'hies']
out = {}
for item in key:
    data = []
    for word in re.findall(item+'.', raw_string):
        data.append(word[-1])
    results = {item:data.count(item) for item in data}
    out[item] = results
</code>```

Output:

```<code>{'fish': {'i': 2, ' ': 1}, 'ishi': {'e': 1, 'n': 1}, 'shie': {'s': 1}, 'hies': {' ': 1}}
</code>```

Body:
I'm currently working on a small piece of code and I seem to have run into a roadblock. I was wondering if it's possible to find the most common occurrence of a character that follows a specific group of characters?

For example, say I have the following sentence:

"fishies are super neat, a fish is a good pet. also, fishing is for dads."

How would could I determine, for example, the most common character that occurs after the fragment "fish"?

In this specific example, doing it by hand, I get something like this:

{"i": 2, " ": 1}

Currently, I have this chunk of code written to grab the "fish" portion of the word:

b = Class(n, 'file.txt')
ngrams = [b.file[i:i+n] for i in range(len(b.file)-1)]

this will break up all of the text into chunks of 4 like so: ['fish', 'ishi', 'shie', 'hies', 'ies ', 'es a'.....]

My goal is to combine these two thoughts so that I can print something that looks like the following:

{'fish' : {'i':2, ' ':1} ..... }

I also currently have a defaultdict defined in __init__ like so: self.counts=defaultdict(lambda: defaultdict(int))

This is the closest I can get to achieving my desired solution, although I am unsure how to grab the individual characters that follow and how to count those characters:

b.counts = {i : { j : 5 for j in ngrams } for i in ngrams }

5 is merely a placeholder so I could see what printed. j in ngrams was also a placeholder to see what printed. Any input or ideas from anyone would be greatly appreciated!

Body:
import re

raw_string = "fishies are super neat, a fish is a good pet. also, fishing is for dads."

key =  ['fish', 'ishi', 'shie', 'hies']
out = {}
for item in key:
    data = []
    for word in re.findall(item+'.', raw_string):
        data.append(word[-1])
    results = {item:data.count(item) for item in data}
    out[item] = results

Output:

{'fish': {'i': 2, ' ': 1}, 'ishi': {'e': 1, 'n': 1}, 'shie': {'s': 1}, 'hies': {' ': 1}}


问:
How to set the date in materialize datepicker
I am using materializecss.com Datepicker. When i try to set date with jquery, the date doesn't get set. Here is my Code :-

```<code>// Materialize Date Picker
    window.picker = $('.datepicker').pickadate({
        selectMonths: true, // Creates a dropdown to control month
        selectYears: 100, // Creates a dropdown of 15 years to control year
        format: 'dd/mm/yyyy'
    });

<input type="text" id="Date" class="datepicker" />
</code>```

On Click event of a Button , I am setting the date :-

```<code>$("#Date").val('23/01/2015');
</code>```

When i open the datepicker it shows me today's date.

How to set the date in materialize datepicker?

答:
As per the docs materializecss.com
Check the Date format options.

```<code>// date picker
$(document).ready(function(){

  $('.datepicker').datepicker( {"format":'dd-mm-yyyy'} ).datepicker("setDate", new Date());

});
</code>```

You can remove and change the code to below if you do not need current date as highlighted in calendar,

```<code>// date picker
$(document).ready(function(){

  $('.datepicker').datepicker( {"format":'dd-mm-yyyy'});

});
</code>```

Body:
I am using materializecss.com Datepicker. When i try to set date with jquery, the date doesn't get set. Here is my Code :-

// Materialize Date Picker
    window.picker = $('.datepicker').pickadate({
        selectMonths: true, // Creates a dropdown to control month
        selectYears: 100, // Creates a dropdown of 15 years to control year
        format: 'dd/mm/yyyy'
    });

<input type="text" id="Date" class="datepicker" />

On Click event of a Button , I am setting the date :-

$("#Date").val('23/01/2015');

When i open the datepicker it shows me today's date.

How to set the date in materialize datepicker?

Body:
As per the docs materializecss.com
Check the Date format options.

// date picker
$(document).ready(function(){

  $('.datepicker').datepicker( {"format":'dd-mm-yyyy'} ).datepicker("setDate", new Date());

});

You can remove and change the code to below if you do not need current date as highlighted in calendar,

// date picker
$(document).ready(function(){

  $('.datepicker').datepicker( {"format":'dd-mm-yyyy'});

});


问:
How to convert date format from different country languages to numeric date format
example

26/Veebr/2020 to 26/02/2020

I have a problem to convert date from a different language to dd/mm/yy

Like:

18/Helmi/2020 to 18/02/2020

答:
With PHP you can created arrays for different languages with elements 'Month Name' => Number. With strtr() the month names are exchanged for numbers. The result can then be parsed with DateTime::createFromFormat.

```<code>$transEstonian = ['Veebr' => '02'];  //this for all

$strDate = '26/Veebr/2020';

$strDateNum = strtr($strDate,$transEstonian);
$date = DateTime::createFromFormat("d/m/Y H:i",$strDateNum." 00:00");
echo $date->format('Y-m-d');  //2020-02-26
</code>```

This can be done with javascript similarly.

Body:
With PHP you can created arrays for different languages with elements 'Month Name' => Number. With strtr() the month names are exchanged for numbers. The result can then be parsed with DateTime::createFromFormat.

$transEstonian = ['Veebr' => '02'];  //this for all

$strDate = '26/Veebr/2020';

$strDateNum = strtr($strDate,$transEstonian);
$date = DateTime::createFromFormat("d/m/Y H:i",$strDateNum." 00:00");
echo $date->format('Y-m-d');  //2020-02-26

This can be done with javascript similarly.


问:
How can I terminate an infinite loop in Turbo C?
I get stuck in an infinite loop. How can I terminate this loop?  I tried to use/press Cntrlc but nothing happens.  I don't know how to stop it.

```<code>main()
{
     while (1)
     {
          char ch;
          printf("Enter a character: \n");
          ch = getche();
          printf("\nThe code for %c is %d.\n", ch, ch);
     }
}
</code>```

答:
CTRLBREAK will probably work for this. I have a vague recollection that CTRLC did not always work with the Borland products.

Though, that was a long time ago so I had to retrieve that from very deep memory, which may have faded somewhat :-)

My question for you is: Why is anyone still using Turbo C when much better and equally cheap solutions are available? Like gcc (such as in Code::Blocks) or even Microsoft Visual C Express.

Body:
I get stuck in an infinite loop. How can I terminate this loop?  I tried to use/press Cntrlc but nothing happens.  I don't know how to stop it.

main()
{
     while (1)
     {
          char ch;
          printf("Enter a character: \n");
          ch = getche();
          printf("\nThe code for %c is %d.\n", ch, ch);
     }
}


问:
Generate a Certificate Signing Request for ssl using java program
I want to write a program that can generate Certificate Signing Request with all information like domain name, country name, state organisation etc. I know to how to generate it with open-ssl but I want to generate it with only java program. How can I do this?

Thanks for your help

答:
Bouncy castle provides all the tools you need to do that.

Here is the code to generate a CSR:

```<code>    PrivateKey priKey = entry.getPrivateKey(keystore, pwd);
    PKCS10CertificationRequestBuilder p10Builder
            = new JcaPKCS10CertificationRequestBuilder(
                    cert.getSubjectX500Principal(), cert.getPublicKey());
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(cert.getSigAlgName());
    ContentSigner signer = csBuilder.build(priKey);
    PKCS10CertificationRequest csr = p10Builder.build(signer);
    try (OutputStream stream = new FileOutputStream(file);
            Writer writer = new OutputStreamWriter(stream, "UTF-8");
            JcaPEMWriter out = new JcaPEMWriter(writer)) {
        out.writeObject(csr);
    }
</code>```

Body:
Bouncy castle provides all the tools you need to do that.

Here is the code to generate a CSR:

    PrivateKey priKey = entry.getPrivateKey(keystore, pwd);
    PKCS10CertificationRequestBuilder p10Builder
            = new JcaPKCS10CertificationRequestBuilder(
                    cert.getSubjectX500Principal(), cert.getPublicKey());
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(cert.getSigAlgName());
    ContentSigner signer = csBuilder.build(priKey);
    PKCS10CertificationRequest csr = p10Builder.build(signer);
    try (OutputStream stream = new FileOutputStream(file);
            Writer writer = new OutputStreamWriter(stream, "UTF-8");
            JcaPEMWriter out = new JcaPEMWriter(writer)) {
        out.writeObject(csr);
    }


问:
Split/group collectible by consecutive elements
Suppose I have a list/array containing chars. How do I group/split/join them so that I get something like this?</p>

```<code>val input = arrayOf('b', 'b', 'c', 'd', 'e', 'e', 'e')

val output = groupOrSplit(input) // ['bb', 'c', 'd', 'eee']
</code>```

答:
Without more details, then I would do something like this:</p>

```<code>listOf("b", "b", "c", "d", "e", "e", "e").asSequence()

    // b => b to ["b", "b"]
    // c => c to ["c"], etc
    .groupBy { it }

    // b => "bb", etc
    .map { entry -> entry.value.joinToString("") }

    .toList()

// Result is listOf("bb", "c", "d", "eee")
</code>```

Body:
Suppose I have a list/array containing chars. How do I group/split/join them so that I get something like this?

val input = arrayOf('b', 'b', 'c', 'd', 'e', 'e', 'e')

val output = groupOrSplit(input) // ['bb', 'c', 'd', 'eee']

Body:
Without more details, then I would do something like this:

listOf("b", "b", "c", "d", "e", "e", "e").asSequence()

    // b => b to ["b", "b"]
    // c => c to ["c"], etc
    .groupBy { it }

    // b => "bb", etc
    .map { entry -> entry.value.joinToString("") }

    .toList()

// Result is listOf("bb", "c", "d", "eee")


问:
PHP / MySQL: Undefined index after user update a data
Currently, I develop a system that required an update function. The flow of the system will be like this:

1) list of data row in dashboard.php

2) User can select one of the data to view the details. It will redirect to view_task.php

3) At view_task.php, user can update the task name and click 'save' button to save.

The problem is. After I click button save, It will show the error 'undefined index: report id at line 7' and "undefined variable: task_name at line 55"

below is my current code:

view_task.php

```<code><?php

  require_once "../../../../config/configPDO.php";
  require_once "../../../../config/check.php";

  $report_id = $_GET['report_id']; //line 7

  $sql = "SELECT * FROM ot_report WHERE report_id = :report_id";
  $query = $conn->prepare($sql);
  $query->execute(array(':report_id' => $report_id));
  while($row = $query->fetch(PDO::FETCH_ASSOC)){

      $report_id = $row["report_id"];
      $task_name = $row["task_name"];
  }

?>

<form action="update_task_name.php" method="POST">
  <td><b>Task Name</b></td>
  <td colspan = '2'><input type="text" class="form-control" name="task_name" value="<?php echo $task_name; ?>"/></td> //line 55
  <input type="hidden" name="report_id" value="<?php echo $report_id ?>">
  <td><input type="submit" class="btn btn-primary btn-block" value = "Save" onclick="confirm('Are you sure?')"></td>
</form>
</code>```

update_task_name.php

```<code><?php

    require_once '../../../../config/configPDO.php';

    $update = "UPDATE ot_report SET task_name = :task_name WHERE report_id = :report_id";
    $stmt = $conn->prepare($update);
    $stmt->bindParam(':task_name', $_POST['task_name']);
    $stmt->bindParam(':report_id', $_POST['report_id']);
    $stmt->execute();

    class Result {}
    $response = new Result();
    $response->result = 'OK';
    $response->message = 'Update successful';
    header("Location: view_task.php");

?>
</code>```

Although get the error at view_task.php, but the data successfully save!

Can anyone know what is the error?

答:
Your error is this...

just access your page with a valid report_id

```<code>localhost/project_name/view_task/1
</code>```

You're probably not proving the id in the url, hence view_task query itself is not working because it is not getting the id from the URL for GET method.

Body:
Currently, I develop a system that required an update function. The flow of the system will be like this:

1) list of data row in dashboard.php

2) User can select one of the data to view the details. It will redirect to view_task.php

3) At view_task.php, user can update the task name and click 'save' button to save.

The problem is. After I click button save, It will show the error 'undefined index: report id at line 7' and "undefined variable: task_name at line 55"

below is my current code:

view_task.php

<?php

  require_once "../../../../config/configPDO.php";
  require_once "../../../../config/check.php";

  $report_id = $_GET['report_id']; //line 7

  $sql = "SELECT * FROM ot_report WHERE report_id = :report_id";
  $query = $conn->prepare($sql);
  $query->execute(array(':report_id' => $report_id));
  while($row = $query->fetch(PDO::FETCH_ASSOC)){

      $report_id = $row["report_id"];
      $task_name = $row["task_name"];
  }

?>

<form action="update_task_name.php" method="POST">
  Task Name
  <input type="text" class="form-control" name="task_name" value="<?php echo $task_name; ?>"/>	 //line 55
  <input type="hidden" name="report_id" value="<?php echo $report_id ?>">
  <input type="submit" class="btn btn-primary btn-block" value = "Save" onclick="confirm('Are you sure?')">
</form>

update_task_name.php

<?php

    require_once '../../../../config/configPDO.php';

    $update = "UPDATE ot_report SET task_name = :task_name WHERE report_id = :report_id";
    $stmt = $conn->prepare($update);
    $stmt->bindParam(':task_name', $_POST['task_name']);
    $stmt->bindParam(':report_id', $_POST['report_id']);
    $stmt->execute();

    class Result {}
    $response = new Result();
    $response->result = 'OK';
    $response->message = 'Update successful';
    header("Location: view_task.php");

?>

Although get the error at view_task.php, but the data successfully save!

Can anyone know what is the error?

Body:
Your error is this...

just access your page with a valid report_id

localhost/project_name/view_task/1

You're probably not proving the id in the url, hence view_task query itself is not working because it is not getting the id from the URL for GET method.


问:
Get file location that opened c# application
i am trying to make a basic console application (like command propmt)

what im trying to do is (in simple terms) is if i right click a file, lets call it my.file and i click open with and select my console application to run that file. how can i get my.file location.

I have tried everything and searched on the internet and found nothing.
Thanks

答:
Its simple the file being opened is sent as arguments to the program. So query the args to get the filename</p>

```<code>static void Main(string[] args)
{
    //Returns the path to the file
    Console.WriteLine(args[0]);
    // Index 1 returns file path, while index 0 returns the executable path
    Console.WriteLine(Environment.GetCommandLineArgs()[1].ToString());

}

</code>```

Body:
Its simple the file being opened is sent as arguments to the program. So query the args to get the filename

static void Main(string[] args)
{
    //Returns the path to the file
    Console.WriteLine(args[0]);
    // Index 1 returns file path, while index 0 returns the executable path
    Console.WriteLine(Environment.GetCommandLineArgs()[1].ToString());

}


答:
You could try something like this:

```<code>import re
from collections import Counter

sentence = "fishies are super neat, a fish is a good pet. also, fishing is for dads."
word = 'fish'
result = {}
result[word] = Counter(re.findall(f'{word}(.)', sentence, flags=re.IGNORECASE))

print(result)
</code>```

Note that this will also count cases where the fragment you are looking for appears in the middle of a word. If you only want to count words that start with the fragment, you could use something like re.findall(f'\\W{word}(.)') instead.

Title: Python3: Counting occurrence of characters in a nested dict

Body:
You could try something like this:

import re
from collections import Counter

sentence = "fishies are super neat, a fish is a good pet. also, fishing is for dads."
word = 'fish'
result = {}
result[word] = Counter(re.findall(f'{word}(.)', sentence, flags=re.IGNORECASE))

print(result)

Note that this will also count cases where the fragment you are looking for appears in the middle of a word. If you only want to count words that start with the fragment, you could use something like re.findall(f'\\W{word}(.)') instead.


问:
Add two Decimal Values and Convert the Final value to INT
i am adding two decimal values like

```<code>decimal one=0; decimal two=0; decimal sum=0;
sum = one+ two;
Int final =0;
</code>```

example

```<code>sum = 1.2 + 2.2;
sum = 3.4;
</code>```

Now i want to save this 3.4 in Integer Final by neglecting that decimal part (.4). How can I do this?

答:
```<code>Decimal value = Decimal.Add(a1, a2);
FinalOutout int = Convert.ToInt32(value);
</code>```

<p>It will work. </p>

Body:
i am adding two decimal values like

decimal one=0; decimal two=0; decimal sum=0;
sum = one+ two;
Int final =0;

example

sum = 1.2 + 2.2;
sum = 3.4;

Now i want to save this 3.4 in Integer Final by neglecting that decimal part (.4). How can I do this?

Body:
Decimal value = Decimal.Add(a1, a2);
FinalOutout int = Convert.ToInt32(value);

It will work.


问:
Is there a way to use integers as label in StaticText
I'm making a game with wxpython and I want to calculate the result every time button is clicked, so I created first the result on the screen, with StaticText, and then when any button is clicked, I want to add (+1) to the result.

But my problem is that I can't use integers as a label in StaticText, and then I can't also use SetLabel to set new result.

Example:

```<code># Error
self.answers_count_num = wx.StaticText(self.panel, pos=(645, 50), label=0)

def answers_count(self, event):
     result = int(self.answers_count_num.GetLabel()) + 1
     self.answers_count_num.SetLabel(result)
</code>```

Is there a way to use integers in a StaticText ?

答:
To use integers as the label of a wx.StaticText object, you first need to convert them to strings. Like:

# Error
self.answers_count_num = wx.StaticText(self.panel, pos=(645, 50), label=str(0))

def answers_count(self, event):
    result = str(int(self.answers_count_num.GetLabel()) + 1)
    self.answers_count_num.SetLabel(result)
```

Body:
I'm making a game with wxpython and I want to calculate the result every time button is clicked, so I created first the result on the screen, with StaticText, and then when any button is clicked, I want to add (+1) to the result.

But my problem is that I can't use integers as a label in StaticText, and then I can't also use SetLabel to set new result.

Example:

# Error
self.answers_count_num = wx.StaticText(self.panel, pos=(645, 50), label=0)

def answers_count(self, event):
     result = int(self.answers_count_num.GetLabel()) + 1
     self.answers_count_num.SetLabel(result)

Is there a way to use integers in a StaticText ?


问:
Class 'Illuminate\Session\CommandsServiceProvider' not found in laravel 6.1
```<code>    /**
     * @param  string  $provider
     * @return \Illuminate\Support\ServiceProvider
     */
    public function createProvider($provider)
    {
        return new $provider($this->app);
    }
</code>```

答:
composer update' should fix your issue.</p>

```<code>composer dump-autoload

</code>```

```<code>composer update
</code>```

Body:
composer update' should fix your issue.

composer dump-autoload

composer update


问:
C++ How to make a std::list of arrays?
I have a class that contains a 2D array.

```<code>int arr[3][3];
</code>```

How would I go about storing that matrix in a std::list?

```<code>list<*> explored;

explored.pushback(classname->arr);
</code>```

I thought maybe because I already knew the size of the arrays I would just create a list of pointers with something like the above but that obviously doesn't work. How would I initialize the list? How would I go about accessing the 2D arrays individually?

Edit: I wanted to have a list of multiple 2D arrays. Meaning each index position would hold an array. In order to solve my problem I instead decided to make a class, have the class hold a matrix. Then I would simply get the matrix by doing something like

```<code>Class Node{
    Int matrix[3][3];
}
//Store a node with a matrix inside of it.
list<node> v;
v.pushback(node);

//retrieve the matrix by iterating to that position in the list then
v.matrix;
</code>```

答:
How would I go about storing that matrix in a std::list?

You cannot store raw arrays in a std::list.

From https://en.cppreference.com/w/cpp/container/list,

T must meet the requirements of CopyAssignable and CopyConstructible (until C++11).

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable, but many member functions impose stricter requirements (since C++11, until C++17).

Raw arrays do not meet any of those requirements.

However, you may use:

std::list of std::array.

Create a struct that holds the array and then use std::list of the struct.

Unless you intend to add any behavior to the array, I would recomment using the first option.

Title: C++ How to make a std::list of arrays?

Body:
I have a class that contains a 2D array.

int arr[3][3];

How would I go about storing that matrix in a std::list?

list<*> explored;

explored.pushback(classname->arr);

I thought maybe because I already knew the size of the arrays I would just create a list of pointers with something like the above but that obviously doesn't work. How would I initialize the list? How would I go about accessing the 2D arrays individually?

Edit: I wanted to have a list of multiple 2D arrays. Meaning each index position would hold an array. In order to solve my problem I instead decided to make a class, have the class hold a matrix. Then I would simply get the matrix by doing something like

Class Node{
    Int matrix[3][3];
}
//Store a node with a matrix inside of it.
list<node> v;
v.pushback(node);

//retrieve the matrix by iterating to that position in the list then
v.matrix;


问:
Get maximum value of a field in django
I have a model Foo in my models.py like this:

```<code>class Foo(models.Model):

    transaction_no = models.IntegerField(default=0, blank=True, null=True)
    transaction_date = models.DateField(default=datetime.now)
    quantity = models.IntegerField(default=0, blank=True, null=True)
</code>```

I want to get the max quantity from the table. How can I get that?

答:
Use Django Aggregations:</p>

```<code>from django.db.models import Max

Foo.objects.all().aggregate(Max('quantity'))

# or

Foo.objects.aggregate(Max('quantity'))

# or ignore empty quantities

Foo.objects.filter(quantity__isnull=False).aggregate(Max('quantity'))

# how to get the max value

max_quantity = Foo.objects.aggregate(Max('quantity')).get('quantity__max')
</code>```

Title: Get maximum value of a field in django

Body:
I have a model Foo in my models.py like this:

class Foo(models.Model):

    transaction_no = models.IntegerField(default=0, blank=True, null=True)
    transaction_date = models.DateField(default=datetime.now)
    quantity = models.IntegerField(default=0, blank=True, null=True)

I want to get the max quantity from the table. How can I get that?

Body:
Use Django Aggregations:

from django.db.models import Max

Foo.objects.all().aggregate(Max('quantity'))

# or

Foo.objects.aggregate(Max('quantity'))

# or ignore empty quantities

Foo.objects.filter(quantity__isnull=False).aggregate(Max('quantity'))

# how to get the max value

max_quantity = Foo.objects.aggregate(Max('quantity')).get('quantity__max')


问:
How to get the integer portion of a float column in pandas
Suppose I have a dataframe df as shown below

```<code>    qty
0   1.300
1   1.909
</code>```

Now I want to extract only the integer portion of the qty column and the df should look like

```<code>   qty
0   1
1   1
</code>```

Tried using df['qty'].round(0) but didn't get the desired result as it rounds of the number to the nearest integer.

Java has a function intValue() which does the desired operation. Is there a similar function in pandas ?

答:
Convert values to integers by Series.astype:

```<code>df['qty'] = df['qty'].astype(int)
print (df)
   qty
0    1
1    1
</code>```

If not working above is possible use numpy.modf for extract values before .:

```<code>a, b = np.modf(df['qty'])
df['qty'] = b.astype(int)
print (df)
   qty
0    1
1    1
</code>```

Or by split before ., but it should be slow if large DataFrame:

```<code>df['qty'] = b.astype(str).str.strip('.').str[0].astype(int)
</code>```

Or use numpy.floor:

```<code>df['qty'] = np.floor(df['qty']).astype(int)
</code>```

Body:
Suppose I have a dataframe df as shown below

    qty
0   1.300
1   1.909

Now I want to extract only the integer portion of the qty column and the df should look like

   qty
0   1
1   1

Tried using df['qty'].round(0) but didn't get the desired result as it rounds of the number to the nearest integer.

Java has a function intValue() which does the desired operation. Is there a similar function in pandas ?

Body:
Convert values to integers by Series.astype:

df['qty'] = df['qty'].astype(int)
print (df)
   qty
0    1
1    1

If not working above is possible use numpy.modf for extract values before .:

a, b = np.modf(df['qty'])
df['qty'] = b.astype(int)
print (df)
   qty
0    1
1    1

Or by split before ., but it should be slow if large DataFrame:

df['qty'] = b.astype(str).str.strip('.').str[0].astype(int)

Or use numpy.floor:

df['qty'] = np.floor(df['qty']).astype(int)


答:
you need a condition to break out of your while loop.

so like,

```<code>main()
{
   char ch = ' ';
   while (ch != 'q')
   {

      printf("Enter a character: \n");
      ch = getche();
      printf("\nThe code for %c is %d.\n", ch, ch);
   }
}
</code>```

would break out if the entered char was 'q', or if you insist on while(1), you could use the "break" keyword:

```<code>main()
{

   while (1)
   {
      char ch;
      printf("Enter a character: \n");
      ch = getche();
      printf("\nThe code for %c is %d.\n", ch, ch);

      if (ch == 'q')
         break;

   }
}
</code>```

Title: How can I terminate an infinite loop in Turbo C?

Body:
I get stuck in an infinite loop. How can I terminate this loop?  I tried to use/press Cntrlc but nothing happens.  I don't know how to stop it.

main()
{
     while (1)
     {
          char ch;
          printf("Enter a character: \n");
          ch = getche();
          printf("\nThe code for %c is %d.\n", ch, ch);
     }
}

Body:
you need a condition to break out of your while loop.

so like,

main()
{
   char ch = ' ';
   while (ch != 'q')
   {

      printf("Enter a character: \n");
      ch = getche();
      printf("\nThe code for %c is %d.\n", ch, ch);
   }
}

would break out if the entered char was 'q', or if you insist on while(1), you could use the "break" keyword:

main()
{

   while (1)
   {
      char ch;
      printf("Enter a character: \n");
      ch = getche();
      printf("\nThe code for %c is %d.\n", ch, ch);

      if (ch == 'q')
         break;

   }
}


问:
Android EditText not visible and does not show keyboard
Using the following layouts and views below, I cannot get the EditText et_messageText box to show up in my display properly. If I run this in the emulator, I am able to click in the area and get a "null" selection cursor, so I know the EditText is there, but the keyboard never shows, and I am not able to get input to work. What am I doing wrong?

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewModel"
            type="com.example.project.model.MyViewModel" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.project.MainActivity">

        <com.example.project.view.ChannelHeaderView
            android:id="@+id/channelHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true" />

        <com.example.project.view.MessageInputView
            android:id="@+id/message_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" />
    </RelativeLayout>

</layout>
</code>```

message_input.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable
            name="viewModel"
            type="com.example.project.model.MyViewMOdel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/iv_send"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="13dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:srcCompat="@drawable/stream_ic_send" />

        <EditText
            android:id="@+id/et_messageText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="112dp"
            android:ems="10"
            android:inputType="text"
            android:text="@={viewModel.inputText}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/iv_send"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="1.0" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

MessageInputView.java

```<code>public class MessageInputView extends RelativeLayout {

    private MessageInputBinding binding;
    private MyViewModel viewModel;
    public MessageInputView(Context context) {
        super(context);
        binding = initBinding(context);
    }
    public MessageInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        binding = initBinding(context);
        // Focus Listening
        binding.etMessageText.setOnFocusChangeListener((v, hasFocus) -> {

            if (hasFocus) {
                binding.etMessageText.setTextIsSelectable(true);
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(v,InputMethodManager.SHOW_FORCED);
            }
        });
    }

    private MessageInputBinding initBinding(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        binding = MessageInputBinding.inflate(inflater, this, true);
        binding.etMessageText.clearFocus();
        return binding;
    }

    public void setViewModel(MyViewMOdel model, LifecycleOwner lifecycleOwner) {
        this.viewModel = model;
        binding.setLifecycleOwner(lifecycleOwner);
        binding.setViewModel(viewModel);
    }
}
</code>```

and finally in the onCreate() of
MainActivity.java

```<code>binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setLifecycleOwner(this);

viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
viewModel.setPreferences(this);
binding.setViewModel(viewModel);
binding.channelHeader.setViewModel(viewModel, this);
binding.messageInput.setViewModel(viewModel, this);
</code>```

答:
Why are you extending your MessageInputView class with RelativeLayout?
I guess that your MessageInputView class is a Fragment so extend it with Fragment and use the default LayoutInflater inflater and ViewGroup container.

Hence your:

```<code>private MessageInputBinding initBinding(Context context) {
    LayoutInflater inflater = LayoutInflater.from(context);
    binding = MessageInputBinding.inflate(inflater, this, true);
    binding.etMessageText.clearFocus();
    return binding;
}
</code>```

Should be like this:

```<code>private MessageInputBinding initBinding(LayoutInflater inflater, ViewGroup container) {
    binding = DataBindingUtil.inflate(inflater, R.layout.message_input, container, false);
    binding.etMessageText.clearFocus();
    return binding;
}
</code>```

Body:
Using the following layouts and views below, I cannot get the EditText et_messageText box to show up in my display properly. If I run this in the emulator, I am able to click in the area and get a "null" selection cursor, so I know the EditText is there, but the keyboard never shows, and I am not able to get input to work. What am I doing wrong?

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewModel"
            type="com.example.project.model.MyViewModel" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.project.MainActivity">

        <com.example.project.view.ChannelHeaderView
            android:id="@+id/channelHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true" />

        <com.example.project.view.MessageInputView
            android:id="@+id/message_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" />
    </RelativeLayout>

</layout>

message_input.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable
            name="viewModel"
            type="com.example.project.model.MyViewMOdel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/iv_send"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="13dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:srcCompat="@drawable/stream_ic_send" />

        <EditText
            android:id="@+id/et_messageText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="112dp"
            android:ems="10"
            android:inputType="text"
            android:text="@={viewModel.inputText}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/iv_send"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="1.0" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

MessageInputView.java

public class MessageInputView extends RelativeLayout {

    private MessageInputBinding binding;
    private MyViewModel viewModel;
    public MessageInputView(Context context) {
        super(context);
        binding = initBinding(context);
    }
    public MessageInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        binding = initBinding(context);
        // Focus Listening
        binding.etMessageText.setOnFocusChangeListener((v, hasFocus) -> {

            if (hasFocus) {
                binding.etMessageText.setTextIsSelectable(true);
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(v,InputMethodManager.SHOW_FORCED);
            }
        });
    }

    private MessageInputBinding initBinding(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        binding = MessageInputBinding.inflate(inflater, this, true);
        binding.etMessageText.clearFocus();
        return binding;
    }

    public void setViewModel(MyViewMOdel model, LifecycleOwner lifecycleOwner) {
        this.viewModel = model;
        binding.setLifecycleOwner(lifecycleOwner);
        binding.setViewModel(viewModel);
    }
}

and finally in the onCreate() of
MainActivity.java

binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setLifecycleOwner(this);

viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
viewModel.setPreferences(this);
binding.setViewModel(viewModel);
binding.channelHeader.setViewModel(viewModel, this);
binding.messageInput.setViewModel(viewModel, this);

Body:
Why are you extending your MessageInputView class with RelativeLayout?
I guess that your MessageInputView class is a Fragment so extend it with Fragment and use the default LayoutInflater inflater and ViewGroup container.

Hence your:

private MessageInputBinding initBinding(Context context) {
    LayoutInflater inflater = LayoutInflater.from(context);
    binding = MessageInputBinding.inflate(inflater, this, true);
    binding.etMessageText.clearFocus();
    return binding;
}

Should be like this:

private MessageInputBinding initBinding(LayoutInflater inflater, ViewGroup container) {
    binding = DataBindingUtil.inflate(inflater, R.layout.message_input, container, false);
    binding.etMessageText.clearFocus();
    return binding;
}


问:
Create database link to connect another PC in SQL Server?
On Oracle/SQLDeveloper I use

```<code>CONNECT TO username IDENTIFIED BY p123
</code>```

for distributing project but in SQL Server I can't do this.

I mean one PC for example PC1 is a global table on this pc,  and I want others PC to be able to access this PC1 such as fragment and distribute, I try it in SQL developer successfully but I can't this in SQL Server.

答:
On the remote machine, make sure the ports are opened in the Firewall config and TCP is enabled:
Microsoft SQL Server ports

Reference: linked server

USE [master]
GO
EXEC master.dbo.sp_addlinkedserver
    @server = N'SRVR002\ACCTG',
    @srvproduct=N'SQL Server' ;
GO
```

<p>Execute the following code to configure the linked server to use the domain credentials of the login that is using the linked server.</p>

<pre class="lang-sql prettyprint-override"><code>EXEC master.dbo.sp_addlinkedsrvlogin
    @rmtsrvname = N'SRVR002\ACCTG',
    @locallogin = NULL ,
    @useself = N'True' ;
GO
</code>```

Add a password login:
Reference: sp_addlinkedsrvlogin

EXEC sp_addlinkedsrvlogin
    @rmtsrvname = 'SRVR002\ACCTG',
    @useself = 'false',
    --@locallogin = 'MACHINENAME\windowsLogin' -- Restrict the connection to a local login
    @rmtuser = 'User',
    @rmtpassword = 'Password'
```

<p>Accessing the linked server:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT name FROM [SRVR002\ACCTG].master.sys.databases ;
GO
</code>```

You can also setup remote server links via the MSSQL Management Studio GUI.

Here's a more detailed reference with images on how to do it via MSSQL Management Studio
Querying remote data sources in sql server

To execute remote queries you will have to set rpc out to true.

You can also create linked server connections on the fly via OPENDATASOURCE, but this requires you to set this config:

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
```

Body:
On Oracle/SQLDeveloper I use

CONNECT TO username IDENTIFIED BY p123

for distributing project but in SQL Server I can't do this.

I mean one PC for example PC1 is a global table on this pc,  and I want others PC to be able to access this PC1 such as fragment and distribute, I try it in SQL developer successfully but I can't this in SQL Server.

Body:
On the remote machine, make sure the ports are opened in the Firewall config and TCP is enabled:
Microsoft SQL Server ports

Reference: linked server

USE [master]
GO
EXEC master.dbo.sp_addlinkedserver
    @server = N'SRVR002\ACCTG',
    @srvproduct=N'SQL Server' ;
GO

Execute the following code to configure the linked server to use the domain credentials of the login that is using the linked server.

EXEC master.dbo.sp_addlinkedsrvlogin
    @rmtsrvname = N'SRVR002\ACCTG',
    @locallogin = NULL ,
    @useself = N'True' ;
GO

Add a password login:
Reference: sp_addlinkedsrvlogin

EXEC sp_addlinkedsrvlogin
    @rmtsrvname = 'SRVR002\ACCTG',
    @useself = 'false',
    --@locallogin = 'MACHINENAME\windowsLogin' -- Restrict the connection to a local login
    @rmtuser = 'User',
    @rmtpassword = 'Password'

Accessing the linked server:

SELECT name FROM [SRVR002\ACCTG].master.sys.databases ;
GO

You can also setup remote server links via the MSSQL Management Studio GUI.

Here's a more detailed reference with images on how to do it via MSSQL Management Studio
Querying remote data sources in sql server

To execute remote queries you will have to set rpc out to true.

You can also create linked server connections on the fly via OPENDATASOURCE, but this requires you to set this config:

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO


问:
How does the “scala.sys.process” from Scala 2.9 work?
I just had a look at the new scala.sys and scala.sys.process packages to see if there is something helpful here. However, I am at a complete loss.

Has anybody got an example on how to actually start a process?

And, which is most interesting for me: Can you detach processes?

A detached process will continue to run when the parent process ends and is one of the weak spots of Ant.

UPDATE:

There seem to be some confusion what detach is. Have a real live example from my current project. Once with z-Shell and once with TakeCommand:

Z-Shell:

```<code>if ! ztcp localhost 5554; then
    echo "[ZSH] Start emulator"
    emulator                        \
    -avd    Nexus-One               \
    -no-boot-anim                   \
    1>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.out   \
    2>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.err   &
    disown
else
    ztcp -c "${REPLY}"
fi;
</code>```

Take-Command:

```<code>IFF %@Connect[localhost 5554] lt 0 THEN
   ECHO [TCC] Start emulator
   DETACH emulator -avd Nexus-One -no-boot-anim
ENDIFF
</code>```

In both cases it is fire and forget, the emulator is started and will continue to run even after the script has ended. Of course having to write the scripts twice is a waste. So I look into Scala now for unified process handling without cygwin or xml syntax.

答: Documenting process a little better was second on my list for probably two months.  You can infer my list from the fact that I never got to it.  Unlike most things I don't do, this is something I said I'd do, so I greatly regret that it remains as undocumented as it was when it arrived.  Sword, ready yourself! I fall upon thee!</p>

Body:
I just had a look at the new scala.sys and scala.sys.process packages to see if there is something helpful here. However, I am at a complete loss.

Has anybody got an example on how to actually start a process?

And, which is most interesting for me: Can you detach processes?

A detached process will continue to run when the parent process ends and is one of the weak spots of Ant.

UPDATE:

There seem to be some confusion what detach is. Have a real live example from my current project. Once with z-Shell and once with TakeCommand:

Z-Shell:

if ! ztcp localhost 5554; then
    echo "[ZSH] Start emulator"
    emulator                        \
    -avd    Nexus-One               \
    -no-boot-anim                   \
    1>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.out   \
    2>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.err   &
    disown
else
    ztcp -c "${REPLY}"
fi;

Take-Command:

IFF %@Connect[localhost 5554] lt 0 THEN
   ECHO [TCC] Start emulator
   DETACH emulator -avd Nexus-One -no-boot-anim
ENDIFF

In both cases it is fire and forget, the emulator is started and will continue to run even after the script has ended. Of course having to write the scripts twice is a waste. So I look into Scala now for unified process handling without cygwin or xml syntax.


问:
How to find most frequent user agent in nginx access.log
In order to counter a botnet attack, I am trying to analyze a nginx access.log file to find which user agents are the most frequent, so that I can find the culprits and deny them. How can I do that? </p>

答:
To get user agent</p>

```<code>sudo awk -F'"' '/GET/ {print $6}' /var/log/nginx-access.log | cut -d' ' -f1 | sort | uniq -c | sort -rn

awk(1) - selecting full User-Agent string of GET requests
cut(1) - using first word from it
sort(1) - sorting
uniq(1) - count
sort(1) - sorting by count, reversed
</code>```

Body:
To get user agent

sudo awk -F'"' '/GET/ {print $6}' /var/log/nginx-access.log | cut -d' ' -f1 | sort | uniq -c | sort -rn

awk(1) - selecting full User-Agent string of GET requests
cut(1) - using first word from it
sort(1) - sorting
uniq(1) - count
sort(1) - sorting by count, reversed


问:
Predicate condition to RemoveAll items off a list based on a condition not working
I have two List as defined below

```<code>IEnumerable<Type01> newItems

List<Type02> oldItems
</code>```

I simply want to remove the items in the new list that are same as the items in the old list

Even though no exception/errors are thrown , the required objective is not fulfilled here

any idea why that might be ?

```<code>foreach (var item inoldItems )
{
    newItems.ToList().RemoveAll(x => x.Name == item.Name);
}
</code>```

答:
Well, ToList() creates a new list from which the items are removed

```<code> newItems.ToList().RemoveAll(x => x.Name == item.Name);
</code>```

since you don't assign this list back but throw it away, nothing happends. If you want to remove all items from newItems if their names are in oldItems you can just filter them out with a help of Where:

```<code> newItems = newItems
   .Where(item => !oldItems.Any(old => old.Name == item.Name))
   .ToList(); // If you want to have a list
</code>```

Body:
I have two List as defined below

IEnumerable<Type01> newItems

List<Type02> oldItems

I simply want to remove the items in the new list that are same as the items in the old list

Even though no exception/errors are thrown , the required objective is not fulfilled here

any idea why that might be ?

foreach (var item inoldItems )
{
    newItems.ToList().RemoveAll(x => x.Name == item.Name);
}

Body:
Well, ToList() creates a new list from which the items are removed

 newItems.ToList().RemoveAll(x => x.Name == item.Name);

since you don't assign this list back but throw it away, nothing happends. If you want to remove all items from newItems if their names are in oldItems you can just filter them out with a help of Where:

 newItems = newItems
   .Where(item => !oldItems.Any(old => old.Name == item.Name))
   .ToList(); // If you want to have a list


问:
Python3: Counting occurrence of characters in a nested dict
I'm currently working on a small piece of code and I seem to have run into a roadblock. I was wondering if it's possible to find the most common occurrence of a character that follows a specific group of characters?

For example, say I have the following sentence:

"fishies are super neat, a fish is a good pet. also, fishing is for dads."

How would could I determine, for example, the most common character that occurs after the fragment "fish"?

In this specific example, doing it by hand, I get something like this:

{"i": 2, " ": 1}

Currently, I have this chunk of code written to grab the "fish" portion of the word:

```<code>b = Class(n, 'file.txt')
ngrams = [b.file[i:i+n] for i in range(len(b.file)-1)]
</code>```

this will break up all of the text into chunks of 4 like so: ['fish', 'ishi', 'shie', 'hies', 'ies ', 'es a'.....]

My goal is to combine these two thoughts so that I can print something that looks like the following:

{'fish' : {'i':2, ' ':1} ..... }

I also currently have a defaultdict defined in __init__ like so: self.counts=defaultdict(lambda: defaultdict(int))

This is the closest I can get to achieving my desired solution, although I am unsure how to grab the individual characters that follow and how to count those characters:

b.counts = {i : { j : 5 for j in ngrams } for i in ngrams }

5 is merely a placeholder so I could see what printed. j in ngrams was also a placeholder to see what printed. Any input or ideas from anyone would be greatly appreciated!

答:
```<code>sentence = "fishies are super neat, a fish is a good pet. also, fishing is for dads."
s_list = sentence.split("fish")
stat = {}
for i in s_list[1:]:
    if i[0] in stat.keys():
        stat[i[0]] += 1
    else:
        stat[i[0]] = 1

print(stat)
</code>```

Body:
I'm currently working on a small piece of code and I seem to have run into a roadblock. I was wondering if it's possible to find the most common occurrence of a character that follows a specific group of characters?

For example, say I have the following sentence:

"fishies are super neat, a fish is a good pet. also, fishing is for dads."

How would could I determine, for example, the most common character that occurs after the fragment "fish"?

In this specific example, doing it by hand, I get something like this:

{"i": 2, " ": 1}

Currently, I have this chunk of code written to grab the "fish" portion of the word:

b = Class(n, 'file.txt')
ngrams = [b.file[i:i+n] for i in range(len(b.file)-1)]

this will break up all of the text into chunks of 4 like so: ['fish', 'ishi', 'shie', 'hies', 'ies ', 'es a'.....]

My goal is to combine these two thoughts so that I can print something that looks like the following:

{'fish' : {'i':2, ' ':1} ..... }

I also currently have a defaultdict defined in __init__ like so: self.counts=defaultdict(lambda: defaultdict(int))

This is the closest I can get to achieving my desired solution, although I am unsure how to grab the individual characters that follow and how to count those characters:

b.counts = {i : { j : 5 for j in ngrams } for i in ngrams }

5 is merely a placeholder so I could see what printed. j in ngrams was also a placeholder to see what printed. Any input or ideas from anyone would be greatly appreciated!


问:
JSON.parse() string that contains new line in a value
For reasons that can not be changed I have a string with a shitty piece of JSON with new lines like this:

```<code>{
    "description" : "- some text;
              - some more text;"
}
</code>```

I want to JSON.parse() it so it becomes usable. Of course, it fails when hitting the new line:

Unexpected token in JSON at position 156

How can I make this work?

答:
You need to remove line break,</p>

```<code>var x = `{
   "description" : "- some text
      - some more text"
      }`
x = x.replace( /[\r\n]+/gm, "" );
JSON.parse(x)
</code>```

Body:
For reasons that can not be changed I have a string with a shitty piece of JSON with new lines like this:

{
    "description" : "- some text;
              - some more text;"
}

I want to JSON.parse() it so it becomes usable. Of course, it fails when hitting the new line:

Unexpected token in JSON at position 156

How can I make this work?

Body:
You need to remove line break,

var x = `{
   "description" : "- some text
      - some more text"
      }`
x = x.replace( /[\r\n]+/gm, "" );
JSON.parse(x)


问:
print the diagonal pettern in PHP
hy i want to print diagonal pattern ini PHP, the output like bellow

this is my code

```<code>  for ($i = 0; $i < 7; $i++)
{

    // Loop denoting columns
    for ($j = 0; $j < 7; $j++)
    {

        if ($i == 0 || $j == 0 || $i == $j ||
            $i == 7 - 1 || $j == 7 - 1 ||
            $i + $j == 7 - 1)
            echo "# ";
        else
            echo " ";
    }
      echo "<br>";
}
</code>```

but i get output like this

the output is look different,, where my code is wrong ??

thanks

答:
You enter # with space (2 characters) VS space alone (1 char). You have two alternatives to change code:

```<code>    ...
        echo "# ";
    else
        echo " ";
    ...
</code>```

either to (2 characters):

```<code>    ...
        echo "# ";
    else
        echo "  ";
    ...
</code>```

or to (1 character):

```<code>    ...
        echo "#";
    else
        echo " ";
    ...
</code>```

Title: print the diagonal pettern in PHP

Body:
hy i want to print diagonal pattern ini PHP, the output like bellow

this is my code

  for ($i = 0; $i < 7; $i++)
{

    // Loop denoting columns
    for ($j = 0; $j < 7; $j++)
    {

        if ($i == 0 || $j == 0 || $i == $j ||
            $i == 7 - 1 || $j == 7 - 1 ||
            $i + $j == 7 - 1)
            echo "# ";
        else
            echo " ";
    }
      echo "
";
}

but i get output like this

the output is look different,, where my code is wrong ??

thanks

Body:
You enter # with space (2 characters) VS space alone (1 char). You have two alternatives to change code:

    ...
        echo "#&nbsp;";
    else
        echo "&nbsp;";
    ...

either to (2 characters):

    ...
        echo "#&nbsp;";
    else
        echo "&nbsp;&nbsp;";
    ...

or to (1 character):

    ...
        echo "#";
    else
        echo "&nbsp;";
    ...


问:
Round df values but exclude given row if named "x"
Is there an easy way to round df values but exclude a given row based on name?

This is how I am rounding the values in my df:

```<code>#multiply value by 100 then round
df = df.applymap(lambda x: int(round(x*100)))
</code>```

However, I want to exclude "Mean" from the rounding. The position/index of "Mean" is unknown, it is not fixed. Number of rows in the df are also unknown.

Below, I have shown how the df looks like "before", how it looks like "after" I apply my code and what I would like the df to look like "desired".

答:
You can do it this way:

```<code>df.loc[df.index != 'Mean'] = df.applymap(lambda x: int(round(x*100)))
</code>```

Would return

```<code>       male     female
honda   48.0    24.0
ford    78.0    48.0
nissan  69.0    12.0
jag     47.0    36.0
Mean    102.0   204.0
</code>```

Body:
Is there an easy way to round df values but exclude a given row based on name?

This is how I am rounding the values in my df:

#multiply value by 100 then round
df = df.applymap(lambda x: int(round(x*100)))

However, I want to exclude "Mean" from the rounding. The position/index of "Mean" is unknown, it is not fixed. Number of rows in the df are also unknown.

Below, I have shown how the df looks like "before", how it looks like "after" I apply my code and what I would like the df to look like "desired".

Body:
You can do it this way:

df.loc[df.index != 'Mean'] = df.applymap(lambda x: int(round(x*100)))

Would return

       male     female
honda   48.0    24.0
ford    78.0    48.0
nissan  69.0    12.0
jag     47.0    36.0
Mean    102.0   204.0


答:
```<code>using namespace std;

list<list<int>> matrix;
for (int row = 0; row < 3; row++)
{
     std::list<int> rowList;
     for (int col = 0; col < 3; col++)
     {
          rowList.push_back(arr[row][col]);
     }
     matrix.push_back(rowList);
}
</code>```

Since elements of a matrix are more traditionally accessed directly (like an array), std::vector actually makes more sense.  Similar to above, except replace list with vector.

```<code>vector<vector<int>> matrix;
matrix.resize(3);
for (int row = 0; row < 3; row++)
{
     auto& row = matrix[row];
     row.resize(3);
     for (int col = 0; col < 3; col++)
     {
         row[col] = arr[row][col];
     }
}
</code>```

Title: C++ How to make a std::list of arrays?

Body:
I have a class that contains a 2D array.

int arr[3][3];

How would I go about storing that matrix in a std::list?

list<*> explored;

explored.pushback(classname->arr);

I thought maybe because I already knew the size of the arrays I would just create a list of pointers with something like the above but that obviously doesn't work. How would I initialize the list? How would I go about accessing the 2D arrays individually?

Edit: I wanted to have a list of multiple 2D arrays. Meaning each index position would hold an array. In order to solve my problem I instead decided to make a class, have the class hold a matrix. Then I would simply get the matrix by doing something like

Class Node{
    Int matrix[3][3];
}
//Store a node with a matrix inside of it.
list<node> v;
v.pushback(node);

//retrieve the matrix by iterating to that position in the list then
v.matrix;

Body:
using namespace std;

list<list<int>> matrix;
for (int row = 0; row < 3; row++)
{
     std::list<int> rowList;
     for (int col = 0; col < 3; col++)
     {
          rowList.push_back(arr[row][col]);
     }
     matrix.push_back(rowList);
}

Since elements of a matrix are more traditionally accessed directly (like an array), std::vector actually makes more sense.  Similar to above, except replace list with vector.

vector<vector<int>> matrix;
matrix.resize(3);
for (int row = 0; row < 3; row++)
{
     auto& row = matrix[row];
     row.resize(3);
     for (int col = 0; col < 3; col++)
     {
         row[col] = arr[row][col];
     }
}


问:
How to set different applicationId for each flavor combination using flavorDimensions?
I have and old android app that I am trying to migrate to the android gradle build system. The app is currently built in a multi project setup and published as four different apps (two different data sets included and free/paid versions for both datasets). I have managed to get away from the multi project setup by using flavorDimensions (previously called flavorGroups), but I can not figure out how to set a different applicationId for each flavor combination.

Since the app versions are already published, I need to keep the same applicationid as they currently have. Because of how my original package naming was done, I can not simply use flavor-buildtype combination with "packageNameSuffix" (which would have been a great option if it was an unpublished app).

https://stackoverflow.com/a/20956353/4177090 is answering how to use different source folders for flavor combinations, but not how (if even possible) to set specific configuration for each combination in the build file.

Gradle build file snippet:

```<code>flavorDimensions "price", "dataset"

productFlavors {
    free { flavorDimension "price" }
    paid { flavorDimension "price" }
    dataset1 { flavorDimension "dataset" }
    dataset2 { flavorDimension "dataset" }
}
</code>```

I would like to have something like the following in my gradle build file (notice how unlogic my naming is, which is why I cannot use packageNameSuffix):

```<code>freeDataset1 { applicationId "com.beansys.freeappdataset1" }
freeDataset2 { applicationId "com.beansys.freedataset2" }
paidDataset1 { applicationId "com.beansys.dataset1paid" }
paidDataset2 { applicationId "com.beansys.mypaiddataset2" }
</code>```

答: I had problems converting the answers given to the gradle kotlin dsl. I found a solution and shared it here: https://stackoverflow.com/a/60103604/2793394</p>

Body:
I have and old android app that I am trying to migrate to the android gradle build system. The app is currently built in a multi project setup and published as four different apps (two different data sets included and free/paid versions for both datasets). I have managed to get away from the multi project setup by using flavorDimensions (previously called flavorGroups), but I can not figure out how to set a different applicationId for each flavor combination.

Since the app versions are already published, I need to keep the same applicationid as they currently have. Because of how my original package naming was done, I can not simply use flavor-buildtype combination with "packageNameSuffix" (which would have been a great option if it was an unpublished app).

https://stackoverflow.com/a/20956353/4177090 is answering how to use different source folders for flavor combinations, but not how (if even possible) to set specific configuration for each combination in the build file.

Gradle build file snippet:

flavorDimensions "price", "dataset"

productFlavors {
    free { flavorDimension "price" }
    paid { flavorDimension "price" }
    dataset1 { flavorDimension "dataset" }
    dataset2 { flavorDimension "dataset" }
}

I would like to have something like the following in my gradle build file (notice how unlogic my naming is, which is why I cannot use packageNameSuffix):

freeDataset1 { applicationId "com.beansys.freeappdataset1" }
freeDataset2 { applicationId "com.beansys.freedataset2" }
paidDataset1 { applicationId "com.beansys.dataset1paid" }
paidDataset2 { applicationId "com.beansys.mypaiddataset2" }


问:
Winforms Checkbox Focus Problem if no Text is Applied on Checkbox
I have a multiple checkboxes on a Winforms without having the Text Property of all checkboxes,
so the problem is that when i hover a mouse on the checkbox it highlighted but when i go to the checkbox using tab key it never get highlighted..

If anyone have the similar issue and already solved it Please help..

答:
I added an event handler for the CheckBox.Paint event and added the following:

```<code>private void checkBox1_Paint(object sender, PaintEventArgs e)
{
    CheckBox checkBox = sender as CheckBox;

    if (checkBox.Focused)
    {
        // e.ClipRectangle is affected by checkBox.Padding. Be careful when changing the Padding.
        ControlPaint.DrawFocusRectangle(e.Graphics, e.ClipRectangle, checkBox.ForeColor, checkBox.BackColor);
    }
}
</code>```

I also adjusted the CheckBox.Padding to be 2, 2, 0, 1 in order to get a border that was 1 pixel from the edge of the CheckBox.

ContentLicense: CC BY-SA 2.5

Body:
I added an event handler for the CheckBox.Paint event and added the following:

private void checkBox1_Paint(object sender, PaintEventArgs e)
{
    CheckBox checkBox = sender as CheckBox;

    if (checkBox.Focused)
    {
        // e.ClipRectangle is affected by checkBox.Padding. Be careful when changing the Padding.
        ControlPaint.DrawFocusRectangle(e.Graphics, e.ClipRectangle, checkBox.ForeColor, checkBox.BackColor);
    }
}

I also adjusted the CheckBox.Padding to be 2, 2, 0, 1 in order to get a border that was 1 pixel from the edge of the CheckBox.


问:
Android Studio : "Could not get unknown property 'VERSION_NAME' for project of type org.gradle.api.Project"
I am a newbie with Android Studio. I am trying to use this project library : https://github.com/2dxgujun/AndroidTagGroup in my project.

So what I did is to import it as a module in my project ; with the name "androidtaggroup"

Now, I have got the following error at compilation:

```<code>"Could not get unknown property 'VERSION_NAME' for project ':androidtaggroup' of type org.gradle.api.Project."
</code>```

Here is where the problem occurs in the Gradle file:

```<code> defaultConfig {
        applicationId 'me.gujun.android.taggroup.demo'
        minSdkVersion 8
        targetSdkVersion 21
        versionName project.VERSION_NAME // ERROR HERE !!!!
        versionCode Integer.parseInt(project.VERSION_CODE)
    }
</code>```

Anybody can tell me how to fix this problem ?

Thanks !!!

答: I had a similar problem. 'VERSION_NAME' was not defined in the ext{} from build.gradle(Project: 'PROJECT_NAME')</p>

Body:
I am a newbie with Android Studio. I am trying to use this project library : https://github.com/2dxgujun/AndroidTagGroup in my project.

So what I did is to import it as a module in my project ; with the name "androidtaggroup"

Now, I have got the following error at compilation:

"Could not get unknown property 'VERSION_NAME' for project ':androidtaggroup' of type org.gradle.api.Project."

Here is where the problem occurs in the Gradle file:

 defaultConfig {
        applicationId 'me.gujun.android.taggroup.demo'
        minSdkVersion 8
        targetSdkVersion 21
        versionName project.VERSION_NAME // ERROR HERE !!!!
        versionCode Integer.parseInt(project.VERSION_CODE)
    }

Anybody can tell me how to fix this problem ?

Thanks !!!


问:
How to join intermediate table in ManyToMany mappings in the hibernate
Is there a way I can join intermediate table in the ManyToMany table. You can consider the example given at https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-many-to-many-using-annotations-1.html

As an example in the above Student to Course many to many relation, we can have tables STUDENT, COURSE and STUDENT_COURSE.

My question is to check if there is any way we can provide this in hibernate in java so that Student class has mapping for STUDENT_COURSE intermediate table instead of COURSE table?

I want to modify below class to get the above output:-

@Entity
@Table(name = "STUDENT")
public class Student {

    private long studentId;
    private String studentName;
    private Set<Course> courses = new HashSet<Course>(0);

    public Student() {
    }

    public Student(String studentName) {
        this.studentName = studentName;
    }

    public Student(String studentName, Set<Course> courses) {
        this.studentName = studentName;
        this.courses = courses;
    }

    @Id
    @GeneratedValue
    @Column(name = "STUDENT_ID")
    public long getStudentId() {
        return this.studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    @Column(name = "STUDENT_NAME", nullable = false, length = 100)
    public String getStudentName() {
        return this.studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "STUDENT_COURSE",
               joinColumns = { @JoinColumn(name = "STUDENT_ID") },
               inverseJoinColumns = { @JoinColumn(name = "COURSE_ID") })
    public Set<Course> getCourses() {
        return this.courses;
    }

    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }
}
```

答:
Short answer:

you should divide your many to many association to two many to one association and use @Embedded annotation to define compound key for your intermediate entity
look at below link for detail

https://vladmihalcea.com/the-best-way-to-map-a-many-to-many-association-with-extra-columns-when-using-jpa-and-hibernate/

Long answer:

Actually when you use @ManyToMany annotation to establish many to many association in hibernate it creates another table to establish ManyToMany association behind the scene  this table is defined with @JoinTable annotation in your code, query to that table is completely managed by hibernate to achieve many to many association and you don't have  entity which  is mapped to that table. It is fine unless you need extra column in your intermediate table(here STUDENT_COURSE) or you want to execute some specific query to that table in a way that you behave with your other entity and you want to access the Id of your Course and Student table in CourseStudent table. because when hibernate creates intermediate table behind the scene you don't have entity in your program  that maps to that table and therefore you can't have other column for that table and you can't behave to that table as an entity in your program. if you need extra column you can divide your @ManyToMany association to two @ManyToOne association. Here you should have another entity with name StudentCourse which has two @ManyToOne association one to Student entity and the other one to Course entity. However when you are defining your many to many association this way you should consider data integriry for instance the combination of student_id and course_id in your student_course table is unique and actually it should be a compound key in your student_course table. Fortunately there are some annotations in hibernate and jpa that provide this capability. Writing all the code for this sitiuation in this answer is redundant because there is already a good example in the link below .

https://vladmihalcea.com/the-best-way-to-map-a-many-to-many-association-with-extra-columns-when-using-jpa-and-hibernate/


问:
Failure to get a positive integer
Here is the code that I've written:

number = int(input('Enter a nonnegative integer: '))

product=1
for i in range(number):
    product = product * (i+1)
    print(product)
```

<p>The result is:</p>

<pre class="lang-py prettyprint-override"><code>1
2
6
24...
5040
</code>```

But I only need the resulted nonnegative integer when the input is 7, which is 5040. How do I get that?

答:
You have fix your indentation. Let's make a function named make_product that achieves your goal.

def make_product():

    # take input
    number = input('Enter a nonnegative integer: ')

    # strip whitespace of the input string
    number = number.strip()

    # convert to positive integer
    number = int(number)

    product=1
    for i in range(number):
        product = product * (i+1)

    return product
```

<p>Use the function like this:</p>

<pre class="lang-py prettyprint-override"><code>make_product()
</code>```

If you enter 7 into the prompt, this should show 5040. Moreover, even if there is extra whitespace in your input, the program will be able to handle that.

Title: Failure to get a positive integer

Body:
Here is the code that I've written:

number = int(input('Enter a nonnegative integer: '))

product=1
for i in range(number):
    product = product * (i+1)
    print(product)

The result is:

1
2
6
24...
5040

But I only need the resulted nonnegative integer when the input is 7, which is 5040. How do I get that?

Body:
You have fix your indentation. Let's make a function named make_product that achieves your goal.

def make_product():

    # take input
    number = input('Enter a nonnegative integer: ')

    # strip whitespace of the input string
    number = number.strip()

    # convert to positive integer
    number = int(number)

    product=1
    for i in range(number):
        product = product * (i+1)

    return product

Use the function like this:

make_product()

If you enter 7 into the prompt, this should show 5040. Moreover, even if there is extra whitespace in your input, the program will be able to handle that.


问:
Is SSL set on a per machine or per connection basis
Is it possible to have a FTP server using SSL on a application server that does not use SSL?

How would you setup an ASP.NET 2.0 to consume a SSL certificate?

This certianly sounds possible but is it advisable, is it good practice?

答:
While protecting an application with SSL is always a good idea, it is technically not trivial.

Having a web application protected with SSL requires the webserver to be reachable on a new port (443/https instead of 80/http). This has to be configured "system-wide". Also, there may be only one certificate per IP-address, which is often a problem when hosting multiple domains on the same server.

OwnerDisplayName: Dean

OwnerDisplayName: David Schmitt


问:
Problem between context and thread in drawRect
I'm trying to draw a couple of UIImages in a UIView, and I'm doing it by hand with drawRect:. Given that the images are dynamically downloaded from the web, I create an NSOperation and I perform the image loading code from a second thread, in order to keep UI responsive. So once the images are downloaded, they appear on screen.

But... I get the following errors, for each of the images:

```<code><Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextSetBlendMode: invalid context 0x0
<Error>: CGContextSetAlpha: invalid context 0x0
<Error>: CGContextTranslateCTM: invalid context 0x0
<Error>: CGContextScaleCTM: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0
</code>```

For what I've seen, this means that the context in which I'm trying to make [image drawInRect...] is nil, because I'm not in drawRect: anymore.

Attempted doing

```<code>UIGraphicsPushContext(UIGraphicsGetCurrentContext());
</code>```

before drawing the image but nothing changed. How can I overcome this thing? Multithreading is a must for responsiveness, and the context gets lost in the way.

UPDATE: Here's my code:

```<code>- (void)drawContentView:(CGRect)r
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    ....
    CGContextFillRect(context, r);
    UIApplication* app = [UIApplication sharedApplication];
        app.networkActivityIndicatorVisible = YES;

    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                            initWithTarget:self
                                            selector:@selector(loadPreview)
                                            object:nil];
    [queue addOperation:operation];
    [operation release];
}
</code>```

And then

```<code>-(void)loadPreview
{
    self.preview = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString:self.picStringPreview]]];
    [self.preview drawInRect:CGRectMake(256, 18, 80, 65)];
}
</code>```

I tried adding a UIGraphicsPushContext... in loadPreview, even doing a [self performSelectorOnMainThread...] there, and nothing. And this is a custom cell based on Atebit's model, so my cell's superclass makes:

```<code>- (void)drawRect:(CGRect)r
{
    [(ABTableViewCell *)[self superview] drawContentView:r];
}
</code>```

and the code in drawContentView: gets draw'd in superclass's drawRect:. Any hint?

答:
The most straightforward way to do this is not to mess with drawRect: at all, and instead put your images in UIImageViews. Apple claims that even an empty drawRect: changes something-or-other that makes rendering much slower.

But if you must, you'll have to save the images to ivars in your class (don't forget to retain them), call setNeedsDisplay or setNeedsDisplayInRect: (on the main thread, so you'll need to use performSelector:withObject:onMainThread: if you aren't already) to inform the system that it needs to call your drawRect: again, and then when drawRect: is called again use the saved images to draw.

Body:
I'm trying to draw a couple of UIImages in a UIView, and I'm doing it by hand with drawRect:. Given that the images are dynamically downloaded from the web, I create an NSOperation and I perform the image loading code from a second thread, in order to keep UI responsive. So once the images are downloaded, they appear on screen.

But... I get the following errors, for each of the images:

<Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextSetBlendMode: invalid context 0x0
<Error>: CGContextSetAlpha: invalid context 0x0
<Error>: CGContextTranslateCTM: invalid context 0x0
<Error>: CGContextScaleCTM: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0

For what I've seen, this means that the context in which I'm trying to make [image drawInRect...] is nil, because I'm not in drawRect: anymore.

Attempted doing

UIGraphicsPushContext(UIGraphicsGetCurrentContext());

before drawing the image but nothing changed. How can I overcome this thing? Multithreading is a must for responsiveness, and the context gets lost in the way.

UPDATE: Here's my code:

- (void)drawContentView:(CGRect)r
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    ....
    CGContextFillRect(context, r);
    UIApplication* app = [UIApplication sharedApplication];
        app.networkActivityIndicatorVisible = YES;

    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                            initWithTarget:self
                                            selector:@selector(loadPreview)
                                            object:nil];
    [queue addOperation:operation];
    [operation release];
}

And then

-(void)loadPreview
{
    self.preview = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString:self.picStringPreview]]];
    [self.preview drawInRect:CGRectMake(256, 18, 80, 65)];
}

I tried adding a UIGraphicsPushContext... in loadPreview, even doing a [self performSelectorOnMainThread...] there, and nothing. And this is a custom cell based on Atebit's model, so my cell's superclass makes:

- (void)drawRect:(CGRect)r
{
    [(ABTableViewCell *)[self superview] drawContentView:r];
}

and the code in drawContentView: gets draw'd in superclass's drawRect:. Any hint?


问:
How to Control PostgreSQL Password authentication both Front end and Command line in Windows 10 and Redhat (Linux)?
Recently I'm using PostgreSQL9.2 both in Windows 10 and Redhat (Linux).

But now I'm little concern about PostgreSQL access authentication.

Late me explain...

When i first installed PostgreSQL in my system i used two different password for two log in role postgres (default) and adempiere (created). In Redhat i use to psql -h localhost -U postgres db_name and psql -h localhost -U adempiere db_name command. Sometime this command wants password sometime not.

Recently I have used ALTER USER postgres WITH PASSWORD 'new_password'; and ALTER USER adempiere WITH PASSWORD 'new_password'; command to change. But here is an another problem. After changed my password when i get database access with psql -h localhost -U adempiere db_name command, i can access with both old_passwod and new_password.

Now what can i do for Strong authentication in my Database both Windows 10 and Redhat (linux) ?

Here is part of my pg_hba.conf for reference:

```<code># Put your actual configuration here
# ----------------------------------
#
# If you want to allow non-local connections, you need to add more
# "host" records.  In that case you will also need to make PostgreSQL
# listen on a non-local interface via the listen_addresses
# configuration parameter, or via the -i or -h command line switches.

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
host    all             all             192.168.2.151/32            trust
host    all             all             192.168.2.5/32            trust
host    all             all             192.168.2.6/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                md5
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5

</code>```

答:
To force password authentication for every connection, replace trust with md5 everywhere in pg_hba.conf and reload the server.

It is dangerously negligent to use PostgreSQL 9.2. Use a later version. For one, this will offer the more secure scram-sha-256 hashing method for password authentication.

Body:
Recently I'm using PostgreSQL9.2 both in Windows 10 and Redhat (Linux).

But now I'm little concern about PostgreSQL access authentication.

Late me explain...

When i first installed PostgreSQL in my system i used two different password for two log in role postgres (default) and adempiere (created). In Redhat i use to psql -h localhost -U postgres db_name and psql -h localhost -U adempiere db_name command. Sometime this command wants password sometime not.

Recently I have used ALTER USER postgres WITH PASSWORD 'new_password'; and ALTER USER adempiere WITH PASSWORD 'new_password'; command to change. But here is an another problem. After changed my password when i get database access with psql -h localhost -U adempiere db_name command, i can access with both old_passwod and new_password.

Now what can i do for Strong authentication in my Database both Windows 10 and Redhat (linux) ?

Here is part of my pg_hba.conf for reference:

# Put your actual configuration here
# ----------------------------------
#
# If you want to allow non-local connections, you need to add more
# "host" records.  In that case you will also need to make PostgreSQL
# listen on a non-local interface via the listen_addresses
# configuration parameter, or via the -i or -h command line switches.

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
host    all             all             192.168.2.151/32            trust
host    all             all             192.168.2.5/32            trust
host    all             all             192.168.2.6/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                md5
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5