答:
Python object variables are references.

The assignment operator in python does not work on the values themselves, but on those references.

a = [1,2] # creates object [1,2]
b = [3,4] # creates object [3,4]

# a now holds a reference to [1,2]
# b now holds a reference to [3,4]

c = a

# c now holds a reference to [1,2] as well

c = [5,6] # creates object [5,6]

# c now holds a reference to [5,6] and forgets about the [1,2].
# This does NOT change the [1,2] object.
```

<p>The same applies to your function call:</p>

<pre class="lang-py prettyprint-override"><code>def modify_dict(a_dict,a_key,a_value):
    # a_dict is a REFERENCE to whatever the argument of the function is

    a_dict = {a_key:a_value} # creates a new dict
    # a_dict now holds a reference to that NEW dict and forgets what it
    # was previously referencing.
    # This does not influence the object that was given as an argument
</code>```

I think the key concept to understand here is that arguments inside functions are references to objects, not the objects themselves.

To actually change the a_dict, you need do access it directly instead of assigning to it, like:

def modify_dict(a_dict,a_key,a_value):
    a_dict[a_key] = a_value
```

Body:
Python object variables are references.

The assignment operator in python does not work on the values themselves, but on those references.

a = [1,2] # creates object [1,2]
b = [3,4] # creates object [3,4]

# a now holds a reference to [1,2]
# b now holds a reference to [3,4]

c = a

# c now holds a reference to [1,2] as well

c = [5,6] # creates object [5,6]

# c now holds a reference to [5,6] and forgets about the [1,2].
# This does NOT change the [1,2] object.

The same applies to your function call:

def modify_dict(a_dict,a_key,a_value):
    # a_dict is a REFERENCE to whatever the argument of the function is

    a_dict = {a_key:a_value} # creates a new dict
    # a_dict now holds a reference to that NEW dict and forgets what it
    # was previously referencing.
    # This does not influence the object that was given as an argument

I think the key concept to understand here is that arguments inside functions are references to objects, not the objects themselves.

To actually change the a_dict, you need do access it directly instead of assigning to it, like:

def modify_dict(a_dict,a_key,a_value):
    a_dict[a_key] = a_value


来源: stackexchange

问:
Swift4: How to resolve "Fatal error: Can't form Range with upperBound < lowerBound"? (duration time delay in UI)
I try to close the menu animatedly using animation,
I decided to reduce the size of the UIScrollView on button press when size reduces up to my desired value, then I hide it.

to accomplish the task according to my desired user interface at some points, I had used the "time delay function" (300 milisec given)

everything goes well: if I don't press the button again and again until time limit reached

Error occurred: when i press button again and again before  with in 300 milisec

```<code>func disAppearBlanceMenu(){
    let x1 = btn_addBalance.clickableimg.frame.midX
    let y1 = btn_addBalance.clickableimg.frame.maxY

    UIView.animate(withDuration: 0.3) {
        self.BalanceMenu.scrollview.frame = CGRect(x: x1 - 150, y: y1 + 20, width: 200, height: 20)
    }
    time.delay(milliSec: 300) {
        self.BalanceMenu.triangle.isHidden = true
        self.BalanceMenu.scrollview.isHidden = true
        for i in 0...(self.BalanceMenuBtn.count - 1) {
            self.BalanceMenuBtn[i].imag.removeFromSuperview()
            self.BalanceMenuBtn[i].button.removeFromSuperview()
        }
        self.BalanceMenuBtn.removeAll()

    }
    displayBalanceMenu = true
}
</code>```

Where

```<code>class time {
    static func delay(milliSec:Int, code: @escaping () -> Void ) {
        let deadline = DispatchTime.now() + .milliseconds(milliSec)
        DispatchQueue.main.asyncAfter(deadline: deadline) {
            code()
        }
    }
}
</code>```

The error occurs here:

```<code>time.delay(milliSec: 300) {
</code>```

It says

'Thread 1: Fatal error: Can't form Range with upperBound < lowerBound'

答:
It looks like you want to do something when the animation is done. If so, use its completion parameter:

```<code>UIView.animate(withDuration: 0.3, animations: {
    self.BalanceMenu.scrollview.frame = CGRect(x: x1 - 150, y: y1 + 20, width: 200, height: 20)
}, completion: { _ in
    self.BalanceMenu.triangle.isHidden = true
    self.BalanceMenu.scrollview.isHidden = true
    for button in self.BalanceMenuBtn {
        button.imag.removeFromSuperview()
        button.button.removeFromSuperview()
    }
    self.BalanceMenuBtn.removeAll()
})
</code>```

It avoids timing problems introduced by that delay method. It also makes the intent more explicit.

Needless to say, once you get this immediate issue behind you, the properties BalanceMenu and BalanceMenuBtn should be renamed to start with lowercase letters, e.g., maybe balanceMenu and balanceMenuButtons, respectively. Also note the use of Buttons suffix rather than Btn, to make it clear it’s an array of buttons.

ContentLicense: CC BY-SA 4.0

Body:
I try to close the menu animatedly using animation,
I decided to reduce the size of the UIScrollView on button press when size reduces up to my desired value, then I hide it.

to accomplish the task according to my desired user interface at some points, I had used the "time delay function" (300 milisec given)

everything goes well: if I don't press the button again and again until time limit reached

Error occurred: when i press button again and again before  with in 300 milisec

func disAppearBlanceMenu(){
    let x1 = btn_addBalance.clickableimg.frame.midX
    let y1 = btn_addBalance.clickableimg.frame.maxY

    UIView.animate(withDuration: 0.3) {
        self.BalanceMenu.scrollview.frame = CGRect(x: x1 - 150, y: y1 + 20, width: 200, height: 20)
    }
    time.delay(milliSec: 300) {
        self.BalanceMenu.triangle.isHidden = true
        self.BalanceMenu.scrollview.isHidden = true
        for i in 0...(self.BalanceMenuBtn.count - 1) {
            self.BalanceMenuBtn[i].imag.removeFromSuperview()
            self.BalanceMenuBtn[i].button.removeFromSuperview()
        }
        self.BalanceMenuBtn.removeAll()

    }
    displayBalanceMenu = true
}

Where

class time {
    static func delay(milliSec:Int, code: @escaping () -> Void ) {
        let deadline = DispatchTime.now() + .milliseconds(milliSec)
        DispatchQueue.main.asyncAfter(deadline: deadline) {
            code()
        }
    }
}

The error occurs here:

time.delay(milliSec: 300) {

It says

'Thread 1: Fatal error: Can't form Range with upperBound < lowerBound'

Body:
It looks like you want to do something when the animation is done. If so, use its completion parameter:

UIView.animate(withDuration: 0.3, animations: {
    self.BalanceMenu.scrollview.frame = CGRect(x: x1 - 150, y: y1 + 20, width: 200, height: 20)
}, completion: { _ in
    self.BalanceMenu.triangle.isHidden = true
    self.BalanceMenu.scrollview.isHidden = true
    for button in self.BalanceMenuBtn {
        button.imag.removeFromSuperview()
        button.button.removeFromSuperview()
    }
    self.BalanceMenuBtn.removeAll()
})

It avoids timing problems introduced by that delay method. It also makes the intent more explicit.

Needless to say, once you get this immediate issue behind you, the properties BalanceMenu and BalanceMenuBtn should be renamed to start with lowercase letters, e.g., maybe balanceMenu and balanceMenuButtons, respectively. Also note the use of Buttons suffix rather than Btn, to make it clear it’s an array of buttons.


问:
Angular values are not reflecting in view
Angular values are not reflecting in view

HTML

```<code><div class="col-md-6 cardexpiry-block" [ngClass]="{'cardexpiry-block-remove':!!hasCardExpiryDate}"><!-- -->
    <div class="col-sm-6 text-left"><label for="CardExpiry">Card Expiry</label></div>
    <div class="col-md-3 text-left d-inline-flex"> <input name="hasCardExpiry" type="radio" (click)="hasCardExpiry(true)">
        Yes </div>
    <div class="col-md-3 text-left d-inline-flex"> <input name="hasCardExpiry" type="radio" (click)="hasCardExpiry(false)"
            checked> No</div>
    <my-date-picker *ngIf="!!hasCardExpiryDate" name="CardExpiry" [options]="myDatePickerOptions"
        formControlName="expiryDate"></my-date-picker>
</div>
</code>```

TS Code:

```<code>hasCardExpiryDate : boolean = false;

hasCardExpiry(falg){
    this.hasCardExpiryDate = falg;
}
</code>```

When I toggle between Yes and No, the values if "hasCardExpiryDate" is not changing
when i check-in HTML using  {{ hasCardExpiryDate | json }}

答:
Use *ngIf = hasCardExpiryDate  on specified div. It will show and hide the div for the corresponding value .

or
use *ngShow = !hasCardExpiryDate to show hide the div.

Body:
Angular values are not reflecting in view

HTML

Card Expiry

 <input name="hasCardExpiry" type="radio" (click)="hasCardExpiry(true)">
        Yes

 <input name="hasCardExpiry" type="radio" (click)="hasCardExpiry(false)"
            checked> No

    <my-date-picker *ngIf="!!hasCardExpiryDate" name="CardExpiry" [options]="myDatePickerOptions"
        formControlName="expiryDate"></my-date-picker>

TS Code:

hasCardExpiryDate : boolean = false;

hasCardExpiry(falg){
    this.hasCardExpiryDate = falg;
}

When I toggle between Yes and No, the values if "hasCardExpiryDate" is not changing
when i check-in HTML using  {{ hasCardExpiryDate | json }}


问:
Data not show in view using express.js + mysql + ejs + typeORM
I'm sorry if I have some stupid question, in my end, I'm a newbie in node.js, my probme is i'm failed to displaying data from entity in express.js framework, I'm using Mysql with TypeORM, and ejs template engine.

I have tried many examples, and below is one of them
https://github.com/typeorm/typescript-express-example
but seem's not work.

my editor is VSC, and below is my directory. directory

below is my codes

1 - the entity (MasterKategori.ts):

```<code>import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";

@Entity("mst_kategori")
export class MasterKategori {

    @PrimaryGeneratedColumn()
    public id: number;

    @Column("varchar")
    public KodeKategori: string;

    @Column("varchar")
    public NamaKategori: string;

    @Column("varchar")
    public Keterangan: string;

    @Column("timestamp")
    public AddDate: Date;

    @Column("datetime")
    public ModifiedDate: Date;

    @Column("int")
    public ModifiedUser: number;

    @Column("int")
    public AddUser: number;
}
</code>```

2 - index.ts

below is my index.ts, in this script I called the routes (routes.ts):

```<code>import dotenv from "dotenv";
import express from "express";
import path from "path";
import "reflect-metadata";
import {createConnection} from "typeorm";

import * as routes from "./routes";
createConnection().then(async (connection) => {
    dotenv.config();

    const port = process.env.SERVER_PORT;
    const app = express();

    app.set( "views", path.join( __dirname, "views" ) );
    app.set( "view engine", "ejs" );

    routes.web(app);

    app.listen(port);
    console.log(`Alhamdulillah, aplikasi ini menggunakan port ${port}!`);
}).catch((error) => console.log("TypeORM connection error: ", error));
</code>```

3 - routes.ts:

```<code>import * as express from "express";
import HomeController from "./controllers/HomeController";

export const web = ( app: express.Application ) => {
   // default homepage routes, and calling the controller
   app.get( "/", HomeController.home);
};
</code>```

4 - mycontroller (HomeController.ts), in this code I called the entity (MasterKategori.ts) and rendered to the view, I'm using ejs template engine

```<code>import * as express from "express";
import {getConnection} from "typeorm"; //calling typeORM
import {MasterKategori} from "../entity/MasterKategori"; //calling the Entity

class HomeController {
    public home = (request: express.Request, response: express.Response) => {
        const kategoriData = getConnection().getRepository(MasterKategori).find(); //get all data
        const kategori = Object.entries(kategoriData);
        response.render("page", {kat: kategori});
    }
}

export default new HomeController();
</code>```

5 - the view (page.ejs)

```<code><ul>
    <% kat.forEach(function(katdata){ %>
        <li><%= katdata.NamaKategori %> - <%= katdata.KodeKategori %></li>
    <% }) %>
</ul>
</code>```

and below is the mysql table and records:

```<code>select * from `mst_kategori`;

    id  KodeKategori  NamaKategori  Keterangan  AddDate              ModifiedDate         ModifiedUser  AddUser
------  ------------  ------------  ----------  -------------------  -------------------  ------------  ---------
     1  Coba          Coba          Coba        2019-05-25 09:21:00  0000-00-00 00:00:00             0          0
     2  lagi          lagi          lagi        2019-05-25 10:02:48  0000-00-00 00:00:00             0          0

</code>```

Unfortunately the result is given blank in the browser, and if I do 'console.log(kategori)' the return is '[]' (no data given).

I'm really appreciate for your any kind of help, I' getting headache for this problem in my end.

however I'm very newbie in node.js, this is will help me to start with ORM and MVC in express.js for my project

答:
it works Now, I put 'await', thank you very much, below is the update:</p>

```<code>import * as express from "express";
import {getConnection} from "typeorm";
import {MasterKategori} from "../entity/MasterKategori";

class HomeController {

    public home  = async (request: express.Request, response: express.Response) => {
        const kategoriData = await getConnection().getRepository(MasterKategori).find();
        const kategori = Object.entries(kategoriData);
        console.log(kategori);
        response.render("page", {kat: kategori});
    }
}

export default new HomeController();
</code>```

Body:
I'm sorry if I have some stupid question, in my end, I'm a newbie in node.js, my probme is i'm failed to displaying data from entity in express.js framework, I'm using Mysql with TypeORM, and ejs template engine.

I have tried many examples, and below is one of them
https://github.com/typeorm/typescript-express-example
but seem's not work.

my editor is VSC, and below is my directory. directory

below is my codes

1 - the entity (MasterKategori.ts):

import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";

@Entity("mst_kategori")
export class MasterKategori {

    @PrimaryGeneratedColumn()
    public id: number;

    @Column("varchar")
    public KodeKategori: string;

    @Column("varchar")
    public NamaKategori: string;

    @Column("varchar")
    public Keterangan: string;

    @Column("timestamp")
    public AddDate: Date;

    @Column("datetime")
    public ModifiedDate: Date;

    @Column("int")
    public ModifiedUser: number;

    @Column("int")
    public AddUser: number;
}

2 - index.ts

below is my index.ts, in this script I called the routes (routes.ts):

import dotenv from "dotenv";
import express from "express";
import path from "path";
import "reflect-metadata";
import {createConnection} from "typeorm";

import * as routes from "./routes";
createConnection().then(async (connection) => {
    dotenv.config();

    const port = process.env.SERVER_PORT;
    const app = express();

    app.set( "views", path.join( __dirname, "views" ) );
    app.set( "view engine", "ejs" );

    routes.web(app);

    app.listen(port);
    console.log(`Alhamdulillah, aplikasi ini menggunakan port ${port}!`);
}).catch((error) => console.log("TypeORM connection error: ", error));

3 - routes.ts:

import * as express from "express";
import HomeController from "./controllers/HomeController";

export const web = ( app: express.Application ) => {
   // default homepage routes, and calling the controller
   app.get( "/", HomeController.home);
};

4 - mycontroller (HomeController.ts), in this code I called the entity (MasterKategori.ts) and rendered to the view, I'm using ejs template engine

import * as express from "express";
import {getConnection} from "typeorm"; //calling typeORM
import {MasterKategori} from "../entity/MasterKategori"; //calling the Entity

class HomeController {
    public home = (request: express.Request, response: express.Response) => {
        const kategoriData = getConnection().getRepository(MasterKategori).find(); //get all data
        const kategori = Object.entries(kategoriData);
        response.render("page", {kat: kategori});
    }
}

export default new HomeController();

5 - the view (page.ejs)

    <% kat.forEach(function(katdata){ %>

<%= katdata.NamaKategori %> - <%= katdata.KodeKategori %>

    <% }) %>

and below is the mysql table and records:

select * from `mst_kategori`;

    id  KodeKategori  NamaKategori  Keterangan  AddDate              ModifiedDate         ModifiedUser  AddUser
------  ------------  ------------  ----------  -------------------  -------------------  ------------  ---------
     1  Coba          Coba          Coba        2019-05-25 09:21:00  0000-00-00 00:00:00             0          0
     2  lagi          lagi          lagi        2019-05-25 10:02:48  0000-00-00 00:00:00             0          0

Unfortunately the result is given blank in the browser, and if I do 'console.log(kategori)' the return is '[]' (no data given).

I'm really appreciate for your any kind of help, I' getting headache for this problem in my end.

however I'm very newbie in node.js, this is will help me to start with ORM and MVC in express.js for my project

Body:
it works Now, I put 'await', thank you very much, below is the update:

import * as express from "express";
import {getConnection} from "typeorm";
import {MasterKategori} from "../entity/MasterKategori";

class HomeController {

    public home  = async (request: express.Request, response: express.Response) => {
        const kategoriData = await getConnection().getRepository(MasterKategori).find();
        const kategori = Object.entries(kategoriData);
        console.log(kategori);
        response.render("page", {kat: kategori});
    }
}

export default new HomeController();


问:
How to create binary search tree from strings?
I have the following task: create a binary search tree from strings, and after that print them in alphabetical order.
As example,

```<code>orange
melon
apple
grapes
plum
banana
</code>```

should have

```<code>apple
banana
grapes
melon
orange
plum
</code>```

as output. I wrote a solution, but I have a problem: only the last string in input is printed (in this example, it's banana), and I can't find the mistake in my code.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
    char *data;
    struct Node *left;
    struct Node *right;
} Node;
Node* getFreeNode(char *value) {
    Node* tmp = (Node*)malloc(sizeof(Node));
    tmp->left = tmp->right = NULL;
    tmp->data = value;
    return tmp;
}
void insert(Node **head, char *value) {
    Node* tmp = (Node*)malloc(sizeof(Node));
    tmp = *head;
    if (*head  == NULL) {
        *head = getFreeNode(value);
        return;
    }
    else{
        if (strcmp(value, tmp->data) > 0) {
            return insert(&(tmp->right), value);
        }
        else if (strcmp(value, tmp->data) < 0) {
            return insert(&(tmp->left), value);
        }
    }
}
void print_tree(Node *t)
{
    if (!t) return;
    print_tree(t->left);
    printf("%s\n", t->data);
    print_tree(t->right);
}
int main(){
    Node* a = NULL;
    FILE *in = fopen("input.txt", "r");
    freopen("output.txt", "w", stdout);
    char word[20];
    while (fscanf(in, "%s", word) == 1){
        insert(&a, word);
    }
    print_tree(a);
    return 0;
}
</code>```

答:
In main, your code is inserting word, which is a local stack variable. Hence, the data member of every node is pointing to the same address.   After you insert the memory address of word into the tree, you overwrite word with the next line of your file.  Again, the end effect is that thedata member of ever node is pointing to the same string - the last string read in.

You need to make a copy of the string before inserting it into the tree.  Modify your getFreeNode function as follows:

```<code>Node* getFreeNode(char *value) {
    Node* tmp = (Node*)malloc(sizeof(Node));
    tmp->left = tmp->right = NULL;
    // tmp->data = value;
    tmp->data = strdup(value); // make a copy of the string for the new node
    return tmp;
}
</code>```

strdup makes a copy of the string. You can use it by including #include <strings.h> at the top of your source file. Otherwise, it's identical to this:

```<code>tmp->data = malloc(strlen(value) + 1);
strcpy(tmp->data, value);
</code>```

As the comments section in the original question suggests, this might not be your only bug.

Body:
I have the following task: create a binary search tree from strings, and after that print them in alphabetical order.
As example,

orange
melon
apple
grapes
plum
banana

should have

apple
banana
grapes
melon
orange
plum

as output. I wrote a solution, but I have a problem: only the last string in input is printed (in this example, it's banana), and I can't find the mistake in my code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
    char *data;
    struct Node *left;
    struct Node *right;
} Node;
Node* getFreeNode(char *value) {
    Node* tmp = (Node*)malloc(sizeof(Node));
    tmp->left = tmp->right = NULL;
    tmp->data = value;
    return tmp;
}
void insert(Node **head, char *value) {
    Node* tmp = (Node*)malloc(sizeof(Node));
    tmp = *head;
    if (*head  == NULL) {
        *head = getFreeNode(value);
        return;
    }
    else{
        if (strcmp(value, tmp->data) > 0) {
            return insert(&(tmp->right), value);
        }
        else if (strcmp(value, tmp->data) < 0) {
            return insert(&(tmp->left), value);
        }
    }
}
void print_tree(Node *t)
{
    if (!t) return;
    print_tree(t->left);
    printf("%s\n", t->data);
    print_tree(t->right);
}
int main(){
    Node* a = NULL;
    FILE *in = fopen("input.txt", "r");
    freopen("output.txt", "w", stdout);
    char word[20];
    while (fscanf(in, "%s", word) == 1){
        insert(&a, word);
    }
    print_tree(a);
    return 0;
}

Body:
In main, your code is inserting word, which is a local stack variable. Hence, the data member of every node is pointing to the same address.   After you insert the memory address of word into the tree, you overwrite word with the next line of your file.  Again, the end effect is that thedata member of ever node is pointing to the same string - the last string read in.

You need to make a copy of the string before inserting it into the tree.  Modify your getFreeNode function as follows:

Node* getFreeNode(char *value) {
    Node* tmp = (Node*)malloc(sizeof(Node));
    tmp->left = tmp->right = NULL;
    // tmp->data = value;
    tmp->data = strdup(value); // make a copy of the string for the new node
    return tmp;
}

strdup makes a copy of the string. You can use it by including #include <strings.h> at the top of your source file. Otherwise, it's identical to this:

tmp->data = malloc(strlen(value) + 1);
strcpy(tmp->data, value);

As the comments section in the original question suggests, this might not be your only bug.


问:
How can i navigate from a screen inside a DrawerNavigator to an other one inside the same DrawerNavigator
When my user update his email adress (inside ChangeMail screen)  i would like to redirect him to the first screen of the DrawerNavigator: 'Exercices'

I don't understand hos this.props.navigation works in this case.

```<code>
const drawerNavigator = createDrawerNavigator({
    Exercices: {
        screen: stackNavigator
    },
    ResetPassword: {
        screen: ResetPassword
    },
    ChangeMail: {
        screen: ChangeMail
    },
    DeleteAccount: {
        screen: DeleteAccount
    },
    Disconnect: {
        screen: ExitScreen
    }
})

</code>```

//inside the ChangeMail screen
changeEmail = (currentPassword, newEmail) => {
        this.reauthenticate(currentPassword).then(() => {
            var user = firebase.auth().currentUser;
            user.updateEmail(newEmail).then(() => {
                console.log("Email updated!");
            }).catch((error) => { console.log(error); });
        }).catch((error) => { console.log(error); }).then(() => {
            updateDatabaseEmail(newEmail)
        }).then(() => this.props.navigation.navigate("Exercice"))
          //not working

    }

```

答:
Your route name is Exercices but you are navigating to Exercice

```<code>this.props.navigation.navigate("Exercices")
</code>```

Body:
When my user update his email adress (inside ChangeMail screen)  i would like to redirect him to the first screen of the DrawerNavigator: 'Exercices'

I don't understand hos this.props.navigation works in this case.

const drawerNavigator = createDrawerNavigator({
    Exercices: {
        screen: stackNavigator
    },
    ResetPassword: {
        screen: ResetPassword
    },
    ChangeMail: {
        screen: ChangeMail
    },
    DeleteAccount: {
        screen: DeleteAccount
    },
    Disconnect: {
        screen: ExitScreen
    }
})

//inside the ChangeMail screen
changeEmail = (currentPassword, newEmail) => {
        this.reauthenticate(currentPassword).then(() => {
            var user = firebase.auth().currentUser;
            user.updateEmail(newEmail).then(() => {
                console.log("Email updated!");
            }).catch((error) => { console.log(error); });
        }).catch((error) => { console.log(error); }).then(() => {
            updateDatabaseEmail(newEmail)
        }).then(() => this.props.navigation.navigate("Exercice"))
          //not working

    }

Body:
Your route name is Exercices but you are navigating to Exercice

this.props.navigation.navigate("Exercices")


问:
AAPT: error: unexpected element <uses-permission> found in <manifest><application>
I am trying to create an android app for watchduino2.. When i follow the provided steps  i encounter the error

AAPT: error: unexpected element <uses-permission> found in <manifest><application>

Can somebody explain this problem? And also help me to resolve it as well.

答:
<uses-permission> needs to be a child of the root <manifest> element. You have it as a child of the <application> element. So, move the <uses-permission> element.

So, you have something like:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.whatever">
    <application android:icon="@drawable/icon"
                 android:debuggable="true"
                 android:label="@string/app_name">
        <uses-permission android:name="android.permission.INTERNET"/>
      <!-- other stuff here -->
    </application>
</manifest>
</code>```

It needs to be more like:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.whatever">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application android:icon="@drawable/icon"
                 android:debuggable="true"
                 android:label="@string/app_name">
      <!-- other stuff here -->
    </application>
</manifest>
</code>```

Body:
<uses-permission> needs to be a child of the root <manifest> element. You have it as a child of the <application> element. So, move the <uses-permission> element.

So, you have something like:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.whatever">
    <application android:icon="@drawable/icon"
                 android:debuggable="true"
                 android:label="@string/app_name">
        <uses-permission android:name="android.permission.INTERNET"/>
      <!-- other stuff here -->
    </application>
</manifest>

It needs to be more like:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.whatever">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application android:icon="@drawable/icon"
                 android:debuggable="true"
                 android:label="@string/app_name">
      <!-- other stuff here -->
    </application>
</manifest>


问:
Understand super() in diamond inheritance
I am learning python and started learning MRO in inheritance.

I have read the use of super and the way it can be used however I cannot place my understanding for below question. If it was not super I know B is called. D->B->C->A but when super gets added, I don't know why the output is like this

```<code>class A:
    def test(self):
        print("test of A called")
class B(A):
    def test(self):
        print("test of B called")
        super().test()
class C(A):
    def test(self):
        print("test of C called")
        super().test()
class D(B, C):
    def test2(self):
        print("test of D called")
obj=D()
obj.test()
</code>```

Output

```<code>test of B called
test of C called
test of A called
</code>```

Please help me understand how super is functioning here.

答:
super() will go to the next class in the method resolution order for which Python follows C3 linerization (https://en.wikipedia.org/wiki/C3_linearization): Children are called before their parents and multiple parents are called in the order in which they are set.

So if you invoke a method in class D, the MRO is D -> B -> C -> A, but e.g. if you originally invoke it in class B, the MRO is B -> A.

Does that make it clearer?

Edit: so in your example:
You call D.test() which does not exist, so it gets delegated to B.test() which prints a string and then invokes super(). Due to the MRO as described above, B's super() in this case is C, so C.test() is called next, which then finally invokes A.test().

Body:
I am learning python and started learning MRO in inheritance.

I have read the use of super and the way it can be used however I cannot place my understanding for below question. If it was not super I know B is called. D->B->C->A but when super gets added, I don't know why the output is like this

class A:
    def test(self):
        print("test of A called")
class B(A):
    def test(self):
        print("test of B called")
        super().test()
class C(A):
    def test(self):
        print("test of C called")
        super().test()
class D(B, C):
    def test2(self):
        print("test of D called")
obj=D()
obj.test()

Output

test of B called
test of C called
test of A called

Please help me understand how super is functioning here.


问:
Aurelia I18N: Scan html sources for new keys and update translation.json files
Is there any tool to scan aurelia project sources (html, js) files and create (update) keys in translation.json files?

Especially I want to collect keys from HTML files that use TBindingBehavior and TValueConverter translation style.

答:
Disclaimer: The packages suggested, are developed by my employer company.

Following are main steps involved in this process.

Generating i18n keys for the html templates, using gulp-i18n-update-localization-ids

Extract keys and values to an external resource, using gulp-i18n-extract

Manually translate the values for different languages

Compile the translations to generate locale files for different language, using gulp-i18n-compile2

Following are the minimalistic gulp tasks

```<code>const gulp = require("gulp");
const path = require("path");
const updateLocalizationIds = require('gulp-i18n-update-localization-ids');
const i18nExtract = require('gulp-i18n-extract');
const i18nCompile = require('gulp-i18n-compile2');

const src = path.resolve(__dirname, "src"),
    json = path.resolve(src, "*.r.json"),
    html = path.resolve(src, "*.html"),
    translations = path.resolve(__dirname, "translations/i18n.json"),
    locales = path.resolve(__dirname, "locales"),
    i18nGlobalPrefixes = new Map();

const generateI18nKeys = function () {
    return gulp.src(html)
        .pipe(updateLocalizationIds({
            emit: 'onChangeOnly',
            ignore: [{ content: v => v.startsWith('${') && v.endsWith('}') }],
            idTemplate: updateLocalizationIds.prefixFilename(i18nGlobalPrefixes),
            whitelist: [
                { tagName: 'h2' },
                {
                    tagName: 'another-custom-el',
                    attrs: ['some-other-value1', 'some-other-value2']
                }
            ]
        }))
        .pipe(gulp.dest(src));
}

const i18nExtractOptions = {
    plugIns: [
        new i18nExtract.html(),
        new i18nExtract.json()
    ],
    markUpdates: true,
    defaultLanguages: ['de', "fr"] // add more language here as per your need
};

const extractI18n = function () {
    return gulp.src([html, json])
        .pipe(i18nExtract.extract(translations, i18nExtractOptions))
        .pipe(gulp.dest("."));
}

const compileOptions = {
    fileName: "translation.json",
    defaultLanguage: "en"
};

const compileI18n = function () {
    return gulp.src(translations)
        .pipe(i18nCompile(compileOptions))
        .pipe(gulp.dest(locales));
}

gulp.task("i18n", gulp.series(generateI18nKeys, extractI18n, compileI18n));
</code>```

What's happening here?

Let us assume that you have all the html files under src directory. You can also have some plain json files under src that act as external resources. Though it is not really needed, in this example, I have used the extension *.r.json for that (r indicates resource).

The first task generateI18nKeys generates i18n keys for the html templates. For example, it transforms the following edit.html
...

some text

<another-custom-el some-other-value1="value1" some-other-value2="value2"></another-custom-el>
```

<p>... to the following</p>

<pre class="lang-html prettyprint-override"><code><!--edit.html-->
<h2 t="edit.t0">some text</h2>
<another-custom-el some-other-value1="value1" some-other-value2="value2"
  t="[some-other-value1]edit.t1;[some-other-value2]edit.t2"></another-custom-el>
</code>```

Use the whitelist property in the config option for this task, to mark elements and attributes for the key generation target.

In the next step, the keys and the corresponding values are extracted to a json file which looks like as follows.

```<code>{
  "edit": {
    "content": {
      "edit.t0": {
        "content": "some text",
        "lastModified": "2019-05-26T16:23:42.306Z",
        "needsUpdate": true,
        "translations": {
          "de": {
            "content": "",
            "lastModified": ""
          },
          "fr": {
            "content": "",
            "lastModified": ""
          }
        }
      },
      "edit.t1": {
        "content": "value1",
        "lastModified": "2019-05-26T16:23:42.306Z",
        "needsUpdate": true,
        "translations": {
          "de": {
            "content": "",
            "lastModified": ""
          },
          "fr": {
            "content": "",
            "lastModified": ""
          }
        }
      },
      "edit.t2": {
        "content": "value2",
        "lastModified": "2019-05-26T16:23:42.306Z",
        "needsUpdate": true,
        "translations": {
          "de": {
            "content": "",
            "lastModified": ""
          },
          "fr": {
            "content": "",
            "lastModified": ""
          }
        }
      }
    },
    "src": "src\\edit.html"
  }
}
</code>```

Note that empty contents are generated for the localeIds, specified in the task. You can manually change this file to add translations for every language, configured.

Lastly, the compileI18n task generates files for every language from the last json, that looks something like below.

```<code>{
  "edit": {
    "t0": "some text",
    "t1": "value1",
    "t2": "value2"
  }
}
</code>```

Note that this file can directly be consumed by the aurelia-i18n plugin. For more details check the package specific documentation.

Hope this helps.

Body:
Disclaimer: The packages suggested, are developed by my employer company.

Following are main steps involved in this process.

Generating i18n keys for the html templates, using gulp-i18n-update-localization-ids

Extract keys and values to an external resource, using gulp-i18n-extract

Manually translate the values for different languages

Compile the translations to generate locale files for different language, using gulp-i18n-compile2

Following are the minimalistic gulp tasks

const gulp = require("gulp");
const path = require("path");
const updateLocalizationIds = require('gulp-i18n-update-localization-ids');
const i18nExtract = require('gulp-i18n-extract');
const i18nCompile = require('gulp-i18n-compile2');

const src = path.resolve(__dirname, "src"),
    json = path.resolve(src, "*.r.json"),
    html = path.resolve(src, "*.html"),
    translations = path.resolve(__dirname, "translations/i18n.json"),
    locales = path.resolve(__dirname, "locales"),
    i18nGlobalPrefixes = new Map();

const generateI18nKeys = function () {
    return gulp.src(html)
        .pipe(updateLocalizationIds({
            emit: 'onChangeOnly',
            ignore: [{ content: v => v.startsWith('${') && v.endsWith('}') }],
            idTemplate: updateLocalizationIds.prefixFilename(i18nGlobalPrefixes),
            whitelist: [
                { tagName: 'h2' },
                {
                    tagName: 'another-custom-el',
                    attrs: ['some-other-value1', 'some-other-value2']
                }
            ]
        }))
        .pipe(gulp.dest(src));
}

const i18nExtractOptions = {
    plugIns: [
        new i18nExtract.html(),
        new i18nExtract.json()
    ],
    markUpdates: true,
    defaultLanguages: ['de', "fr"] // add more language here as per your need
};

const extractI18n = function () {
    return gulp.src([html, json])
        .pipe(i18nExtract.extract(translations, i18nExtractOptions))
        .pipe(gulp.dest("."));
}

const compileOptions = {
    fileName: "translation.json",
    defaultLanguage: "en"
};

const compileI18n = function () {
    return gulp.src(translations)
        .pipe(i18nCompile(compileOptions))
        .pipe(gulp.dest(locales));
}

gulp.task("i18n", gulp.series(generateI18nKeys, extractI18n, compileI18n));

What's happening here?

Let us assume that you have all the html files under src directory. You can also have some plain json files under src that act as external resources. Though it is not really needed, in this example, I have used the extension *.r.json for that (r indicates resource).

The first task generateI18nKeys generates i18n keys for the html templates. For example, it transforms the following edit.html
...

<!--edit.html-->
<h2>some text</h2>
<another-custom-el some-other-value1="value1" some-other-value2="value2"></another-custom-el>

... to the following

<!--edit.html-->
<h2 t="edit.t0">some text</h2>
<another-custom-el some-other-value1="value1" some-other-value2="value2"
  t="[some-other-value1]edit.t1;[some-other-value2]edit.t2"></another-custom-el>

Use the whitelist property in the config option for this task, to mark elements and attributes for the key generation target.

In the next step, the keys and the corresponding values are extracted to a json file which looks like as follows.

{
  "edit": {
    "content": {
      "edit.t0": {
        "content": "some text",
        "lastModified": "2019-05-26T16:23:42.306Z",
        "needsUpdate": true,
        "translations": {
          "de": {
            "content": "",
            "lastModified": ""
          },
          "fr": {
            "content": "",
            "lastModified": ""
          }
        }
      },
      "edit.t1": {
        "content": "value1",
        "lastModified": "2019-05-26T16:23:42.306Z",
        "needsUpdate": true,
        "translations": {
          "de": {
            "content": "",
            "lastModified": ""
          },
          "fr": {
            "content": "",
            "lastModified": ""
          }
        }
      },
      "edit.t2": {
        "content": "value2",
        "lastModified": "2019-05-26T16:23:42.306Z",
        "needsUpdate": true,
        "translations": {
          "de": {
            "content": "",
            "lastModified": ""
          },
          "fr": {
            "content": "",
            "lastModified": ""
          }
        }
      }
    },
    "src": "src\\edit.html"
  }
}

Note that empty contents are generated for the localeIds, specified in the task. You can manually change this file to add translations for every language, configured.

Lastly, the compileI18n task generates files for every language from the last json, that looks something like below.

{
  "edit": {
    "t0": "some text",
    "t1": "value1",
    "t2": "value2"
  }
}

Note that this file can directly be consumed by the aurelia-i18n plugin. For more details check the package specific documentation.

Hope this helps.


问:
Android :: DRM for video content
did not want to revive an old thread.
OMA DRM v1 & v2 support on Android

we are trying to implement a DRM solution for video content for both streaming and offline. And have searched both high and low, these where are the few which repeats itself every time.

http://www.irdeto.com/documents/HL_CW_OMA_DRM_Android_EN_H.pdf

http://www.discretix.com/Android_Security.html

http://www.haihaisoft.com/customize_android_media_player.aspx

http://www.authentec.com/a/Production/Home.aspx

we are targeting phones & tabs
so android 3.0 can be helpful, went through the sdk docs, still couldn't make out how to use them.

also read somewhere android 2.4 (for phones) will support the DRM framework, in the meantime the market we are targeting may not upgrade to android 2.4 so soon. this requires us to find some custom implementation.

have been hitting the wall on all sides. please give your invaluable insights.
if i have missed something very obvious, correct me as well.

答:
Security through obscurity.  It's the only way that DRM can work on a device owned by someone else.  Obsfucate your code and require updates to the latest version, which changes every week.

It's like putting a lock on a box, then putting the key in the lock, and hoping that no one finds the lock and key.  The solution is to change the location of the lock and key every few days, so that the vast majority of users can't be bothered to find it themselves or even to get the latest "crack".

ContentLicense: CC BY-SA 3.0

Title: Android :: DRM for video content


问:
Cannot add foreign key with WordPress wp_posts table
I'm trying to add a new table which has a relation with {wp_posts} table, This code is working properly in localhost and it passes all tests but it failed on server database and generates [Cannot add foreign key constraint].

The [post_id] field is exactly like {wp_posts->ID} field .. I don't know what I missed.

```<code>global $wpdb;
$charset_collate = $wpdb->collate;

$tbl_my_users = $wpdb->prefix . '_TABLE_NAME';

dbDelta( "CREATE TABLE IF NOT EXISTS {$tbl_my_users} (
            user_id BIGINT(20) UNSIGNED NOT NULL,
            post_id BIGINT(20) UNSIGNED NOT NULL,
            name VARCHAR(150) NOT NULL,
            email TINYTEXT NULL,
            INDEX (name),
            PRIMARY KEY  (user_id),
            CONSTRAINT Constr_Unique_UserID UNIQUE( user_id ),
            CONSTRAINT Constr_Unique_PostID UNIQUE( post_id ),
            CONSTRAINT Constr_Unique_User UNIQUE( name ),
            CONSTRAINT Constr_My_Users
                FOREIGN KEY FK_My_Users (post_id) REFERENCES {$wpdb->posts} (ID) ON DELETE CASCADE ON UPDATE CASCADE
        ) COLLATE {$charset_collate}" );
</code>```

答:
old question but i face this problem now.

the issue is when we want to set relation we need to match the column type, collation and the engine.

wp_posts ID : bigint(20) UNSIGNED

your table post_id: bigint(20) UNSIGNED

this is match, but you have problem with ENGINE.

example : the old table is written as innodb but your MYSQL default engine is set as MYISAM. so you without define ENGINE type, you will create MYISAM table instead InnoDB which not support relationship/foreign key. Note: old mysql version using MYISAM as default engine, not InnoDB

In my problem:

wp_posts ID: bigint(20) UNSIGNED InnoDB

my table post_id: bigint(20) InnoDB

the engine and type is match, but i got the eror. Because i forgot to set attribute UNSIGNED. when i set the same attribute, all works perfectly.

Note: don't forget about collation when using string type like varchar, char, etc

i hope this will help others.

Body:
I'm trying to add a new table which has a relation with {wp_posts} table, This code is working properly in localhost and it passes all tests but it failed on server database and generates [Cannot add foreign key constraint].

The [post_id] field is exactly like {wp_posts->ID} field .. I don't know what I missed.

global $wpdb;
$charset_collate = $wpdb->collate;

$tbl_my_users = $wpdb->prefix . '_TABLE_NAME';

dbDelta( "CREATE TABLE IF NOT EXISTS {$tbl_my_users} (
            user_id BIGINT(20) UNSIGNED NOT NULL,
            post_id BIGINT(20) UNSIGNED NOT NULL,
            name VARCHAR(150) NOT NULL,
            email TINYTEXT NULL,
            INDEX (name),
            PRIMARY KEY  (user_id),
            CONSTRAINT Constr_Unique_UserID UNIQUE( user_id ),
            CONSTRAINT Constr_Unique_PostID UNIQUE( post_id ),
            CONSTRAINT Constr_Unique_User UNIQUE( name ),
            CONSTRAINT Constr_My_Users
                FOREIGN KEY FK_My_Users (post_id) REFERENCES {$wpdb->posts} (ID) ON DELETE CASCADE ON UPDATE CASCADE
        ) COLLATE {$charset_collate}" );


答:
it might be about misplaced tag, make sure your manifest elements are nested correctly

Previous versions of AAPT would simply ignore the misplaced tag. However, with AAPT2, you will get error

read below official document for proper Manifest structure :

Manifest File Structure

Body:
I am trying to create an android app for watchduino2.. When i follow the provided steps  i encounter the error

AAPT: error: unexpected element <uses-permission> found in <manifest><application>

Can somebody explain this problem? And also help me to resolve it as well.


问:
Logic error with moving all files in a folder
I am writing two simple scripts, one to move all files into a folder, and one to move all files back to said folder. I am not getting any errors, but the files aren't moving so I am likely missing something stupidly obvious somewhere.  </p>

<p>I tried making sure the file paths were correct, looked up how the syntax of the commands worked, and checked for any basic errors. </p>

```<code>import shutil
import os

source = r'C:\\Users\JonTh\Saved Games\DCS\Mods\aircraft'
destination = r'C:\\Users\JonTh\Saved Games\dcs planes'

files = os.listdir(source)

for index in files:
    shutil.move(source,destination)
</code>```

答:
you should modify your code to consider files from for loop</p>

```<code>for index in files:
    shutil.move(source+"\\"+index,destination)
</code>```

Body:
I am writing two simple scripts, one to move all files into a folder, and one to move all files back to said folder. I am not getting any errors, but the files aren't moving so I am likely missing something stupidly obvious somewhere.

I tried making sure the file paths were correct, looked up how the syntax of the commands worked, and checked for any basic errors.

import shutil
import os

source = r'C:\\Users\JonTh\Saved Games\DCS\Mods\aircraft'
destination = r'C:\\Users\JonTh\Saved Games\dcs planes'

files = os.listdir(source)

for index in files:
    shutil.move(source,destination)

Body:
you should modify your code to consider files from for loop

for index in files:
    shutil.move(source+"\\"+index,destination)


问:
Android AnimationDrawable, why always shot two times?
my Codes:

```<code>package net.tq5.bubbleexplosion;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.ImageView;

public class BubbleExplosionActivity extends Activity {
 public static final String TAG = "BubbleExplosionActivity";
 /** Called when the activity is first created. */
 private FrameLayout parent;
 private ExplosionView customView;
 private AnimationDrawable exal;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // set no title;
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  // Create a FrameLayout and set the background;
  parent = new FrameLayout(this);
  parent.setBackgroundResource(R.drawable.bg);

  customView = new ExplosionView(this);
  customView.setVisibility(View.INVISIBLE);
  customView.setBackgroundResource(R.anim.explosion);

  exal = (AnimationDrawable) customView.getBackground();

  parent.addView(customView);
  parent.setOnTouchListener(new LayoutListener());
  setContentView(parent);
 }

 class ExplosionView extends ImageView {
  public ExplosionView(Context context) {
   super(context);
  }

  // handle the location of the Explosion;
  public void setLocation(int left, int top) {
   this.setFrame(left, top, left + 40, top + 40);
  }
 }

 class LayoutListener implements OnTouchListener {
  @Override
  public boolean onTouch(View view, MotionEvent event) {

   // first you stop the animation
   // you can always restart it;

   customView.setVisibility(View.INVISIBLE);
   if (exal.isRunning())
    return false;
//    exal.stop();
   float x = event.getX();
   float y = event.getY();
   Log.i(TAG, "on Touch");
   customView.setLocation((int) x - 20, (int) y - 20);
   customView.setVisibility(View.VISIBLE);
   exal.start();
   return false;
  }

 }
}
</code>```

```<code><?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">
     <item android:drawable="@drawable/bubble0" android:duration="500" />
    <item android:drawable="@drawable/explode1" android:duration="500" />
    <item android:drawable="@drawable/explode2" android:duration="500" />
    <item android:drawable="@drawable/explode3" android:duration="500" />
    <item android:drawable="@drawable/explode4" android:duration="500" />
    <item android:drawable="@drawable/explode5" android:duration="500" />
