问:
Angular: why does (change) event for checkbox only trigger after double click?
I have an Angular application with a checkbox list (mat-checkbox) that is properly displaying the English or Spanish values depending on locale.

Problem: However, the checkbox itself is not consistently being checked when the user clicks on it. It appears to require a double click. What could cause something like this?

I've tried:

I have looked into [checkex] and (change).

I have tried changing my
objects/class/interface.

I've looked through Angular documentation.

I've done console.log on everything I could find

I've looked through SO articles such as:
Mat-checkbox checked not changing checkbox state

component.html:

```<code><div class="student-history-checkbox" *ngFor="let item of gradesInCurrentLanguage()">
    <mat-checkbox [checked]="isChecked(item.ID)" (change)="onChangeCB($event, item.ID)">{{item.Value}}</mat-checkbox>
</div>
</code>```

component.ts:

```<code>public gradesInCurrentLanguage() : CGenericRecord[] {
    return this.ms.XFormForLocale(this.grades, this.localeId);
}

isChecked(ID : number)
{
    return (this.gradeInfo.Grades.indexOf(ID) > -1) ? true : false;
}

onChangeCB(event : any, id : number)
{
    if(event.checked && this.gradeInfo.Grades.indexOf(id) == -1){
        this.gradeInfo.Grades.push(id);
    }else{
        let index = this.gradeInfo.Grades.indexOf(id);
        this.gradeInfo.Grades.splice(index, 1);
    }
}
</code>```

interface.ts:

```<code>export class CGenericRecord
{
    constructor(
        public ID: number,
        public Value: string)
    {}
}
export interface GenericTranslationRecord {
    ID      :   number,
    Value   :   string,
    SpanishValue: string
}
</code>```

service.ts:

```<code>public XFormForLocale(grades: GenericTranslationRecord[], localeId: string) : CGenericRecord[] {
    let recs :CGenericRecord[] = [];
    for (let g of grades)
    {
        recs.push( new CGenericRecord(d.ID, localeId === "es" ? d.SpanishValue : d.Value));
    }
    return recs;
}
</code>```

Expected result: Checkbox should show that it is checked when the user clicks on it once. It should also show that it is unchecked after one click.

Actual result: Checkbox is only checked after multiple clicks

答:
The code above was resulting in an infinite loop. Instead of having the method in the ngFor, I made a variable in the typescript and set it = to the method. Then I used that variable in the HTML. It works now.

HTML:

```<code><div class="student-history-checkbox" *ngFor="let item of gradesInCurrentLanguageVar">
</code>```

TS:

```<code>this.gradesInCurrentLanguagevar = gradesInCurrentLanguage();
</code>```

Body:
I have an Angular application with a checkbox list (mat-checkbox) that is properly displaying the English or Spanish values depending on locale.

Problem: However, the checkbox itself is not consistently being checked when the user clicks on it. It appears to require a double click. What could cause something like this?

I've tried:

I have looked into [checkex] and (change).

I have tried changing my
objects/class/interface.

I've looked through Angular documentation.

I've done console.log on everything I could find

I've looked through SO articles such as:
Mat-checkbox checked not changing checkbox state

component.html:

    <mat-checkbox [checked]="isChecked(item.ID)" (change)="onChangeCB($event, item.ID)">{{item.Value}}</mat-checkbox>

component.ts:

public gradesInCurrentLanguage() : CGenericRecord[] {
    return this.ms.XFormForLocale(this.grades, this.localeId);
}

isChecked(ID : number)
{
    return (this.gradeInfo.Grades.indexOf(ID) > -1) ? true : false;
}

onChangeCB(event : any, id : number)
{
    if(event.checked && this.gradeInfo.Grades.indexOf(id) == -1){
        this.gradeInfo.Grades.push(id);
    }else{
        let index = this.gradeInfo.Grades.indexOf(id);
        this.gradeInfo.Grades.splice(index, 1);
    }
}

interface.ts:

export class CGenericRecord
{
    constructor(
        public ID: number,
        public Value: string)
    {}
}
export interface GenericTranslationRecord {
    ID      :   number,
    Value   :   string,
    SpanishValue: string
}

service.ts:

public XFormForLocale(grades: GenericTranslationRecord[], localeId: string) : CGenericRecord[] {
    let recs :CGenericRecord[] = [];
    for (let g of grades)
    {
        recs.push( new CGenericRecord(d.ID, localeId === "es" ? d.SpanishValue : d.Value));
    }
    return recs;
}

Expected result: Checkbox should show that it is checked when the user clicks on it once. It should also show that it is unchecked after one click.

Actual result: Checkbox is only checked after multiple clicks

Body:
The code above was resulting in an infinite loop. Instead of having the method in the ngFor, I made a variable in the typescript and set it = to the method. Then I used that variable in the HTML. It works now.

HTML:

<div class="student-history-checkbox" *ngFor="let item of gradesInCurrentLanguageVar">

TS:

this.gradesInCurrentLanguagevar = gradesInCurrentLanguage();


来源: stackexchange

问:
MSAL 3.x GetAuthorizationRequestUrlParameterBuilder returns wrong datatype
According to the reference for ConfidentialClientApplication.GetAuthorizationRequestUrl, the method

Computes the URL of the authorization request letting the user sign-in and consent to the application accessing specific scopes in the user's name. The URL targets the /authorize endpoint of the authority configured in the application.

So, I should be able to get the authorization request URL with the code like the following:

```<code>string[] graphScopes = { "Files.Read.All", "User.Read" };

ConfidentialClientApplicationBuilder clientBuilder = ConfidentialClientApplicationBuilder.Create(Settings.AzureADClientId);
ConfidentialClientApplication clientApp = (ConfidentialClientApplication)clientBuilder.Build();

var urlBuilder = clientApp.GetAuthorizationRequestUrl(graphScopes);
urlBuilder.WithRedirectUri(loginRedirectUri.ToString());
urlBuilder.WithAuthority(Settings.AzureADAuthority);
var authUrl = await urlBuilder.ExecuteAsync();
authUrl. ????
</code>```

But the GetAuthorizationRequestUrlParameterBuilder.ExecuteAsync() method returns an AuthorizationResult which is not a URL and has no property with a URL in it.

Can someone explain what I'm doing wrong, or explain how to actually get the authorization request URL?

答:
Apparently the method ExecuteAsync() that returns Uri is not the parameterless one:

```<code>public Task<Uri> ExecuteAsync(CancellationToken cancellationToken)
</code>```

So, maybe what you want to do is:

```<code>var authUrl = await urlBuilder.ExecuteAsync(System.Threading.CancellationToken.None);
</code>```

The bug got fixed on MSAL v4: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/msal-net-4

ContentLicense: CC BY-SA 4.0

Body:
According to the reference for ConfidentialClientApplication.GetAuthorizationRequestUrl, the method

Computes the URL of the authorization request letting the user sign-in and consent to the application accessing specific scopes in the user's name. The URL targets the /authorize endpoint of the authority configured in the application.

So, I should be able to get the authorization request URL with the code like the following:

string[] graphScopes = { "Files.Read.All", "User.Read" };

ConfidentialClientApplicationBuilder clientBuilder = ConfidentialClientApplicationBuilder.Create(Settings.AzureADClientId);
ConfidentialClientApplication clientApp = (ConfidentialClientApplication)clientBuilder.Build();

var urlBuilder = clientApp.GetAuthorizationRequestUrl(graphScopes);
urlBuilder.WithRedirectUri(loginRedirectUri.ToString());
urlBuilder.WithAuthority(Settings.AzureADAuthority);
var authUrl = await urlBuilder.ExecuteAsync();
authUrl. ????

But the GetAuthorizationRequestUrlParameterBuilder.ExecuteAsync() method returns an AuthorizationResult which is not a URL and has no property with a URL in it.

Can someone explain what I'm doing wrong, or explain how to actually get the authorization request URL?

Body:
Apparently the method ExecuteAsync() that returns Uri is not the parameterless one:

public Task<Uri> ExecuteAsync(CancellationToken cancellationToken)

So, maybe what you want to do is:

var authUrl = await urlBuilder.ExecuteAsync(System.Threading.CancellationToken.None);

The bug got fixed on MSAL v4: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/msal-net-4


问:
How to get function to run within if statement
I'm attempting to create a new WordPress plugin and have setup an Options page though am having some troubles making my Dropdown menu's selection trigger a function.

This is the function I'm calling in my options page.

I'm attempting to make it so when the value of the Dropdown menu is set to "2" to run the function to hide the Admin Toolbar.

When echoing out $wp_icon it shows either 1 or 2 is being passed.
However when 2 is selected it doesn't ever seem to run the function within the if statement but will call any other code.

```<code>function my_plugins_options() {

    if (isset($_POST['wp_icon'])) { $wp_icon = $_POST['wp_icon']; update_option('wp_icon', $wp_icon); }
    $wp_icon = get_option('wp_icon');

    include 'page.php';

    if ($wp_icon == 2) {
        function remove_toolbar_nodes($wp_admin_bar) { $wp_admin_bar->remove_node('wp-logo'); }
        add_action('admin_bar_menu', 'remove_toolbar_nodes', 999);
    }

}
</code>```

page.php

```<code><form method="POST">
    <label for="wp_icon">WordPress Icon</label>
    <select id="wp_icon" name="wp_icon">
        <option value="1" <?php selected( $wp_icon, 1 ); ?>>Show</option>
        <option value="2" <?php selected( $wp_icon, 2 ); ?>>Hide</option>
    </select>
    <input type="submit" value="Save" class="button button-primary button-large">
</form>
</code>```

The expected result is to have it so when setting the option to "Hide" it would pass the value 2 and then hide the WordPress Icon in the dashboard.

答:
You created a function but you haven't called it - used.

Check the code below if it is working as expected:

```<code><?php

//function definition
function remove_toolbar_nodes($wp_admin_bar)
{
    //just for debugiing - remove line below if success
    echo '<H1>remove_toolbar_nodes executed!</h1>';

    $wp_admin_bar->remove_node('wp-logo');
}

function my_plugins_options() {

    if (isset($_POST['wp_icon'])) { $wp_icon = $_POST['wp_icon']; update_option('wp_icon', $wp_icon); }
    $wp_icon = get_option('wp_icon');

    include 'page.php';

    if ($wp_icon == 2) {
        //function call - requires () after the name of function;
        remove_toolbar_nodes($wp_admin_bar);
        add_action('admin_bar_menu', 'remove_toolbar_nodes', 999);
    }

}
</code>```

you should see debug printed from the function:

remove_toolbar_nodes executed!

that you can remove of course :)

Body:
I'm attempting to create a new WordPress plugin and have setup an Options page though am having some troubles making my Dropdown menu's selection trigger a function.

