问:
Common Lisp: non-nil arguments and their names to alist, how?
I am quite new to Common Lisp and programming, and I'm trying to write a certain function that turns all non-nil args into an alist. The only way I can think of so far is:

```<code>(let ((temp nil))
    (if arg1
        (setf temp (acons 'arg1 arg1 nil)))
    (if arg2
        (setf temp (acons 'arg2 arg2 temp)))
    ...
    (if arg20-ish
        (setf temp (acons 'arg20-ish arg20-ish temp)))

    (do-something-with temp))
</code>```

which does not seem very elegant, it would be messy with many arguments and when these need to be changed. I am looking for a smarter way to do this, both for the sake of writing this particular function and for learning how to think in Lisp and/or functional programming.

The tricky part for me is figuring out how to get the names of the arguments or what symbol to use, without hand coding each case. If &rest provided arg names it would be easy to filter out NILs with loop or mapcar, but since it doesn't, I can't see how to "automate" this.

I'm totally interested in other solutions than the one described, if people think this way is unnatural.

Edit: Below is an example of what I am trying to do:

An object is created, with a non-fixed number of data pairs and some tags, e.g.:

```<code>user = "someone"
creation-time = (get-universal-time)
color-of-sky = "blue"
temperature-in-celsius = 32
language = "Common Lisp"
...
tags = '("one" "two" "three")
</code>```

These properties (i.e. key/arg names) could be different each time. The new object will then be added to a collection; I thought the array might work well since I want constant access time and only need a numeric ID.

The collection will hold more and more such custom objects, indefinitely.

I want to be able to quickly access all objects matching any combination of any of the tags used in these objects.

Since the array is supposed to store more and more data over a long period, I don't want to parse every item in it each time I need to search for a tag. Thus I also store the index of each object with a given tag in a hash-table, under the tag name. I have written this function, what I find difficult is figuring out how to collect the data and turn it into an alist or anything that I can easily parse, index, and store.

答:
Here's a sort of solution using macros:

```<code>(defmacro named-args (fun-name alist-sym (&rest syms) &body body)
  `(defun ,fun-name (&key ,@syms)
     (declare (special ,@syms))
     (let ((,alist-sym
            (loop
               for s in ',syms
               collecting (cons s (symbol-value s)))))
       ,@body)))
</code>```

You can then use it with something like

```<code>(named-args f u (a b c)
  (format t "~A~%" u))
</code>```

which expands to

```<code>(DEFUN F (&KEY A B C)
  (DECLARE (SPECIAL A B C))
  (LET ((U
         (LOOP FOR S IN '(A B C)
            COLLECTING (CONS S (SYMBOL-VALUE S)))))
    (FORMAT T "~A~%" U)))