</animation-list>
</code>```

The image bubble0 always show two times; It seems that the animation has been fired two times, but I event tried this to make sure the start() method only be triggered once, but the animation will still be performed twice:

```<code>public class BubbleExplosionActivity extends Activity {
 public static final String TAG = "BubbleExplosionActivity";
 /** Called when the activity is first created. */
 private FrameLayout parent;
 private ExplosionView customView;
 private AnimationDrawable exal;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // set no title;
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  // Create a FrameLayout and set the background;
  parent = new FrameLayout(this);
  parent.setBackgroundResource(R.drawable.bg);

  customView = new ExplosionView(this);
  customView.setVisibility(View.INVISIBLE);
  customView.setBackgroundResource(R.anim.explosion);

  exal = (AnimationDrawable) customView.getBackground();

  parent.addView(customView);
  parent.setOnTouchListener(new LayoutListener());
  setContentView(parent);

  (new Handler()).postDelayed(new Runnable() {

   @Override
   public void run() {
    customView.setLocation((int) 100 - 20, (int) 100 - 20);
    customView.setVisibility(View.VISIBLE);
    exal.start();
   }

  }, 3000);
 }
}
</code>```

Help!

答:
It may be a little late for you, but I came across this question when I had the same problem.

The reason for the animation to run twice is that changing the visibility of the view to VISIBLE will restart the animation from the beginning.

The solution is to either start() the animation or to change the view visibility to View.VISIBLE, but not both.

ContentLicense: CC BY-SA 2.5

Body:
my Codes:

package net.tq5.bubbleexplosion;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.ImageView;

public class BubbleExplosionActivity extends Activity {
 public static final String TAG = "BubbleExplosionActivity";
 /** Called when the activity is first created. */
 private FrameLayout parent;
 private ExplosionView customView;
 private AnimationDrawable exal;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // set no title;
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  // Create a FrameLayout and set the background;
  parent = new FrameLayout(this);
  parent.setBackgroundResource(R.drawable.bg);

  customView = new ExplosionView(this);
  customView.setVisibility(View.INVISIBLE);
  customView.setBackgroundResource(R.anim.explosion);

  exal = (AnimationDrawable) customView.getBackground();

  parent.addView(customView);
  parent.setOnTouchListener(new LayoutListener());
  setContentView(parent);
 }

 class ExplosionView extends ImageView {
  public ExplosionView(Context context) {
   super(context);
  }

  // handle the location of the Explosion;
  public void setLocation(int left, int top) {
   this.setFrame(left, top, left + 40, top + 40);
  }
 }

 class LayoutListener implements OnTouchListener {
  @Override
  public boolean onTouch(View view, MotionEvent event) {

   // first you stop the animation
   // you can always restart it;

   customView.setVisibility(View.INVISIBLE);
   if (exal.isRunning())
    return false;
//    exal.stop();
   float x = event.getX();
   float y = event.getY();
   Log.i(TAG, "on Touch");
   customView.setLocation((int) x - 20, (int) y - 20);
   customView.setVisibility(View.VISIBLE);
   exal.start();
   return false;
  }

 }
}

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">
     <item android:drawable="@drawable/bubble0" android:duration="500" />
    <item android:drawable="@drawable/explode1" android:duration="500" />
    <item android:drawable="@drawable/explode2" android:duration="500" />
    <item android:drawable="@drawable/explode3" android:duration="500" />
    <item android:drawable="@drawable/explode4" android:duration="500" />
    <item android:drawable="@drawable/explode5" android:duration="500" />
</animation-list>

The image bubble0 always show two times; It seems that the animation has been fired two times, but I event tried this to make sure the start() method only be triggered once, but the animation will still be performed twice:

public class BubbleExplosionActivity extends Activity {
 public static final String TAG = "BubbleExplosionActivity";
 /** Called when the activity is first created. */
 private FrameLayout parent;
 private ExplosionView customView;
 private AnimationDrawable exal;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // set no title;
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  // Create a FrameLayout and set the background;
  parent = new FrameLayout(this);
  parent.setBackgroundResource(R.drawable.bg);

  customView = new ExplosionView(this);
  customView.setVisibility(View.INVISIBLE);
  customView.setBackgroundResource(R.anim.explosion);

  exal = (AnimationDrawable) customView.getBackground();

  parent.addView(customView);
  parent.setOnTouchListener(new LayoutListener());
  setContentView(parent);

  (new Handler()).postDelayed(new Runnable() {

   @Override
   public void run() {
    customView.setLocation((int) 100 - 20, (int) 100 - 20);
    customView.setVisibility(View.VISIBLE);
    exal.start();
   }

  }, 3000);
 }
}

Help!


问:
Persistent socket connection in Lua/Python
I'm trying to create a persistent socket connection between a Lua client and Python server. Effectively a script that'll constantly ping the server with keepalive messages

My current issue is that the socket closes after each connection without a means to reopen it for transmission.

Lua Client:

local HOST, PORT = "localhost", 9999
local socket = require('socket')

-- Create the client and initial connection
client, err = socket.connect(HOST, PORT)
client:setoption('keepalive', true)

-- Attempt to ping the server once a second
start = os.time()
while true do
  now = os.time()
  if os.difftime(now, start) >= 1 then
    data = client:send("Hello World")
    -- Receive data from the server and print out everything
    s, status, partial = client:receive()
    print(data, s, status, partial)
    start = now
  end
end
```