This is the function I'm calling in my options page.

I'm attempting to make it so when the value of the Dropdown menu is set to "2" to run the function to hide the Admin Toolbar.

When echoing out $wp_icon it shows either 1 or 2 is being passed.
However when 2 is selected it doesn't ever seem to run the function within the if statement but will call any other code.

function my_plugins_options() {

    if (isset($_POST['wp_icon'])) { $wp_icon = $_POST['wp_icon']; update_option('wp_icon', $wp_icon); }
    $wp_icon = get_option('wp_icon');

    include 'page.php';

    if ($wp_icon == 2) {
        function remove_toolbar_nodes($wp_admin_bar) { $wp_admin_bar->remove_node('wp-logo'); }
        add_action('admin_bar_menu', 'remove_toolbar_nodes', 999);
    }

}

page.php

<form method="POST">
    WordPress Icon
    <select id="wp_icon" name="wp_icon">
        <option value="1" <?php selected( $wp_icon, 1 ); ?>>Show</option>
        <option value="2" <?php selected( $wp_icon, 2 ); ?>>Hide</option>
    </select>
    <input type="submit" value="Save" class="button button-primary button-large">
</form>

The expected result is to have it so when setting the option to "Hide" it would pass the value 2 and then hide the WordPress Icon in the dashboard.

Body:
You created a function but you haven't called it - used.

Check the code below if it is working as expected:

<?php

//function definition
function remove_toolbar_nodes($wp_admin_bar)
{
    //just for debugiing - remove line below if success
    echo '<H1>remove_toolbar_nodes executed!</h1>';

    $wp_admin_bar->remove_node('wp-logo');
}

function my_plugins_options() {

    if (isset($_POST['wp_icon'])) { $wp_icon = $_POST['wp_icon']; update_option('wp_icon', $wp_icon); }
    $wp_icon = get_option('wp_icon');

    include 'page.php';

    if ($wp_icon == 2) {
        //function call - requires () after the name of function;
        remove_toolbar_nodes($wp_admin_bar);
        add_action('admin_bar_menu', 'remove_toolbar_nodes', 999);
    }

}

you should see debug printed from the function:

remove_toolbar_nodes executed!

that you can remove of course :)


问:
Android, delete files in my data directory?
My application stores some files that are required for it to run in the data directory of the app

```<code>/data/data/com.example.myapp/files/filehere.file
</code>```

When my application is updated from the market, it is important that I clear the files in the data directory, and update them to the latest ones from the new package that has just been downloaded.

My question is, how do I programatically delete the files in the directory in question?

Alternatively, is there an alternative directory that I can store the files in that are persistent across the lifetime of my application version, but will be cleared once an update is installed?

答: You might be better off using a database wrapped in SQLiteOpenHelper. You can then use the onUpgrade function to detect a new app version.</p>

ContentLicense: CC BY-SA 3.0

Body:
My application stores some files that are required for it to run in the data directory of the app

/data/data/com.example.myapp/files/filehere.file

When my application is updated from the market, it is important that I clear the files in the data directory, and update them to the latest ones from the new package that has just been downloaded.

My question is, how do I programatically delete the files in the directory in question?

Alternatively, is there an alternative directory that I can store the files in that are persistent across the lifetime of my application version, but will be cleared once an update is installed?


问:
Graph database and javascript
I would like to implement a simple web application in apache(php or python) with an open source Graph database.

I would like also to query the "Graph database" using just javascript (client). It will be possible?

Which Graph database do you suggest me to use for this (the most simple)?

答: I would heavily recommend using ArangoDB. They offer an official and well supported JS driver and their query language (AQL) is both semantically more pleasant and productive than alternatives such as gremlin and Neo4J's Cypher. </p>

Title: Graph database and javascript


问:
Java: How to create new child class instance from abstract parent class?
Here is the gist of what I am trying to do:

```<code>abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}
</code>```

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.

答:
This would satisfy the requirements of your question:

```<code>public interface Animal<T> {

    List<T> makeFive();
}
</code>```

And then Dog and Cat would both implement Animal

```<code>public class Dog implements Animal<DogType> {

   public Dog(){
      super();
   }

   @Override
   public List<DogType> makeFive(){
     // do stuff;
   }

}

public class Cat implements Animal<CatType> {

   public Cat(){
      super();
   }

    @Override
   public List<CatType> makeFive(){
     // do stuff;
   }
}
</code>```

Alternatively, if you're using Java 8+ you can make an Animal an interface and define makeFive as a default method

```<code>public interface Animal<T> {
    List<T> makeFive();

}
</code>```

Body:
Here is the gist of what I am trying to do:

abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.

Body:
This would satisfy the requirements of your question:

public interface Animal<T> {

    List<T> makeFive();
}

And then Dog and Cat would both implement Animal

public class Dog implements Animal<DogType> {

   public Dog(){
      super();
   }

   @Override
   public List<DogType> makeFive(){
     // do stuff;
   }

}

public class Cat implements Animal<CatType> {

   public Cat(){
      super();
   }

    @Override
   public List<CatType> makeFive(){
     // do stuff;
   }
}

Alternatively, if you're using Java 8+ you can make an Animal an interface and define makeFive as a default method

public interface Animal<T> {
    List<T> makeFive();

}


问:
Add custom fields (like phone number) to react-stripe-elements
I'm getting pretty lost in the documentation about how to create custom fields like a phone number using react-stripe-elements. I've gotten a quick example running on collecting card info using the <CardElement> component, but I can't see anywhere how to add another input for a phone number to the data that will be tokenized.

I know I could just receive the token with the card info from the built-in fields and then pass that token plus the un-tokenized phone number to my server, but I'd like to have stripe tokenize all the data together if possible.

This examples page shows a number of forms collecting phone number, but the source code seems to mostly show how they're setting up the styling, and either way it's not using react-stripe-elements so the example doesn't mirror over like I'd like it to.

Edit: I found this github issue on their page that mentions implementing your own component to provide other supported parameters like name, adress_line1, etc. Looking at the token that gets returned, it appears that phone simply isn't a supported field, so I would just need to send that info to the server in an un-tokenized format. If that's just the way it needs to be done I'm totally fine with that. Just wanted to make sure I'm going about it with the right approach.

答:
Let's assume that you want to add a name field and tokenize it, at the same time you want to pass the card holder's name and another information, alongside  CardElement of react-stripe-elements, you need to create a form wrapping CardElement with some other inputs.

onSubmit event, you need to extract the form data and tokenize it using createToken function coming from react-stripe-elements as follows:

import React, { Component } from 'react';
import { CardElement, injectStripe } from 'react-stripe-elements';
class CheckoutForm extends Component {

    submit = async (ev) => {
        ev.preventDefault();
        const { currentTarget } = ev;
        const fD = new FormData(currentTarget);
        const cardInfo = {
          name: fD.get('name'),
        };
        let { token } = await this.props.stripe.createToken(
          { name: cardInfo.name, }
        );
        console.log(token)
        let response = await fetch(`YOUR_API_URL/charge`, {
          method: "POST",
          headers: { "Content-Type": "text/plain" },
          body: token.id
        });

        if (response.ok) console.log("Purchase Complete!")
      }