</code>```

Finally, calling will give

```<code>(f :a 3) => ((A . 3) (B) (C))
</code>```

Note that we need the special declaration otherwise symbol-value doesn't work (you need a global binding for symbol-value). I couldn't find a way to get rid of that.

Looking at your question again, it looks like you actually don't want the keyword arguments that didn't get passed. In which case you could parse a &rest argument (although that's a flat list, so you'd need to map along it in twos) or you could modify the macro as follows:

```<code>(defmacro named-args (fun-name alist-sym (&rest syms) &body body)
  `(defun ,fun-name (&key ,@syms)
     (declare (special ,@syms))
     (let ((,alist-sym
            (loop
               for s in ',syms
               when (symbol-value s)
               collecting (cons s (symbol-value s)))))
       ,@body)))
</code>```

and then you get

```<code>(f :a 3) => ((A . 3))
</code>```

Body:
I am quite new to Common Lisp and programming, and I'm trying to write a certain function that turns all non-nil args into an alist. The only way I can think of so far is:

(let ((temp nil))
    (if arg1
        (setf temp (acons 'arg1 arg1 nil)))
    (if arg2
        (setf temp (acons 'arg2 arg2 temp)))
    ...
    (if arg20-ish
        (setf temp (acons 'arg20-ish arg20-ish temp)))

    (do-something-with temp))

which does not seem very elegant, it would be messy with many arguments and when these need to be changed. I am looking for a smarter way to do this, both for the sake of writing this particular function and for learning how to think in Lisp and/or functional programming.

The tricky part for me is figuring out how to get the names of the arguments or what symbol to use, without hand coding each case. If &rest provided arg names it would be easy to filter out NILs with loop or mapcar, but since it doesn't, I can't see how to "automate" this.

I'm totally interested in other solutions than the one described, if people think this way is unnatural.

Edit: Below is an example of what I am trying to do:

An object is created, with a non-fixed number of data pairs and some tags, e.g.:

user = "someone"
creation-time = (get-universal-time)
color-of-sky = "blue"
temperature-in-celsius = 32
language = "Common Lisp"
...
tags = '("one" "two" "three")

These properties (i.e. key/arg names) could be different each time. The new object will then be added to a collection; I thought the array might work well since I want constant access time and only need a numeric ID.

The collection will hold more and more such custom objects, indefinitely.

I want to be able to quickly access all objects matching any combination of any of the tags used in these objects.

Since the array is supposed to store more and more data over a long period, I don't want to parse every item in it each time I need to search for a tag. Thus I also store the index of each object with a given tag in a hash-table, under the tag name. I have written this function, what I find difficult is figuring out how to collect the data and turn it into an alist or anything that I can easily parse, index, and store.

Body:
Here's a sort of solution using macros:

(defmacro named-args (fun-name alist-sym (&rest syms) &body body)
  `(defun ,fun-name (&key ,@syms)
     (declare (special ,@syms))
     (let ((,alist-sym
            (loop
               for s in ',syms
               collecting (cons s (symbol-value s)))))
       ,@body)))

You can then use it with something like

(named-args f u (a b c)
  (format t "~A~%" u))

which expands to

(DEFUN F (&KEY A B C)
  (DECLARE (SPECIAL A B C))
  (LET ((U
         (LOOP FOR S IN '(A B C)
            COLLECTING (CONS S (SYMBOL-VALUE S)))))
    (FORMAT T "~A~%" U)))

Finally, calling will give

(f :a 3) => ((A . 3) (B) (C))

Note that we need the special declaration otherwise symbol-value doesn't work (you need a global binding for symbol-value). I couldn't find a way to get rid of that.

Looking at your question again, it looks like you actually don't want the keyword arguments that didn't get passed. In which case you could parse a &rest argument (although that's a flat list, so you'd need to map along it in twos) or you could modify the macro as follows:

(defmacro named-args (fun-name alist-sym (&rest syms) &body body)
  `(defun ,fun-name (&key ,@syms)
     (declare (special ,@syms))
     (let ((,alist-sym
            (loop
               for s in ',syms
               when (symbol-value s)
               collecting (cons s (symbol-value s)))))
       ,@body)))

and then you get

(f :a 3) => ((A . 3))


来源: stackexchange

问:
Class variable query in python
Framework: Robot, Language: Python-3.7.1 Proficiency: Novice

I have a variable args=[] defined at class level. The values of the variables are being assigned from command prompt using module 'sys'

```<code>import sys

class Runner():
    args = []

    def argument_reader(self):
        self.args = list(sys.argv)

    def login(self):
        return self.args[1], self.args[2]
</code>```

I could print all the values of args as long as execution stays within the module. If I wanted to call the same values from other module, it does not return anything as the values are being cleared out from the memory. Since class variables are static by default in python, why system is not RETAINING the values?

```<code>cmd line>>py Runner.py testing test@123
</code>```

For Example:

```<code>Calling method from same class:-

run = Runner()
run.argument_reader()
print(run.login())

Output>>> testing, testing@123

Calling the same method from another class:-

runn = Runner.Runner()
print(runn.login())

output>> IndexError: list index out of range
</code>```

答:
If you want a singleton-type value, change your code to look like this.

class Runner():
    args = []

    def argument_reader(self):
        Runner.args = list(sys.argv)

    def login(self):
        return Runner.args[1], Runner.args[2]
```

Otherwise, you'll have to call argument_reader() on each instance.

ContentLicense: CC BY-SA 4.0

Title: Class variable query in python

Body:
Framework: Robot, Language: Python-3.7.1 Proficiency: Novice

I have a variable args=[] defined at class level. The values of the variables are being assigned from command prompt using module 'sys'

import sys

class Runner():
    args = []

    def argument_reader(self):
        self.args = list(sys.argv)

    def login(self):
        return self.args[1], self.args[2]

I could print all the values of args as long as execution stays within the module. If I wanted to call the same values from other module, it does not return anything as the values are being cleared out from the memory. Since class variables are static by default in python, why system is not RETAINING the values?

cmd line>>py Runner.py testing test@123

For Example:

Calling method from same class:-

run = Runner()
run.argument_reader()
print(run.login())

Output>>> testing, testing@123

Calling the same method from another class:-

runn = Runner.Runner()
print(runn.login())

output>> IndexError: list index out of range

Body:
If you want a singleton-type value, change your code to look like this.

class Runner():
    args = []

    def argument_reader(self):
        Runner.args = list(sys.argv)

    def login(self):
        return Runner.args[1], Runner.args[2]

Otherwise, you'll have to call argument_reader() on each instance.


问:
How to search columns in search input only from logged-in user data?
How will I get only the columns of the logged user on input search query? Means that I search only the data that he has stored

```<code>$restaurants = Restaurant::where('title', 'like', '%'.$query.'%')
</code>```

Restaurant have user_id column, in user model:

```<code>public function restaurants() {
    return $this->hasMany('App\Restaurant');
}
</code>```

in restaurant model:

```<code>public function user() {
    return $this->belongsTo('App\User');
}
</code>```

答:
You can get current user with Auth Facade :

```<code>    $currentUser = \Auth::user();//Get current User Model
    $restaurants = Restaurant::where([
    ['user_id','=',$currentUser->id],
    ['title', 'like', '%'.$query.'%']
])->get();
</code>```

Not tested,

Hope this helps

Edit : Tested Now

You should use get() method or ( alternates to get() rows that match your conditions .

Body:
How will I get only the columns of the logged user on input search query? Means that I search only the data that he has stored

$restaurants = Restaurant::where('title', 'like', '%'.$query.'%')

Restaurant have user_id column, in user model:

public function restaurants() {
    return $this->hasMany('App\Restaurant');
}

in restaurant model:

public function user() {
    return $this->belongsTo('App\User');
}

Body:
You can get current user with Auth Facade :

    $currentUser = \Auth::user();//Get current User Model
    $restaurants = Restaurant::where([
    ['user_id','=',$currentUser->id],
    ['title', 'like', '%'.$query.'%']
])->get();

Not tested,

Hope this helps

Edit : Tested Now

You should use get() method or ( alternates to get() rows that match your conditions .


问:
name 'DataFrameSelector' is not defined
I am currently reading the "Hands-On Machine Learning with Scikit-Learn & TensorFlow". I get an error when I am trying to recreate the Transformation Pipelines code.  How can I fix this?

Code:

```<code>from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

num_pipeline = Pipeline([('imputer', Imputer(strategy = "median")),
                        ('attribs_adder', CombinedAttributesAdder()),
                        ('std_scaler', StandardScaler()),
                        ])

housing_num_tr = num_pipeline.fit_transform(housing_num)

from sklearn.pipeline import FeatureUnion

num_attribs = list(housing_num)
cat_attribs = ["ocean_proximity"]

num_pipeline = Pipeline([
                         ('selector', DataFrameSelector(num_attribs)),
                         ('imputer', Imputer(strategy = "median")),
                         ('attribs_adder', CombinedAttributesAdder()),
                         ('std_scaler', StandardScaler()),
                        ])

cat_pipeline = Pipeline([('selector', DataFrameSelector(cat_attribs)),
                         ('label_binarizer', LabelBinarizer()),
                        ])

full_pipeline = FeatureUnion(transformer_list = [("num_pipeline", num_pipeline),
                                                 ("cat_pipeline", cat_pipeline),
                                                ])

# And we can now run the whole pipeline simply:

housing_prepared = full_pipeline.fit_transform(housing)
housing_prepared
</code>```

Error:

```<code>---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-350-3a4a39e5bc1c> in <module>()
     43
     44 num_pipeline = Pipeline([
---> 45                          ('selector', DataFrameSelector(num_attribs)),
     46                          ('imputer', Imputer(strategy = "median")),
     47                          ('attribs_adder', CombinedAttributesAdder()),

NameError: name 'DataFrameSelector' is not defined
</code>```

答:
```<code>from sklearn.pipeline import FeatureUnion
class DataFrameSelector(BaseEstimator, TransformerMixin):
    def __init__(self, attribute_names):
        self.attribute_names = attribute_names
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        return X[self.attribute_names].values
</code>```

<p>It may work. </p>

ContentLicense: CC BY-SA 3.0

Title: name 'DataFrameSelector' is not defined

Body:
I am currently reading the "Hands-On Machine Learning with Scikit-Learn & TensorFlow". I get an error when I am trying to recreate the Transformation Pipelines code.  How can I fix this?

Code:

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

num_pipeline = Pipeline([('imputer', Imputer(strategy = "median")),
                        ('attribs_adder', CombinedAttributesAdder()),
                        ('std_scaler', StandardScaler()),
                        ])

housing_num_tr = num_pipeline.fit_transform(housing_num)

from sklearn.pipeline import FeatureUnion

num_attribs = list(housing_num)
cat_attribs = ["ocean_proximity"]

num_pipeline = Pipeline([
                         ('selector', DataFrameSelector(num_attribs)),
                         ('imputer', Imputer(strategy = "median")),
                         ('attribs_adder', CombinedAttributesAdder()),
                         ('std_scaler', StandardScaler()),
                        ])

cat_pipeline = Pipeline([('selector', DataFrameSelector(cat_attribs)),
                         ('label_binarizer', LabelBinarizer()),
                        ])

full_pipeline = FeatureUnion(transformer_list = [("num_pipeline", num_pipeline),
                                                 ("cat_pipeline", cat_pipeline),
                                                ])

# And we can now run the whole pipeline simply:

housing_prepared = full_pipeline.fit_transform(housing)
housing_prepared

Error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-350-3a4a39e5bc1c> in <module>()
     43
     44 num_pipeline = Pipeline([
---> 45                          ('selector', DataFrameSelector(num_attribs)),
     46                          ('imputer', Imputer(strategy = "median")),
     47                          ('attribs_adder', CombinedAttributesAdder()),

NameError: name 'DataFrameSelector' is not defined

Body:
from sklearn.pipeline import FeatureUnion
class DataFrameSelector(BaseEstimator, TransformerMixin):
    def __init__(self, attribute_names):
        self.attribute_names = attribute_names
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        return X[self.attribute_names].values

It may work.


问:
How to copy whole workbook to a desired location by changing a cell value
I have a excel workbook containing 5 sheets and a drop-down button in sheet-3. I want to save the entire file when i choose a option from the drop-down button with the drop-down selected option to a desired folder. It would be great if anyone can help me.

Thanks.

答:
You need to know the drop down's name, then this should work:

Sub SaveToDesktop()

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim strName As String
    With ActiveWorkbook.Sheets("Sheet3").Shapes("Drop Down Name")   'Set your drop down name
        strName = .List(.Value) 'get the selected value
    End With

    With ActiveWorkbook
        .SaveAs "D:\R\" & strName
        '.Close
    End With

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

    MsgBox "Completed" 'To let you know when it is done
End Sub
```


问:
how to set data to firebase map object
I have a firebase map object and i need to insert arrays inside

I am trying to use update function but it doesn't work

```<code>dialogRef.afterClosed().subscribe(result => {
  console.log(result);

  const arrayname = result.name;
  const fireupdate = this.af.list('/users/' + this.Uid + '/items').update(arrayname, result);
});
</code>```

this is how the result array looks like

```<code>{name: "item", price: 25, desc: "a simple item"}
</code>```

I don't get anything in the firebase

答:
So what is easiest to do is add the array to the doc as shown in the other answer.

```<code>this.db.collection("users").doc(this.Uid).update({items: [{name: "item", price: 25, desc: "a simple item"}, {name: "item2", price: 20, desc: "a simple item2"}]})
</code>```

What you must be careful about is that firestore not really have a good way to query an array with objects yet:

query an array

What Firestore want you to do is basicly:

```<code>this.db.collection("users").doc(this.Uid).collection('items').add({name: "item", price: 25, desc: "a simple item"})
</code>```

Title: how to set data to firebase map object

Body:
I have a firebase map object and i need to insert arrays inside

I am trying to use update function but it doesn't work

dialogRef.afterClosed().subscribe(result => {
  console.log(result);

  const arrayname = result.name;
  const fireupdate = this.af.list('/users/' + this.Uid + '/items').update(arrayname, result);
});

this is how the result array looks like

{name: "item", price: 25, desc: "a simple item"}

I don't get anything in the firebase

Body:
So what is easiest to do is add the array to the doc as shown in the other answer.

this.db.collection("users").doc(this.Uid).update({items: [{name: "item", price: 25, desc: "a simple item"}, {name: "item2", price: 20, desc: "a simple item2"}]})

What you must be careful about is that firestore not really have a good way to query an array with objects yet:

query an array

What Firestore want you to do is basicly:

this.db.collection("users").doc(this.Uid).collection('items').add({name: "item", price: 25, desc: "a simple item"})


问:
PHP - Identifying Individual Users Under Same Router (main IP address)
Is it possible to find the IP address of (or otherwise identify) each user on the same "router" or "main IP address"?

Update, clarifying question:

Use-case:
I'd like to be able to track whether each of N individual computer users on a possibly common network has landed on a page.

Currently, using other PHP IP detect snippets on S/O, this seems to only identify all N individual computers on the network as coming from the same IP address. This does not help solve the problem of identifying whether these come from different users on the same network, or if it's the same user on the network hitting the page several times.

--

Note: cookies are likely disabled.

答:
So I have a log file for tracking my users on my Site and I do something like this to get the IP:

```<code>if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}
</code>```

You could try tracking all of the three above but in cases where users on the same network are appearing with one IP they will usually just have the last one very few will show individual IPs as it would probably be a security risk.

As for different users on the same network I also try track a session id:

```<code>$session_id = session_id();
</code>```

So even if the IP is the same for multiple users they should have different browsing sessions.

If you wanted to track the same user over multiple sessions you can try setting a unique cookie, then even if it is a new session the cookie on that users computer should still exist (presuming they haven't cleared their cache etc,.) but as you said in your question if cookies are disabled this isn't an option.

Body:
So I have a log file for tracking my users on my Site and I do something like this to get the IP:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

You could try tracking all of the three above but in cases where users on the same network are appearing with one IP they will usually just have the last one very few will show individual IPs as it would probably be a security risk.

As for different users on the same network I also try track a session id:

$session_id = session_id();

So even if the IP is the same for multiple users they should have different browsing sessions.

If you wanted to track the same user over multiple sessions you can try setting a unique cookie, then even if it is a new session the cookie on that users computer should still exist (presuming they haven't cleared their cache etc,.) but as you said in your question if cookies are disabled this isn't an option.


问:
Cloudmade distance between two points
I need to get the distance between two points without showing the map on a iPhone app. I'm trying to use CLoudMade ... but I can't figure it out from the documentation provided.
CAn anyone help me ... and make a little step-by-step tutorial or give me some pointers ?
Thank you

*i want to use CloudMade because i need the distance by following public roads. I know it's a stupid "question" but I really can't seem to get my head around this ...

答: I think this post will be useful for you, you can get this info from route instructions.</p>

ContentLicense: CC BY-SA 2.5

Title: Cloudmade distance between two points


问:
How to split on commas and dot?
You are given a string consisting only of digits, commas, and dots. Your task is to complete the regex_pattern defined below, which will be used to re.split() all of the , and . symbols in. It's guaranteed that every comma and every dot in is preceded and followed by a digit.

Sample Input 0

100,000,000.000

Sample Output 0
```

<p>I am using Python 3.7.2 and I tried <code>re.split</code> by using <code>\,*</code> and <code>\.*</code> as shown below in the code but it seems to print after every numeral.</p>

```regex_pattern = r"\,*\.*"

import re
print("\n".join(re.split(regex_pattern, input())))
```

<p>However, this seems to be printing in the wrong order. </p>

<p>What should I add in <code>regex_pattern</code>?</p>

<p>Expected result was:</p>

<pre class="lang-none prettyprint-override"><code>100
000
000
000
</code>```

However, I am getting:

1
0
0

0
0
0

0
0
0
```

答:
string = "100,000,000.000"

regex_pattern = r"[,.]"

import re
print("\n".join(re.split(regex_pattern, string)))
```

```100
000
000
000
```

Edit: Fixed the pattern based on the solution Diwakar SHARMA added to the comments.

Title: How to split on commas and dot?

Body:
You are given a string consisting only of digits, commas, and dots. Your task is to complete the regex_pattern defined below, which will be used to re.split() all of the , and . symbols in. It's guaranteed that every comma and every dot in is preceded and followed by a digit.

Sample Input 0

100,000,000.000

Sample Output 0

I am using Python 3.7.2 and I tried re.split by using \,* and \.* as shown below in the code but it seems to print after every numeral.

regex_pattern = r"\,*\.*"

import re
print("\n".join(re.split(regex_pattern, input())))

However, this seems to be printing in the wrong order.

What should I add in regex_pattern?

Expected result was:

100
000
000
000

However, I am getting:

1
0
0

0
0
0

0
0
0

Body:
string = "100,000,000.000"

regex_pattern = r"[,.]"

import re
print("\n".join(re.split(regex_pattern, string)))

100
000
000
000

Edit: Fixed the pattern based on the solution Diwakar SHARMA added to the comments.


问:
Difference b/w Mapr Vs Cloudera?
Cloudera is free edition and enterprise edition but MapR is almost enterprise edition why? is there any major difference between them?</p>

答:
Cloudera runs on HDFS wheras MAPR runs on MAPRFS. HDFS is append only whereas MAPRFS allows random read/writes making it highly efficient. This effectively means MAPR can provide the same performance in much lesser memory requirement than HDFS. The lowest unit or read/write is much smaller in MAPRFS. HDFS is a distributed file system but underneath it uses linux file system to write data to the actual disk. This is lack of control on optimization during actual writes on raw disk, in MapR they directly have the native code which writes directly into disks in an optimized way. This itself is single big reason for improved writes.Since the code is written in C, there is no need of JVM garbage collection.
For further details, you could look up the link :
https://mapr.com/blog/database-comparison-an-in-depth-look-at-mapr-db/</p>

Title: Difference b/w Mapr Vs Cloudera?


问:
How to send angular html form input to spring boot rest web controller
i'm trying to send a list of 1 or more genes to my backend, through angular frontend and a spring boot rest web controller

my html page:

```<code><div class="container">
  <h1>Clustertool gene(s) input</h1>
  <form (ngSubmit)="onSubmit()" #clusterForm="ngForm">
    <div class="form-group">
      <label for="gene">gene(s) </label>
      <input type="text" class="form-control" id="gene" required>
    </div>
    <button type="submit" class="btn btn-success">Submit</button>
    </form>
</div>
</code>```

component

```<code>import { Component, OnInit } from '@angular/core';
import { ClustertoolService} from "../../clustertool.service";

@Component({
  selector: 'app-cluster-tool',
  templateUrl: './cluster-tool.component.html',
  styleUrls: ['./cluster-tool.component.css']
})
export class ClusterToolComponent implements OnInit {
  onSubmit() {
    this.clustertoolService.getCell()
  }
  constructor(private clustertoolService: ClustertoolService) { }

  ngOnInit() {
    this.clustertoolService.getCell()
  }
}
</code>```

servicepage

```<code>import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class ClustertoolService {
  private clusterUrl: string;

  constructor(private http: HttpClient) {
    this.clusterUrl = 'localhost:8080/clustertool/singleGene';
  }
  getCell(): Observable<any> {
    return this.http.get(this.clusterUrl);
  }
}
</code>```

app-routing module

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

web controller

```<code>package singleCell.controllers.WebController;

import org.springframework.web.bind.annotation.*;
import singleCell.DatabaseAccess.DAO.DatabaseRetriever;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/clustertool")
public class ClusterController {

    @RequestMapping(value = "/singleGene", method = RequestMethod.GET)
            public ArrayList singleGeneResponse(@RequestParam String gene){
        return DatabaseRetriever.getSingleGene(gene);
    }

    @RequestMapping(value = "/multipleGenes", method = RequestMethod.GET)
    public ArrayList multipleGeneResponse(@RequestParam List<String> genes){
        System.out.println(genes);
        return DatabaseRetriever.getMultipleGenes(genes);
    }

}
</code>```

i want backend result to be send to the frontend, so i can further use it there. going to make plots out of the data with js libraries.

答:
First of all, your ClustertoolService.getCell() should accept a parameter for gene

```<code>getCell(gene: string): Observable<any> {
  return this.http.get(this.clusterUrl+'?gene='+gene);
}
</code>```

Then, you should call this method on submit of form with input value.

```<code>onSubmit() {
  this.clustertoolService.getCell(this.geneModel); // geneModel is ngModel for your input.
}
</code>```

EDIT: in your HTML, you need to define ngModel on gene input field

```<code><input type="text" class="form-control" id="gene" [(ngModel)]="geneModel" required>
</code>```

Body:
i'm trying to send a list of 1 or more genes to my backend, through angular frontend and a spring boot rest web controller

my html page:

Clustertool gene(s) input

  <form (ngSubmit)="onSubmit()" #clusterForm="ngForm">

      gene(s)
      <input type="text" class="form-control" id="gene" required>

    <button type="submit" class="btn btn-success">Submit</button>
    </form>

component

import { Component, OnInit } from '@angular/core';
import { ClustertoolService} from "../../clustertool.service";

@Component({
  selector: 'app-cluster-tool',
  templateUrl: './cluster-tool.component.html',
  styleUrls: ['./cluster-tool.component.css']
})
export class ClusterToolComponent implements OnInit {
  onSubmit() {
    this.clustertoolService.getCell()
  }
  constructor(private clustertoolService: ClustertoolService) { }

  ngOnInit() {
    this.clustertoolService.getCell()
  }
}

servicepage

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class ClustertoolService {
  private clusterUrl: string;

  constructor(private http: HttpClient) {
    this.clusterUrl = 'localhost:8080/clustertool/singleGene';
  }
  getCell(): Observable<any> {
    return this.http.get(this.clusterUrl);
  }
}

app-routing module

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

web controller

package singleCell.controllers.WebController;

import org.springframework.web.bind.annotation.*;
import singleCell.DatabaseAccess.DAO.DatabaseRetriever;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/clustertool")
public class ClusterController {

    @RequestMapping(value = "/singleGene", method = RequestMethod.GET)
            public ArrayList singleGeneResponse(@RequestParam String gene){
        return DatabaseRetriever.getSingleGene(gene);
    }

    @RequestMapping(value = "/multipleGenes", method = RequestMethod.GET)
    public ArrayList multipleGeneResponse(@RequestParam List<String> genes){
        System.out.println(genes);
        return DatabaseRetriever.getMultipleGenes(genes);
    }

}

i want backend result to be send to the frontend, so i can further use it there. going to make plots out of the data with js libraries.

Body:
First of all, your ClustertoolService.getCell() should accept a parameter for gene

getCell(gene: string): Observable<any> {
  return this.http.get(this.clusterUrl+'?gene='+gene);
}

Then, you should call this method on submit of form with input value.

onSubmit() {
  this.clustertoolService.getCell(this.geneModel); // geneModel is ngModel for your input.
}

EDIT: in your HTML, you need to define ngModel on gene input field

<input type="text" class="form-control" id="gene" [(ngModel)]="geneModel" required>


问:
Building login secured php scripts
So I'm trying to make a secure homepage that checks if you're logged in by getting the text that the user entered on the login page and checking they are correct (so you can't just do www.website.com/home.php to bypass login)

```<code><body onload="OpenPhp()">
<form name="GetLogin" action="GetIfLoggedIn.php">
</body>
</code>```

The script is :

```<code><script>
function OpenPhp(){
document.GetLogin.submit();
}
</script>
</code>```

the php script should include the username and password vars from the login script and re-check them

```<code><?php include "Login.php";
   if($Username === "*****" and $Password === "******"){

// Return To Page

}else{
   //Go Back To Login Page
}

?>
</code>```

But the include statement makes the home page inaccessible. Every time I go to the home page it just sends me back to the index.html page.

Are there any better ways to secure a web page? If so please tell me or explain why this doesn't work,

答:
You Might Wanna Use This.

```<code>   <!DOCTYPE html>
   <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Fetch Array Trick</title>
</head>
<body>
    <?php
$con = mysqli_connect("localhost","root","","lesson") or die("Connection Not Established");
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    $username = $_POST['username'];
    $password = $_POST['password'];
    $get=array("0"=>$username,"username"=>$username,'1'=>$password,"password"=>$password);
//Created an array above that matches username and password.
$lol = mysqli_query($con,"Select username,password from users");
    while($pre= mysqli_fetch_array($lol)){
        //Now we check if, while in the loop, any tuple matches
        if (($get == $pre)){
            echo '<h1><font color=green>Found</font></h1>';
            //Use JavaScript To Redirect or clear headers to use header("location: dashboard.php");
            exit;
        }
    }
    echo '<h1><font color=red>Not Found</font></h1>';
}
?>

<form action="" method="post">
<p><label for="u">Username</label><input type="text" name="username" id="u"></p>

<p><label for="password">Password</label><input type="password" name="password" id="password"></p>
<p><input type="submit" name="submit" value="Login" id="submit"></p>
</form>
</body>
</html>
</code>```

Title: Building login secured php scripts

Body:
So I'm trying to make a secure homepage that checks if you're logged in by getting the text that the user entered on the login page and checking they are correct (so you can't just do www.website.com/home.php to bypass login)

<form name="GetLogin" action="GetIfLoggedIn.php">

The script is :

the php script should include the username and password vars from the login script and re-check them

<?php include "Login.php";
   if($Username === "*****" and $Password === "******"){

// Return To Page

}else{
   //Go Back To Login Page
}

?>

But the include statement makes the home page inaccessible. Every time I go to the home page it just sends me back to the index.html page.

Are there any better ways to secure a web page? If so please tell me or explain why this doesn't work,

Body:
You Might Wanna Use This.

   <!DOCTYPE html>
   <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Fetch Array Trick</title>
</head>
<body>
    <?php
$con = mysqli_connect("localhost","root","","lesson") or die("Connection Not Established");
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    $username = $_POST['username'];
    $password = $_POST['password'];
    $get=array("0"=>$username,"username"=>$username,'1'=>$password,"password"=>$password);
//Created an array above that matches username and password.
$lol = mysqli_query($con,"Select username,password from users");
    while($pre= mysqli_fetch_array($lol)){
        //Now we check if, while in the loop, any tuple matches
        if (($get == $pre)){
            echo '<h1><font color=green>Found</font></h1>';
            //Use JavaScript To Redirect or clear headers to use header("location: dashboard.php");
            exit;
        }
    }
    echo '<h1><font color=red>Not Found</font></h1>';
}
?>

<form action="" method="post">
<p><label for="u">Username</label><input type="text" name="username" id="u"></p>

<p><label for="password">Password</label><input type="password" name="password" id="password"></p>
<p><input type="submit" name="submit" value="Login" id="submit"></p>
</form>
</body>
</html>


问:
Database too large - store as a row or serialise data?
I have Quiz App that constitutes many Modules containing Questions. Each question has many Categories (many-to-many). Every time a quiz is completed, the user's score is sent to the Scores Table. (I've attached an entity-relation diagram for clarification purposes).

I have been thinking of breaking down the user scores according to categories (i.e. a user when completing a quiz will get an overall quiz score along with score for each category).

However, if each quiz consists of at least 30 questions, there could around 15-20 categories per quiz. So if one user completes a quiz, then it would create a minimum of 15-20 rows in the scores table. With multiple users, the Scores table would get really big really fast.

I assume this would affect the performance of retrieving data from the Scores table. For example, if I wanted to calculate the average score for a user for a specific category.

Does anyone have a better suggestion for how I can still be able to store scores based on categories?

I thought about serialising the JSON data, but of course, this has its limitations.

答:
The DB should be able to handle millions of rows and there is nothing inherently wrong with your design. A few things I would suggest:

Put indexes in the following (or combinations of) user id, exam id (which I assume is what you call scorable id ) exam type (scorable Type?) and creation date.

As your table grows, partition it. Potential candidates could be creation date buckets (by year or year/month would probably work well) or maybe if students are in particular classes you could have class buckets

As your table grow even more you could move the partitions to different different disks (how you partitioned the data will be even more crucial here because if the data has to go across too many partitions you may end up hurting performance instead of helping)

Beyond that another suggestion would be to break the scores table into two score and scoreDetail. The score table would contain top level stuff like user id ,exam id, overall score, etc... While the child table would contain the scores by category (philosophy, etc....). I would bet 80% of the time people only care about the top score anyways. This way you only reach out to the bigger table when some one wants to get the details of their score in a particular exam.

Finally, you probably want to have the score by category in rows rather than columns to make it easier to do analysis and aggregations, but this is not necessarily a performance booster and really depends on how you plan to use the data.

In the end though, the best optimizations really depend on how you plan to use your data. I would suggest just creating a random data set that represents a few years worth of data and play with that.


问:
request.user.is_authenticated working only in the home page
I am creating a website where a user can upload documents. If user is logged out he can view other's document but not download it
if user is logged in he can download the document from the toolbar in pdf viewer

Even when I am logged out request.user.is_authenticated is false in home page but its true in other pages. So the download button does not hide nor a login button shows up.

I have tried using user.is_authenticated but it was returning true all the time

the if else condition works fine in the index page but not in doc_detail.html

urls.py

re_path(r'^all_files/(?P<doc_id>[0-9]+)/$',views.doc_detail,name = 'doc_detail'),
path('login/',auth_views.LoginView.as_view(template_name='homework/login.html'),name = 'login'),

```

<p>views.py</p>

<pre class="lang-py prettyprint-override"><code>def doc_detail(request,doc_id):
    template = loader.get_template('homework/doc_detail.html')
    doc = get_object_or_404(Document, pk = doc_id)
    context = {
    'doc':doc
    }
    return HttpResponse(template.render(context,request))
</code>```

doc_detail.html

{{ doc.user.username }}
{{ doc.title }}
{{ doc.doc_type }}

{% if request.user.is_authenticated %}

{% else %}

    login
{% endif %}
```

<p>index page</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
This is the homework page implement upload-routine explore-routine here
{% if request.user.is_authenticated %}
the user is {{ request.user.email }} {{ request.user.profile.institution }}

{% else %}
user not logged in
{% endif %}

{% if request.user.is_authenticated %}
    logout
    update
    upload
    my uploads<br>
{% else %}
    login<br>
{% endif %}

all files
</body>
</html>
</code>```

答:
As pointed out in the comments, you should be using the render shortcut; it seems you are confusing that with the render method of a template. There's no reason to be using the template object directly here, or just about anywhere in standard Django code.</p>

```<code>def doc_detail(request, doc_id):
    doc = get_object_or_404(Document, pk=doc_id)
    context = {
        'doc':doc
    }
    return render(request, 'homework/doc_detail.html', context)
</code>```

Body:
I am creating a website where a user can upload documents. If user is logged out he can view other's document but not download it
if user is logged in he can download the document from the toolbar in pdf viewer

Even when I am logged out request.user.is_authenticated is false in home page but its true in other pages. So the download button does not hide nor a login button shows up.

I have tried using user.is_authenticated but it was returning true all the time

the if else condition works fine in the index page but not in doc_detail.html

urls.py

re_path(r'^all_files/(?P<doc_id>[0-9]+)/$',views.doc_detail,name = 'doc_detail'),
path('login/',auth_views.LoginView.as_view(template_name='homework/login.html'),name = 'login'),

views.py

def doc_detail(request,doc_id):
    template = loader.get_template('homework/doc_detail.html')
    doc = get_object_or_404(Document, pk = doc_id)
    context = {
    'doc':doc
    }
    return HttpResponse(template.render(context,request))

doc_detail.html

{{ doc.user.username }}
{{ doc.title }}
{{ doc.doc_type }}

{% if request.user.is_authenticated %}

{% else %}

    login
{% endif %}

index page

<!DOCTYPE html>

    <title></title>

This is the homework page implement upload-routine explore-routine here
{% if request.user.is_authenticated %}
the user is {{ request.user.email }} {{ request.user.profile.institution }}

{% else %}
user not logged in
{% endif %}

{% if request.user.is_authenticated %}
    logout
    update
    upload
    my uploads

{% else %}
    login

{% endif %}

all files

Body:
As pointed out in the comments, you should be using the render shortcut; it seems you are confusing that with the render method of a template. There's no reason to be using the template object directly here, or just about anywhere in standard Django code.

def doc_detail(request, doc_id):
    doc = get_object_or_404(Document, pk=doc_id)
    context = {
        'doc':doc
    }
    return render(request, 'homework/doc_detail.html', context)


问:
How do I add a column to my data table that shows the sum of multiple other columns' values?
I have 8 age categories, with each of them having its own column (i.e. residents_under_5, residents_6_to_12, etc. Each column has a value between 0 and 3, for the number of people in that household in that specific age category.
What I want is a new column with which I can plot the total distribution of age of my population on a histogram. So I was thinking of a column that has 66 rows of residents_under_5, 32 rows of residents_6_to_12, etc., for the sum of those categories.

My data looks like this:

```<code>a b c d
0 3 2 1
1 3 2 1
2 0 2 1
3 1 0 0
</code>```

What I want is a column e that shows:

```<code>e
a
a
a
a
b
b
b
b
b
c
c
c
d
d
d
</code>```

For the total number of occurences in the other columns.

I've tried declaring new columns with sum(residents_under_5), but that will give me 1 row with 66 (as the sum of that category). I can't plot a histogram with such a column. I hope someone can figure it out!

This is the dput() of the relevant columns

```<code>residents_under_5 = c(0, 0, 0, 1, 1, 2),
residents_6_to_12 = c(0, 0, 0, 0, 0, 0),
        residents_13_to_18 = c(0, 0, 0, 0, 0, 0),
residents_19_to_24 = c(0,
        0, 0, 0, 0, 0),
residents_25_to_34 = c(0, 1, 2, 0, 1, 0),
       residents_35_to_49 = c(0, 0, 0, 2, 1, 2),
residents_50_to_64 = c(0,
        1, 0, 0, 0, 0),
residents_65_and_older = c(2, 0, 0, 0, 1,
        0)
</code>```

答:
You can unlist the dataframe and calculate frequencies using table and then repeat letters using rep.

```<code>rep(letters[seq_len(ncol(df))], colSums(df))
</code>```

data

```<code>df <- data.frame(residents_under_5 = c(0, 0, 0, 1, 1, 2),
                 residents_6_to_12 = c(0, 0, 0, 0, 0, 0),
                 residents_13_to_18 = c(0, 0, 0, 0, 0, 0),
                 residents_19_to_24 = c(0, 0, 0, 0, 0, 0),
                 residents_25_to_34 = c(0, 1, 2, 0, 1, 0),
                 residents_35_to_49 = c(0, 0, 0, 2, 1, 2),
                 residents_50_to_64 = c(0, 1, 0, 0, 0, 0),
                 residents_65_and_older = c(2, 0, 0, 0, 1, 0))
</code>```

Body:
I have 8 age categories, with each of them having its own column (i.e. residents_under_5, residents_6_to_12, etc. Each column has a value between 0 and 3, for the number of people in that household in that specific age category.
What I want is a new column with which I can plot the total distribution of age of my population on a histogram. So I was thinking of a column that has 66 rows of residents_under_5, 32 rows of residents_6_to_12, etc., for the sum of those categories.

My data looks like this:

a b c d
0 3 2 1
1 3 2 1
2 0 2 1
3 1 0 0

What I want is a column e that shows:

e
a
a
a
a
b
b
b
b
b
c
c
c
d
d
d

For the total number of occurences in the other columns.

I've tried declaring new columns with sum(residents_under_5), but that will give me 1 row with 66 (as the sum of that category). I can't plot a histogram with such a column. I hope someone can figure it out!

This is the dput() of the relevant columns

residents_under_5 = c(0, 0, 0, 1, 1, 2),
residents_6_to_12 = c(0, 0, 0, 0, 0, 0),
        residents_13_to_18 = c(0, 0, 0, 0, 0, 0),
residents_19_to_24 = c(0,
        0, 0, 0, 0, 0),
residents_25_to_34 = c(0, 1, 2, 0, 1, 0),
       residents_35_to_49 = c(0, 0, 0, 2, 1, 2),
residents_50_to_64 = c(0,
        1, 0, 0, 0, 0),
residents_65_and_older = c(2, 0, 0, 0, 1,
        0)

Body:
You can unlist the dataframe and calculate frequencies using table and then repeat letters using rep.

rep(letters[seq_len(ncol(df))], colSums(df))

data

df <- data.frame(residents_under_5 = c(0, 0, 0, 1, 1, 2),
                 residents_6_to_12 = c(0, 0, 0, 0, 0, 0),
                 residents_13_to_18 = c(0, 0, 0, 0, 0, 0),
                 residents_19_to_24 = c(0, 0, 0, 0, 0, 0),
                 residents_25_to_34 = c(0, 1, 2, 0, 1, 0),
                 residents_35_to_49 = c(0, 0, 0, 2, 1, 2),
                 residents_50_to_64 = c(0, 1, 0, 0, 0, 0),
                 residents_65_and_older = c(2, 0, 0, 0, 1, 0))


问:
How to enhance window size selection on a tkinter project including button-image as label?
I'm currently working on a little project on python-3.x including some tkinter ressources. My program is made to display on a screen a list of pictures included in a directory, each picture is put on a button that is a sixth of the original image, and if we click on it, it display the image on his original size on a new window. The original window is set by the amount of pictures i put in the columns (i can choose in the code) and i ve made a scrollbar because i have to work with a lot of pictures.

But here is my problem, it's works fine except that if i change the window size, like reduce it for example, the buttons don't follow, they just vanish behind the window, and with the scrollbar.

I'm not particularly good in python so i was wondering that maybe by doing like a threading we could get the window size in live and then if the window size is inferior/superior of our columns of buttons, we could resize it and change the amount of columns then reload the page, but i will have to work with multiple image so it will take a lot of time.

from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
from PIL import Image, ImageTk
import tkinter as tk
import glob
import os
import cv2
import copy
import _thread
import time

folder = 'X:/users/Robin/data/dataset-valid/visu/*.jpg'

a=glob.glob(folder)

fic = "../data/list.txt"

fichObj=open(fic,"w")

p = []

for f in a:
    fichObj.write(f+"\n")
fichObj.close()

class SuperPhoto(object):
        def __init__(self, photo , image):

                self.photo = photo
                temp = cv2.resize(image, (int((self.photo.width())/6) , int((self.photo.height())/6)))
                red = temp[:,:,2].copy()
                blue = temp[:,:,0].copy()
                temp[:,:,0] = red
                temp[:,:,2] = blue
                temp = Image.fromarray(temp)
                self.miniature = ImageTk.PhotoImage(temp)

        def agrandir(self):
                Newfen=Toplevel()
                Newfen.geometry("+60+60")
                #self.photo.resize((500,500))

                print(type(self.photo))
                label = Label(Newfen, image=self.photo, width=self.photo.width(), height=self.photo.height())
                label.image = self.photo # keep a reference!
                label.pack()

if os.path.exists (fic):     #os.path utile
        count = len(open(fic).readlines())
        print(count)
        #lin = open(fic).readlines()
        #print(lin)

class ScrollableCanvas(Frame):
     def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        canvas=Canvas(self,bg='#FFFFFF',width=300,height=300,scrollregion=(0,0,500,500))

        canvas.update_idletasks()

        vbar=Scrollbar(self,orient=VERTICAL)
        vbar.pack(side=RIGHT, fill=Y)
        vbar.config(command=canvas.yview)

        canvas.config(width=1200,height=700)
        canvas.config(yscrollcommand=vbar.set)
        canvas.pack(side=LEFT,expand=True,fill=BOTH)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior, anchor=NW )

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)

class Main_frame(Frame):
    # Init
    def __init__(self, fenetre_principale=None):
        Frame.__init__(self, fenetre_principale)
        self.grid()
        self.scrollable_canvas = ScrollableCanvas(self)
        self.scrollable_canvas.grid(row=1,column=1)

        nbCol = 4

        for file in a:
                image = Image.open(file)
                photo = ImageTk.PhotoImage(image)
                w = photo.width()
                L.append(int(w/6))
                #print(L)
                sumL = int(sum(L)/nbCol)

                print(sumL)

                p.append(SuperPhoto(photo, cv2.imread(file)))

        for ligne in range(int(count/nbCol)):
                for colonne in range(nbCol):
                        photo = p[ligne * nbCol + colonne]
                        button = Button(self.scrollable_canvas.interior, image=photo.miniature, command=photo.agrandir)
                        button.grid(row=ligne, column=colonne)

if __name__ == "__main__":
    root = Tk()
    root.title("VISU")
    root.geometry("+0+0")
    L= []

    interface = Main_frame(fenetre_principale=root)
    root.update_idletasks()
    print(root.winfo_width())
    print(root.geometry())
    interface.mainloop()

```

So, I except this program to work like a classic directory display, with the columns that change automatically when we resize the window and with the scrollbar that follow it.

If you have any solutions it will really help me ..

You can try it, just put some jpeg pictures in a directory and change the folder variable with the link of your directory.

Thanks in advance for your help, if you have any questions to understand more clearly what  i've said don't hesitate.

答:
Each time the root window is resized, a <Configure> event is triggered. Catch it as follows:

```<code>def resize(event):
    root.update_idletasks()
    #update all image sizes here if needed
    #all widgets can be 're-grided' here based on new width and height of root window

root.bind('<Configure>', resize)
</code>```

If you want to ensure that your window cannot be resized, use the following:

```<code>root.resizable(False, False)
</code>```

Body:
I'm currently working on a little project on python-3.x including some tkinter ressources. My program is made to display on a screen a list of pictures included in a directory, each picture is put on a button that is a sixth of the original image, and if we click on it, it display the image on his original size on a new window. The original window is set by the amount of pictures i put in the columns (i can choose in the code) and i ve made a scrollbar because i have to work with a lot of pictures.

But here is my problem, it's works fine except that if i change the window size, like reduce it for example, the buttons don't follow, they just vanish behind the window, and with the scrollbar.

I'm not particularly good in python so i was wondering that maybe by doing like a threading we could get the window size in live and then if the window size is inferior/superior of our columns of buttons, we could resize it and change the amount of columns then reload the page, but i will have to work with multiple image so it will take a lot of time.

from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
from PIL import Image, ImageTk
import tkinter as tk
import glob
import os
import cv2
import copy
import _thread
import time

folder = 'X:/users/Robin/data/dataset-valid/visu/*.jpg'

a=glob.glob(folder)

fic = "../data/list.txt"

fichObj=open(fic,"w")

p = []

for f in a:
    fichObj.write(f+"\n")
fichObj.close()

class SuperPhoto(object):
        def __init__(self, photo , image):

                self.photo = photo
                temp = cv2.resize(image, (int((self.photo.width())/6) , int((self.photo.height())/6)))
                red = temp[:,:,2].copy()
                blue = temp[:,:,0].copy()
                temp[:,:,0] = red
                temp[:,:,2] = blue
                temp = Image.fromarray(temp)
                self.miniature = ImageTk.PhotoImage(temp)

        def agrandir(self):
                Newfen=Toplevel()
                Newfen.geometry("+60+60")
                #self.photo.resize((500,500))

                print(type(self.photo))
                label = Label(Newfen, image=self.photo, width=self.photo.width(), height=self.photo.height())
                label.image = self.photo # keep a reference!
                label.pack()

if os.path.exists (fic):     #os.path utile
        count = len(open(fic).readlines())
        print(count)
        #lin = open(fic).readlines()
        #print(lin)

class ScrollableCanvas(Frame):
     def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        canvas=Canvas(self,bg='#FFFFFF',width=300,height=300,scrollregion=(0,0,500,500))

        canvas.update_idletasks()

        vbar=Scrollbar(self,orient=VERTICAL)
        vbar.pack(side=RIGHT, fill=Y)
        vbar.config(command=canvas.yview)

        canvas.config(width=1200,height=700)
        canvas.config(yscrollcommand=vbar.set)
        canvas.pack(side=LEFT,expand=True,fill=BOTH)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior, anchor=NW )

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)

class Main_frame(Frame):
    # Init
    def __init__(self, fenetre_principale=None):
        Frame.__init__(self, fenetre_principale)
        self.grid()
        self.scrollable_canvas = ScrollableCanvas(self)
        self.scrollable_canvas.grid(row=1,column=1)

        nbCol = 4

        for file in a:
                image = Image.open(file)
                photo = ImageTk.PhotoImage(image)
                w = photo.width()
                L.append(int(w/6))
                #print(L)
                sumL = int(sum(L)/nbCol)

                print(sumL)

                p.append(SuperPhoto(photo, cv2.imread(file)))

        for ligne in range(int(count/nbCol)):
                for colonne in range(nbCol):
                        photo = p[ligne * nbCol + colonne]
                        button = Button(self.scrollable_canvas.interior, image=photo.miniature, command=photo.agrandir)
                        button.grid(row=ligne, column=colonne)

if __name__ == "__main__":
    root = Tk()
    root.title("VISU")
    root.geometry("+0+0")
    L= []

    interface = Main_frame(fenetre_principale=root)
    root.update_idletasks()
    print(root.winfo_width())
    print(root.geometry())
    interface.mainloop()

So, I except this program to work like a classic directory display, with the columns that change automatically when we resize the window and with the scrollbar that follow it.

If you have any solutions it will really help me ..

You can try it, just put some jpeg pictures in a directory and change the folder variable with the link of your directory.

Thanks in advance for your help, if you have any questions to understand more clearly what  i've said don't hesitate.

Body:
Each time the root window is resized, a <Configure> event is triggered. Catch it as follows:

def resize(event):
    root.update_idletasks()
    #update all image sizes here if needed
    #all widgets can be 're-grided' here based on new width and height of root window

root.bind('<Configure>', resize)

If you want to ensure that your window cannot be resized, use the following:

root.resizable(False, False)


问:
How can I subscribe and unsubscribe from an observable?
I have two functions where I need to subscribe to an observable in the first one, and unsubscribe to it in the second. But in my code , I can't access the observable from the second function because it's not in its scope.

here are my functions :

```<code> start() {
    this.max = this.duration;
    const interval = Observable.interval(this.selectedSprint.duration);
    interval
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1)
      .subscribe();
    }

    stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
    // if true logic
        }
      });
      }
</code>```

答:
If you are in a class, you can keep the subscription object, returned by the call to .subscribe(), as a property.

```<code>start() {
   this.max = this.duration;
   const interval = Observable.interval(this.selectedSprint.duration);
   interval
     .takeWhile(_ => !this.isFinished)
     .do(i => this.current += 1);
   this.intervalSubscription = interval.subscribe();
}
</code>```

This will allow you to unsubscribe in your stop method

```<code>stop() {
    this.intervalSubscription.unsubscribe(...);
}
</code>```

Body:
I have two functions where I need to subscribe to an observable in the first one, and unsubscribe to it in the second. But in my code , I can't access the observable from the second function because it's not in its scope.

here are my functions :

 start() {
    this.max = this.duration;
    const interval = Observable.interval(this.selectedSprint.duration);
    interval
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1)
      .subscribe();
    }

    stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
    // if true logic
        }
      });
      }

Body:
If you are in a class, you can keep the subscription object, returned by the call to .subscribe(), as a property.

start() {
   this.max = this.duration;
   const interval = Observable.interval(this.selectedSprint.duration);
   interval
     .takeWhile(_ => !this.isFinished)
     .do(i => this.current += 1);
   this.intervalSubscription = interval.subscribe();
}

This will allow you to unsubscribe in your stop method

stop() {
    this.intervalSubscription.unsubscribe(...);
}


问:
displaying column based on value of another column
There is a table like this:

```<code>Parent | Child
1      | 11
11     | 12
11     | 13
12     | 14
12     | 14
</code>```

If pass 1, it should return all the ‘1’ children’s: 11, 12, 13, 14

答:
```<code>-- Test data
declare @T table (ParentID int, ChildID int)
insert into @T values(1,       11)
insert into @T values(11,      12)
insert into @T values(11,      13)
insert into @T values(12,      14)
insert into @T values(12,      14)

-- ID to search for
declare @ParentID int = 1

-- Recorsive cte
;with cte as
(
  select T.*
  from @T as T
  where T.ParentID = @ParentID
  union all
  select T.*
  from cte as C
    inner join @T as T
      on C.ChildID = T.ParentID
)
select distinct ChildID
from cte
</code>```

Result

```<code>ChildID
-------
11
12
13
14
</code>```

Body:
There is a table like this:

Parent | Child
1      | 11
11     | 12
11     | 13
12     | 14
12     | 14

If pass 1, it should return all the ‘1’ children’s: 11, 12, 13, 14

Body:
-- Test data
declare @T table (ParentID int, ChildID int)
insert into @T values(1,       11)
insert into @T values(11,      12)
insert into @T values(11,      13)
insert into @T values(12,      14)
insert into @T values(12,      14)

-- ID to search for
declare @ParentID int = 1

-- Recorsive cte
;with cte as
(
  select T.*
  from @T as T
  where T.ParentID = @ParentID
  union all
  select T.*
  from cte as C
    inner join @T as T
      on C.ChildID = T.ParentID
)
select distinct ChildID
from cte

Result

ChildID
-------
11
12
13
14


问:
OTP autofilling not working - facebook account kit
I'm using the following link to integrate facebook account kit (version 5.0.0) to my android app. I'm using both the sms and whatsapp logins but the received codes are not being autofilled in both the cases:

https://developers.facebook.com/docs/accountkit/android/

What could be the possible cause of this? Thanks.

答:
The autofill feature has been removed in their latest sdk. Reference:

https://developers.facebook.com/support/bugs/704794763310779/
https://developers.facebook.com/support/bugs/615262038994308/


问:
Remove query param from url
I have the following URL:

```<code>http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860
</code>```

And I want to redirect to:

```<code>http://my.site#/homepage
</code>```

I do that with:

```<code>import { push } from 'react-router-redux'

...

dispatch(push('/homepage'))
</code>```

But react takes me to:

```<code>http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860#/homepage
</code>```

How can I tell React to drop the query param in the browser's address bar without reloading the application?

答:
Per the following links, I git cloned this and ran npm install in both the main directory and the example basic directory, and ran npm start to get a working example.

https://github.com/reactjs/react-router-redux

https://github.com/reactjs/react-router-redux/tree/master/examples/basic

https://github.com/reactjs/react-router-redux#pushlocation-replacelocation-gonumber-goback-goforward

Code to remove query params (close to the bottom) and validate that they're removed:

```<code>import { createStore, combineReducers, applyMiddleware } from 'redux'
import { browserHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer, routerMiddleware, push } from 'react-router-redux'
import * as reducers from './reducers'

const reducer = combineReducers({
  ...reducers,
  routing: routerReducer
})

const middleware = routerMiddleware(browserHistory)

const store = createStore(
  reducer,
  applyMiddleware(middleware)
)
const history = syncHistoryWithStore(browserHistory, store)

// Dispatch from anywhere like normal.
store.dispatch(push("/?test=ok"));
// store2.dispatch(push(history.createHref("/")));
var count = 0;

history.listen(location => {
    console.log(location);
    if (count > 1) { return; }
    count++;
    store.dispatch(push({ pathname:'/', search: '' })); // Drops the params
});
</code>```

Check console and you'll see the query params (search) field is empty

Title: Remove query param from url

Body:
I have the following URL:

http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860

And I want to redirect to:

http://my.site#/homepage

I do that with:

import { push } from 'react-router-redux'

...

dispatch(push('/homepage'))

But react takes me to:

http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860#/homepage

How can I tell React to drop the query param in the browser's address bar without reloading the application?

Body:
Per the following links, I git cloned this and ran npm install in both the main directory and the example basic directory, and ran npm start to get a working example.

https://github.com/reactjs/react-router-redux

https://github.com/reactjs/react-router-redux/tree/master/examples/basic

https://github.com/reactjs/react-router-redux#pushlocation-replacelocation-gonumber-goback-goforward

Code to remove query params (close to the bottom) and validate that they're removed:

import { createStore, combineReducers, applyMiddleware } from 'redux'
import { browserHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer, routerMiddleware, push } from 'react-router-redux'
import * as reducers from './reducers'

const reducer = combineReducers({
  ...reducers,
  routing: routerReducer
})

const middleware = routerMiddleware(browserHistory)

const store = createStore(
  reducer,
  applyMiddleware(middleware)
)
const history = syncHistoryWithStore(browserHistory, store)

// Dispatch from anywhere like normal.
store.dispatch(push("/?test=ok"));
// store2.dispatch(push(history.createHref("/")));
var count = 0;

history.listen(location => {
    console.log(location);
    if (count > 1) { return; }
    count++;
    store.dispatch(push({ pathname:'/', search: '' })); // Drops the params
});

Check console and you'll see the query params (search) field is empty


问:
Android webview fail to load large html content (some part load as white)
I have a WebView load html data from a response in a ViewPager which contain WebView,so if I swipe fast the data will load but some portion will be white, initial i thought its a render issue onRenderProcessGone but it was not coming it to that method

```<code>@Override
    public boolean onRenderProcessGone(WebView view,
            RenderProcessGoneDetail detail) {
}
</code>```

This is how the render webview in view pager looks like

if you see the above image you can see the some portion not rendered. if I swipe back  after going to other page, the data will load perfectly, so how can I solve the issue. i followed the Managing WebView objects
but noting is working, Hope some one will help to fix the issue

答:
This was a bug in chrome version v74, when we using webview inside cardview, as i can see your webview is inside cardview,So dont worry they have done a fix in canary version v75 for details check the link below
Rendering issue

So for testing you can download the canary version of chrome from play-store and enable it as your webview from developer console, after that check whether you are getting the issue or not.
If fixed wait for the stable version of chrome v75 meanwhile if you need a urgent fix , i can suggest you that change the cardview to linear-layout and make card image with shadow as background,for generating card you can check shadow4android

Else wait for the stable relase,Hope this helped you

Body:
I have a WebView load html data from a response in a ViewPager which contain WebView,so if I swipe fast the data will load but some portion will be white, initial i thought its a render issue onRenderProcessGone but it was not coming it to that method

@Override
    public boolean onRenderProcessGone(WebView view,
            RenderProcessGoneDetail detail) {
}

This is how the render webview in view pager looks like

if you see the above image you can see the some portion not rendered. if I swipe back  after going to other page, the data will load perfectly, so how can I solve the issue. i followed the Managing WebView objects
but noting is working, Hope some one will help to fix the issue


问:
How to search columns in search input only from logged-in user data?
How will I get only the columns of the logged user on input search query? Means that I search only the data that he has stored

```<code>$restaurants = Restaurant::where('title', 'like', '%'.$query.'%')
</code>```

Restaurant have user_id column, in user model:

```<code>public function restaurants() {
    return $this->hasMany('App\Restaurant');
}
</code>```

in restaurant model:

```<code>public function user() {
    return $this->belongsTo('App\User');
}
</code>```

答:
Since you have relations you can write the code like this</p>

```<code>$user = Auth::user();
if ($user) {
    $restaurants = $user->restaurants()->where('title', 'like', '%'.$query.'%')->get();
}
</code>```

Body:
How will I get only the columns of the logged user on input search query? Means that I search only the data that he has stored

$restaurants = Restaurant::where('title', 'like', '%'.$query.'%')

Restaurant have user_id column, in user model:

public function restaurants() {
    return $this->hasMany('App\Restaurant');
}

in restaurant model:

public function user() {
    return $this->belongsTo('App\User');
}

Body:
Since you have relations you can write the code like this

$user = Auth::user();
if ($user) {
    $restaurants = $user->restaurants()->where('title', 'like', '%'.$query.'%')->get();
}


问:
How to add own modules in Shopify?
I Want to create my own customized modules in Shopify when customers is logged in.

Example: I would to show near by doctors through the map.

Is it possible to do in Shopify.

答:
Yes it is. You would install a custom App that would contain a list of doctors and locations. You would create a Proxy in the App so you could make a secure callback to the endpoint. As data, you'd send the customer ID. Using the customer ID, the App would get the customer's location. The data you return would be the matching doctors.

Very common to do this with Shopify.

Title: How to add own modules in Shopify?


问:
Store does not implement IUserRoleStore<TUser> ASP.NET Core Identity
I'm using ASP.NET Core 2.1 Identity.  I've overridden IdentityUser because I need to add some additional properties on the user.

In Startup.cs

```<code>services.AddDefaultIdentity<PortalUser>().AddEntityFrameworkStores<ApplicationDbContext>();
</code>```

ApplicationDbContext.cs

```<code>public partial class ApplicationDbContext : IdentityDbContext<PortalUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }
}
</code>```

PortalUser class

```<code>public class PortalUser : IdentityUser
{
    [PersonalData]
    public DateTime? LastLoginDateUtc { get; set; }

    [PersonalData]
    public DateTime? RegistrationDateUtc { get; set; }
}
</code>```

That's all working fine.  I can add a user via.

```<code>_userManager.CreateAsync(user)
</code>```

However, when I call AddToRolesAsync to add a role to a user, I'm getting an exception.  Any ideas why?

```<code>_userManager.AddToRolesAsync(user, new List<string> { roleName });

{System.NotSupportedException: Store does not implement IUserRoleStore<TUser>.
   at Microsoft.AspNetCore.Identity.UserManager`1.GetUserRoleStore()
   at Microsoft.AspNetCore.Identity.UserManager`1.AddToRolesAsync(TUser user, IEnumerable`1 roles)}
</code>```

答:
For there are not any answers about the solution in asp.net Core 2.2, I would like to share the same error I meet in asp.net Core 2.2

First, here is another solution for the same error in asp.net core 2.1
https://github.com/aspnet/AspNetCore.Docs/issues/8683

And thanks to the author's idea, I meet the problem when I follow the official guidance in asp.net core 2.2 (the url is in here : MicrosoftDocs For asp.net core 2.2). When I finish the step he says and try to run the project, it throws a exception "Store does not implement IUserRoleStore"

and the problem is : actually, this is the sample for asp.net core 2.1 (And I strongly doubt that why the Microsoft will provide users a docs with not any sample codes, which can't make sense probably)

And you will find that, in Areas/Identity/Data/IdentityHostingStartup.cs IdentityHostingStartup::Configure method you have the following codes :

```<code>services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>();
</code>```

which is same as the code you should add in /Program.cs ConfigureService as the step : Add Role services to Identity in docs mentioned :

```<code>services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
</code>```

so if you meet the same problem in asp.net core 2.2, an alternative solution is :

Following the docs in asp.net 2.2

When you meet this Chapter : Add Role services to Identity , just ignore the official docs and do it :

replace the row

```<code>services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>();
</code>```

with

```<code>services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
</code>```

in Areas/Identity/Data/IdentityHostingStartup.cs IdentityHostingStartup::Configure method, but not add it in program.cs (the file can't be deleted in asp.net core 2.2)

The project I use Asp.net Identity will be updated later in my repos : UWPHelper , Good Luck :)

Body:
I'm using ASP.NET Core 2.1 Identity.  I've overridden IdentityUser because I need to add some additional properties on the user.

In Startup.cs

services.AddDefaultIdentity<PortalUser>().AddEntityFrameworkStores<ApplicationDbContext>();

ApplicationDbContext.cs

public partial class ApplicationDbContext : IdentityDbContext<PortalUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }
}

PortalUser class

public class PortalUser : IdentityUser
{
    [PersonalData]
    public DateTime? LastLoginDateUtc { get; set; }

    [PersonalData]
    public DateTime? RegistrationDateUtc { get; set; }
}

That's all working fine.  I can add a user via.

_userManager.CreateAsync(user)

However, when I call AddToRolesAsync to add a role to a user, I'm getting an exception.  Any ideas why?

_userManager.AddToRolesAsync(user, new List<string> { roleName });

{System.NotSupportedException: Store does not implement IUserRoleStore<TUser>.
   at Microsoft.AspNetCore.Identity.UserManager`1.GetUserRoleStore()
   at Microsoft.AspNetCore.Identity.UserManager`1.AddToRolesAsync(TUser user, IEnumerable`1 roles)}

Body:
For there are not any answers about the solution in asp.net Core 2.2, I would like to share the same error I meet in asp.net Core 2.2

First, here is another solution for the same error in asp.net core 2.1
https://github.com/aspnet/AspNetCore.Docs/issues/8683

And thanks to the author's idea, I meet the problem when I follow the official guidance in asp.net core 2.2 (the url is in here : MicrosoftDocs For asp.net core 2.2). When I finish the step he says and try to run the project, it throws a exception "Store does not implement IUserRoleStore"

and the problem is : actually, this is the sample for asp.net core 2.1 (And I strongly doubt that why the Microsoft will provide users a docs with not any sample codes, which can't make sense probably)

And you will find that, in Areas/Identity/Data/IdentityHostingStartup.cs IdentityHostingStartup::Configure method you have the following codes :

services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>();

which is same as the code you should add in /Program.cs ConfigureService as the step : Add Role services to Identity in docs mentioned :

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

so if you meet the same problem in asp.net core 2.2, an alternative solution is :

Following the docs in asp.net 2.2

When you meet this Chapter : Add Role services to Identity , just ignore the official docs and do it :

replace the row

services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>();

with

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

in Areas/Identity/Data/IdentityHostingStartup.cs IdentityHostingStartup::Configure method, but not add it in program.cs (the file can't be deleted in asp.net core 2.2)

The project I use Asp.net Identity will be updated later in my repos : UWPHelper , Good Luck :)


问:
Scala Slick Escape User Input Strings
I'm currently developing a service where customers can enter free text in the web interface. To avoid XSS or similar attacks, the text should be escaped in the backend. Does Scala or Slick offer a possibility similar to PHP to escape strings?

So far I checked StackOverflow and the Scala Essential Book for a working solution, so far with no luck.
Is there a native solution provided by Scala or Slick comparable to PHP's mysql-escape-string?

答:
Function mysqli-escape-string from PHP doesn't help you with doing any sanitization against XSS. It was intended to attempt to escape strings, that could cause SQL Injection. It is now deprecated and shouldn't be used anymore. The preferred way in PHP to prevent your code against SQL Injection is to use Prepared Statement with bind variables.

That said, neither Slick nor Scala have built-in functions doing string sanitization against XSS.

Slick has a nice feature, that changes all strings you are inserting using interpolation to bind variables, which prevents SQL Injection, but it has nothing to do with preventing XSS (it is something similar to Prepared Statements but with less boilerplate).

To prevent XSS you should use some library, which allows sanitization of strings, that might potentially contain XSS. There's Java project java-html-sanitizer from OWASP, that does that. You could use it like:

```<code>object HtmlSanitizer {

    //First define your policy for allowed elements
    private lazy val policy = new HtmlPolicyBuilder()
       .allowElements("p")
       .allowElements("a")
       .allowUrlProtocols("https")
       .allowAttributes("href").onElements("a")
       .requireRelNofollowOnLinks()
       .toFactory()

    def sanitize(unsafeHTML: String) = policy.sanitize(unsafeHTML)
 }
</code>```

and then:

```<code>HtmlSanitizer.sanitize("<p><svg/onload=alert('XSS')</p>") // "<p></p>"
</code>```

Title: Scala Slick Escape User Input Strings

Body:
Function mysqli-escape-string from PHP doesn't help you with doing any sanitization against XSS. It was intended to attempt to escape strings, that could cause SQL Injection. It is now deprecated and shouldn't be used anymore. The preferred way in PHP to prevent your code against SQL Injection is to use Prepared Statement with bind variables.

That said, neither Slick nor Scala have built-in functions doing string sanitization against XSS.

Slick has a nice feature, that changes all strings you are inserting using interpolation to bind variables, which prevents SQL Injection, but it has nothing to do with preventing XSS (it is something similar to Prepared Statements but with less boilerplate).

To prevent XSS you should use some library, which allows sanitization of strings, that might potentially contain XSS. There's Java project java-html-sanitizer from OWASP, that does that. You could use it like:

object HtmlSanitizer {

    //First define your policy for allowed elements
    private lazy val policy = new HtmlPolicyBuilder()
       .allowElements("p")
       .allowElements("a")
       .allowUrlProtocols("https")
       .allowAttributes("href").onElements("a")
       .requireRelNofollowOnLinks()
       .toFactory()

    def sanitize(unsafeHTML: String) = policy.sanitize(unsafeHTML)
 }

and then:

HtmlSanitizer.sanitize("<p><svg/onload=alert('XSS')</p>") // "<p></p>"


问:
When to alexa-smapi and alexa-avs
I need recommendations as when to use the above mentioned .Can i use
both of them is it possible .
Also in the botium.json's -

Containermode

only one of these can be mentioned
how to understand what and when exactly I have to chose any one of these

Below is my botium.json file

{
      "botium": {
        "Capabilities": {
          "PROJECTNAME": "Alexa Conversation Sample",
          "SCRIPTING_FORMAT": "xlsx",
          "SCRIPTING_XLSX_STARTROW": 2,
          "SCRIPTING_XLSX_STARTCOL": 1,
          "CONTAINERMODE": "alexa-avs",
      }
      }   }

I want to know if I can use alexa-smapi or alexa-avs
for eg inwatson we use something like below in botium.json

"CONTAINERMODE": "watson",
        "WATSON_USER": "0274cb6f-3680-4cf7-bd6b-71c7f447542d",
        "WATSON_PASSWORD": "ZWDE5xo02sby",
        "WATSON_WORKSPACE_ID": "97513bc0-c581-4bec-ac9f-ea6a8ec308a9"

In the same sense how and what should i do to run alexa skill

答:
The Botium Connector for Amazon Alexa Skills API is for testing the Skill on a very low API level. You can test the intent resolution (with the Skill Simulation API), and the backend response (with the Skill Invocation API). The recommendation is to start testing on API level with this connector.

The Botium Connector for Amazon Alexa with AVS simulates a virtual Alexa-enabled device connected to the Alexa services to test on End-2-End level - it uses Speech-to-text and Text-to-speech technologies to connect to your Alexa skill like a real user would do, and navigates through the conversation with voice commands.

Title: When to alexa-smapi and alexa-avs


问:
What are some common misunderstandings about TDD?
Reading over the responses to this question Disadvantages of Test Driven Development? I got the impression there is alot of misunderstanding on what TDD is and how it should be conducted. It may prove useful to address these issues here.</p>

答:
Just chucking another answer in the pot.

One of the most common misunderstandings is that your code is fixed, ie. I have this code, now how on earth will I test it? If it's hard to write a test, we should ask the question: how can I change this code to make it easier to test?

Why..?

Well The sort of code that's easy to test is:

Modular - each method does one thing.

Parameterised - each method accepts everything it needs and outputs everything it should.

Well Specified - each method does exactly what it should, no more, no less.

If we write code like this, testing is a doddle. The interesting thing is that code that is easy to test is, coincidentally, better code.

Better as in easier to read, easier to test, easier to understand, easier to debug. This is why TDD is often described as a design exercise.

OwnerDisplayName: wioota


问:
Item you requested is not available for purchase - android in app billing
As I am developing an application which uses in app billing, I am not able to test it using my own product ID. I have followed every step as documented on developer site. I have,

Uploaded the signed apk with release certificated to developer console.

I have published my apk to alpha channel.

I have listed my product Ids to developer console.

I have activated my product Ids and on developer console it is marked as Active.

I have listed the test account in developer console.

I have installed the same apk that I uploaded to developer console to my deveice.

The device is logged in with the test account not the developer account.

The Id that I use in my app is same as I had listed on console as per logcat message.

But, I am getting Item is not available for purchase.

Do not know what's wrong.

I know that this question has been asked on stack overflow before several times, and I have gone through each and every one of them, but none of the solutions seems to work for me so please do not close this issue as duplicate.

答:
I am also getting this error. For this 1st generate a new signed app with upgraded version and then follow these steps

open google play console

Go to Release Management->App Release

In beta track create a app http://prntscr.com/ntxgr5

If app is create on beta track then go to production but if u click on go to production, then u getting some error like draft is full for that u have to clear the draft

In app release top most track is production track click on edit release
in left of bottom a Discard button is present click on that and remove that app

After that go to beta track and go to production and conform it
after 15-20 minute your latest app will reflect on play-store


问:
Pytests on web.py application not covering methods code
First of all, sorry if the linguo is not 100% correct or something does not make 100% of sense, I am quite new into web aplication development and posting on stack overflow in general.

I have a web.py application and need to test its functionalities with pytest and generate a code coverage report with pytest-cov. I get the tests to work and assert on the responses, but when I generate the code report, all the lines of code inside the methods are uncovered and therefore get a really low test coverage (23%)

I am successfully running pytest --cov in my repository via cmd and getting the coverage result in it. But then I tried using coverage run -m pytest test_Server.py and running coverage report to get a bit more detail.

In this report is where I could see which lines of code I was missing, and I was missing all of them except the definition of each method/class.

Another thing I tried is pytest --cov=Server.py, which then gives me the error

```<code>Coverage.py warning: Module Server.py was never imported. (module-not-imported)
Coverage.py warning: No data was collected. (no-data-collected)
WARNING: Failed to generate report: No data to report.
</code>```

Server.py

```<code>import os

import web

URLS = ("/", "Index")

APP = web.application(URLS, globals())

class Index:
    """
    Just a test echo server.
    """

    def POST(self):
        web.header("Access-Control-Allow-Origin", "*")
        data = web.data()

        return data
</code>```

test_Server.py

```<code>
from paste.fixture import TestApp
import pytest
import os
import sys

sys.path.insert(1,(os.path.join(sys.path[0],'..'))) #adding parent path to import server script
import Server as lm
from Server import APP as app, Index

host = "localHost:9999"

class TestRig():
    def test_server_setup(self):
        middleware = []
        testApp = TestApp(app.wsgifunc(*middleware))
        try:
            r = testApp.post("http://%s/" %host)
            print ("request:", r.status)
            assert r.status ==  200

        except TypeError:
            print ("Request failed. Status:"+ r.status)
            raise

</code>```

This is a very simplifyed version of what I am currently running, and one way or another I manage to get the tests working and assert the responses correctly.

What I would expect is for the code inside the methods to be covered with the tests, but the actual output tells me only the definition of the method is covered and nothing else.

答:
Thanks to @hoefling I figured out two things:

When using Web.py, you need to use paste.fixture library to test the code, requests library WON'T cover your code even though you can assert and use get/post methods (here is why I got such a bad code coverage in the beginning).

When using pytest-cov (or coverage.py), make the call as such: pytest --cov=name_of_your_script_to_cover --cov-report=term-missing --cov-report=html to avoid the Failed to generate report: No data to report. error (and additionally get a nice HTML report to view your code coverage).

Body:
First of all, sorry if the linguo is not 100% correct or something does not make 100% of sense, I am quite new into web aplication development and posting on stack overflow in general.

I have a web.py application and need to test its functionalities with pytest and generate a code coverage report with pytest-cov. I get the tests to work and assert on the responses, but when I generate the code report, all the lines of code inside the methods are uncovered and therefore get a really low test coverage (23%)

I am successfully running pytest --cov in my repository via cmd and getting the coverage result in it. But then I tried using coverage run -m pytest test_Server.py and running coverage report to get a bit more detail.

In this report is where I could see which lines of code I was missing, and I was missing all of them except the definition of each method/class.

Another thing I tried is pytest --cov=Server.py, which then gives me the error

Coverage.py warning: Module Server.py was never imported. (module-not-imported)
Coverage.py warning: No data was collected. (no-data-collected)
WARNING: Failed to generate report: No data to report.

Server.py

import os

import web

URLS = ("/", "Index")

APP = web.application(URLS, globals())

class Index:
    """
    Just a test echo server.
    """

    def POST(self):
        web.header("Access-Control-Allow-Origin", "*")
        data = web.data()

        return data

test_Server.py

from paste.fixture import TestApp
import pytest
import os
import sys

sys.path.insert(1,(os.path.join(sys.path[0],'..'))) #adding parent path to import server script
import Server as lm
from Server import APP as app, Index

host = "localHost:9999"

class TestRig():
    def test_server_setup(self):
        middleware = []
        testApp = TestApp(app.wsgifunc(*middleware))
        try:
            r = testApp.post("http://%s/" %host)
            print ("request:", r.status)
            assert r.status ==  200

        except TypeError:
            print ("Request failed. Status:"+ r.status)
            raise

This is a very simplifyed version of what I am currently running, and one way or another I manage to get the tests working and assert the responses correctly.

What I would expect is for the code inside the methods to be covered with the tests, but the actual output tells me only the definition of the method is covered and nothing else.