<p>Python Server:</p>

<pre class="lang-py prettyprint-override"><code>import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print("{} wrote".format(self.client_address[0]))
        print(self.data)
        print(self.client_address)
        # Send back some arbitrary data
        self.request.sendall(b'1')

if __name__ == '__main__':
    HOST, PORT = "localhost", 9999
    # Create a socketserver and serve is forever
    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        server.serve_forever()
</code>```

The expected result is a keepalive ping every second to ensure the client is still connected to the server.

答:
I ended up finding a solution.

The problem seems to have been with the socketserver library in Python. I switched it to raw sockets and things began working how I wanted them to. From there I created threads to handle the back and forth in the background

Python Server:

import socket, threading

HOST, PORT = "localhost", 9999

# Ensures the connection is still active
def keepalive(conn, addr):
    print("Client connected")
    with conn:
        conn.settimeout(3)
        while True:
            try:
                data = conn.recv(1024)
                if not data: break
                message = data.split(b',')
                if message[0] == b'ping':
                    conn.sendall(b'pong' + b'\n')
            except Exception as e:
                break
        print("Client disconnected")

# Listens for connections to the server and starts a new keepalive thread
def listenForConnections():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.bind((HOST, PORT))
        while True:
            sock.listen()
            conn, addr = sock.accept()
            t = threading.Thread(target=keepalive, args=(conn, addr))
            t.start()

if __name__ == '__main__':
    # Starts up the socket server
    SERVER = threading.Thread(target=listenForConnections)
    SERVER.start()

    # Run whatever code after this
```