        render() {
        return (

Credit Card / Debit Card

            <form onSubmit={this.submit}>
              <input type='text' name='name' placeholder="Card Holder's Name" />

              <CardElement />
              <button type='submit'>Pay</button>
            </form>

        );
      }

export default injectStripe(CheckoutForm);```

Body:
Let's assume that you want to add a name field and tokenize it, at the same time you want to pass the card holder's name and another information, alongside  CardElement of react-stripe-elements, you need to create a form wrapping CardElement with some other inputs.

onSubmit event, you need to extract the form data and tokenize it using createToken function coming from react-stripe-elements as follows:

import React, { Component } from 'react';
import { CardElement, injectStripe } from 'react-stripe-elements';
class CheckoutForm extends Component {

    submit = async (ev) => {
        ev.preventDefault();
        const { currentTarget } = ev;
        const fD = new FormData(currentTarget);
        const cardInfo = {
          name: fD.get('name'),
        };
        let { token } = await this.props.stripe.createToken(
          { name: cardInfo.name, }
        );
        console.log(token)
        let response = await fetch(`YOUR_API_URL/charge`, {
          method: "POST",
          headers: { "Content-Type": "text/plain" },
          body: token.id
        });

        if (response.ok) console.log("Purchase Complete!")
      }

        render() {
        return (
          <div className="checkout">
            <p>Credit Card / Debit Card</p>

            <form onSubmit={this.submit}>
              <input type='text' name='name' placeholder="Card Holder's Name" />

              <CardElement />
              <button type='submit'>Pay</button>
            </form>

          </div>
        );
      }

export default injectStripe(CheckoutForm);


问:
Creating a table from a query in MySQL/PHP
I'm not sure this is possible, but the code I tried using first is:

```<code>mysql_query ("CREATE TABLE My_table as ( SELECT * FROM CPE LEFT JOIN Greenwich_j20 ON CPE.cust_index = Greenwich_j20.cust_index LEFT JOIN Liverpool_j20 ON CPE.cust_index = Liverpool_j20.cust_index)")
 or die ("this certainly didn't work\n");
</code>```

The query itself works fine, and the syntax for the table works fine, but the combination is what it really doesn't like.  Does it have a problem creating a table from a left join query?

答:
If there is any auto increment column in your existing tables that will be not remain auto_increment in the table to be created.

You could  try by selecting columns instead of * there should be an error of column Ambiguous.

Body:
I'm not sure this is possible, but the code I tried using first is:

mysql_query ("CREATE TABLE My_table as ( SELECT * FROM CPE LEFT JOIN Greenwich_j20 ON CPE.cust_index = Greenwich_j20.cust_index LEFT JOIN Liverpool_j20 ON CPE.cust_index = Liverpool_j20.cust_index)")
 or die ("this certainly didn't work\n");

The query itself works fine, and the syntax for the table works fine, but the combination is what it really doesn't like.  Does it have a problem creating a table from a left join query?


问:
Elegant way to translate set of weighted sums to python
Given a set of terms ||(p_i' - sum{w_ji*(R_j*p_i+v_j)})||^2, where ||...||^2 denotes the squared norm, I want to efficiently set up an array (or a list) in Python filled with these terms. p_i', p_i, v_j are three-dimensional vectors, and R_j is a 3x3 matrix.

I've already tried this but I don't know how to incorporate the sum over j.

```<code>new_points = r_mesh.points() # p', return Nx3 array
old_points = avg_mesh.points() # p
n_joints = 3
rv = np.arange(n_joints * 15) # R_j and v_j are stored in rv
weights = np.random.rand(n_joints, len(new_points)) # w

func = [[np.linalg.norm(
        new_points[i] - (weights[j, i] * ((np.array(rv[j * 15:j * 15 + 9]).reshape(3, 3) @ old_points[i]) + np.array(
            rv[j * 9 + 9: j * 9 + 12])))) for j in range(n_joints)] for i in range(len(new_points))]
</code>```

To make things clearer here is the original equation that I transformed into a non-linear function as to feed it to the Levenberg-Marquardt method.

EDIT: I'm sorry, before, there was a wrong image.

答:
The simplest ("auto pilot", no actual thinking required) method would be np.einsum:

```<code># set up example:
n_i, n_j = 20, 30

p = np.random.random((n_i, 3))
pp = np.random.random((n_i, 3))
R = np.random.random((n_j, 3, 3))
w = np.random.random((n_j, n_i))
v = np.random.random((n_j, 3))

# now just tell einsum which index is where and let it
# do its magic

# R_j p_i
Rp = np.einsum('jkl,il', R,p)
# by Einstein convention this will sum over l,
# so Rp has indices ijk

# w_ji (Rp_ij + v_j)
wRpv = np.einsum('ji,ijk->ik', w,Rp+v)
# pure Einstein convention would sum over i and j,
# we  override this by passing explicit output indices
# ik to keep i alive

# squared norm
d = pp - wRpv
result = np.einsum('ik,ik', d,d)
</code>```

Body:
Given a set of terms ||(p_i' - sum{w_ji*(R_j*p_i+v_j)})||^2, where ||...||^2 denotes the squared norm, I want to efficiently set up an array (or a list) in Python filled with these terms. p_i', p_i, v_j are three-dimensional vectors, and R_j is a 3x3 matrix.

I've already tried this but I don't know how to incorporate the sum over j.

new_points = r_mesh.points() # p', return Nx3 array
old_points = avg_mesh.points() # p
n_joints = 3
rv = np.arange(n_joints * 15) # R_j and v_j are stored in rv
weights = np.random.rand(n_joints, len(new_points)) # w

func = [[np.linalg.norm(
        new_points[i] - (weights[j, i] * ((np.array(rv[j * 15:j * 15 + 9]).reshape(3, 3) @ old_points[i]) + np.array(
            rv[j * 9 + 9: j * 9 + 12])))) for j in range(n_joints)] for i in range(len(new_points))]

To make things clearer here is the original equation that I transformed into a non-linear function as to feed it to the Levenberg-Marquardt method.

EDIT: I'm sorry, before, there was a wrong image.

Body:
The simplest ("auto pilot", no actual thinking required) method would be np.einsum:

# set up example:
n_i, n_j = 20, 30

p = np.random.random((n_i, 3))
pp = np.random.random((n_i, 3))
R = np.random.random((n_j, 3, 3))
w = np.random.random((n_j, n_i))
v = np.random.random((n_j, 3))

# now just tell einsum which index is where and let it
# do its magic

# R_j p_i
Rp = np.einsum('jkl,il', R,p)
# by Einstein convention this will sum over l,
# so Rp has indices ijk

# w_ji (Rp_ij + v_j)
wRpv = np.einsum('ji,ijk->ik', w,Rp+v)
# pure Einstein convention would sum over i and j,
# we  override this by passing explicit output indices
# ik to keep i alive

# squared norm
d = pp - wRpv
result = np.einsum('ik,ik', d,d)


问:
How to structure my API call, and where to put the key and query?
I am trying to structure my API call to the openweatherapi properly, just trying to create a simple weather app, where upon the user entering a city the forecast is rendered to the page. This is what I have so far, also trying to prevent the default action where the page refreshes when the button is pressed. I am using react.

```<code>class App extends Component {
  getWeatherData = (userInput, event) => {
    event.preventDefault();
    axios({
      url: "http://openweathermap.org/data/2.5/weather/",
      method: "GET",
      dataType: "json",
      data: {
        q: userInput,
        API_KEY: "d108038ec889cfe762230283abaa7c7b"
      }
    }).then(res => {
      console.log(res);
      this.setState({});
    });
  };
</code>```

./Form. js is as follows

```<code>class Form extends Component {
  render() {
    return (
      <div>
        <form onSubmit={(this.props.getWeather, e)}>
          <input type="text" name="city" placeholder="City..." />
          <input type="text" name="country" placeholder="Country" />
          <button>Get Weather</button>

        </form>
      </div>
    );
  }
}
</code>```

Error:

```<code>./src/Form.js
  Line 7:  'e' is not defined  no-undef
</code>```

答:
You can just move your form to your app class, passing up form data between components doenst work perfectly in react. </p>

```<code>class App extends Component {
  getWeatherData = (event) => {
    const userInput = {
             event.target.city.value,
             event.target.country.value
       }
    event.preventDefault();
    axios({
      url: "http://openweathermap.org/data/2.5/weather/",
      method: "GET",
      dataType: "json",
      data: {
        q: userInput,
        API_KEY: "d108038ec889cfe762230283abaa7c7b"
      }
    }).then(res => {
      console.log(res);
      this.setState({});
    });

  render() {
    return (
      <div>
        <form onSubmit={this.getWeatherData}>
          <input type="text" name="city" placeholder="City..." />
          <input type="text" name="country" placeholder="Country" />
          <button>Get Weather</button>

        </form>
      </div>
    );
  }
}
</code>```

<p>You also dont need to specify the userInput as a parameter you can set inside your function by accessing the values with the event keyword. </p>

Body:
I am trying to structure my API call to the openweatherapi properly, just trying to create a simple weather app, where upon the user entering a city the forecast is rendered to the page. This is what I have so far, also trying to prevent the default action where the page refreshes when the button is pressed. I am using react.

class App extends Component {
  getWeatherData = (userInput, event) => {
    event.preventDefault();
    axios({
      url: "http://openweathermap.org/data/2.5/weather/",
      method: "GET",
      dataType: "json",
      data: {
        q: userInput,
        API_KEY: "d108038ec889cfe762230283abaa7c7b"
      }
    }).then(res => {
      console.log(res);
      this.setState({});
    });
  };

./Form. js is as follows

class Form extends Component {
  render() {
    return (

        <form onSubmit={(this.props.getWeather, e)}>
          <input type="text" name="city" placeholder="City..." />
          <input type="text" name="country" placeholder="Country" />
          <button>Get Weather</button>

        </form>

    );
  }
}

Error:

./src/Form.js
  Line 7:  'e' is not defined  no-undef

Body:
You can just move your form to your app class, passing up form data between components doenst work perfectly in react.

class App extends Component {
  getWeatherData = (event) => {
    const userInput = {
             event.target.city.value,
             event.target.country.value
       }
    event.preventDefault();
    axios({
      url: "http://openweathermap.org/data/2.5/weather/",
      method: "GET",
      dataType: "json",
      data: {
        q: userInput,
        API_KEY: "d108038ec889cfe762230283abaa7c7b"
      }
    }).then(res => {
      console.log(res);
      this.setState({});
    });

  render() {
    return (
      <div>
        <form onSubmit={this.getWeatherData}>
          <input type="text" name="city" placeholder="City..." />
          <input type="text" name="country" placeholder="Country" />
          <button>Get Weather</button>

        </form>
      </div>
    );
  }
}

You also dont need to specify the userInput as a parameter you can set inside your function by accessing the values with the event keyword.


问:
How do I query for the size of the newest island in SQL Server?
I would like to query for the size of the last island in a 'gaps and islands' problem in SQL Server (Azure).

Say I have the following table:

```<code>ID date status
500 2019-05-15 1
528 2019-05-16 0
538 2019-05-17 0
550 2019-05-18 1
580 2019-05-19 0
590 2019-05-20 0
</code>```

ID is an identity column
date is a date column
status is 0 or 1.

I want to find out how many days that a status has been set to 0. In this case today is 2019-05-20.

How do I write a query to pull the count of the last status columns being 0 (ie 2)?

答:
Assuming that you want to count rows (rather than use date arithmetic), then a safe method is:

```<code>select count(*) as cnt
from t
where [date] > all (select [date] from t where status = 1);
</code>```

This should work even when there are no 1s.

Body:
I would like to query for the size of the last island in a 'gaps and islands' problem in SQL Server (Azure).

Say I have the following table:

ID date status
500 2019-05-15 1
528 2019-05-16 0
538 2019-05-17 0
550 2019-05-18 1
580 2019-05-19 0
590 2019-05-20 0

ID is an identity column
date is a date column
status is 0 or 1.

I want to find out how many days that a status has been set to 0. In this case today is 2019-05-20.

How do I write a query to pull the count of the last status columns being 0 (ie 2)?

Body:
Assuming that you want to count rows (rather than use date arithmetic), then a safe method is:

select count(*) as cnt
from t
where [date] > all (select [date] from t where status = 1);

This should work even when there are no 1s.


问:
Bootstrap column width adjustments
I am new to using Bootstrap. I tried adjusting a 3-coulmn row to fit, with the last column divided into another 3, but it overlaps and having difficulty in making it look right.

My cshtml for the 1st row:

```<code> <div class="row">
        <div class="col-md-4 col-sm-4">
            <strong>Last Name</strong> <span class="required">*</span>
            @Html.TextBoxFor(m => m.Patient_Lastname, new { @class = "text-primary", required = "required" })
        </div>
        <div class="col-md-4 col-sm-4">
            <strong>First Name</strong> <span class="required">*</span>
            @Html.TextBoxFor(m => m.Patient_Firstname, new { @class = "text-primary", required = "required" })
        </div>
       <div class="col-md-1 col-sm-1">
            <strong>birth</strong> <span class="required">*</span>
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1900, 119).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Year--", new { @class = "form-control", style = "width: 90px; height:30px;", required = "required" })
        </div>
        <div class="col-md-1 col-sm-1">
            <strong>Month</strong> <span class="required">*</span>
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Month--", new { @class = "form-control", style = "width: 90px; height:30px;", required = "required" })
        </div>
        <div class="col-md-2 col-sm-2">
            <strong>Day</strong> <span class="required">*</span>
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Day--", new { @class = "form-control", style = "width: 80px; height:30px;", required = "required" })
        </div>
    </div>
</code>```

The 2nd and 3rd row are straight forward with col-md-4

Could you help me fix this ?

TIA
Ron.

答: I think the problem is the input filled width is bigger than available try resizing it.</p>

Title: Bootstrap column width adjustments

Body:
I am new to using Bootstrap. I tried adjusting a 3-coulmn row to fit, with the last column divided into another 3, but it overlaps and having difficulty in making it look right.

My cshtml for the 1st row:

            Last Name *
            @Html.TextBoxFor(m => m.Patient_Lastname, new { @class = "text-primary", required = "required" })

            First Name *
            @Html.TextBoxFor(m => m.Patient_Firstname, new { @class = "text-primary", required = "required" })

            birth *
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1900, 119).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Year--", new { @class = "form-control", style = "width: 90px; height:30px;", required = "required" })

            Month *
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Month--", new { @class = "form-control", style = "width: 90px; height:30px;", required = "required" })

            Day *
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Day--", new { @class = "form-control", style = "width: 80px; height:30px;", required = "required" })

The 2nd and 3rd row are straight forward with col-md-4

Could you help me fix this ?

TIA
Ron.


问:
How to pass variable to dynamic SQL statement's SELECT list within a DB2 stored procedure?
I created DB2-400 stored procedure with a declared variables EFFDT Varchar(10). The value for this variable is supposed to be passed to a SQL statement within the same stored procedure.  The procedure compiles fine, but when I execute the procedure, I get

SQL-0206 error "Column or global variable @EFFDT not found".

Here is the code:

```<code>BEGIN
-- Variable used to replace effective in SQL below with 1st
-- day of current month as text in 'MM/DD/YYYY' format

DECLARE     EFFDT VARCHAR(10);

SET EFFDT = VARCHAR_FORMAT(MONTH(CURRENT DATE) || '/01/' || YEAR(CURRENT DATE),'MM/DD/YYYY') ;  -- First day of current month

    ...

--SQL STATEMENT
CREATE TABLE INFOMATICS.TEMP_CHGS_2_ADDS AS
  (SELECT FNAME, MI, LNAME, MAILING_ZIP,
          SPECLTY, SPECLTY_DESC, @EFFDT AS EFF_DATE
     FROM INFOMATICS.TEMP_CHGS) WITH DATA;

    ...
End;
</code>```

I expect to see

```<code>John M Smith 1111 GD General Dentist 05/01/2019
</code>```

答: It appears that @EFFDT is not defined either as a declare, or as a parameter. I see where you are declaring EFFDT though. Maybe try changing @EFFDT to EFFDT.

Body:
I created DB2-400 stored procedure with a declared variables EFFDT Varchar(10). The value for this variable is supposed to be passed to a SQL statement within the same stored procedure.  The procedure compiles fine, but when I execute the procedure, I get

SQL-0206 error "Column or global variable @EFFDT not found".

Here is the code:

BEGIN
-- Variable used to replace effective in SQL below with 1st
-- day of current month as text in 'MM/DD/YYYY' format

DECLARE     EFFDT VARCHAR(10);

SET EFFDT = VARCHAR_FORMAT(MONTH(CURRENT DATE) || '/01/' || YEAR(CURRENT DATE),'MM/DD/YYYY') ;  -- First day of current month

    ...

--SQL STATEMENT
CREATE TABLE INFOMATICS.TEMP_CHGS_2_ADDS AS
  (SELECT FNAME, MI, LNAME, MAILING_ZIP,
          SPECLTY, SPECLTY_DESC, @EFFDT AS EFF_DATE
     FROM INFOMATICS.TEMP_CHGS) WITH DATA;

    ...
End;

I expect to see

John M Smith 1111 GD General Dentist 05/01/2019


问:
How to Convert CSS Grid Template Columns to Rows Responsively
I am trying to display a 3 column layout on desktop and a single column layout on mobile using CSS Grid.

However, when I try the following a 3 column layout persists with a viewport smaller than 650px.

```<code>.page {
  display: grid;
  grid-template-columns: 33% 34% 33%
}

@media (max-width: 650px) {
  .page {
    grid-template-columns: 100%;
  }
}
</code>```

How do I transition between a 3 column wide layout to single column stacked layout responsively with CSS Grid?

答:
You can use repeat() for this and just set the columns to one frame for the media query.

```<code>.page {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

@media (max-width: 650px) {
  .page {
    grid-template-columns: 1fr;
  }
}
</code>```

Body:
I am trying to display a 3 column layout on desktop and a single column layout on mobile using CSS Grid.

However, when I try the following a 3 column layout persists with a viewport smaller than 650px.

.page {
  display: grid;
  grid-template-columns: 33% 34% 33%
}

@media (max-width: 650px) {
  .page {
    grid-template-columns: 100%;
  }
}

How do I transition between a 3 column wide layout to single column stacked layout responsively with CSS Grid?

Body:
You can use repeat() for this and just set the columns to one frame for the media query.

.page {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

@media (max-width: 650px) {
  .page {
    grid-template-columns: 1fr;
  }
}


问:
How to use WS-Discovery spec to discover ONVIF devices on a network in Java?
I am trying to discover ONVIF devices with some Java code. Specifically, I am trying to get their device service address (which is just their IP address I believe?), as the ONVIF Core Spec notes (in Section 4.3) that "A successful discovery provides the device service address. Once a client has the device service address it can receive detailed device information through the device service...". Ultimately getting this detailed information of the ONVIF devices on the network is my goal. In general I'm also looking for some guidance relating to using the ONVIF Spec.

I am still new to the web service world (and networking in general), so forgive me if I say anything dumb. However, I have put in a lot of effort into this myself: I have read a good deal of ONVIF Core Spec, ONVIF Application Programmer's Guide, and WS-Discovery Specification. If I may I'll just summarize what I know so you can tell me if I'm on the right track:

"Web Services" is the name of a standard technology using platform and language independent web service standards such as XML, SOAP, and WSDL over an IP Network. The basic idea is that we want to be able to call what are effectively methods/functions (a service) from any programming language.

A web service is typically hosted on a server; but in the ONVIF use case, the web service provider is the ONVIF device (eg, an IP Camera). Thus to interact with the device from any language we use web service operations / calls, as web service calls can be implemented in any language.

XML is the data description syntax (used because it's language agnostic; any language can parse it). SOAP is the communication protocol used to get SOAP-infused XML documents back and forth (basically, make our method calls). WSDL is used for describing the services (it's an XML based description of the web services' interface). I have downloaded the WSDL for device management here, and generated via WSDL compiler wsimport (provided by JDK) the Java classes from the WSDL to use in my code. But I understand that calling these methods will come after device discovery, correct?

ONVIF Devices are discovered according WS-Discovery specification. You send a Probe message, and devices that match the Probe's constraints send back a ProbeMatch message, as described on page 13 and 14 in ONVIF Application Programmers Guide

Here is where I begin to get confused. How exactly do I send this message in Java? The ONVIF Application Programmer's Guide provides some pseudocode on page 15, but I can't figure out how to implement it. Section 4.3.1 in that guide specifically is what I'm stuck on. I understand that the "scopes" and "types" are just constraints you can embed in a probe, but they are not required (as per page 5 of WS discovery spec). Since I want to discover all devices I figure I need no constraints to start, right?

So that guide also provides a sample SOAP Message on page 110 used for discovery. Removing the type declaration out of it (because I don't want that constraint), I understand that my SOAP Message to send would be (I believe?) this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<e:Envelope xmlns:e="http://www.w3.org/2003/05/soap-envelope"
 xmlns:w="http://schemas.xmlsoap.org/ws/2004/08/addressing"
 xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery"
 xmlns:dn="http://www.onvif.org/ver10/network/wsdl">
 <e:Header>
 <w:MessageID>uuid:84ede3de-7dec-11d0-c360-f01234567890</w:MessageID>
 <w:To e:mustUnderstand="true">urn:schemas-xmlsoap-org:ws:2005:04:discovery</w:To>
 <w:Action
a:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2005/04/discovery/Pr
obe</w:Action>
 </e:Header>
 <e:Body>
 <d:Probe>
 </d:Probe>
 </e:Body>
</e:Envelope>
</code>```

And I also understand the WS-Discovery technology used address 239.255.255.259 with UDP port 3702... but that's the end of what I get. How do I send that SOAP Message to that address and port in Java? How do I read the response (I think that I'll get back a ProbeMatch message, in the form of an SOAP-infused XML document, so I'll need to parse that XML to get the XAddrs, but not sure). Do I need to send a UDP broadcast of that SOAP message to that address somehow?

TL;DR: I believe to do ONVIF Device Discovery I need to send that SOAP message above to address 239.255.255.259 on UDP Port 3702. I have no clue how to do that in Java and was just looking for some guidance; I'm not even sure I'm on the right track to do device discovery.

答:
Using CXF WSDiscoveryClient you can probe ONVIF Device.

By default WSDiscoveryClient use WS-discovery 1.1 and ONVIF use WS-discovery 1.0, so you need to enable WS-discovery 1.0.

A short implementation could be :

```<code>import java.util.List;
import javax.xml.ws.EndpointReference;
import org.apache.cxf.ws.discovery.WSDiscoveryClient;

public class Main
{
    public static void main(String[] args)
    {
        WSDiscoveryClient client = new WSDiscoveryClient();
        client.setVersion10(); // use WS-discovery 1.0
        client.setDefaultProbeTimeout(1000); // timeout 1s

        System.out.println("Probe:" + client.getAddress());
        List<EndpointReference> references = client.probe();

        System.out.println("Nb answsers:" + references.size());
        for (EndpointReference ref : references)
        {
            System.out.println(ref.toString());
        }
    }
}
</code>```

Body:
I am trying to discover ONVIF devices with some Java code. Specifically, I am trying to get their device service address (which is just their IP address I believe?), as the ONVIF Core Spec notes (in Section 4.3) that "A successful discovery provides the device service address. Once a client has the device service address it can receive detailed device information through the device service...". Ultimately getting this detailed information of the ONVIF devices on the network is my goal. In general I'm also looking for some guidance relating to using the ONVIF Spec.

I am still new to the web service world (and networking in general), so forgive me if I say anything dumb. However, I have put in a lot of effort into this myself: I have read a good deal of ONVIF Core Spec, ONVIF Application Programmer's Guide, and WS-Discovery Specification. If I may I'll just summarize what I know so you can tell me if I'm on the right track:

"Web Services" is the name of a standard technology using platform and language independent web service standards such as XML, SOAP, and WSDL over an IP Network. The basic idea is that we want to be able to call what are effectively methods/functions (a service) from any programming language.

A web service is typically hosted on a server; but in the ONVIF use case, the web service provider is the ONVIF device (eg, an IP Camera). Thus to interact with the device from any language we use web service operations / calls, as web service calls can be implemented in any language.

XML is the data description syntax (used because it's language agnostic; any language can parse it). SOAP is the communication protocol used to get SOAP-infused XML documents back and forth (basically, make our method calls). WSDL is used for describing the services (it's an XML based description of the web services' interface). I have downloaded the WSDL for device management here, and generated via WSDL compiler wsimport (provided by JDK) the Java classes from the WSDL to use in my code. But I understand that calling these methods will come after device discovery, correct?

ONVIF Devices are discovered according WS-Discovery specification. You send a Probe message, and devices that match the Probe's constraints send back a ProbeMatch message, as described on page 13 and 14 in ONVIF Application Programmers Guide

Here is where I begin to get confused. How exactly do I send this message in Java? The ONVIF Application Programmer's Guide provides some pseudocode on page 15, but I can't figure out how to implement it. Section 4.3.1 in that guide specifically is what I'm stuck on. I understand that the "scopes" and "types" are just constraints you can embed in a probe, but they are not required (as per page 5 of WS discovery spec). Since I want to discover all devices I figure I need no constraints to start, right?

So that guide also provides a sample SOAP Message on page 110 used for discovery. Removing the type declaration out of it (because I don't want that constraint), I understand that my SOAP Message to send would be (I believe?) this:

<?xml version="1.0" encoding="UTF-8"?>
<e:Envelope xmlns:e="http://www.w3.org/2003/05/soap-envelope"
 xmlns:w="http://schemas.xmlsoap.org/ws/2004/08/addressing"
 xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery"
 xmlns:dn="http://www.onvif.org/ver10/network/wsdl">
 <e:Header>
 <w:MessageID>uuid:84ede3de-7dec-11d0-c360-f01234567890</w:MessageID>
 <w:To e:mustUnderstand="true">urn:schemas-xmlsoap-org:ws:2005:04:discovery</w:To>
 <w:Action
a:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2005/04/discovery/Pr
obe</w:Action>
 </e:Header>
 <e:Body>
 <d:Probe>
 </d:Probe>
 </e:Body>
</e:Envelope>

And I also understand the WS-Discovery technology used address 239.255.255.259 with UDP port 3702... but that's the end of what I get. How do I send that SOAP Message to that address and port in Java? How do I read the response (I think that I'll get back a ProbeMatch message, in the form of an SOAP-infused XML document, so I'll need to parse that XML to get the XAddrs, but not sure). Do I need to send a UDP broadcast of that SOAP message to that address somehow?

TL;DR: I believe to do ONVIF Device Discovery I need to send that SOAP message above to address 239.255.255.259 on UDP Port 3702. I have no clue how to do that in Java and was just looking for some guidance; I'm not even sure I'm on the right track to do device discovery.

Body:
Using CXF WSDiscoveryClient you can probe ONVIF Device.

By default WSDiscoveryClient use WS-discovery 1.1 and ONVIF use WS-discovery 1.0, so you need to enable WS-discovery 1.0.

A short implementation could be :

import java.util.List;
import javax.xml.ws.EndpointReference;
import org.apache.cxf.ws.discovery.WSDiscoveryClient;

public class Main
{
    public static void main(String[] args)
    {
        WSDiscoveryClient client = new WSDiscoveryClient();
        client.setVersion10(); // use WS-discovery 1.0
        client.setDefaultProbeTimeout(1000); // timeout 1s

        System.out.println("Probe:" + client.getAddress());
        List<EndpointReference> references = client.probe();

        System.out.println("Nb answsers:" + references.size());
        for (EndpointReference ref : references)
        {
            System.out.println(ref.toString());
        }
    }
}


问:
How to write a string algorithm
given a FASTA text file (Rosalind_gc.txt), I am supposed to go through each DNA record and identify the percentage (%) of Guanine-Cytosine (GC) content.

Example of this is :

Sample Dataset:

```<code>>Rosalind_6404
CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC
TCCCACTAATAATTCTGAGG
>Rosalind_5959
CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT
ATATCCATTTGTCAGCAGACACGC
>Rosalind_0808
CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC
TGGGAACCTGCGGGCAGTAGGTGGAAT
</code>```

Sample output:

Rosalind_0808
60.919540

So basically go through each string, count the amt of times G/C show up and then divide that total by the length of each string. My issue is learning how to identify the breaks in code (i.e. >Rosalind_6404 ). I would like an example of this code without using Biopython and also with the biopython approach.

答:
You could read the file line by line and accumulate sequence data up to the next line that starts with ">" (plus one more time for the end of the file)</p>

```<code>def getCount(seq):
    return seq.count("G")+seq.count("C")

with open("input.txt","r") as file:
    sequence = ""
    name     = ""
    for line in file:
        line = line.strip()
        if not line.startswith(">"):
            sequence += line
            continue
        if name != "":
            print(name, 100*getCount(sequence)/len(sequence))
        name     = line[1:]
        sequence = ""
    print(name, 100*getCount(sequence)/len(sequence))

# Rosalind_6404 53.75
# Rosalind_5959 53.57142857142857
# Rosalind_0808 60.91954022988506
</code>```

Title: How to write a string algorithm

Body:
given a FASTA text file (Rosalind_gc.txt), I am supposed to go through each DNA record and identify the percentage (%) of Guanine-Cytosine (GC) content.

Example of this is :

Sample Dataset:

>Rosalind_6404
CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC
TCCCACTAATAATTCTGAGG
>Rosalind_5959
CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT
ATATCCATTTGTCAGCAGACACGC
>Rosalind_0808
CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC
TGGGAACCTGCGGGCAGTAGGTGGAAT

Sample output:

Rosalind_0808
60.919540

So basically go through each string, count the amt of times G/C show up and then divide that total by the length of each string. My issue is learning how to identify the breaks in code (i.e. >Rosalind_6404 ). I would like an example of this code without using Biopython and also with the biopython approach.

Body:
You could read the file line by line and accumulate sequence data up to the next line that starts with ">" (plus one more time for the end of the file)

def getCount(seq):
    return seq.count("G")+seq.count("C")

with open("input.txt","r") as file:
    sequence = ""
    name     = ""
    for line in file:
        line = line.strip()
        if not line.startswith(">"):
            sequence += line
            continue
        if name != "":
            print(name, 100*getCount(sequence)/len(sequence))
        name     = line[1:]
        sequence = ""
    print(name, 100*getCount(sequence)/len(sequence))

# Rosalind_6404 53.75
# Rosalind_5959 53.57142857142857
# Rosalind_0808 60.91954022988506


问:
In TypeScript , how to use a class located in another file
I'm a little confused with typescript namespaces , modules . I need to solve a simple task - create two typescript files and use a class from one in another.
But , how do I get it working.

The structure :

```<code> installation :
          typescript :
                Person.ts
                main.ts
</code>```

The code of main.ts is

```<code>//Using this tag I am trying to load another file
/// <reference path = "Person.ts" />

var person:Person = new Person("Sergey" , "Sckoriy");
console.log(person.greet());
</code>```

The code of Person.ts is

```<code>export class Person {
    name : string;
    surname : string;

    constructor (name : string , surname : string){
        this.name = name;
        this.surname = surname;
    }

    greet():string {
        var text:string = "Hello" + this.name;
        return text;
    }
}
</code>```

But , when it's being compiled with

```<code>  ..../tsc main.ts
</code>```

there are errors such as :

```<code>main.ts:3:12 - error TS2304: Cannot find name 'Person'.
3 var person:Person = new Person("Sergey" , "Sckoriy");
main.ts:3:25 - error TS2552: Cannot find name 'Person'. Did you mean 'person'?
3 var person:Person = new Person("Sergey" , "Sckoriy");
main.ts:3:5
3 var person:Person = new Person("Sergey" , "Sckoriy");
      ~~~~~~
'person' is declared here.

 Found 2 errors.
</code>```

Actually , I have refered another file with the tag but it's not working...Whats wrong here?

答: import { Person } from './Person

Body:
I'm a little confused with typescript namespaces , modules . I need to solve a simple task - create two typescript files and use a class from one in another.
But , how do I get it working.

The structure :

 installation :
          typescript :
                Person.ts
                main.ts

The code of main.ts is

//Using this tag I am trying to load another file
/// <reference path = "Person.ts" />

var person:Person = new Person("Sergey" , "Sckoriy");
console.log(person.greet());

The code of Person.ts is

export class Person {
    name : string;
    surname : string;

    constructor (name : string , surname : string){
        this.name = name;
        this.surname = surname;
    }

    greet():string {
        var text:string = "Hello" + this.name;
        return text;
    }
}

But , when it's being compiled with

  ..../tsc main.ts

there are errors such as :

main.ts:3:12 - error TS2304: Cannot find name 'Person'.
3 var person:Person = new Person("Sergey" , "Sckoriy");
main.ts:3:25 - error TS2552: Cannot find name 'Person'. Did you mean 'person'?
3 var person:Person = new Person("Sergey" , "Sckoriy");
main.ts:3:5
3 var person:Person = new Person("Sergey" , "Sckoriy");
      ~~~~~~
'person' is declared here.

 Found 2 errors.

Actually , I have refered another file with the tag but it's not working...Whats wrong here?

Body: import { Person } from './Person


问:
Using FsCheck I get different results on tests, once 100% passed and the other time error
I created a generator to generate lists of int with the same lenght and to test the property of zip and unzip.
Running the test I get once in a while the error

Error: System.ArgumentException: list2 is 1 element shorter than list1

but it shouldn't happen because of my generator.

I got three times the test 100% passed and then the error above. Why?
It seems my generator is not working properly.

```<code>let samelength (x, y) =
    List.length x = List.length y

let arbMyGen2 = Arb.filter samelength Arb.from<int list * int list>

type MyGenZ =
    static member genZip() =
       {
        new Arbitrary<int list * int list>() with
            override x.Generator = arbMyGen2 |> Arb.toGen
            override x.Shrinker t = Seq.empty
    }

let _ = Arb.register<MyGenZ>()

let pro_zip (xs: int list, ys: int list) =
   (xs, ys) = List.unzip(List.zip xs ys)
   |> Prop.collect (List.length xs = List.length ys)

do Check.Quick pro_zip
</code>```

答:
Your code, as written, works for me. So I'm not sure what exactly is wrong, but I can give you a few helpful (hopefully!) hints.

In the first instance, try not using the registrating mechanism, but instead using Prop.forAll, as follows:

```<code>let pro_zip  =
   Prop.forAll arbMyGen2 (fun (xs,ys) ->
        (xs, ys) = List.unzip(List.zip xs ys)
        |> Prop.collect (List.length xs))

do Check.Quick pro_zip
</code>```

Note I've also changed your Prop.collect call to collect the length of the list(s), which gives somewhat more interesting output. In fact your property already checks that the lists are the same length (albeit implicitly) so the test will fail with a counterexample if they are not.

Arb.filter transforms an existing Arbitrary (i.e. generator and filter) to a new Arbitrary. In other words, arbMyGen2 has a shrinking function that'll work (i.e. only returns smaller pairs of lists that are of equal length), while in genZip() you throw the shrinker away. It would be fine to simply write

```<code>type MyGenZ =
    static member genZip() = arbMyGen2
</code>```

instead.

Body:
I created a generator to generate lists of int with the same lenght and to test the property of zip and unzip.
Running the test I get once in a while the error

Error: System.ArgumentException: list2 is 1 element shorter than list1

but it shouldn't happen because of my generator.

I got three times the test 100% passed and then the error above. Why?
It seems my generator is not working properly.

let samelength (x, y) =
    List.length x = List.length y

let arbMyGen2 = Arb.filter samelength Arb.from<int list * int list>

type MyGenZ =
    static member genZip() =
       {
        new Arbitrary<int list * int list>() with
            override x.Generator = arbMyGen2 |> Arb.toGen
            override x.Shrinker t = Seq.empty
    }

let _ = Arb.register<MyGenZ>()

let pro_zip (xs: int list, ys: int list) =
   (xs, ys) = List.unzip(List.zip xs ys)
   |> Prop.collect (List.length xs = List.length ys)

do Check.Quick pro_zip

Body:
Your code, as written, works for me. So I'm not sure what exactly is wrong, but I can give you a few helpful (hopefully!) hints.

In the first instance, try not using the registrating mechanism, but instead using Prop.forAll, as follows:

let pro_zip  =
   Prop.forAll arbMyGen2 (fun (xs,ys) ->
        (xs, ys) = List.unzip(List.zip xs ys)
        |> Prop.collect (List.length xs))

do Check.Quick pro_zip

Note I've also changed your Prop.collect call to collect the length of the list(s), which gives somewhat more interesting output. In fact your property already checks that the lists are the same length (albeit implicitly) so the test will fail with a counterexample if they are not.

Arb.filter transforms an existing Arbitrary (i.e. generator and filter) to a new Arbitrary. In other words, arbMyGen2 has a shrinking function that'll work (i.e. only returns smaller pairs of lists that are of equal length), while in genZip() you throw the shrinker away. It would be fine to simply write

type MyGenZ =
    static member genZip() = arbMyGen2

instead.


问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
My personal preference is that toString() should never be used for anything other than debugging.  If you want to produce a string for an object, provide a separate method that clearly documents your intent (getName(), getDescription(), etc).  Never rely on the implementation of a toString().

The problem is that many developers see toString() as a debug-level string and think nothing of changing it (say when new fields are added or removed).  Heck, some automated toString() builders use reflection to generate a toString() from the fields.

I've found this preference has served me well over the years.

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

OwnerDisplayName: Alex Miller


问:
Testing cache.manifest on an iPad with Apache Web Server 2
I am trying to build an offline web app for the iPad, and I am trying to verify that the cache.manifest is being served correctly by Apache Web Server 2, and is working. I have added an 'AddType' for the .manifest extension to the mime-types configuration file for the Apache web server.

If I look at the access logs, the first request to the cache-manifest is returned with a 200 HTTP response code, any further requests are served with 304, which is 'not modified'. I take this to mean it is working. The assets (html, images) are returned with a combination of both (200, then 304 as above) so indicates it is working.

When I load it on the iPad, I get the page, but when I go offline, and reload it is unable to load as it does not have a connection to the internet.

I am serving it off the Apache web server of my Mac, so having trouble reliably testing it with my Mac. Any ideas on what is going wrong, or how to verify it is working?

答:
Testing the cache manifest is somewhat of a pain in general, but there are a few useful techniques.

First, start with testing it using Safari on the Mac directly.  Just turn off Apache when you want to check it in offline mode.

In Safari, open the Activity monitor and look for any resources that are listed as "cancelled" -- those are typically ones that are missing from the manifest.

Also use the Web Inspector to check the response-type of the manifest file.

In most cases the problem is that you have resources in the application which aren't specified in the manifest; this causes the whole caching operation to fail.  Unfortunately there's no method in the HTML5 API to list which resources failed; this would be supremely helpful to developers.


问:
Is it possible to finish an Activity through data binding in the XML?
I have an ImageView (A back button) inside an activity and i want to finish the Activity by using data binding in the XML itself as such:

```<code><ImageView
        android:id="@id/ImageView_fromAddItemActivity_BackIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:onClick = "@{ finish()}"
        app:srcCompat="@drawable/ic_back_dark"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</code>```

But it doesn't work. Anyone has an idea whether this is possible ?

答:
For onClick() to work you need to use the following notation: android:onClick=@{() -> function()}.

What you could do is pass the Activity in the databinding as a variable, i.e.

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="activity"
            type="android.app.activity" />
    </data>
    <ConstraintLayout... /> <!-- UI layout's root element -->
</layout>
</code>```

then do activity.finish(). I wouldn't do it that way though since you are tightly coupling the context with the data binding. You could instead go through a viewmodel which you can bind, then do the finish() through it.

Body:
I have an ImageView (A back button) inside an activity and i want to finish the Activity by using data binding in the XML itself as such:

<ImageView
        android:id="@id/ImageView_fromAddItemActivity_BackIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:onClick = "@{ finish()}"
        app:srcCompat="@drawable/ic_back_dark"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

But it doesn't work. Anyone has an idea whether this is possible ?

Body:
For onClick() to work you need to use the following notation: android:onClick=@{() -> function()}.

What you could do is pass the Activity in the databinding as a variable, i.e.

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="activity"
            type="android.app.activity" />
    </data>
    <ConstraintLayout... /> <!-- UI layout's root element -->
</layout>

then do activity.finish(). I wouldn't do it that way though since you are tightly coupling the context with the data binding. You could instead go through a viewmodel which you can bind, then do the finish() through it.


问:
How to make C# application crash with an AccessViolationException
How to intentionally crash an application with an AccessViolationException in c#?

I have a console application that use an unmanaged DLL that eventually crashes because of access violation exceptions. Because of that, I need to intentionally throw an AccessViolationException to test how it behaves under certain circumstances.

Besides that, it must be specifically an AccessViolationException because this exception is not handled by the catch blocks.

Surprisingly, this does not work:

public static void Crash()
{
    throw new AccessViolationException();
}
```

<p>Neither this:</p>

```public static unsafe void Crash()
{
    for (int i = 1; true; i++)
    {
        var ptr = (int*)i;
        int value = *ptr;
    }
}
```

答:
This is the "native" way - although the @Storm approach is 100% deterministic. Trick is to attempt to write into memory far away from the current pointer. I.E. even though I allocated 4 bytes in my program, the next few thousand bytes are still within the part of memory reserved for my program. Shoot far away and you should get it.</p>

```<code>int[] array = new int[1];
fixed (int* ptr = array)
{
      ptr[2000000] = 42;
}
</code>```

Body:
How to intentionally crash an application with an AccessViolationException in c#?

I have a console application that use an unmanaged DLL that eventually crashes because of access violation exceptions. Because of that, I need to intentionally throw an AccessViolationException to test how it behaves under certain circumstances.

Besides that, it must be specifically an AccessViolationException because this exception is not handled by the catch blocks.

Surprisingly, this does not work:

public static void Crash()
{
    throw new AccessViolationException();
}

Neither this:

public static unsafe void Crash()
{
    for (int i = 1; true; i++)
    {
        var ptr = (int*)i;
        int value = *ptr;
    }
}

Body:
This is the "native" way - although the @Storm approach is 100% deterministic. Trick is to attempt to write into memory far away from the current pointer. I.E. even though I allocated 4 bytes in my program, the next few thousand bytes are still within the part of memory reserved for my program. Shoot far away and you should get it.

int[] array = new int[1];
fixed (int* ptr = array)
{
      ptr[2000000] = 42;
}


问:
How is the method Total being called in this example
I see in the code below how the list item's class and state is being modified but I don't understand where or how the total() method is being triggered. The total is added to the markup in the {{total() | currency}} but there is no click event or anything reactive that I see in the code that is bound to it.

```<code><template>

    <!-- v-cloak hides any un-compiled data bindings until the Vue instance is ready. -->
    <form id="main" v-cloak>

        <h1>Services</h1>

        <ul>
            <!-- Loop through the services array, assign a click handler, and set or
                remove the "active" css class if needed -->
            <li
                v-for="service in services"
                v-bind:key="service.id"
                v-on:click="toggleActive(service)"
                v-bind:class="{ 'active': service.active}">
                <!-- Display the name and price for every entry in the array .
                    Vue.js has a built in currency filter for formatting the price -->
                {{service.name}} <span>{{service.price | currency}}</span>
            </li>
        </ul>

        <div class="total">
            <!-- Calculate the total price of all chosen services. Format it as currency. -->
            Total: <span>{{total() | currency}}</span>
        </div>

    </form>
</template>

<script>
export default {
    name: 'OrderForm',
    data(){
        return{
        // Define the model properties. The view will loop
        // through the services array and genreate a li
        // element for every one of its items.
        services: [
            {
                name: 'Web Development',
                price: 300,
                active:true
            },{
                name: 'Design',
                price: 400,
                active:false
            },{
                name: 'Integration',
                price: 250,
                active:false
            },{
                name: 'Training',
                price: 220,
                active:false
            }
        ]
        }
    },
    // Functions we will be using.
    methods: {
        toggleActive: function(s){
            s.active = !s.active;
        },
        total: function(){

            var total = 0;

            this.services.forEach(function(s){
                if (s.active){
                    total+= s.price;
                }
            });

           return total;
        }
    },
    filters: {
        currency: function(value) {
            return '$' + value.toFixed(2);
        }
    }
}
</script>
</code>```

EDIT:

Working example
https://tutorialzine.com/2016/03/5-practical-examples-for-learning-vue-js

答:
So I believe the explanation for what is happening is that data's services object is reactive. Since the total method is being bound to it, when the toggleActive method is being called, it is updating services which causes the total method to also be called.

From the docs here 'How Changes Are Tracked' https://v2.vuejs.org/v2/guide/reactivity.html

Every component instance has a corresponding watcher instance, which records any properties “touched” during the component’s render as dependencies. Later on when a dependency’s setter is triggered, it notifies the watcher, which in turn causes the component to re-render.

Often I find simplifying what is going on helps me understand it. If you did a very simplified version of above it might look like this.

```<code><div id="app">
  <button @click="increment">Increment by 1</button>
  <p>{{total()}}</p>
</div>

new Vue({
  el: "#app",
  data: {
    counter: 0,
  },
  methods: {
   increment: function(){
     this.counter += 1;
   },
   total: function(){
    return this.counter;
   }
  }
})
</code>```

working example: https://jsfiddle.net/skribe/yq4moz2e/10/

If you simplify it even further by putting the data property counter in the template, when its value changes, you would naturally expect the value in the template to also be updated. So this should help you understand why the total method gets called.

```<code><div id="app">
  <button @click="increment">Increment by 1</button>
  <p>{{counter}}</p>
</div>

new Vue({
   el: "#app",
   data: {
    counter: 0,
   },
   methods: {
      increment: function(){
         this.counter += 1;
      },
   }
})
</code>```

working example:  https://jsfiddle.net/skribe/yq4moz2e/6/

Body:
I see in the code below how the list item's class and state is being modified but I don't understand where or how the total() method is being triggered. The total is added to the markup in the {{total() | currency}} but there is no click event or anything reactive that I see in the code that is bound to it.

<template>

    <form id="main" v-cloak>

Services

                {{service.name}} {{service.price | currency}}

            Total: {{total() | currency}}

    </form>
</template>

EDIT:

Working example
https://tutorialzine.com/2016/03/5-practical-examples-for-learning-vue-js

Body:
So I believe the explanation for what is happening is that data's services object is reactive. Since the total method is being bound to it, when the toggleActive method is being called, it is updating services which causes the total method to also be called.

From the docs here 'How Changes Are Tracked' https://v2.vuejs.org/v2/guide/reactivity.html

Every component instance has a corresponding watcher instance, which records any properties “touched” during the component’s render as dependencies. Later on when a dependency’s setter is triggered, it notifies the watcher, which in turn causes the component to re-render.

Often I find simplifying what is going on helps me understand it. If you did a very simplified version of above it might look like this.

<div id="app">
  <button @click="increment">Increment by 1</button>
  <p>{{total()}}</p>
</div>

new Vue({
  el: "#app",
  data: {
    counter: 0,
  },
  methods: {
   increment: function(){
     this.counter += 1;
   },
   total: function(){
    return this.counter;
   }
  }
})

working example: https://jsfiddle.net/skribe/yq4moz2e/10/

If you simplify it even further by putting the data property counter in the template, when its value changes, you would naturally expect the value in the template to also be updated. So this should help you understand why the total method gets called.

<div id="app">
  <button @click="increment">Increment by 1</button>
  <p>{{counter}}</p>
</div>

new Vue({
   el: "#app",
   data: {
    counter: 0,
   },
   methods: {
      increment: function(){
         this.counter += 1;
      },
   }
})

working example:  https://jsfiddle.net/skribe/yq4moz2e/6/


问:
Trouble to only move files and not directories
Trying to move files from logfile_directory to tmp_directory in blocks of 7 using random.sample.
If there are less than 7 files in the folder it will just move the remainder of the files. However when I try and move less that 7 files I get an error as the tmp_folder is trying to copy into itself.

Tried using glob.glob command but can't get that to work either. Not sure what I'm doing wrong to just move the files and not folder. Any help would be appreciated.

Running the same code on a different machine and getting the below message where as before the error message was related to copying the tmp_folder into itself. Nothing special about this file it's creating the error on so don't know why I'm now getting this.

Message=[WinError 5] Access is denied: 'c:\securelog_test\bdlog.txt'
  Source=C:\Users\jarra\source\repos\archive_test\archive_test.py
  StackTrace:
  File "\archive_test.py", line 72, in
    shutil.move(path, tmp_folder)

logfile_directory = 'c:\\securelog_test\\'
archive_folder = 'c:\\securelog_archive\\'
workfiles_folder = 'c:\\securelog_workfiles\\'
tmp_folder = 'c:\\securelog_test\\temp\\'
completed_folder = 'c:\\securelog_test\\completed\\'

#count how many files are in the log file folder
onlyfiles = [f for f in listdir(logfile_directory) if isfile(join(logfile_directory, f))]
print('-----------------')
print (len(onlyfiles))

if len(onlyfiles) > 7:
    #move 7 random files to the temp folder for archiving
    files = os.listdir(logfile_directory)
    for fileName in random.sample(files, min(len(files), 8)):
        path = os.path.join(logfile_directory, fileName)
        shutil.move(path, tmp_folder)
else:
    #if there are less than 7 files move them
    #for file in glob.glob(logfile_directory):
    #    shutil.move(file, tmp_folder)
    for fileName in os.listdir(logfile_directory):
        path = os.path.join(logfile_directory, fileName)
        shutil.move(path, tmp_folder)
```

答:
Well, seems that file existed in the destination folder and couldn't write over it. Not sure why so will look into that eventually.
In order to make my life a bit easier I put the temp and completed folders into their own root folders like below and this seems to work with out any issues. Feel this is cheating a bit and would love to try and figure this out but I need to move onto other elements of the program.

logfile_directory = 'c:\\securelog\\securelog_test\\'
archive_folder = 'c:\\securelog\\securelog_archive\\'
workfiles_folder = 'c:\\securelog\\securelog_workfiles\\'
tmp_folder = 'c:\\securelog\\temp\\'
completed_folder = 'c:\\securelog\\completed\\'
```


问:
docker build: Returned a non-zero code: 5
I wonna run this (https://github.com/thomashossler/synthetic-data-generator#config-file) project and I can't build the docker image.
I didn't find this error on stackoverflow so i hope you can help me

```<code>/synthetic-data-generator$ docker build . -f Dockerfile
Sending build context to Docker daemon  3.944MB
Step 1/11 : FROM python:3.6
 ---> 0668df180a32
Step 2/11 : RUN apt-get update &&     apt-get install -y
bzip2         git         git-core         libfontconfig1
libgconf-2-4         libglu1         libsm6         libxext6
libxrender1         vim         wget
 ---> Using cache
 ---> 0c92c577bdf4
Step 3/11 : WORKDIR /root/
 ---> Using cache
 ---> 2221c959662d
Step 4/11 : RUN wget -c --quiet
download.blender.org/release/Blender2.79/blender-2.79a-linux-
glibc219-x86_64.tar.bz2 &&     tar -xf blender-2.79a-linux-glibc219-
x86_64.tar.bz2 &&     rm blender-2.79a-linux-glibc219-x86_64.tar.bz2
&&     mv blender-2.79a-linux-glibc219-x86_64/ blender/ &&     cp -r
blender /usr/lib/blender &&     echo "export
PATH="/usr/lib/blender:$PATH"" >> /root/.bashrc
 ---> Running in 03a48a002fe6
The command '/bin/sh -c wget -c --quiet
download.blender.org/release/Blender2.79/blender-2.79a-linux-
glibc219-x86_64.tar.bz2 &&     tar -xf blender-2.79a-linux-glibc219-
x86_64.tar.bz2 &&     rm blender-2.79a-linux-glibc219-x86_64.tar.bz2
&&     mv blender-2.79a-linux-glibc219-x86_64/ blender/ &&     cp -r
blender /usr/lib/blender &&     echo "export
PATH="/usr/lib/blender:$PATH"" >> /root/.bashrc' returned a non-zero
code: 5
</code>```

my Dockerfile

```<code>FROM python:3.6

RUN apt-get update && \
    apt-get install -y \
        bzip2 \
        git \
        git-core \
        libfontconfig1 \
        libgconf-2-4 \
        libglu1 \
        libsm6 \
        libxext6 \
        libxrender1 \
        vim \
        wget

WORKDIR /root/
RUN wget -c --quiet
download.blender.org/release/Blender2.79/blender-2.79a-linux-
   glibc219-x86_64.tar.bz2 && \
tar -xf blender-2.79a-linux-glibc219-x86_64.tar.bz2 && \
rm blender-2.79a-linux-glibc219-x86_64.tar.bz2 && \
mv blender-2.79a-linux-glibc219-x86_64/ blender/ && \
cp -r blender /usr/lib/blender && \
echo "export PATH="/usr/lib/blender:$PATH"" >> /root/.bashrc

COPY /src/requirements.txt /root
RUN pip3 install -r /root/requirements.txt

RUN pip3 install --user
git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI

COPY models /root/models/
COPY src /root/
COPY deploy/config.json /root/

CMD ["python3", "dataset_creation.py"]
# ENTRYPOINT ["/root/entrypoint.sh"]
#EXPOSE 8889
#CMD ["jupyter notebook", "--ip=0.0.0.0", "--allow-root", "--port=8889"]
</code>```

Can anyone have similar experience and give me an solution. Very appreciated!

答:
It is most likely failing on the wget command.  That RUN line has 6 separate commands.  The other 5 would all likely produce some error message if they failed.  The wget has the --quiet flag passed which is suppressing output.

To debug further, try removing the --quiet flag from the wget.

From man wget, EXIT STATUS of 5 = SSL verification error.  Perhaps you are behind a corporate proxy and do not have the SSL certs installed in the container that is running the wget.

Body:
I wonna run this (https://github.com/thomashossler/synthetic-data-generator#config-file) project and I can't build the docker image.
I didn't find this error on stackoverflow so i hope you can help me

/synthetic-data-generator$ docker build . -f Dockerfile
Sending build context to Docker daemon  3.944MB
Step 1/11 : FROM python:3.6
 ---> 0668df180a32
Step 2/11 : RUN apt-get update &&     apt-get install -y
bzip2         git         git-core         libfontconfig1
libgconf-2-4         libglu1         libsm6         libxext6
libxrender1         vim         wget
 ---> Using cache
 ---> 0c92c577bdf4
Step 3/11 : WORKDIR /root/
 ---> Using cache
 ---> 2221c959662d
Step 4/11 : RUN wget -c --quiet
download.blender.org/release/Blender2.79/blender-2.79a-linux-
glibc219-x86_64.tar.bz2 &&     tar -xf blender-2.79a-linux-glibc219-
x86_64.tar.bz2 &&     rm blender-2.79a-linux-glibc219-x86_64.tar.bz2
&&     mv blender-2.79a-linux-glibc219-x86_64/ blender/ &&     cp -r
blender /usr/lib/blender &&     echo "export
PATH="/usr/lib/blender:$PATH"" >> /root/.bashrc
 ---> Running in 03a48a002fe6
The command '/bin/sh -c wget -c --quiet
download.blender.org/release/Blender2.79/blender-2.79a-linux-
glibc219-x86_64.tar.bz2 &&     tar -xf blender-2.79a-linux-glibc219-
x86_64.tar.bz2 &&     rm blender-2.79a-linux-glibc219-x86_64.tar.bz2
&&     mv blender-2.79a-linux-glibc219-x86_64/ blender/ &&     cp -r
blender /usr/lib/blender &&     echo "export
PATH="/usr/lib/blender:$PATH"" >> /root/.bashrc' returned a non-zero
code: 5

my Dockerfile

FROM python:3.6

RUN apt-get update && \
    apt-get install -y \
        bzip2 \
        git \
        git-core \
        libfontconfig1 \
        libgconf-2-4 \
        libglu1 \
        libsm6 \
        libxext6 \
        libxrender1 \
        vim \
        wget

WORKDIR /root/
RUN wget -c --quiet
download.blender.org/release/Blender2.79/blender-2.79a-linux-
   glibc219-x86_64.tar.bz2 && \
tar -xf blender-2.79a-linux-glibc219-x86_64.tar.bz2 && \
rm blender-2.79a-linux-glibc219-x86_64.tar.bz2 && \
mv blender-2.79a-linux-glibc219-x86_64/ blender/ && \
cp -r blender /usr/lib/blender && \
echo "export PATH="/usr/lib/blender:$PATH"" >> /root/.bashrc

COPY /src/requirements.txt /root
RUN pip3 install -r /root/requirements.txt

RUN pip3 install --user
git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI

COPY models /root/models/
COPY src /root/
COPY deploy/config.json /root/

CMD ["python3", "dataset_creation.py"]
# ENTRYPOINT ["/root/entrypoint.sh"]
#EXPOSE 8889
#CMD ["jupyter notebook", "--ip=0.0.0.0", "--allow-root", "--port=8889"]

Can anyone have similar experience and give me an solution. Very appreciated!


问:
TextBox: TextChanged Event - Autovalidating when x chars have been entered
I have an app that reads in a barcode from a USB scanner. I want to do a DB lookup as soon as the barcode is entered in a particular textbox.

Clearly, I'm going to put my code in the TextChanged  event handler, but I have a slight problem in that the barcode being read could be either 41 or 43 characters. The question is, how will I know which type of code is being entered. The scanner simply enters the code into whatever field has focus as a string of characters - as if it were entered by a keyboard - so I can't query the scanner to determine the code length.

I've thought of two approaches so far:

Detect first character, wait x.x seconds, and then do my lookup - allow enough time for a full code to be entered

Detect the 41st character, wait 0.x seconds and then do my lookup.

OK, I'm sure these will work OK, but are there any more eloquent solutions?

CONCLUSION:

Some useful suggestions, however Ondrej has inspired the simplest solution for my scenario. The 43 char codes have two characters that are fixed for all codes - the presence (or not) of these two characters means I know to wait if these two characters are present but only 41 characters are present.

I just need to confirm my suspicion that the 41 character codes can't have this pair of characters in this particular position - which I'm fairly sure is the case.

答:
I'd wrap the DB lookup call in a background worker class.

On the TextChanged event handler, the first thing I'd do is if the backgroundworker is working, I'd cancel it.  Then if the text length is 41 or 43, I'd process the DB call in the backgroundworker.

This way if the user hits 41 characters, the call happens, if they type in a 42nd character the call is cancelled, however if they type in 43, then delete two characters (to get back down to 41 characters) you'll still be doing the proper lookup.


问:
How to deny or invert the memory address
I'm doing some tasks and I need to solve the following problem:
I need to load with a descending table, this table starts at the value 0000 and ends with ffff, for example:

```<code>Addres    value
0000      ffff
0001      fffe
0002      fffd
....      ....
....      ....
ffff      0000
</code>```

My code:

```<code>mov ax,0000
mov bx,0000
not bx
mov ax,bx ; this is line 41
inc ax
dec bx
cmp ax,ffff
jne 41
int 3
</code>```

directly, this code does not work, does nothing. I don't have great knowledge in assembly and I can't detect the error.

答:
Successive addresses store a single byte that can hold values from 0 to 255. For the values from 0 to FFFFh that you want to store, you would need 131072 bytes (65536*2).
In 16-bit mode (real address mode) a memory segment can have 65536 bytes making your task a bit complicated!

```<code>    cld
    xor     di, di    ; Address 0000h
    mov     ax, FFFFh ; Value
More:
    stosw
    dec     ax
    js      More
</code>```

This will store 32768 descending word-values at offset addresses 0, 2, 4, 6, ... , 65534.

At this point you would have to change the ES segment register by adding 2048 to it.

Then continu with next code:

```<code>    ; DI=0 AX=7FFFh
More_:
    stosw
    dec     ax
    jnz      More_
</code>```

A byte solution is possible however:

```<code>    mov     bx, 0
    mov     al, 255
Next:
    mov     [bx], al
    inc     bx
    dec     al
    jnz     Next

    ; 0000  FF
    ; 0001  FE
    ; 0002  FD
    ;
    ; 00FE  01
    ; 00FF  00
</code>```

A byte solution using 1 register:

```<code>    xor     bx, bx
 ext:
    mov     [bx], bl
    not     byte ptr [bx]
    inc     bx
    test    bl, bl
    jnz     Next

    ; 0000  FF
    ; 0001  FE
    ; 0002  FD
    ;
    ; 00FE  01
    ; 00FF  00
</code>```

Body:
I'm doing some tasks and I need to solve the following problem:
I need to load with a descending table, this table starts at the value 0000 and ends with ffff, for example:

Addres    value
0000      ffff
0001      fffe
0002      fffd
....      ....
....      ....
ffff      0000

My code:

mov ax,0000
mov bx,0000
not bx
mov ax,bx ; this is line 41
inc ax
dec bx
cmp ax,ffff
jne 41
int 3

directly, this code does not work, does nothing. I don't have great knowledge in assembly and I can't detect the error.

Body:
Successive addresses store a single byte that can hold values from 0 to 255. For the values from 0 to FFFFh that you want to store, you would need 131072 bytes (65536*2).
In 16-bit mode (real address mode) a memory segment can have 65536 bytes making your task a bit complicated!

    cld
    xor     di, di    ; Address 0000h
    mov     ax, FFFFh ; Value
More:
    stosw
    dec     ax
    js      More

This will store 32768 descending word-values at offset addresses 0, 2, 4, 6, ... , 65534.

At this point you would have to change the ES segment register by adding 2048 to it.

Then continu with next code:

    ; DI=0 AX=7FFFh
More_:
    stosw
    dec     ax
    jnz      More_

A byte solution is possible however:

    mov     bx, 0
    mov     al, 255
Next:
    mov     [bx], al
    inc     bx
    dec     al
    jnz     Next

    ; 0000  FF
    ; 0001  FE
    ; 0002  FD
    ;
    ; 00FE  01
    ; 00FF  00

A byte solution using 1 register:

    xor     bx, bx
 ext:
    mov     [bx], bl
    not     byte ptr [bx]
    inc     bx
    test    bl, bl
    jnz     Next

    ; 0000  FF
    ; 0001  FE
    ; 0002  FD
    ;
    ; 00FE  01
    ; 00FF  00


问:
How to handle console input type validation in Go?
I'm trying to build a very basic console inputs for a program using a loop. However, when user inputs something else than an integer, the error message triggers as many times as there are characters in the input string (including newline).

I've tried Scan(), Scanln(), as well as bufio.NewReader() with string parsing, as well as using continue after Println(). All produce the same result.

```<code>var threads int

func main() {
    fmt.Println("Enter number of threads:")
    for {
        _, err := fmt.Scanln(&threads)
        if err != nil {
            fmt.Println("Enter a valid number")
        } else {
            break
        }
    }
}
</code>```

User inputs:

asd

Expected result:

Program: Enter a valid number

Actual result:

Program: Enter a valid number

Program: Enter a valid number

Program: Enter a valid number

Program: Enter a valid number

答:
fmt.Scanln(&threads) throws an error because your first char is already not a valid int, thus there are sd\n still remaining in stdin buffer, this would be my explanation for additional three errors. To avoid this you could just read to string and then use int, err := strconv.Atoi(string) like in code below. Note hereby that fmt.Scan or fmt.Scanln split your userinput until the next space, which is probably not perfect for your usecase. Check out How to read input from console line for some insight in how to choose suiting your usecase.

```<code>package main

import (
    "fmt"
    "strconv"
)

func main() {
    var s string
    var i int
    fmt.Println("Enter number of threads:")
    for {
        _, err := fmt.Scan(&s)
        i, err = strconv.Atoi(s)
        if err != nil {
            fmt.Println("Enter a valid number")
        } else {
            fmt.Println("Got: " + strconv.Itoa(i))
            break
        }
    }
    //Todo
}

</code>```

Body:
I'm trying to build a very basic console inputs for a program using a loop. However, when user inputs something else than an integer, the error message triggers as many times as there are characters in the input string (including newline).

I've tried Scan(), Scanln(), as well as bufio.NewReader() with string parsing, as well as using continue after Println(). All produce the same result.

var threads int

func main() {
    fmt.Println("Enter number of threads:")
    for {
        _, err := fmt.Scanln(&threads)
        if err != nil {
            fmt.Println("Enter a valid number")
        } else {
            break
        }
    }
}

User inputs:

asd

Expected result:

Program: Enter a valid number

Actual result:

Program: Enter a valid number

Program: Enter a valid number

Program: Enter a valid number

Program: Enter a valid number

Body:
fmt.Scanln(&threads) throws an error because your first char is already not a valid int, thus there are sd\n still remaining in stdin buffer, this would be my explanation for additional three errors. To avoid this you could just read to string and then use int, err := strconv.Atoi(string) like in code below. Note hereby that fmt.Scan or fmt.Scanln split your userinput until the next space, which is probably not perfect for your usecase. Check out How to read input from console line for some insight in how to choose suiting your usecase.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var s string
    var i int
    fmt.Println("Enter number of threads:")
    for {
        _, err := fmt.Scan(&s)
        i, err = strconv.Atoi(s)
        if err != nil {
            fmt.Println("Enter a valid number")
        } else {
            fmt.Println("Got: " + strconv.Itoa(i))
            break
        }
    }
    //Todo
}


问:
Prefill login form from link php
I have made a php login for my family's website private links.

Would it be possible to prefill the login details if I emailed a family member a link? Also, could I also have another link that automatically logs the user in?

I used to protect my family links with .htaccess/.htpasswd and it would be simple to do this with something like like this:

```<code>http://user:password@myfamilysite.com/family/protectedlinks/
</code>```

答:
In this case you need to use GET parameters. For example

http://myfamilysite.com/family/protectedlinks/?user=LONG_HASH&password=LONG_HASH

In PHP file receive this request, you just need Decrypt this Hash. You can login your family directly or pre fill all form, and his just need to click on submit function. The second alternative is more security, because you don't get directly your application.

In email you pass this link with pessoal access for members of your family.

Title: Prefill login form from link php

Body:
I have made a php login for my family's website private links.

Would it be possible to prefill the login details if I emailed a family member a link? Also, could I also have another link that automatically logs the user in?

I used to protect my family links with .htaccess/.htpasswd and it would be simple to do this with something like like this:

http://user:password@myfamilysite.com/family/protectedlinks/