The Lua client didn't change in this scenario

Body:
I'm trying to create a persistent socket connection between a Lua client and Python server. Effectively a script that'll constantly ping the server with keepalive messages

My current issue is that the socket closes after each connection without a means to reopen it for transmission.

Lua Client:

local HOST, PORT = "localhost", 9999
local socket = require('socket')

-- Create the client and initial connection
client, err = socket.connect(HOST, PORT)
client:setoption('keepalive', true)

-- Attempt to ping the server once a second
start = os.time()
while true do
  now = os.time()
  if os.difftime(now, start) >= 1 then
    data = client:send("Hello World")
    -- Receive data from the server and print out everything
    s, status, partial = client:receive()
    print(data, s, status, partial)
    start = now
  end
end

Python Server:

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print("{} wrote".format(self.client_address[0]))
        print(self.data)
        print(self.client_address)
        # Send back some arbitrary data
        self.request.sendall(b'1')

if __name__ == '__main__':
    HOST, PORT = "localhost", 9999
    # Create a socketserver and serve is forever
    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        server.serve_forever()

The expected result is a keepalive ping every second to ensure the client is still connected to the server.

Body:
I ended up finding a solution.

The problem seems to have been with the socketserver library in Python. I switched it to raw sockets and things began working how I wanted them to. From there I created threads to handle the back and forth in the background

Python Server:

import socket, threading

HOST, PORT = "localhost", 9999

# Ensures the connection is still active
def keepalive(conn, addr):
    print("Client connected")
    with conn:
        conn.settimeout(3)
        while True:
            try:
                data = conn.recv(1024)
                if not data: break
                message = data.split(b',')
                if message[0] == b'ping':
                    conn.sendall(b'pong' + b'\n')
            except Exception as e:
                break
        print("Client disconnected")

# Listens for connections to the server and starts a new keepalive thread
def listenForConnections():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.bind((HOST, PORT))
        while True:
            sock.listen()
            conn, addr = sock.accept()
            t = threading.Thread(target=keepalive, args=(conn, addr))
            t.start()

if __name__ == '__main__':
    # Starts up the socket server
    SERVER = threading.Thread(target=listenForConnections)
    SERVER.start()

    # Run whatever code after this

The Lua client didn't change in this scenario


问:
How to select an element place after an a element?
I have the following HTML code. Why this isn't working if I would like to select the  element if clicked?

$('input[name="USR_NewPassword"] span > a').on('click', function(event) {
  alert()
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>
<span class="input-group-addon">
        <i class="fa fa-eye"></i>
    </span></code>```

答:
You are missing a +:

$('input[name="USR_NewPassword"] + span > a').on('click', function(event) {
  alert();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>
<span class="input-group-addon">
    <i class="fa fa-eye">icon</i>
</span></code>```

Body:
I have the following HTML code. Why this isn't working if I would like to select the  element if clicked?

$('input[name="USR_NewPassword"] span > a').on('click', function(event) {
  alert()
});

<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>

Body:
You are missing a +:

$('input[name="USR_NewPassword"] + span > a').on('click', function(event) {
  alert();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>
<span class="input-group-addon">
    <a href="#"><i class="fa fa-eye">icon</i></a>
</span>


问:
MS CRM: SetStateRequest and business rules conflict
I have a problem.

I use SetStateRequest() to change status of incident. Both statuses have StateCode = 0, but when I send request it activates business rule, which is triggered by changing Incident StateCode to 0, but I don't need that, how can I bypass activating that trigger?

Also tried to get entity using Context, then changing Incident.StatusCode, updating it and then using context.SaveChanges();

Both of this triggers this business rule

答:
If you want to change the status of the record, and both the initial status and target status are Active statuses, then you can do this in an Update request instead of a SetStateRequest. This will result in an update to the statuscode field, but not the statecode field.</p>

```<code>//Swap in whatever status you want
updateIncident.statuscode = new OptionSetValue(incident_statuscode.InProgress.ToInt());
service.Update(updateIncident);
</code>```

Body:
If you want to change the status of the record, and both the initial status and target status are Active statuses, then you can do this in an Update request instead of a SetStateRequest. This will result in an update to the statuscode field, but not the statecode field.

//Swap in whatever status you want
updateIncident.statuscode = new OptionSetValue(incident_statuscode.InProgress.ToInt());
service.Update(updateIncident);


问:
Regex Replace A Variable Within Brackets, Including Brackets
How do I get rid of a variable within square brackets, including the brackets themselves? E.g. [152] or [153] or [154]. I am using Yahoo Pipes.</p>

Body:
try

var rx= '/[\[\.*\]]/g';
var s = "[152]  [153] [154] ";
s.replace(rx,'');

DEMO


问:
Access JSP file Inside Fat Jar
I have spring boot app which creates fat jar and the exploded version of the fat as below,

/META-INF/resources/index.jsp as per the below,

Spring Boot Executable jar structure

i tried to access the prefix in application.properties,

```<code>spring.mvc.view.prefix = /WEB-INF/resources/ - No luck
spring.mvc.view.prefix = /META-INF/resources/  - No luck
spring.mvc.view.prefix = /resources/ - No luck
</code>```

So what could be the correct prefix for this one? Thanks in advance!

答:
You can do as follows :

ApplicationConfigurerAdapter.java

```<code>@Configuration
@EnableWebMvc
public class ApplicationConfigurerAdapter extends WebMvcConfigurerAdapter{

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/web-resources/**").addResourceLocations("/resources/").setCachePeriod(300);
    }

}
</code>```

Title: Access JSP file Inside Fat Jar

Body:
I have spring boot app which creates fat jar and the exploded version of the fat as below,

/META-INF/resources/index.jsp as per the below,

Spring Boot Executable jar structure

i tried to access the prefix in application.properties,

spring.mvc.view.prefix = /WEB-INF/resources/ - No luck
spring.mvc.view.prefix = /META-INF/resources/  - No luck
spring.mvc.view.prefix = /resources/ - No luck

So what could be the correct prefix for this one? Thanks in advance!

Body:
You can do as follows :

ApplicationConfigurerAdapter.java

@Configuration
@EnableWebMvc
public class ApplicationConfigurerAdapter extends WebMvcConfigurerAdapter{

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/web-resources/**").addResourceLocations("/resources/").setCachePeriod(300);
    }

}


问:
JavaScript function similar to Python range()
Is there a function in JavaScript similar to Python's range()?

I think there should be a better way than to write the following lines every time:

```<code>array = new Array();
for (i = 0; i < specified_len; i++) {
    array[i] = i;
}
</code>```

答:
No, there is none, but you can make one.

I'm partial to Python3 behavior of range. You will find below JavaScript's implementation of Python's range():

function* range(start=0, end=undefined, step=1) {
    if(arguments.length === 1) {end = start, start = 0}

    [...arguments].forEach(arg => {
        if( typeof arg !== 'number') {throw new TypeError("Invalid argument")}
    })
    if(arguments.length === 0) {throw new TypeError("More arguments neede")}

    if(start >= end) return
    yield start
    yield* range(start + step, end, step)
}

// Use Cases
console.log([...range(5)])

console.log([...range(2, 5)])

console.log([...range(2, 5, 2)])
console.log([...range(2,3)])
// You can, of course, iterate through the range instance.```

Body:
Is there a function in JavaScript similar to Python's range()?

I think there should be a better way than to write the following lines every time:

array = new Array();
for (i = 0; i < specified_len; i++) {
    array[i] = i;
}


问:
How can I get %i Ruby arrays to be properly highlighted in Vim?
My Vim is not highlighting the relatively new %i syntax. Here's an example:

I included a %w example, which works properly, to show the desired effect.

How can I get Vim to highlight %i properly?

答:
By default, Vim highlights Ruby's string delimiters and symbol delimiters differently. The string delimiters are highlighted as type Delimiter, and the symbol delimiters are highlighted the same as symbols, which is, by default, of type Constant.

If you want to highlight the %i and brackets the same as the %w, you can run the following command:

```<code>:hi link rubySymbolDelimiter rubyStringDelimiter
</code>```

If you like that setting, you can put it in a file called .vim/after/syntax/ruby.vim and it will be picked up automatically whenever the Ruby syntax is enabled.

Note that in newer versions of Vim, the above command will also cause the colon in front of a symbol to be highlighted the same way as the %i. That functionality isn't configurable, since they both use the rubySymbolDelimiter match group.

Body:
By default, Vim highlights Ruby's string delimiters and symbol delimiters differently. The string delimiters are highlighted as type Delimiter, and the symbol delimiters are highlighted the same as symbols, which is, by default, of type Constant.

If you want to highlight the %i and brackets the same as the %w, you can run the following command:

:hi link rubySymbolDelimiter rubyStringDelimiter

If you like that setting, you can put it in a file called .vim/after/syntax/ruby.vim and it will be picked up automatically whenever the Ruby syntax is enabled.

Note that in newer versions of Vim, the above command will also cause the colon in front of a symbol to be highlighted the same way as the %i. That functionality isn't configurable, since they both use the rubySymbolDelimiter match group.


问:
Can't create iPad XIB with Xcode 4
Alright, I have a problem on my hands.  I'm trying to convert my project to a universal app for the iPhone and the iPad.  I'm trying to make iPad-specific versions of my XIB files.  As it's not possible to Create iPad version using autoresizing masks in Xcode 4, I assumed I'd just be able to pop my XIB into Xcode 3's version of IB, and let that do the magic.  No dice.  Here's the error I get when i try to open the XIB file in IB:

To be honest I don't know where to proceed from here.  I guess I could just resize my views manually, but that's quite tedious and I don't really have the time to be doing that.  Any ideas?

答:
This should not happen. One way to fix this problem would be t completely remove the Xcode 4 Installation and re install it from scratch . And then re install it.

Use the following command to uninstall and re install Xcode 4

sudo [xcode-path]/Library/uninstall-devtools --mode=all

PS: If you are creating projects in Xcode 4 that you also want to open in Xcode 3 make sure you keep Document Versioning section to Interface Builder 3.1

Title: Can't create iPad XIB with Xcode 4


问:
How to use condition WHERE json hierarchy column in Postgres?
I've created a small DW in Postgres that contains an XML column, JSON column and GEOmetry column , I want to use a clause group by in json column just.

let's focus on this table contains XML column, JSON column and GEOmetry column

I insert some line in the table.

here is the table view in postgres :

I want to display the lines with which the city is Tanger

note : I used the following query but it did not work :

答:
based on documentation the JSON operator are:

-The operator -> returns JSON object field by key.

-The operator ->> returns JSON object field by text.

Then You have a mistake with the operator, You must use ->  for addres key, for example like this example

```<code>https://dbfiddle.uk/?rdbms=postgres_10&fiddle=67df669c90741366f89671ea9494b287
</code>```

Body:
based on documentation the JSON operator are:

-The operator -> returns JSON object field by key.

-The operator ->> returns JSON object field by text.

Then You have a mistake with the operator, You must use ->  for addres key, for example like this example

https://dbfiddle.uk/?rdbms=postgres_10&fiddle=67df669c90741366f89671ea9494b287


问:
I'm trying to open external links from my app but it won't open
I have a wkwebview app, I need help with my code, I can't seems to open external links from my website inside my app.

```<code>import UIKit
import WebKit
import UserNotifications

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
    var webView: WKWebView!
    var activityIndicator: UIActivityIndicatorView!
    var bgImage: UIImageView!
    var urlString = ""

    override func loadView() {
        super.loadView()
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
    }

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            let vc = ViewController()
            vc.urlString = navigationAction.request.url?.absoluteString ?? "https://mywebsite"
            vc.view.frame = UIScreen.main.bounds
            vc.webView = WKWebView(frame: UIScreen.main.bounds, configuration: configuration)
            navigationController?.pushViewController(vc, animated: false)
            return vc.webView
        }
        return nil
    }

    override var prefersStatusBarHidden: Bool{
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let image : UIImage = UIImage(named:"bgx1")!
        bgImage = UIImageView(image: image)
        bgImage.frame = CGRect(x: 0, y: 0, width: 1000, height: 2000)
        view.addSubview(bgImage)

        let myURL = URL(string: "https://mywebsite/")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
        webView.allowsBackForwardNavigationGestures = true

        activityIndicator = UIActivityIndicatorView()
        activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)

        self.activityIndicator.center = CGPoint(x:self.view.bounds.size.width/2.0,y: self.view.bounds.size.height/2.0);

        activityIndicator.autoresizingMask = (UIView.AutoresizingMask(rawValue: UIView.AutoresizingMask.RawValue(UInt8(UIView.AutoresizingMask.flexibleRightMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleLeftMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleBottomMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleTopMargin.rawValue))))

        activityIndicator.hidesWhenStopped = true

        activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge
        activityIndicator.color = UIColor.darkGray
        self.view.addSubview(activityIndicator)

    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        activityIndicator.startAnimating()
        bgImage.startAnimating()
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("It is an error")
        activityIndicator.stopAnimating()
        bgImage.stopAnimating()
        let alert = UIAlertController(title: "Network Error", message: "You have no internet connection", preferredStyle: .alert)

        let restartAction = UIAlertAction(title: "Reload page", style: .default, handler: { (UIAlertAction) in
            self.viewDidLoad()
        })

        alert.addAction(restartAction)
        present(alert, animated: true, completion: nil)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        activityIndicator.stopAnimating()
        bgImage.stopAnimating()
        bgImage.isHidden = true
    }

}
</code>```

What am I doing wrong? Please help.

答:
please use this webview as I shown in image

code:-

```<code>@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self;
        webView.loadRequest(URLRequest.init(url: URL(string: "https://mywebsite")!));
}

func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.custom)
        SVProgressHUD.show();
    }

    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss();

    }
</code>```

Body:
I have a wkwebview app, I need help with my code, I can't seems to open external links from my website inside my app.

import UIKit
import WebKit
import UserNotifications

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
    var webView: WKWebView!
    var activityIndicator: UIActivityIndicatorView!
    var bgImage: UIImageView!
    var urlString = ""

    override func loadView() {
        super.loadView()
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
    }

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            let vc = ViewController()
            vc.urlString = navigationAction.request.url?.absoluteString ?? "https://mywebsite"
            vc.view.frame = UIScreen.main.bounds
            vc.webView = WKWebView(frame: UIScreen.main.bounds, configuration: configuration)
            navigationController?.pushViewController(vc, animated: false)
            return vc.webView
        }
        return nil
    }

    override var prefersStatusBarHidden: Bool{
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let image : UIImage = UIImage(named:"bgx1")!
        bgImage = UIImageView(image: image)
        bgImage.frame = CGRect(x: 0, y: 0, width: 1000, height: 2000)
        view.addSubview(bgImage)

        let myURL = URL(string: "https://mywebsite/")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
        webView.allowsBackForwardNavigationGestures = true

        activityIndicator = UIActivityIndicatorView()
        activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)

        self.activityIndicator.center = CGPoint(x:self.view.bounds.size.width/2.0,y: self.view.bounds.size.height/2.0);

        activityIndicator.autoresizingMask = (UIView.AutoresizingMask(rawValue: UIView.AutoresizingMask.RawValue(UInt8(UIView.AutoresizingMask.flexibleRightMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleLeftMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleBottomMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleTopMargin.rawValue))))

        activityIndicator.hidesWhenStopped = true

        activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge
        activityIndicator.color = UIColor.darkGray
        self.view.addSubview(activityIndicator)

    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        activityIndicator.startAnimating()
        bgImage.startAnimating()
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("It is an error")
        activityIndicator.stopAnimating()
        bgImage.stopAnimating()
        let alert = UIAlertController(title: "Network Error", message: "You have no internet connection", preferredStyle: .alert)

        let restartAction = UIAlertAction(title: "Reload page", style: .default, handler: { (UIAlertAction) in
            self.viewDidLoad()
        })

        alert.addAction(restartAction)
        present(alert, animated: true, completion: nil)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        activityIndicator.stopAnimating()
        bgImage.stopAnimating()
        bgImage.isHidden = true
    }

}

What am I doing wrong? Please help.

Body:
please use this webview as I shown in image

code:-

@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self;
        webView.loadRequest(URLRequest.init(url: URL(string: "https://mywebsite")!));
}

func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.custom)
        SVProgressHUD.show();
    }

    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss();

    }


问:
Big-query for remove @ImSRK in the tweets string
I am doing sentiment analysis on Twitter using Google cloud. In my bigtable, I have tweets from thousand of people. I want to remove @NarendraModi from the tweets. Could you please help me out to find big-query for that.  For example
@NarendraModi congratulation sir
In the above tweets, I want to remove @narendramodi from the string. There is a single space after @Narendramodi</p>

答:
Below example for BigQuery Standard SQL using either REPLACE or REGEXP_REPLACE

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT '@NarendraModi congratulation sir' tweet
)
SELECT REPLACE(tweet, '@NarendraModi ', ''),
  REGEXP_REPLACE(tweet, r'@NarendraModi\s*', ''),
  REGEXP_REPLACE(tweet, r'@\w+\s+', '')
FROM `project.dataset.table`
</code>```

the output is

```<code>Row f0_                 f1_                 f2_
1   congratulation sir  congratulation sir  congratulation sir
</code>```

I have two patterns left 1) "@somename:" and 2) "@somename."

below addresses additional patterns

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT '@NarendraModi congratulation sir' tweet UNION ALL
  SELECT '@NarendraModi. congratulation sir' tweet UNION ALL
  SELECT '@NarendraModi: congratulation sir' tweet

)
SELECT REGEXP_REPLACE(tweet, r'@\w+[:.\s]*', '')
FROM `project.dataset.table`
</code>```

with result

```<code>Row f0_
1   congratulation sir
2   congratulation sir
3   congratulation sir
</code>```

Body:
Below example for BigQuery Standard SQL using either REPLACE or REGEXP_REPLACE

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '@NarendraModi congratulation sir' tweet
)
SELECT REPLACE(tweet, '@NarendraModi ', ''),
  REGEXP_REPLACE(tweet, r'@NarendraModi\s*', ''),
  REGEXP_REPLACE(tweet, r'@\w+\s+', '')
FROM `project.dataset.table`

the output is

Row f0_                 f1_                 f2_
1   congratulation sir  congratulation sir  congratulation sir

I have two patterns left 1) "@somename:" and 2) "@somename."

below addresses additional patterns

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '@NarendraModi congratulation sir' tweet UNION ALL
  SELECT '@NarendraModi. congratulation sir' tweet UNION ALL
  SELECT '@NarendraModi: congratulation sir' tweet

)
SELECT REGEXP_REPLACE(tweet, r'@\w+[:.\s]*', '')
FROM `project.dataset.table`

with result

Row f0_
1   congratulation sir
2   congratulation sir
3   congratulation sir


问:
How to fix error Msg 102, Level 15, State 1, Line 2 Incorrect syntax near ','.?
I'm writing the following query

```<code>Create Table Worker
(
    Worker_ID Int Not Null Primary Key Auto_Increment,
    First_Name Char(25),
    Last_Name Char(25),
    Salary Int(15),
    Joining_Date Datetime,
    Department Char(25)
)
</code>```

and getting this error:

Msg 102, Level 15, State 1, Line 2

  Incorrect syntax near ','

答:
SQL Server doesn't have an auto_increment statement - try this instead, using the IDENTITY clause on your INT column to have SQL Server automatically create new values when inserting:

```<code>CREATE TABLE dbo.Worker
(
    Worker_ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    First_Name VARCHAR(25),
    Last_Name VARCHAR(25),
    Salary INT,
    Joining_Date DATETIME,
    Department VARCHAR(25)
)
</code>```

Also: I would strongly suggest you use varchar instead of char to avoid filling up all your columns to the defined length with spaces.....

And last of all: the type INT (for your column Salary) in SQL Server never has a precision or anything - an INT is an INT is an INT. Maybe you wanted to define a datatype of DECIMAL(p,s) instead?

Body:
I'm writing the following query

Create Table Worker
(
    Worker_ID Int Not Null Primary Key Auto_Increment,
    First_Name Char(25),
    Last_Name Char(25),
    Salary Int(15),
    Joining_Date Datetime,
    Department Char(25)
)

and getting this error:

Msg 102, Level 15, State 1, Line 2

  Incorrect syntax near ','

Body:
SQL Server doesn't have an auto_increment statement - try this instead, using the IDENTITY clause on your INT column to have SQL Server automatically create new values when inserting:

CREATE TABLE dbo.Worker
(
    Worker_ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    First_Name VARCHAR(25),
    Last_Name VARCHAR(25),
    Salary INT,
    Joining_Date DATETIME,
    Department VARCHAR(25)
)

Also: I would strongly suggest you use varchar instead of char to avoid filling up all your columns to the defined length with spaces.....

And last of all: the type INT (for your column Salary) in SQL Server never has a precision or anything - an INT is an INT is an INT. Maybe you wanted to define a datatype of DECIMAL(p,s) instead?


问:
Where can I find a good NHibernate and ASP.NET MVC Reference Application
Where can I find a good NHibernate and ASP.NET MVC Reference Application? I downloaded S#arp and this seemed to be a lot more than I needed (IOC and CodeGen via T4). I might work my way up to this later, but I need something smaller at first.

Any simple examples? I just want to pick up how NHibernate Session handling works in ASP.NET MVC.  And maybe how some simple query scenarios work. Still trying to grasp how a SELECT DISTINCT would be done in NHibernate and through to the View via the ViewData.

答:
It's not a full sample application or anything but it's a pretty well designed ASP.NET MVC project framework written around DDD/nHibernate etc.

http://code.google.com/p/sharp-architecture/

OwnerDisplayName: Bruno Tyndall

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Chad Moran


问:
Total canvas memory use exceeds the maximum limit (Safari 12)
We are working on a visualization web application which use d3-force to draw a network on a canvas.

But now we’ve got a problem with browsers on iOS, where the process crashes after few interactions with the interface.
To my recollection, this was not a problem with older version (prior to iOS12), but I don’t have any not-updated-device to confirm this.

I think this code summarizes the problem :

```<code>const { range } = require('d3-array')

// create a 1MB image
const createImage = () => {
    const size = 512

    const canvas = document.createElement('canvas')
    canvas.height = size
    canvas.width = size

    const ctx = canvas.getContext('2d')
    ctx.strokeRect(0, 0, size, size)
    return canvas
}

const createImages = i => {
    // create i * 1MB images
    let ctxs = range(i).map(() => {
        return createImage()
    })
    console.log(`done for ${ctxs.length} MB`)
    ctxs = null
}

window.cis = createImages
</code>```

Then on an iPad and in the inspector :

```<code>> cis(256)
[Log] done for 256 MB (main-a9168dc888c2e24bbaf3.bundle.js, line 11317)
< undefined
> cis(1)
[Warning] Total canvas memory use exceeds the maximum limit (256 MB). (main-a9168dc888c2e24bbaf3.bundle.js, line 11307)
< TypeError: null is not an object (evaluating 'ctx.strokeRect')
</code>```

Being, I create 256 x 1MB canvas, everything goes well, but I create one more and the canvas.getContext returns a null pointer.
It is then impossible to create another canvas.

The limit seems to be device related as on the iPad its is 256MB and on an iPhone X it is 288MB.

```<code>> cis(288)
[Log] done for 288 MB (main-a9168dc888c2e24bbaf3.bundle.js, line 11317)
< undefined
> cis(1)
[Warning] Total canvas memory use exceeds the maximum limit (288 MB). (main-a9168dc888c2e24bbaf3.bundle.js, line 11307)
< TypeError: null is not an object (evaluating 'ctx.strokeRect')
</code>```

As it is a cache I should be able to delete some elements, but I’m not (as setting ctxs or ctx to null should trigger the GC, but it does not solve the problem).

The only relevant page I found on this problem is a webkit source code page: HTMLCanvasElement.cpp.

I suspect the problem could come from webkit itself, but I’m would like to be sure before posting to webkit issue tracker.

Is there another way to destroy the canvas contexts ?

Thanks in advance for any idea, pointer, ...

UPDATE

I found this Webkit issue which is (probably) a description of this bug:
https://bugs.webkit.org/show_bug.cgi?id=195325

To add some informations, I tried other browsers. Safari 12 has the same problem on macOS, even if the limit is higher (1/4 of the computer memory, as stated in webkit sources). I also tried with the latest webkit build (236590) without more luck.
But the code works on Firefox 62 and Chrome 69.

I refined the test code, so it can be executed directly from the debugger console. It would be really helpful if someone could test the code on an older safari (like 11).

```<code>let counter = 0

// create a 1MB image
const createImage = () => {
    const size = 512

    const canvas = document.createElement('canvas')
    canvas.height = size
    canvas.width = size

    const ctx = canvas.getContext('2d')
    ctx.strokeRect(0, 0, size, size)
    return canvas
}

const createImages = n => {
    // create n * 1MB images
    const ctxs = []

    for( let i=0 ; i<n ; i++ ){
        ctxs.push(createImage())
    }

    console.log(`done for ${ctxs.length} MB`)
}

const process = (frequency,size) => {
    setInterval(()=>{
        createImages(size)
        counter+=size
        console.log(`total ${counter}`)
    },frequency)
}

process(2000,1000)
</code>```

答:
I've submitted a new bug report to Apple, no reply yet. I added the ability to execute the code shown below after I drew a line using Polylines in google maps:

function makeItSo(){
  var foo = document.getElementsByTagName("canvas");
  console.log(foo);
  for(var i=0;i < foo.length;i++){
    foo[i].width = 32;
    foo[i].height = 32;
  }
}
```

Looking at the console output, only 4 canvas elements were found. But looking at the "canvas" panel in the Safari debugger, there were 33 canvases displayed (amount depends on the size of the web page you have open).

   After the above code runs, the canvases display shows the 4 canvasses that were found at a smaller size, as one might expect. All the other "orphaned" canvases are still displayed in the debugger.

   I suspect this confirms the "memory leak" theory- canvases that exists but are not in the document. When the amount of canvas memory you have is exceeded, nothing more can be rendered using canvases.

   Again, all this worked until IOS12. My older iPad running IOS 10 still works.

Body:
We are working on a visualization web application which use d3-force to draw a network on a canvas.

But now we’ve got a problem with browsers on iOS, where the process crashes after few interactions with the interface.
To my recollection, this was not a problem with older version (prior to iOS12), but I don’t have any not-updated-device to confirm this.

I think this code summarizes the problem :

const { range } = require('d3-array')

// create a 1MB image
const createImage = () => {
    const size = 512

    const canvas = document.createElement('canvas')
    canvas.height = size
    canvas.width = size

    const ctx = canvas.getContext('2d')
    ctx.strokeRect(0, 0, size, size)
    return canvas
}

const createImages = i => {
    // create i * 1MB images
    let ctxs = range(i).map(() => {
        return createImage()
    })
    console.log(`done for ${ctxs.length} MB`)
    ctxs = null
}

window.cis = createImages

Then on an iPad and in the inspector :

> cis(256)
[Log] done for 256 MB (main-a9168dc888c2e24bbaf3.bundle.js, line 11317)
< undefined
> cis(1)
[Warning] Total canvas memory use exceeds the maximum limit (256 MB). (main-a9168dc888c2e24bbaf3.bundle.js, line 11307)
< TypeError: null is not an object (evaluating 'ctx.strokeRect')

Being, I create 256 x 1MB canvas, everything goes well, but I create one more and the canvas.getContext returns a null pointer.
It is then impossible to create another canvas.

The limit seems to be device related as on the iPad its is 256MB and on an iPhone X it is 288MB.

> cis(288)
[Log] done for 288 MB (main-a9168dc888c2e24bbaf3.bundle.js, line 11317)
< undefined
> cis(1)
[Warning] Total canvas memory use exceeds the maximum limit (288 MB). (main-a9168dc888c2e24bbaf3.bundle.js, line 11307)
< TypeError: null is not an object (evaluating 'ctx.strokeRect')

As it is a cache I should be able to delete some elements, but I’m not (as setting ctxs or ctx to null should trigger the GC, but it does not solve the problem).

The only relevant page I found on this problem is a webkit source code page: HTMLCanvasElement.cpp.

I suspect the problem could come from webkit itself, but I’m would like to be sure before posting to webkit issue tracker.

Is there another way to destroy the canvas contexts ?

Thanks in advance for any idea, pointer, ...

UPDATE

I found this Webkit issue which is (probably) a description of this bug:
https://bugs.webkit.org/show_bug.cgi?id=195325

To add some informations, I tried other browsers. Safari 12 has the same problem on macOS, even if the limit is higher (1/4 of the computer memory, as stated in webkit sources). I also tried with the latest webkit build (236590) without more luck.
But the code works on Firefox 62 and Chrome 69.

I refined the test code, so it can be executed directly from the debugger console. It would be really helpful if someone could test the code on an older safari (like 11).

let counter = 0

// create a 1MB image
const createImage = () => {
    const size = 512

    const canvas = document.createElement('canvas')
    canvas.height = size
    canvas.width = size

    const ctx = canvas.getContext('2d')
    ctx.strokeRect(0, 0, size, size)
    return canvas
}

const createImages = n => {
    // create n * 1MB images
    const ctxs = []

    for( let i=0 ; i<n ; i++ ){
        ctxs.push(createImage())
    }

    console.log(`done for ${ctxs.length} MB`)
}

const process = (frequency,size) => {
    setInterval(()=>{
        createImages(size)
        counter+=size
        console.log(`total ${counter}`)
    },frequency)
}

process(2000,1000)

Body:
I've submitted a new bug report to Apple, no reply yet. I added the ability to execute the code shown below after I drew a line using Polylines in google maps:

function makeItSo(){
  var foo = document.getElementsByTagName("canvas");
  console.log(foo);
  for(var i=0;i < foo.length;i++){
    foo[i].width = 32;
    foo[i].height = 32;
  }
}

Looking at the console output, only 4 canvas elements were found. But looking at the "canvas" panel in the Safari debugger, there were 33 canvases displayed (amount depends on the size of the web page you have open).

   After the above code runs, the canvases display shows the 4 canvasses that were found at a smaller size, as one might expect. All the other "orphaned" canvases are still displayed in the debugger.

   I suspect this confirms the "memory leak" theory- canvases that exists but are not in the document. When the amount of canvas memory you have is exceeded, nothing more can be rendered using canvases.

   Again, all this worked until IOS12. My older iPad running IOS 10 still works.