问:
Using an interface with Firebase
Currently I am implementing an interface called RowType for a handful of different classes let's say class A, B, and C. How would I iterate through Firebase to get each different object?

```<code>.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        RowType rowType = snapshot.getValue(RowType.class);
                        Log.d("awdjk", "qwjel");
                    }
</code>```

I would assume that since all the objects inserted in Firebase are of either class A, B, or C, that I could use RowType to get the snapshot value. However, I am getting an error saying that "No properties to serialize found on class RowType".

UPDATE

Interface

```<code>public interface RowType {
int EXERCISE_ROW = 0;
int REST_ROW = 1;
int SUPERSET_ROW = 2;
int PYRAMIDSET_ROW = 3;
int BUTTON_ROW = 4;
}
</code>```

Exercise class

```<code>public class ExerciseModel implements RowType {
public String exercise, sets, reps, view, minutes, seconds, time, weight, childCount;
private EditText weightEditText, setsEditText, repsEditText;
private AutoCompleteTextView exerciseEditText;
private ImageView dragHandle;
private ExerciseRowTextWatcher exerciseRowTextWatcher;

public ExerciseRowTextWatcher getExerciseRowTextWatcher(){
    return exerciseRowTextWatcher;
}

public void setExerciseRowTextWatcher(ExerciseRowTextWatcher exerciseRowTextWatcher){
    this.exerciseRowTextWatcher = exerciseRowTextWatcher;
}

public ImageView getDragHandle(){
    return dragHandle;
}

public void setDragHandle(ImageView dragHandle){
    this.dragHandle = dragHandle;
}

public AutoCompleteTextView getExerciseEditText(){
    return exerciseEditText;
}

public void setExerciseEditText(AutoCompleteTextView exerciseEditText){
    this.exerciseEditText = exerciseEditText;
}

public EditText getWeightEditText(){
    return weightEditText;
}

public void setWeightEditText(EditText weightEditText){
    this.weightEditText = weightEditText;
}

public EditText getSetsEditText(){
    return setsEditText;
}

public void setSetsEditText(EditText setsEditText){
    this.setsEditText = setsEditText;
}

public EditText getRepsEditText(){
    return repsEditText;
}

public void setRepsEditText(EditText repsEditText){
    this.repsEditText = repsEditText;
}

public String getChildCount(){
    return childCount;
}

public void setChildCount(String childCount){
    this.childCount = childCount;
}

public String getExercise(){
    return exercise;
}

public String getWeight(){
    return weight;
}

public String getSets(){
    return sets;
}

public String getReps(){
    return reps;
}

public String getView(){
    return view;
}

public String getMinutes(){
    return minutes;
}

public String getSeconds(){
    return seconds;
}

public String getTime(){   return time;}

public void setExercise(String exercise){
    this.exercise = exercise;
}

public void setTime(String time){ this.time = time; }

public void setWeight(String weight){
    this.weight = weight;
}

public void setMinutes(String minutes){
    this.minutes = minutes;
}

public void setSeconds(String seconds){
    this.seconds = seconds;
}

public void setSets(String sets){
    this.sets = sets;
}

public void setView(String view){
    this.view = view;
}

public void setReps(String reps){
    this.reps = reps;
}

}
</code>```

I have other classes that are implemented in the interface, but to keep this short, I have added only the exercise class. The other classes are relatively similar.

答:
You cannot use as a model class, an interface. This is not possible because the model class must have the public no-argument constructor which is needed for Firebase. As we know, an interface cannot be initialized using the new keyword and therefore cannot have a constructor.

Why does Firebase need the no-argument constructor? When the Firebase Realtime Database SDK deserializes objects coming from the database, it requires that any objects in use have a public no-argument constructor that it can use to instantiate the object and this is not possible with an interface because the SDK doesn't really know how to create an instance of it.

Title: Using an interface with Firebase

Body:
Currently I am implementing an interface called RowType for a handful of different classes let's say class A, B, and C. How would I iterate through Firebase to get each different object?

.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        RowType rowType = snapshot.getValue(RowType.class);
                        Log.d("awdjk", "qwjel");
                    }

I would assume that since all the objects inserted in Firebase are of either class A, B, or C, that I could use RowType to get the snapshot value. However, I am getting an error saying that "No properties to serialize found on class RowType".

UPDATE

Interface

public interface RowType {
int EXERCISE_ROW = 0;
int REST_ROW = 1;
int SUPERSET_ROW = 2;
int PYRAMIDSET_ROW = 3;
int BUTTON_ROW = 4;
}

Exercise class

public class ExerciseModel implements RowType {
public String exercise, sets, reps, view, minutes, seconds, time, weight, childCount;
private EditText weightEditText, setsEditText, repsEditText;
private AutoCompleteTextView exerciseEditText;
private ImageView dragHandle;
private ExerciseRowTextWatcher exerciseRowTextWatcher;

public ExerciseRowTextWatcher getExerciseRowTextWatcher(){
    return exerciseRowTextWatcher;
}

public void setExerciseRowTextWatcher(ExerciseRowTextWatcher exerciseRowTextWatcher){
    this.exerciseRowTextWatcher = exerciseRowTextWatcher;
}

public ImageView getDragHandle(){
    return dragHandle;
}

public void setDragHandle(ImageView dragHandle){
    this.dragHandle = dragHandle;
}

public AutoCompleteTextView getExerciseEditText(){
    return exerciseEditText;
}

public void setExerciseEditText(AutoCompleteTextView exerciseEditText){
    this.exerciseEditText = exerciseEditText;
}

public EditText getWeightEditText(){
    return weightEditText;
}

public void setWeightEditText(EditText weightEditText){
    this.weightEditText = weightEditText;
}

public EditText getSetsEditText(){
    return setsEditText;
}

public void setSetsEditText(EditText setsEditText){
    this.setsEditText = setsEditText;
}

public EditText getRepsEditText(){
    return repsEditText;
}

public void setRepsEditText(EditText repsEditText){
    this.repsEditText = repsEditText;
}

public String getChildCount(){
    return childCount;
}

public void setChildCount(String childCount){
    this.childCount = childCount;
}

public String getExercise(){
    return exercise;
}

public String getWeight(){
    return weight;
}

public String getSets(){
    return sets;
}

public String getReps(){
    return reps;
}

public String getView(){
    return view;
}

public String getMinutes(){
    return minutes;
}

public String getSeconds(){
    return seconds;
}

public String getTime(){   return time;}

public void setExercise(String exercise){
    this.exercise = exercise;
}

public void setTime(String time){ this.time = time; }

public void setWeight(String weight){
    this.weight = weight;
}

public void setMinutes(String minutes){
    this.minutes = minutes;
}

public void setSeconds(String seconds){
    this.seconds = seconds;
}

public void setSets(String sets){
    this.sets = sets;
}

public void setView(String view){
    this.view = view;
}

public void setReps(String reps){
    this.reps = reps;
}

}

I have other classes that are implemented in the interface, but to keep this short, I have added only the exercise class. The other classes are relatively similar.


来源: stackexchange

问:
How to use custom woff2 and oft fonts with Sphinx?
I know you specify theme options with an object like :

```<code>html_theme_options = {'font_family':'Gotham','head_font_family':'Gotham Ultra'}
</code>```

in conf.py. But sometimes browsers don't have access to such custom fonts like Gotham. Where do I put the custom font woff2 or otf file and how do I instruct Sphinx to use that for headers or for other fonts?

答:
Most Sphinx themes don't have fonts as a configurable option. You would have to customize the theme by:

editing the theme template to include the font file, either locally or remotely

editing the theme's CSS to specify the font-face style

optionally adding the static assets to the theme, if you load theme locally

See details of templating in Sphinx.

ContentLicense: CC BY-SA 3.0

Body:
I know you specify theme options with an object like :

html_theme_options = {'font_family':'Gotham','head_font_family':'Gotham Ultra'}

in conf.py. But sometimes browsers don't have access to such custom fonts like Gotham. Where do I put the custom font woff2 or otf file and how do I instruct Sphinx to use that for headers or for other fonts?


问:
Selectively removing trailing string
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"
</code>```

but I want

```<code>"HELLO X" "D HELLO" "TW X" "H"
</code>```

答:
A little lengthy, but you can try like this</p>

```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")
b <- lapply(a, function(x) unlist(strsplit(x, " ")))
b
> b
[[1]]
[1] "HELLO" "XO"

[[2]]
[1] "DO"    "HELLO"

[[3]]
[1] "TWO" "XO"

[[4]]
[1] "HO"

c <- unlist(lapply(b, function(y) paste(ifelse( y == "HELLO", "HELLO", gsub("O", "", y)), collapse = " " )))
c

[1] "HELLO X" "D HELLO" "TW X"    "H"
</code>```

Title: Selectively removing trailing string

Body:
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"

but I want

"HELLO X" "D HELLO" "TW X" "H"

Body:
A little lengthy, but you can try like this

a <- c("HELLO XO","DO HELLO","TWO XO","HO")
b <- lapply(a, function(x) unlist(strsplit(x, " ")))
b
> b
[[1]]
[1] "HELLO" "XO"

[[2]]
[1] "DO"    "HELLO"

[[3]]
[1] "TWO" "XO"

[[4]]
[1] "HO"

c <- unlist(lapply(b, function(y) paste(ifelse( y == "HELLO", "HELLO", gsub("O", "", y)), collapse = " " )))
c

[1] "HELLO X" "D HELLO" "TW X"    "H"


问:
Error Database schema could not be retrieved for this connection
Edit: if you are downvoting can you at least tell me what Im missing so I can improve my question?

I have a website which uses a SQL Server database. It works fine when building both debug and release.

But if I add a new SqlDataSource to my project and try to configure it in design view, I get this error:

Database scheme could not be retrieved for this connection. Please make sure the connection settings are correct and that the database is online.

Failed to retrieve data for this request.

  Failed to connect to server---------.

  Login failed for user 'xxxxxx'.

Even if I configure the connection string with the connection-guide, test the connection and save, it fails afterwards when trying to configure the datasource.

Connection string:

```<code>Data Source=SERVER\SQLEXPRESS,61180;Initial Catalog=DBNAME;User Id=USERNAME;Password=PASSWORD;
</code>```

So to clarify: The connection string works fine when running the website in both debug and release, and if I connect using SQL Server Management Studio, but the only place it doesn't work is when I try to configure the datasource in design view.

答:
After a lot of trial and error I found out that I had to put Persist Security Info=True; into the connectionstring to get it to work.

First time in my 10+ years of programming that I encountered this problem.

Body:
Edit: if you are downvoting can you at least tell me what Im missing so I can improve my question?

I have a website which uses a SQL Server database. It works fine when building both debug and release.

But if I add a new SqlDataSource to my project and try to configure it in design view, I get this error:

Database scheme could not be retrieved for this connection. Please make sure the connection settings are correct and that the database is online.

Failed to retrieve data for this request.

  Failed to connect to server---------.

  Login failed for user 'xxxxxx'.

Even if I configure the connection string with the connection-guide, test the connection and save, it fails afterwards when trying to configure the datasource.

Connection string:

Data Source=SERVER\SQLEXPRESS,61180;Initial Catalog=DBNAME;User Id=USERNAME;Password=PASSWORD;

So to clarify: The connection string works fine when running the website in both debug and release, and if I connect using SQL Server Management Studio, but the only place it doesn't work is when I try to configure the datasource in design view.


问:
git svn - <file> was not found in commit <hash>
In the middle of pulling down a (rather large) svn repo with git-svn, I encountered the following error message (generic info substituted for real info):

```<code>Found possible branch point: svn://server/project/trunk/dir => svn://server/project/branches/branchname, <revision>
Initializing parent: refs/remotes/branchname@<revision>
project/trunk/dir/file was not found in commit <hash> (r<revision>)
</code>```

I have read in other posts that it is possible to "un-fetch" this info through some tinkering.  However, I would rather not lose the history and go forward as painlessly as possible.

How can I get git-svn fetch to continue?

答:
This probably means that you are receiving a new svn revision which modifies a file which (for some reason) does not exist in your git commit equivalent of the parent svn revision.  One very easy way to cause this is to be inconsistent with --ignore-paths (originally there was no way to configure those and they had to be entered on every git-svn command line that might fetch).  Another way is for someone on the svn server end to change repository permissions in such a way that a whole subtree of files suddenly appears (from your perspective) that your git repository has no history for.

The easiest way to get past this immediate problem and continue git-svn fetch is to use --ignore-paths (or better the svn-remote.svn.ignore-paths config entry) to ignore the problem part of the tree.  You can get away with the command line argument to pass a single revision and you won't hit the problem again until someone modifies it on the svn side.

If you want to recover without --ignore-paths then you will need to fix the parent revision so that it includes the file being modified.  I wrote git-svn reset specifically to do the "un-fetch" you refer to with less tinkering.  It can reset your svn remote back to where the file was really created so you can integrate it into your history.  This won't wipe out your working copies, but you will need to reparent any working branches on this new history.

ContentLicense: CC BY-SA 2.5

Body:
In the middle of pulling down a (rather large) svn repo with git-svn, I encountered the following error message (generic info substituted for real info):

Found possible branch point: svn://server/project/trunk/dir => svn://server/project/branches/branchname, <revision>
Initializing parent: refs/remotes/branchname@<revision>
project/trunk/dir/file was not found in commit <hash> (r<revision>)

I have read in other posts that it is possible to "un-fetch" this info through some tinkering.  However, I would rather not lose the history and go forward as painlessly as possible.

How can I get git-svn fetch to continue?


问:
Get a list of users I have recently messaged Mysql
This is 'messages' table

```<code>---------------------------------
id  | sender  | receiver | seen |
---------------------------------
1   | john    |  jane    | 0    |
2   | john    |  jane    | 1    |
3   | dave    |  john    | 0    |   <- John has received one unseen msg
4   | john    |  dave    | 1    |
5   | john    |  rose    | 0    |
</code>```

I need to get a list of users john has interacted with. If john has any received unseen message, I need to highlight that message.

I tried this:

```<code>SELECT  DISTINCT
        CASE WHEN sender = 'john'
            THEN receiver
            ELSE sender
        END userID
FROM    messages
WHERE   'john' IN (sender, receiver)
</code>```

Output:

```<code>|jane|
|dave|
|rose|
</code>```

Expected Output:

```<code>userID|seen|
|dave |  0 |
|jane |  1 |
|rose |  0 |
</code>```

答:
Your question is not too clear, so I'll try to interpret it before providing an answer.

I believe, you would like to provide users with an overview of conversations with their counterparts by counterpart, highlighting those counterparts from which the particular user has an unread message.

This means, if the particular user received a message from a counterpart, which is not read, the query should return 0. In any other cases, the query should return 1. This also means, that if the particular user only sent a message, which is unread, the query still should return 1.

```<code>SELECT
    CASE WHEN sender = 'john' THEN receiver ELSE sender END as userID,
    COALESCE(MIN(CASE WHEN receiver = 'john' THEN seen ELSE null END), 1) AS seen
FROM messages
WHERE
    receiver = 'john' or sender = 'john'
GROUP BY
    CASE WHEN sender = 'john' THEN receiver ELSE sender END;
</code>```

Just to explain the main part of the code COALESCE(MIN(CASE WHEN receiver = 'john' THEN seen ELSE null END), 1):

The case ensures that the calculation runs only on the received messages.

The min() ensures that if there is an unreserved message from a counterpart, then the expression returns 0.

The coalesce() takes care of those counterparties, who did not send any messages back to the current user. In this case the returned value is 1, to make sure that counterpart is not highlighted.

Body:
This is 'messages' table

---------------------------------
id  | sender  | receiver | seen |
---------------------------------
1   | john    |  jane    | 0    |
2   | john    |  jane    | 1    |
3   | dave    |  john    | 0    |   <- John has received one unseen msg
4   | john    |  dave    | 1    |
5   | john    |  rose    | 0    |

I need to get a list of users john has interacted with. If john has any received unseen message, I need to highlight that message.

I tried this:

SELECT  DISTINCT
        CASE WHEN sender = 'john'
            THEN receiver
            ELSE sender
        END userID
FROM    messages
WHERE   'john' IN (sender, receiver)

Output:

|jane|
|dave|
|rose|

Expected Output:

userID|seen|
|dave |  0 |
|jane |  1 |
|rose |  0 |

Body:
Your question is not too clear, so I'll try to interpret it before providing an answer.

I believe, you would like to provide users with an overview of conversations with their counterparts by counterpart, highlighting those counterparts from which the particular user has an unread message.

This means, if the particular user received a message from a counterpart, which is not read, the query should return 0. In any other cases, the query should return 1. This also means, that if the particular user only sent a message, which is unread, the query still should return 1.

SELECT
    CASE WHEN sender = 'john' THEN receiver ELSE sender END as userID,
    COALESCE(MIN(CASE WHEN receiver = 'john' THEN seen ELSE null END), 1) AS seen
FROM messages
WHERE
    receiver = 'john' or sender = 'john'
GROUP BY
    CASE WHEN sender = 'john' THEN receiver ELSE sender END;

Just to explain the main part of the code COALESCE(MIN(CASE WHEN receiver = 'john' THEN seen ELSE null END), 1):

The case ensures that the calculation runs only on the received messages.

The min() ensures that if there is an unreserved message from a counterpart, then the expression returns 0.

The coalesce() takes care of those counterparties, who did not send any messages back to the current user. In this case the returned value is 1, to make sure that counterpart is not highlighted.


问:
Method alias with TypeScript
I assume this is the easiest way to implement a method alias with TS:

```<code>export class Foo {

 bar(){

 }

 aliasOfBar(){
   return this.bar.apply(this, arguments);
 }

}
</code>```

but I am simply wondering if there is another way we can define an alias with TS (or JS). Perhaps ideally without an extra function call.

If I do this, for example:

```<code>let mySharedFn = function () {

};

export class Foo {
  public bar = mySharedFn
  public aliasBar = mySharedFn
}
</code>```

it transpiles to this:

```<code>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var mySharedFn = function () {
};
var Foo = (function () {
    function Foo() {
        this.bar = mySharedFn;
        this.aliasBar = mySharedFn;
    }
    return Foo;
}());
exports.Foo = Foo;
</code>```

I'd like to avoid those extra calls that come with using the constructor to create the methods, etc.

答:
Maybe something with bind or with a reference:

```<code>export class Foo {
    public bar() {}
    public aliasBar = this.bar.bind(this);
    public aliasGreetSecond;
    constructor() {
        this.aliasGreetSecond = this.bar;
    }
}
</code>```

the above will transpile to:

```<code>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Foo = (function () {
    function Foo() {
        this.aliasBar = this.bar.bind(this);
        this.aliasGreetSecond = this.bar;
    }
    Foo.prototype.bar = function () { };
    return Foo;
}());
exports.Foo = Foo;
</code>```

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Test this in TypeScript playground:
https://www.typescriptlang.org/play/

```<code>class Greeter {
    greeting: string;
    aliasGreetSecond;

    constructor(message: string) {
        this.greeting = message;
        this.aliasGreetSecond = this.greet;
    }
    greet() {
        return "Hello, " + this.greeting;
    }

    aliasGreet = this.greet.bind(this);
}

let greeter = new Greeter("world");

let button = document.createElement('button');
let button2 = document.createElement('button');
button.textContent = "With bind";
button.onclick = function() {
    alert(greeter.aliasGreet());
}

 button2.textContent = "With reference";
 button2.onclick = function() {
    alert(greeter.aliasGreetSecond());
}

document.body.appendChild(button);
document.body.appendChild(button2);
</code>```

Which will transpile into:

```<code>var Greeter = /** @class */ (function () {
    function Greeter(message) {
        this.aliasGreet = this.greet.bind(this);
        this.greeting = message;
        this.aliasGreetSecond = this.greet;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
}());
var greeter = new Greeter("world");
var button = document.createElement('button');
var button2 = document.createElement('button');
button.textContent = "With bind";
button.onclick = function () {
    alert(greeter.aliasGreet());
};
button2.textContent = "With reference";
button2.onclick = function () {
    alert(greeter.aliasGreetSecond());
};
document.body.appendChild(button);
document.body.appendChild(button2);
</code>```

Title: Method alias with TypeScript

Body:
I assume this is the easiest way to implement a method alias with TS:

export class Foo {

 bar(){

 }

 aliasOfBar(){
   return this.bar.apply(this, arguments);
 }

}

but I am simply wondering if there is another way we can define an alias with TS (or JS). Perhaps ideally without an extra function call.

If I do this, for example:

let mySharedFn = function () {

};

export class Foo {
  public bar = mySharedFn
  public aliasBar = mySharedFn
}

it transpiles to this:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var mySharedFn = function () {
};
var Foo = (function () {
    function Foo() {
        this.bar = mySharedFn;
        this.aliasBar = mySharedFn;
    }
    return Foo;
}());
exports.Foo = Foo;

I'd like to avoid those extra calls that come with using the constructor to create the methods, etc.

Body:
Maybe something with bind or with a reference:

export class Foo {
    public bar() {}
    public aliasBar = this.bar.bind(this);
    public aliasGreetSecond;
    constructor() {
        this.aliasGreetSecond = this.bar;
    }
}

the above will transpile to:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Foo = (function () {
    function Foo() {
        this.aliasBar = this.bar.bind(this);
        this.aliasGreetSecond = this.bar;
    }
    Foo.prototype.bar = function () { };
    return Foo;
}());
exports.Foo = Foo;

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Test this in TypeScript playground:
https://www.typescriptlang.org/play/

class Greeter {
    greeting: string;
    aliasGreetSecond;

    constructor(message: string) {
        this.greeting = message;
        this.aliasGreetSecond = this.greet;
    }
    greet() {
        return "Hello, " + this.greeting;
    }

    aliasGreet = this.greet.bind(this);
}

let greeter = new Greeter("world");

let button = document.createElement('button');
let button2 = document.createElement('button');
button.textContent = "With bind";
button.onclick = function() {
    alert(greeter.aliasGreet());
}

 button2.textContent = "With reference";
 button2.onclick = function() {
    alert(greeter.aliasGreetSecond());
}

document.body.appendChild(button);
document.body.appendChild(button2);

Which will transpile into:

var Greeter = /** @class */ (function () {
    function Greeter(message) {
        this.aliasGreet = this.greet.bind(this);
        this.greeting = message;
        this.aliasGreetSecond = this.greet;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
}());
var greeter = new Greeter("world");
var button = document.createElement('button');
var button2 = document.createElement('button');
button.textContent = "With bind";
button.onclick = function () {
    alert(greeter.aliasGreet());
};
button2.textContent = "With reference";
button2.onclick = function () {
    alert(greeter.aliasGreetSecond());
};
document.body.appendChild(button);
document.body.appendChild(button2);


问:
Records sorted by date appear correctly in view and stored procedure but appear out of order in PHP results
I have a curious issue: PHP calls a MariaDB stored procedure that selects from an ordered view. The PHP results are sorted in a different date order as compared to running the stored procedure via command line or selecting directly from the view.

Something to do with PHP only being able to handle the date as a string, perhaps? (HTML5 date-type not compatible with required browsers.)  But I assume the data is sorted before being returned to PHP.

Thank you for reading!

Result of stored procedure through command line:

```<code>2017-12-01 | Attendance  |   4.00
2017-12-03 | Clay        |  18.00
2017-12-13 | Attendance  |   4.00
**2017-12-16 | Firing      |  12.00**
</code>```

Result of stored procedure called via PHP:

```<code>Date  Transaction Amount
2017-12-01    Attendance  $4.00
2017-12-03    Clay    $18.00
**2017-12-16  Firing  $12.00**
2017-12-13    Attendance  $4.00
</code>```

Here's the relevant code:

SQL ordered view:

```<code>Create View
`view_invoices`
AS select `view_sum`.`Total` AS `Total`,
    `view_sum`.`Member_ID` AS `Member_ID`,
    `bpg`.`accounts`.`Date` AS `Date`,
    `bpg`.`accounts`.`Transaction` AS `Transaction`,
    `bpg`.`accounts`.`Amount` AS `Amount`,
    `bpg`.`members`.`First_name` AS `First_name`,
    `bpg`.`members`.`Email` AS `Email`,
    `view_member_names`.`Member_name` AS `Member_name`
from ((((select sum(`bpg`.`accounts`.`Amount`) AS `Total`,
        `bpg`.`accounts`.`Member_ID` AS `Member_ID`
        from `bpg`.`accounts`
group by `bpg`.`accounts`.`Member_ID`)
    `view_sum` join `bpg`.`accounts`)
    join `bpg`.`members`)
    join `bpg`.`view_member_names`)
where `view_sum`.`Member_ID` = `bpg`.`accounts`.`Member_ID`
and `view_sum`.`Member_ID` = `bpg`.`members`.`Member_ID`
and `view_sum`.`Member_ID` = `view_member_names`.`Member_ID`
order by `view_member_names`.`Member_name`, `accounts`.`Date`;
</code>```

SQL stored procedure:

```<code>DELIMITER $$

CREATE PROCEDURE `invoices`
    (parameter_start_date DATE
    , parameter_end_date DATE)

    NOT DETERMINISTIC
    MODIFIES SQL DATA

    BEGIN

    SELECT * FROM `view_invoices`
    WHERE `Date` >= parameter_start_date
    AND `Date` <= parameter_end_date
    ;
    END;
$$
DELIMITER ;
</code>```

PHP call:

```<code><?php

function invoices($start_date, $end_date) {
        require LIB_DIR . '\pdo.php';

        // in development
        ini_set('display_errors',1);
        error_reporting(E_ALL);

    $prev = NULL;
    $intro = "<body style='background-color:#f0f2f4;font-family:Calibri,Verdana,Arial;'>";
    $intro .= "<ul style='float:left;list-style-type:none;width:100%;background-color:#d3d9de;'>";
    $intro .=    "<li style='display:inline;float:left;border-width:10px;border-color:#d3d9de;padding:5px;margin:5px;background-color:#FEFEFE;align-self:center;'>";
    $intro .= "<img src='PATH\public\images\BPG_logo_big.png' height='166' width='173'></li>";
    $intro .= "<li style='display:inline;float:left;border:5px;border-color:#d3d9de;margin:5px;padding:5px;background-color:#FEFEFE;width:250px;height:166px;align-self:center;text-indent:5pxeach-line;'>";
    $intro .= "<h2>Invoice</h2>";
    $intro .= "<p style='margin-left:15px;margin-bottom:0px;'>39 Elizabeth Street<br>Cloverdale WA 6076<br>treasurerbpg@gmail.com</p></li></ul>";

    $outro = "<p style='margin-left:15px;margin-bottom:0px;'>You can pay by direct deposit, at your bank, or by cheque using the details below.</p>";
    $outro .= "<p style='font-weight:bold;margin-left:15px;margin-bottom:0px;'>Please use your name as the payment reference. </p>";

    $sql = "CALL invoices (:start_date, :end_date)";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':start_date', $start_date);
    $stmt->bindValue(':end_date', $end_date);
    $stmt->execute();
    $stmt->bindColumn('Total', $total);
    $stmt->bindColumn('Member_ID', $id);
    $stmt->bindColumn('Date', $date);
    $stmt->bindColumn('Transaction', $transaction);
    $stmt->bindColumn('Amount', $amount);
    $stmt->bindColumn('First_name', $fname);
    $stmt->bindColumn('Email', $email);
    $stmt->bindColumn('Member_name', $name);

    $message = NULL;
    $curr_date = date("Y.m.d");
    $due_date = strtotime("+7 day");
    $due_date = date('j F Y', $due_date);
    $curr_date_words = date('j F Y');
    $start_date_words = strtotime($start_date);
    $start_date_words = date('j F Y', $start_date_words);
    $end_date_words = strtotime($end_date);
    $end_date_words = date('j F Y', $end_date_words);
    $filename = NULL;
    $number = $stmt->rowCount();
    echo $number;

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {

        $number = --$number;
        $person = $id;

        if ($person != $prev) {    // if the current member is different from the previous member, print header and row

            if ($row > 0) {
                $message .= "</table>"; /*added line of code*/
                $message .= $outro;

                if($filename != NULL) {
                    $savedfile = fopen(WRITE_DIR . $filename, "w") or die("File BPG_invoice_" . $filename . ".html was not created.");
                    fwrite($savedfile, $message);
                    fclose($savedfile);
                    echo $filename . " was saved here: " . WRITE_DIR . "<br>";
                }

          }

    // file name

            $filename = "\BPG_invoice_" . $curr_date . "_" . $name . ".html";
    // message
            $message = $intro;

            $message .= "<br><br><p style='margin-left:15px;'>Member: " . $name . "<br>";
            $message .= "Date: " . $curr_date_words . "</p>";
            $message .= "<p style='margin-left:15px;margin-bottom:0px;'><br>Dear " . $fname . "</p>";
            $message .= "<p style='margin-left:15px;margin-bottom:0px;'>Please find your fees for the period " . $start_date_words . " to " . $end_date_words . " below. </p>";
            $message .= "<p style='margin-left:15px;margin-bottom:0px;font-size:1.6em;font-weight:bold;'>The total of your invoice is: $" . $total . "</p>";

        if($total <= 0 ) {
            $message .= "<p style='margin-left:15px;margin-bottom:0px;'>Your account is in credit and does not require payment.</p>";
        }else{
            $message .= "<p style='margin-left:15px;margin-bottom:0px;'>Please pay before: " . $due_date . "</p>";
        }

            $message .= "<br><table style='margin-left:15px;width:350px;border-width:1px;border:solid;border:black;'><tr><th  style='padding:5px;text-align:center;'>Date</th><th style='padding:5px;text-align:center;'>Transaction</th><th style='padding:5px;text-align:center;'>Amount</th></tr>";

    // table rows

            $message .= "<tr><td style='padding:5px;text-align:center;'>" . $date . "</td>";
            $message .= "<td style='padding:5px;text-align:center;'>" . $transaction . "</td>";
            $message .= "<td style='padding:5px;text-align:center;'>$" . $amount . "</td></tr>";

    // separate if statement because || or was not working - DUPLICATED
        if($number == 0) {
    //        last_row();

                $message .= "</table>";
                $message .= $outro;

                $savedfile = fopen(WRITE_DIR . $filename, "w") or die("File BPG_invoice_" . $filename . ".html was not created.");
                fwrite($savedfile, $message);
                fclose($savedfile);
                echo $filename . " was saved here: " . WRITE_DIR . "<br>";
       }

            $prev = $person;

        }else{

            $message .= "<tr><td style='padding:5px;text-align:center;'>" . $date . "</td>";
            $message .= "<td style='padding:5px;text-align:center;'>" . $transaction . "</td>";
            $message .= "<td style='padding:5px;text-align:center;'>$" . $amount . "</td></tr>";

            $prev = $person;

// separate if statement because || or was not working - DUPLICATED
        if($number == 0) {
        //    last_row();

                $message .= "</table>";
                $message .= $outro;

                $savedfile = fopen(WRITE_DIR . $filename, "w") or die("File BPG_invoice_" . $filename . ".html was not created.");
                fwrite($savedfile, $message);
                fclose($savedfile);
                echo $filename . " was saved here: " . WRITE_DIR . "<br>";
            }

        }

    }
    $message .= "</table>";
 }

?>
</code>```

答:
without an ORDER BY in the SELECT statement that returns the result, MySQL/MariaDB can return rows in any order and be within the spec. (It's valid for the server to ignore the ORDER BY clause  in the view definition.)

As far as the difference in behavior between PHP and the command line client, that's a little odd (assuming that we are connecting to the same database, same credentials, calling the same procedure.)

Body:
I have a curious issue: PHP calls a MariaDB stored procedure that selects from an ordered view. The PHP results are sorted in a different date order as compared to running the stored procedure via command line or selecting directly from the view.

Something to do with PHP only being able to handle the date as a string, perhaps? (HTML5 date-type not compatible with required browsers.)  But I assume the data is sorted before being returned to PHP.

Thank you for reading!

Result of stored procedure through command line:

2017-12-01 | Attendance  |   4.00
2017-12-03 | Clay        |  18.00
2017-12-13 | Attendance  |   4.00
**2017-12-16 | Firing      |  12.00**

Result of stored procedure called via PHP:

Date  Transaction Amount
2017-12-01    Attendance  $4.00
2017-12-03    Clay    $18.00
**2017-12-16  Firing  $12.00**
2017-12-13    Attendance  $4.00

Here's the relevant code:

SQL ordered view:

Create View
`view_invoices`
AS select `view_sum`.`Total` AS `Total`,
    `view_sum`.`Member_ID` AS `Member_ID`,
    `bpg`.`accounts`.`Date` AS `Date`,
    `bpg`.`accounts`.`Transaction` AS `Transaction`,
    `bpg`.`accounts`.`Amount` AS `Amount`,
    `bpg`.`members`.`First_name` AS `First_name`,
    `bpg`.`members`.`Email` AS `Email`,
    `view_member_names`.`Member_name` AS `Member_name`
from ((((select sum(`bpg`.`accounts`.`Amount`) AS `Total`,
        `bpg`.`accounts`.`Member_ID` AS `Member_ID`
        from `bpg`.`accounts`
group by `bpg`.`accounts`.`Member_ID`)
    `view_sum` join `bpg`.`accounts`)
    join `bpg`.`members`)
    join `bpg`.`view_member_names`)
where `view_sum`.`Member_ID` = `bpg`.`accounts`.`Member_ID`
and `view_sum`.`Member_ID` = `bpg`.`members`.`Member_ID`
and `view_sum`.`Member_ID` = `view_member_names`.`Member_ID`
order by `view_member_names`.`Member_name`, `accounts`.`Date`;

SQL stored procedure:

DELIMITER $$

CREATE PROCEDURE `invoices`
    (parameter_start_date DATE
    , parameter_end_date DATE)

    NOT DETERMINISTIC
    MODIFIES SQL DATA

    BEGIN

    SELECT * FROM `view_invoices`
    WHERE `Date` >= parameter_start_date
    AND `Date` <= parameter_end_date
    ;
    END;
$$
DELIMITER ;

PHP call:

<?php

function invoices($start_date, $end_date) {
        require LIB_DIR . '\pdo.php';

        // in development
        ini_set('display_errors',1);
        error_reporting(E_ALL);

    $prev = NULL;
    $intro = "";
    $intro .= "
";
    $intro .=    "
";
    $intro .= "
";
    $intro .= "
";
    $intro .= "
Invoice
";
    $intro .= "
39 Elizabeth Street
Cloverdale WA 6076
treasurerbpg@gmail.com

";

    $outro = "
You can pay by direct deposit, at your bank, or by cheque using the details below.
";
    $outro .= "
Please use your name as the payment reference.
";

    $sql = "CALL invoices (:start_date, :end_date)";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':start_date', $start_date);
    $stmt->bindValue(':end_date', $end_date);
    $stmt->execute();
    $stmt->bindColumn('Total', $total);
    $stmt->bindColumn('Member_ID', $id);
    $stmt->bindColumn('Date', $date);
    $stmt->bindColumn('Transaction', $transaction);
    $stmt->bindColumn('Amount', $amount);
    $stmt->bindColumn('First_name', $fname);
    $stmt->bindColumn('Email', $email);
    $stmt->bindColumn('Member_name', $name);

    $message = NULL;
    $curr_date = date("Y.m.d");
    $due_date = strtotime("+7 day");
    $due_date = date('j F Y', $due_date);
    $curr_date_words = date('j F Y');
    $start_date_words = strtotime($start_date);
    $start_date_words = date('j F Y', $start_date_words);
    $end_date_words = strtotime($end_date);
    $end_date_words = date('j F Y', $end_date_words);
    $filename = NULL;
    $number = $stmt->rowCount();
    echo $number;

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {

        $number = --$number;
        $person = $id;

        if ($person != $prev) {    // if the current member is different from the previous member, print header and row

            if ($row > 0) {
                $message .= "
"; /*added line of code*/
                $message .= $outro;

                if($filename != NULL) {
                    $savedfile = fopen(WRITE_DIR . $filename, "w") or die("File BPG_invoice_" . $filename . ".html was not created.");
                    fwrite($savedfile, $message);
                    fclose($savedfile);
                    echo $filename . " was saved here: " . WRITE_DIR . "
";
                }

          }

    // file name

            $filename = "\BPG_invoice_" . $curr_date . "_" . $name . ".html";
    // message
            $message = $intro;

            $message .= "

Member: " . $name . "
";
            $message .= "Date: " . $curr_date_words . "
";
            $message .= "

Dear " . $fname . "
";
            $message .= "
Please find your fees for the period " . $start_date_words . " to " . $end_date_words . " below.
";
            $message .= "
The total of your invoice is: $" . $total . "
";

        if($total <= 0 ) {
            $message .= "
Your account is in credit and does not require payment.
";
        }else{
            $message .= "
Please pay before: " . $due_date . "
";
        }

            $message .= "

Date	Transaction	Amount
";

    // table rows

            $message .= "
" . $date . "	";
            $message .= "" . $transaction . "	";
            $message .= "$" . $amount . "
";

    // separate if statement because || or was not working - DUPLICATED
        if($number == 0) {
    //        last_row();

                $message .= "
";
                $message .= $outro;

                $savedfile = fopen(WRITE_DIR . $filename, "w") or die("File BPG_invoice_" . $filename . ".html was not created.");
                fwrite($savedfile, $message);
                fclose($savedfile);
                echo $filename . " was saved here: " . WRITE_DIR . "
";
       }

            $prev = $person;

        }else{

            $message .= "
" . $date . "	";
            $message .= "" . $transaction . "	";
            $message .= "$" . $amount . "
";

            $prev = $person;

// separate if statement because || or was not working - DUPLICATED
        if($number == 0) {
        //    last_row();

                $message .= "
";
                $message .= $outro;

                $savedfile = fopen(WRITE_DIR . $filename, "w") or die("File BPG_invoice_" . $filename . ".html was not created.");
                fwrite($savedfile, $message);
                fclose($savedfile);
                echo $filename . " was saved here: " . WRITE_DIR . "
";
            }

        }

    }
    $message .= "
";
 }

?>


问:
java 8 Map.merge is thread safe?
```<code>import java.util.HashMap;
import java.util.Map;

public class MainTest
{
    static Map<String, Integer> map = new HashMap();

    public static void incr()
    {
        map.merge("counter", 1, Integer::sum);
    }

    public static void decr()
    {
        map.merge("counter", -1, Integer::sum);
    }

    public static void main(String[] args) throws Exception
    {
        map.put("counter", 0);
        for (int i = 0; i < 10000; i++)
        {
            Thread t1 = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    incr();
                }
            });
            t1.join();
            t1.start();

            Thread t2 = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    decr();
                }
            });
            t2.join();
            t2.start();
        }
      System.out.println(map);
    }

}
</code>```

The result is {counter=-2} when main method is run.
Why is it not 0?

答:
The Javadoc of merge on the Map interface says:

The default implementation makes no guarantees about synchronization or atomicity properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties.

While HashMap overrides the default implementation, it has no documentation regarding concurrency properties of that implementation, but it does have this general statement:

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally

Therefore it's not thread safe.

P.S., it's not clear why you call t1.join() and t2.join() before you start the corresponding thread.

If you reverse the calls

```<code>    t1.join();
    t1.start();
</code>```

to

```<code>    t1.start();
    t1.join();
</code>```

and

```<code>    t2.join();
    t2.start();
</code>```

to

```<code>    t2.start();
    t2.join();
</code>```

you'll get an output of 0. Of course if you do that, there will be no concurrent modification at all, since each thread will start after the previous thread dies.

Another alternative is to synchronize the map.merge calls externally:

```<code>public static void incr()
{
    synchronized(map) {map.merge("counter", 1, Integer::sum);}
}

public static void decr()
{
    synchronized(map) {map.merge("counter", -1, Integer::sum);}
}
</code>```

Title: java 8 Map.merge is thread safe?

Body:
import java.util.HashMap;
import java.util.Map;

public class MainTest
{
    static Map<String, Integer> map = new HashMap();

    public static void incr()
    {
        map.merge("counter", 1, Integer::sum);
    }

    public static void decr()
    {
        map.merge("counter", -1, Integer::sum);
    }

    public static void main(String[] args) throws Exception
    {
        map.put("counter", 0);
        for (int i = 0; i < 10000; i++)
        {
            Thread t1 = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    incr();
                }
            });
            t1.join();
            t1.start();

            Thread t2 = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    decr();
                }
            });
            t2.join();
            t2.start();
        }
      System.out.println(map);
    }

}

The result is {counter=-2} when main method is run.
Why is it not 0?

Body:
The Javadoc of merge on the Map interface says:

The default implementation makes no guarantees about synchronization or atomicity properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties.

While HashMap overrides the default implementation, it has no documentation regarding concurrency properties of that implementation, but it does have this general statement:

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally

Therefore it's not thread safe.

P.S., it's not clear why you call t1.join() and t2.join() before you start the corresponding thread.

If you reverse the calls

    t1.join();
    t1.start();

to

    t1.start();
    t1.join();

and

    t2.join();
    t2.start();

to

    t2.start();
    t2.join();

you'll get an output of 0. Of course if you do that, there will be no concurrent modification at all, since each thread will start after the previous thread dies.

Another alternative is to synchronize the map.merge calls externally:

public static void incr()
{
    synchronized(map) {map.merge("counter", 1, Integer::sum);}
}

public static void decr()
{
    synchronized(map) {map.merge("counter", -1, Integer::sum);}
}


问:
Struct user - has many sessions. Find a user given a session
I'm using gorm for Go with MySQL driver, and here's what I'm trying to do.
Here are my two structs:

```<code>type User struct {
    ID       uint      `gorm:"primary_key"`
    Email    string    `sql:"unique_index;not null;type:varchar(64)"`
    Password string    `sql:"index;not null;type:varchar(64)"`
    Sessions []Session `gorm:"ForeignKey:UserID"`
    Roles    []Role    `gorm:"many2many:users_roles;"`
    Level    uint      `sql:"not null;type:tinyint(1);DEFAULT:1"`
}

type Session struct {
    ID       uint      `gorm:"primary_key"`
    SessionID string `sql:"index"`
    UserID    uint   `sql:"index"`
    UpdatedAt time.Time
}
</code>```

As is seen from the code, a struct User is supposed to have a has many relationship with the Sessions.

Now let's suppose I have a user record in the database, and a session record in the sessions table with the user's ID.
I'd like to be able to retrieve the user data based on the Session ID. That is, find a session record based on SessionID, and then grab the user info based on the UserID of that session.

In pure MySQL, I'd do it like this:

```<code>SELECT
    *
FROM
    `users
WHERE `id` = (SELECT `user_id` FROM `sessions` WHERE `session_id` = <MY-SESSION-ID> LIMIT 1)
</code>```

Or I could do it with a join like this

```<code>SELECT
    `u`.*
FROM
    `users` `u`
LEFT JOIN `sessions` `s`
ON `s`.`user_id` = `u`.`id`
WHERE
    `s`.`session_id` = <MY-SESSION-ID>
GROUP BY `u`.`id`
</code>```

Anyway, how would I do it with gorm without resorting to raw SQL?

答:
What you want is gorm's preloading feature: http://jinzhu.me/gorm/crud.html#preloading-eager-loading

It has the ability to filter the child table with a where-like syntax.

Body:
I'm using gorm for Go with MySQL driver, and here's what I'm trying to do.
Here are my two structs:

type User struct {
    ID       uint      `gorm:"primary_key"`
    Email    string    `sql:"unique_index;not null;type:varchar(64)"`
    Password string    `sql:"index;not null;type:varchar(64)"`
    Sessions []Session `gorm:"ForeignKey:UserID"`
    Roles    []Role    `gorm:"many2many:users_roles;"`
    Level    uint      `sql:"not null;type:tinyint(1);DEFAULT:1"`
}

type Session struct {
    ID       uint      `gorm:"primary_key"`
    SessionID string `sql:"index"`
    UserID    uint   `sql:"index"`
    UpdatedAt time.Time
}

As is seen from the code, a struct User is supposed to have a has many relationship with the Sessions.

Now let's suppose I have a user record in the database, and a session record in the sessions table with the user's ID.
I'd like to be able to retrieve the user data based on the Session ID. That is, find a session record based on SessionID, and then grab the user info based on the UserID of that session.

In pure MySQL, I'd do it like this:

SELECT
    *
FROM
    `users
WHERE `id` = (SELECT `user_id` FROM `sessions` WHERE `session_id` = <MY-SESSION-ID> LIMIT 1)

Or I could do it with a join like this

SELECT
    `u`.*
FROM
    `users` `u`
LEFT JOIN `sessions` `s`
ON `s`.`user_id` = `u`.`id`
WHERE
    `s`.`session_id` = <MY-SESSION-ID>
GROUP BY `u`.`id`

Anyway, how would I do it with gorm without resorting to raw SQL?


问:
printing buffer from ReceiveFrom terminates thread
I have a thread in C# that broadcasts from a UDP socket every 1 second

on a different thread, I have this

```<code> while (true)
 {
  if (m_UdpReceiveSocket.Poll(0, SelectMode.SelectRead))
  {
   EndPoint ep = new IPEndPoint(IPAddress.Any, s_BroadcastPort);
   byte[] buffer = new byte[1024];

   m_UdpReceiveSocket.ReceiveFrom(buffer, 0, 1024, SocketFlags.None, ref ep);

   Console.WriteLine("testing");
   Console.WriteLine( ASCIIEncoding.ASCII.GetString(buffer) + "  " + ((IPEndPoint) ep).Address + ":" + ((IPEndPoint) ep).Port);
  }

  Thread.Sleep(1);
 }
</code>```

If I comment out the second call to Console.WriteLine, everything works fine, the other thread broadcasts and this thread receives the information, but if I use the second Console.WriteLine (even without priting the EndPoint) then the thread quits without any exception the second time Console.WriteLine is called

thank you

problem solved, I just needed to take into consideration how much I receive before converting to string

as a side question why can't I see my packets in Wireshark ?

答: As for the sidenote. I believe my colleague had the same issue the other week. You will not see packets in Wireshark if your client is the same machine as the server. </p>

Body:
I have a thread in C# that broadcasts from a UDP socket every 1 second

on a different thread, I have this

 while (true)
 {
  if (m_UdpReceiveSocket.Poll(0, SelectMode.SelectRead))
  {
   EndPoint ep = new IPEndPoint(IPAddress.Any, s_BroadcastPort);
   byte[] buffer = new byte[1024];

   m_UdpReceiveSocket.ReceiveFrom(buffer, 0, 1024, SocketFlags.None, ref ep);

   Console.WriteLine("testing");
   Console.WriteLine( ASCIIEncoding.ASCII.GetString(buffer) + "  " + ((IPEndPoint) ep).Address + ":" + ((IPEndPoint) ep).Port);
  }

  Thread.Sleep(1);
 }

If I comment out the second call to Console.WriteLine, everything works fine, the other thread broadcasts and this thread receives the information, but if I use the second Console.WriteLine (even without priting the EndPoint) then the thread quits without any exception the second time Console.WriteLine is called

thank you

problem solved, I just needed to take into consideration how much I receive before converting to string

as a side question why can't I see my packets in Wireshark ?


问:
JavaScript changing CSS not working inside of if statement
Here is my html :

```<code><a class="btn btn-primary btn-lg" id="signUpBtn" href="./pages/createaccount.php" onmouseover="rotateBtn()"> Sign up »</a>
</code>```

Here is the JS... the style changes don't work when I take it out of the if statement. I need the if statement to toggle back and forth between the two rotations.
Doing this to learn, want to use JS and also see how it works with jQuery

```<code>function rotateBtn() {
var isRotated = 0;
document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}
</code>```

答:
how about setting  </p>

```<code>if(isRotated=='0'){
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}else if(isRotated=='1'){
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}
</code>```

Body:
Here is my html :

 Sign up »

Here is the JS... the style changes don't work when I take it out of the if statement. I need the if statement to toggle back and forth between the two rotations.
Doing this to learn, want to use JS and also see how it works with jQuery

function rotateBtn() {
var isRotated = 0;
document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}

Body:
how about setting

if(isRotated=='0'){
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}else if(isRotated=='1'){
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}


问:
Large gap forms between RecyclerView items when scrolling down
I'm making a ToDo list app, and while testing it, for some reason, a huge gap forms between the items whenever I try to scroll down. It always happens whenever I Drag and Drop the items, but I don't see any errors with my ItemTouchHelper adapter and callback class. It would be awesome if you can help me out.

Before:

After:

RecyclerAdapter.java

```<code>public class RecyclerAdapter extends

RecyclerView.Adapter<RecyclerAdapter.RecyclerVH> implements ItemTouchHelperAdapter{
private LayoutInflater layoutInflater;
ArrayList<Info> data;
Context context;

public RecyclerAdapter(Context context) {
    layoutInflater = LayoutInflater.from(context);
    this.context = context;
}

public void setData(ArrayList<Info> data) {
    this.data = data;
    notifyDataSetChanged();
}

@Override
public RecyclerVH onCreateViewHolder(ViewGroup viewGroup, int position) {
    View view = layoutInflater.inflate(R.layout.custom_row, viewGroup, false);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("R.A onClick Owen", "onClick method triggered");
        }
    });
    RecyclerVH recyclerVH = new RecyclerVH(view);
    return recyclerVH;
}

@Override
public void onBindViewHolder(RecyclerVH recyclerVH, int position) {
    Log.d("RecyclerView", "onBindVH called: " + position);

    final Info currentObject = data.get(position);
    // Current Info object retrieved for current RecyclerView item - USED FOR DELETE
    recyclerVH.listTitle.setText(currentObject.title);
    recyclerVH.listContent.setText(currentObject.content);

    /*recyclerVH.listTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Open new Activity containing note content
            Toast.makeText(this, "Opening: " + currentObject.title, Toast.LENGTH_LONG).show();
        }
    });*/
}

public void deleteItem(int position) {
    DBInfo dbInfo = new DBInfo(context);
    dbInfo.deleteNote(data.get(position));
    // Deletes RV item/position's Info object

    data.remove(position);
    // Removes Info object at specified position

    notifyItemRemoved(position);
    // Notifies the RV that item has been removed
}

@Override
public int getItemCount() {
    return data.size();
}

// This is where the Swipe and Drag-And-Drog methods come into place
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    // Swapping positions
    // ATTEMPT TO UNDERSTAND WHAT IS GOING ON HERE
    Collections.swap(data, fromPosition, toPosition);
    notifyItemMoved(fromPosition, toPosition);
    return true;
}

@Override
public void onItemDismiss(int position) {
    // Deleting item from RV and DB
    deleteItem(position);
}

class RecyclerVH extends RecyclerView.ViewHolder implements View.OnClickListener{
    // OnClickListener is implemented here
    // Can also be added at onBindViewHolder above
    TextView listTitle, listContent;

    public RecyclerVH(View itemView) {
        super(itemView);

        listTitle = (TextView) itemView.findViewById(R.id.title);
        listContent = (TextView) itemView.findViewById(R.id.content);

        listTitle.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(context, "Opening: Note" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
        // PS NEVER ADD listTitle VARIABLE AS PUBLIC VARIABLE ABOVE WHICH IS GIVEN VALUE AT ONBINDVH
        // THIS IS BECAUSE THE VALUE WILL CHANGE IF ITEM IS ADDED OR DELETED
    }
}
}
</code>```

activity_main.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:weightSum="1">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/rounded_corners" />

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <com.melnykov.fab.FloatingActionButton
            android:id="@+id/fab_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginBottom="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginEnd="16dp"
            android:gravity="bottom|end"
            android:onClick="addNote"
            android:src="@drawable/fab_ic_add"
            fab:fab_colorNormal="@color/colorPrimary"
            fab:fab_colorPressed="@color/colorPrimaryDark"
            fab:fab_colorRipple="@color/colorPrimaryDark" />
    </RelativeLayout>
</FrameLayout>
</LinearLayout>
</code>```

custom_row.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/main"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:padding="8dp"
        android:text="@string/test"
        android:textSize="18sp"
        android:textStyle="bold" />
</LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/main"
    android:paddingLeft="8dp">
    <TextView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/test"
        android:textSize="15sp" />
</LinearLayout>
</RelativeLayout>
</code>```

Thank you so much to whoever can help me out. I am pulling my hair out as I type.

EDIT: I have confirmed that it is not my ItemTouchHelper class that's the problem. (Tried running without it being called, problem still occurs.)
Also, it seems that when a dialog is shown and the keyboard brought up, the RecyclerView in the background resolves the problem by itself. After dialog is removed, the problem repeats (i.e. Scrolling puts massive space between items)

答:
Avoid taking the view in item layout with a container like this:

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

<data/>

<android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

<TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?android:listPreferredItemHeight"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</android.support.constraint.ConstraintLayout>
</layout>
</code>```

as in this case match_parent will do its work and the problem will still remain! Rather take it like this:

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

    <data/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?android:listPreferredItemHeight"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</layout>
</code>```

[Note: Above code has data binding attached to it, don't use <layout> & <data> tags if not using data binding]

Other than this, if you must use any view group containers, than take a look the height and width attributes in the container, and try change those from match_parent to wrap_content. That should resolve the issue. For more transparency, one can try giving background colours and see through it to identify actual problem.

Body:
I'm making a ToDo list app, and while testing it, for some reason, a huge gap forms between the items whenever I try to scroll down. It always happens whenever I Drag and Drop the items, but I don't see any errors with my ItemTouchHelper adapter and callback class. It would be awesome if you can help me out.

Before:

After:

RecyclerAdapter.java

public class RecyclerAdapter extends

RecyclerView.Adapter<RecyclerAdapter.RecyclerVH> implements ItemTouchHelperAdapter{
private LayoutInflater layoutInflater;
ArrayList<Info> data;
Context context;

public RecyclerAdapter(Context context) {
    layoutInflater = LayoutInflater.from(context);
    this.context = context;
}

public void setData(ArrayList<Info> data) {
    this.data = data;
    notifyDataSetChanged();
}

@Override
public RecyclerVH onCreateViewHolder(ViewGroup viewGroup, int position) {
    View view = layoutInflater.inflate(R.layout.custom_row, viewGroup, false);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("R.A onClick Owen", "onClick method triggered");
        }
    });
    RecyclerVH recyclerVH = new RecyclerVH(view);
    return recyclerVH;
}

@Override
public void onBindViewHolder(RecyclerVH recyclerVH, int position) {
    Log.d("RecyclerView", "onBindVH called: " + position);

    final Info currentObject = data.get(position);
    // Current Info object retrieved for current RecyclerView item - USED FOR DELETE
    recyclerVH.listTitle.setText(currentObject.title);
    recyclerVH.listContent.setText(currentObject.content);

    /*recyclerVH.listTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Open new Activity containing note content
            Toast.makeText(this, "Opening: " + currentObject.title, Toast.LENGTH_LONG).show();
        }
    });*/
}

public void deleteItem(int position) {
    DBInfo dbInfo = new DBInfo(context);
    dbInfo.deleteNote(data.get(position));
    // Deletes RV item/position's Info object

    data.remove(position);
    // Removes Info object at specified position

    notifyItemRemoved(position);
    // Notifies the RV that item has been removed
}

@Override
public int getItemCount() {
    return data.size();
}

// This is where the Swipe and Drag-And-Drog methods come into place
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    // Swapping positions
    // ATTEMPT TO UNDERSTAND WHAT IS GOING ON HERE
    Collections.swap(data, fromPosition, toPosition);
    notifyItemMoved(fromPosition, toPosition);
    return true;
}

@Override
public void onItemDismiss(int position) {
    // Deleting item from RV and DB
    deleteItem(position);
}

class RecyclerVH extends RecyclerView.ViewHolder implements View.OnClickListener{
    // OnClickListener is implemented here
    // Can also be added at onBindViewHolder above
    TextView listTitle, listContent;

    public RecyclerVH(View itemView) {
        super(itemView);

        listTitle = (TextView) itemView.findViewById(R.id.title);
        listContent = (TextView) itemView.findViewById(R.id.content);

        listTitle.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(context, "Opening: Note" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
        // PS NEVER ADD listTitle VARIABLE AS PUBLIC VARIABLE ABOVE WHICH IS GIVEN VALUE AT ONBINDVH
        // THIS IS BECAUSE THE VALUE WILL CHANGE IF ITEM IS ADDED OR DELETED
    }
}
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:weightSum="1">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/rounded_corners" />

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <com.melnykov.fab.FloatingActionButton
            android:id="@+id/fab_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginBottom="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginEnd="16dp"
            android:gravity="bottom|end"
            android:onClick="addNote"
            android:src="@drawable/fab_ic_add"
            fab:fab_colorNormal="@color/colorPrimary"
            fab:fab_colorPressed="@color/colorPrimaryDark"
            fab:fab_colorRipple="@color/colorPrimaryDark" />
    </RelativeLayout>
</FrameLayout>
</LinearLayout>

custom_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/main"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:padding="8dp"
        android:text="@string/test"
        android:textSize="18sp"
        android:textStyle="bold" />
</LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/main"
    android:paddingLeft="8dp">
    <TextView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/test"
        android:textSize="15sp" />
</LinearLayout>
</RelativeLayout>

Thank you so much to whoever can help me out. I am pulling my hair out as I type.

EDIT: I have confirmed that it is not my ItemTouchHelper class that's the problem. (Tried running without it being called, problem still occurs.)
Also, it seems that when a dialog is shown and the keyboard brought up, the RecyclerView in the background resolves the problem by itself. After dialog is removed, the problem repeats (i.e. Scrolling puts massive space between items)

Body:
Avoid taking the view in item layout with a container like this:

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

<data/>

<android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

<TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?android:listPreferredItemHeight"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</android.support.constraint.ConstraintLayout>
</layout>

as in this case match_parent will do its work and the problem will still remain! Rather take it like this:

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

    <data/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?android:listPreferredItemHeight"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</layout>

[Note: Above code has data binding attached to it, don't use <layout> & <data> tags if not using data binding]

Other than this, if you must use any view group containers, than take a look the height and width attributes in the container, and try change those from match_parent to wrap_content. That should resolve the issue. For more transparency, one can try giving background colours and see through it to identify actual problem.


问:
Combine multiple row to single row for unique values in multiple column

I am trying to get unique rows based on unique values on multiple columns in SQL Server 2012.

Source Data:

UserId  ---- P1 ---- P2 ------ P3

101  ------- NO ---- NO ------- YES

101  ------- NO ---- YES ------ NO

101  ------- YES ---- NO ------- NO

102 -------- NO ----- NO ------- NO

My source data has 'YES' in single columns for multiple rows.

I'm trying to get the result as follows:

Desired Output:

UserId  ---- P1 ---- P2 ------ P3

101  ------- YES ---- YES ----- YES

102 -------- NO ----- NO ------- NO

Any ideas or code-sample will be greatly appreciated.

答:
Try this

```<code>WITH CTE
AS
(
   SELECT
      DISTINCT UserId
  FROM T1
)
SELECT
UserId,
P1 = CASE WHEN EXISTS(SELECT 1 FROM T1 WHERE UserId = CTE.UserId AND P1='YES')
THEN 'YES' ELSE 'NO' END,
P2 = CASE WHEN EXISTS(SELECT 1 FROM T1 WHERE UserId = CTE.UserId AND P2='YES')
THEN 'YES' ELSE 'NO' END,
P3  = CASE WHEN EXISTS(SELECT 1 FROM T1 WHERE UserId = CTE.UserId AND P3='YES')
THEN 'YES' ELSE 'NO' END
FROM CTE
</code>```

Note : Assuming your table name as T1

Body:
Try this

WITH CTE
AS
(
   SELECT
      DISTINCT UserId
  FROM T1
)
SELECT
UserId,
P1 = CASE WHEN EXISTS(SELECT 1 FROM T1 WHERE UserId = CTE.UserId AND P1='YES')
THEN 'YES' ELSE 'NO' END,
P2 = CASE WHEN EXISTS(SELECT 1 FROM T1 WHERE UserId = CTE.UserId AND P2='YES')
THEN 'YES' ELSE 'NO' END,
P3  = CASE WHEN EXISTS(SELECT 1 FROM T1 WHERE UserId = CTE.UserId AND P3='YES')
THEN 'YES' ELSE 'NO' END
FROM CTE

Note : Assuming your table name as T1


问:
How to disable browser caching of CSS, JS files in CakePHP 3
I am developing in CakePHP 3.5.* in localhost in Windows. Is there a way to load most recent versions of assets such as CSS, Javascript while developing? I remember there is something like timestamp settings but could not figure that out while looking at the documentation.</p>

答:
I figured it out. It is:

```<code>'Asset' => [
    'timestamp' => true,
],
</code>```

There is a settings in the config/app.php file, which by default is:

```<code>'Asset' => [
    // 'timestamp' => true,
],
</code>```

A comment just above it says,

Apply timestamps with the last modified time to static assets (js,
  css, images). Will append a querystring parameter containing the time
  the file was modified. This is useful for busting browser caches.

Set to true to apply timestamps when debug is true. Set to 'force' to
  always enable timestamping regardless of debug value.

Which means, to force most recent assets it will look like:

```<code>'Asset' => [
    'timestamp' => true,
],
</code>```

In another answer i found it answered as:

```<code>'Asset' => [
    'force'
],
</code>```

But it does not work in CakePHP 3.5.*. May be it worked in earlier versions.

Body:
I figured it out. It is:

'Asset' => [
    'timestamp' => true,
],

There is a settings in the config/app.php file, which by default is:

'Asset' => [
    // 'timestamp' => true,
],

A comment just above it says,

Apply timestamps with the last modified time to static assets (js,
  css, images). Will append a querystring parameter containing the time
  the file was modified. This is useful for busting browser caches.

Set to true to apply timestamps when debug is true. Set to 'force' to
  always enable timestamping regardless of debug value.

Which means, to force most recent assets it will look like:

'Asset' => [
    'timestamp' => true,
],

In another answer i found it answered as:

'Asset' => [
    'force'
],

But it does not work in CakePHP 3.5.*. May be it worked in earlier versions.


问:
Ionic 3 build error for iOS platform - ARCHIVE FAILED
I'm working with Ionic 3, iPhone 7 plus, iOS 11, and trying to build for iOS. When running ionic cordova build ios I'm getting this error. I've tried to remove and add the platform multiple times, without any result.

** ARCHIVE FAILED **

The following build commands failed:  Ld
  /Users/user/Library/Developer/Xcode/DerivedData/app-appdahiizzsdsdsdddoqgtygiuoqxm/Build/Intermediates.noindex/ArchiveIntermediates/app/IntermediateBuildFilesPath/Fishtank.build/Debug-iphoneos/app.build/Objects-normal/arm64/app
  normal arm64 (1 failure) Error: Error code 65 for command: xcodebuild
  with args:
  -xcconfig,/Users/user/Documents/app/Development/app/platforms/ios/cordova/build-debug.xcconfig,-workspace,app.xcworkspace,-scheme,app,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,app.xcarchive,archive,CONFIGURATION_BUILD_DIR=/Users/user/Documents/app/Development/app/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/Users/user/Documents/app/Development/app/platforms/ios/build/sharedpch

[ERROR] An error occurred while running cordova build ios (exit code
  1).

Here's my ionic info:

cli packages:

```<code>@ionic/cli-utils  : 1.15.2
ionic (Ionic CLI) : 3.15.2
</code>```

global packages:

```<code>cordova (Cordova CLI) : 7.1.0
</code>```

local packages:

```<code>@ionic/app-scripts : 2.1.3
Cordova Platforms  : ios 4.5.2
Ionic Framework    : ionic-angular 3.7.1
</code>```

System:

```<code>ios-deploy : 1.9.2
ios-sim    : 5.0.12
Node       : v7.10.0
npm        : 4.2.0
OS         : macOS Sierra
Xcode      : Xcode 9.0 Build version 9A235
</code>```

Environment Variables:

```<code>ANDROID_HOME : not set
</code>```

Misc:

```<code>backend : legacy
</code>```

答:
if your xcode account isn't "agent" try this way:

when run ionic cordova build ios disconnecting your iphone from your mac

Body:
I'm working with Ionic 3, iPhone 7 plus, iOS 11, and trying to build for iOS. When running ionic cordova build ios I'm getting this error. I've tried to remove and add the platform multiple times, without any result.

** ARCHIVE FAILED **

The following build commands failed:  Ld
  /Users/user/Library/Developer/Xcode/DerivedData/app-appdahiizzsdsdsdddoqgtygiuoqxm/Build/Intermediates.noindex/ArchiveIntermediates/app/IntermediateBuildFilesPath/Fishtank.build/Debug-iphoneos/app.build/Objects-normal/arm64/app
  normal arm64 (1 failure) Error: Error code 65 for command: xcodebuild
  with args:
  -xcconfig,/Users/user/Documents/app/Development/app/platforms/ios/cordova/build-debug.xcconfig,-workspace,app.xcworkspace,-scheme,app,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,app.xcarchive,archive,CONFIGURATION_BUILD_DIR=/Users/user/Documents/app/Development/app/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/Users/user/Documents/app/Development/app/platforms/ios/build/sharedpch

[ERROR] An error occurred while running cordova build ios (exit code
  1).

Here's my ionic info:

cli packages:

@ionic/cli-utils  : 1.15.2
ionic (Ionic CLI) : 3.15.2

global packages:

cordova (Cordova CLI) : 7.1.0

local packages:

@ionic/app-scripts : 2.1.3
Cordova Platforms  : ios 4.5.2
Ionic Framework    : ionic-angular 3.7.1

System:

ios-deploy : 1.9.2
ios-sim    : 5.0.12
Node       : v7.10.0
npm        : 4.2.0
OS         : macOS Sierra
Xcode      : Xcode 9.0 Build version 9A235

Environment Variables:

ANDROID_HOME : not set

Misc:

backend : legacy


问:
How to create dynamic variables in JS?
This is my Code:

```<code>function NewPerson() {
    var count = parseInt($('#HiddenField').html());
    count++;
    $('#HiddenField').html(count);
    Var dynamicVariable = 'Person'+'Count'
}
</code>```

I want to define variable on this line Var **dynamicVariable** = 'Person'+'Count'

Now I need to create variable with count number

答:
Usually, the design pattern in this scenario is to use an object.</p>

```<code>//These are your variables
var myVar1 = '1';
var myVar2 = '2';

//The object holding all your dynamic variables
var MyVarObj = {};

//Create dynamic variables (object properties)
MyVarObj[myVar1] = 'value1'
MyVarObj[myVar2] = 'value2'

console.log(MyVarObj);   // {1: 'value1', 2: 'value2'}
</code>```

Title: How to create dynamic variables in JS?

Body:
This is my Code:

function NewPerson() {
    var count = parseInt($('#HiddenField').html());
    count++;
    $('#HiddenField').html(count);
    Var dynamicVariable = 'Person'+'Count'
}

I want to define variable on this line Var **dynamicVariable** = 'Person'+'Count'

Now I need to create variable with count number

Body:
Usually, the design pattern in this scenario is to use an object.

//These are your variables
var myVar1 = '1';
var myVar2 = '2';

//The object holding all your dynamic variables
var MyVarObj = {};

//Create dynamic variables (object properties)
MyVarObj[myVar1] = 'value1'
MyVarObj[myVar2] = 'value2'

console.log(MyVarObj);   // {1: 'value1', 2: 'value2'}


问:
Finding gameObject via direction of input

I have a list of gameObjects added to a List within the area as shown. What I need is a directional input to choose a target from the origin point. I have got it work to get this origin point.

My first attempt of this was to get it via rayCast, but by doing that there were times directional inputs need to directly hit target object by the ray. This is no problem if input was done like case #1.

However, what I need it to really work is when input direction was as if case #2 or #3 the input will still get a target. My second attempt was to do this with sphereCast, but it still needed a target in sphere proximity and multiple targets hit by sphereCast still needed to result in only one and more accurate target selection by input.

Since I have all the transform.position of all the possible targets as well as the origin point I wondered there would be a more elegant way of resolving this via comparing vector3's of these coordinates(origin and targets in the general direction).

Here's my latest approach:

```<code>//
// m_targetList is the list containing all GameObjects as GameObjects in other script m_collector. All m_collector does is this.
//

using System.Collections.Generic;
using UnityEngine;

public class TargetSwitcher : MonoBehaviour
{
    private TargetCollector m_collector;
    private Transform m_origin;

    public bool m_targetChanged = false;

    public GameObject m_target;

    public LayerMask m_targetMask;

    private Dictionary<Vector3, float> m_targetInfo = new Dictionary<Vector3, float>();

    private void Awake()
    {
        m_collector = GetComponent<TargetCollector>();
        m_origin = GameObject.Find("TargetOrigin").transform;
        m_tracker = GameObject.Find("TargetTracker").transform;
        m_bound = GetComponent<BoxCollider>();
    }

    public void UpdateBearing(GameObject origin)
    {
        m_origin = origin.transform;

        foreach (GameObject target in m_collector.m_targetList)
        {
            Vector3 dir = (target.transform.position - origin.transform.position).normalized
            float dist = Vector3.Distance(origin.transform.position, target.transform.position);

            m_targetInfo.Add(dir, dist);
        }
    }

    public void SwitchTarget()
    {
        if (!m_targetChanged)
        {
            Vector2 dir = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized;

            // Find closest direction value from Dictionary to dir of here
            // Compare distance from origin if multiple targets and choose the nearest
        }
    }

    public void ReturnToIdle()
    {
        m_origin.position = m_target.transform.position;
        m_targetChanged = false;
        m_targetInfo.Clear();
    }

    public struct TargetInfo
    {
        public Vector3 bearing;
        public float distance;

        public TargetInfo(Vector3 bearing, float distance)
        {
            this.bearing = bearing;
            this.distance = distance;
        }
    }
}
</code>```

Generally, I'm trying to compare the normalized vector of directional input to the normalized vector from the origin to each target before SwitchTarget(). The input method here is Gamepad axis x and y as Horizontal and Vertical.

Reposting this question since a provided answer was very far from the question and marked as duplicate(Given answer was about finding gameObject by distance only, this question is about direction and distance portion is to compare second-handedly when multiple items were found in the direction)

Edit

After some trials with dot product now I'm sure this is much likely where I want to head. There are much inconsistency I need to get on with, though.
Here's my most recent attempt:

```<code>private void Update()
{
    UpdateBearing();

    Vector3 input = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);

    if (input != Vector3.zero)
    {
        SwitchTarget();
    }
}

public void UpdateBearing(GameObject origin)
{
    m_origin.position = origin.transform.position;

    foreach (GameObject target in m_collector.m_targetList)
    {
        Vector3 dir = (target.transform.position - origin.transform.position).normalized;
        if (!m_targetInfo.ContainsKey(target))
        {
            m_targetInfo.Add(target, dir);
        }
    }
}

public void SwitchTarget()
{
    GameObject oldTarget = m_collector.m_target;

    if (!m_targetChanged)
    {
        Vector3 dir = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0).normalized;
        Debug.DrawRay(m_origin.position, dir * 100, Color.yellow, 0.5f);

        foreach (KeyValuePair<GameObject, Vector3> possibleTarget in m_targetInfo)
        {
            float dot = Vector3.Dot(dir, possibleTarget.Value);

            if (dot > 0.5f) // Compare DP difference of added dot and input dot
            {
                GameObject newTarget = possibleTarget.Key;

                if (oldTarget != newTarget)
                {
                    Debug.Log(possibleTarget.Value + " // " + dot);

                    m_target = newTarget;
                    m_collector.m_target = newTarget;
                    m_targetChanged = true;
                }
            }
        }
    }
}
</code>```

With this, I'm kind of getting gameObject selection without raycasting and missing any targets. However, I'm sure I need better case comparison than if(dot > 0.5f). Also, my rough assumption is that if I don't update the value of the dictionary m_targetInfo for each Key I'd have another inconsistency if those targets ever move. Anyways, I'm still confused how properly utilize this to achieve my end goal.

答:
Since you have all the desired game objects in the area you can create a for loop and check the angle between your look direction and their position, if it is lower than some value (you can make it super low so it's precise or a little bit higher to allow for some margin of error) put it in a list of gameobjects and if there's more than one object there get the closest one.

The code for getting closest object in angle would look something like this:

```<code>GameObject CheckObjects()
{
    List<GameObject> InAngle = new List<GameObject>();

    for(int i = 0; i < YourObjectsList.Count; i++)
    {
        GameObject tested = YourObjectsList[i];

        Vector3 dir = tested.transform.position - origin.transform.forward;

        // I'm assuming here that youre rotating your origin with the
        directional input, not then instead of origin.transform.forward
        place there your directional vector3

        float angle = Vector3.Angle(dir, tested.transform.position);

        if(angle <= desiredAngle)
        {
            InAngle.Add(tested);
        }
    }

    GameObject closest = null;

    for(int j = 0; j < InAngle.Count; i++)
    {
        GameObject tested = InAngle[i];

        Vector3 dir1 = tested.transform.position - origin.transform.position;
        Vector3 dir2 = closest.transform.position - origin.transform.position;

        if(!closest)
        {
            closest = tested;
        }
        else
        {
            if(dir2.sqrMagnitude > dir1.sqrMagnitude)
            {
                closest = tested;
            }
        }
    }

    return closest;
}
</code>```

Body:
I have a list of gameObjects added to a List within the area as shown. What I need is a directional input to choose a target from the origin point. I have got it work to get this origin point.

My first attempt of this was to get it via rayCast, but by doing that there were times directional inputs need to directly hit target object by the ray. This is no problem if input was done like case #1.

However, what I need it to really work is when input direction was as if case #2 or #3 the input will still get a target. My second attempt was to do this with sphereCast, but it still needed a target in sphere proximity and multiple targets hit by sphereCast still needed to result in only one and more accurate target selection by input.

Since I have all the transform.position of all the possible targets as well as the origin point I wondered there would be a more elegant way of resolving this via comparing vector3's of these coordinates(origin and targets in the general direction).

Here's my latest approach:

//
// m_targetList is the list containing all GameObjects as GameObjects in other script m_collector. All m_collector does is this.
//

using System.Collections.Generic;
using UnityEngine;

public class TargetSwitcher : MonoBehaviour
{
    private TargetCollector m_collector;
    private Transform m_origin;

    public bool m_targetChanged = false;

    public GameObject m_target;

    public LayerMask m_targetMask;

    private Dictionary<Vector3, float> m_targetInfo = new Dictionary<Vector3, float>();

    private void Awake()
    {
        m_collector = GetComponent<TargetCollector>();
        m_origin = GameObject.Find("TargetOrigin").transform;
        m_tracker = GameObject.Find("TargetTracker").transform;
        m_bound = GetComponent<BoxCollider>();
    }

    public void UpdateBearing(GameObject origin)
    {
        m_origin = origin.transform;

        foreach (GameObject target in m_collector.m_targetList)
        {
            Vector3 dir = (target.transform.position - origin.transform.position).normalized
            float dist = Vector3.Distance(origin.transform.position, target.transform.position);

            m_targetInfo.Add(dir, dist);
        }
    }

    public void SwitchTarget()
    {
        if (!m_targetChanged)
        {
            Vector2 dir = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized;

            // Find closest direction value from Dictionary to dir of here
            // Compare distance from origin if multiple targets and choose the nearest
        }
    }

    public void ReturnToIdle()
    {
        m_origin.position = m_target.transform.position;
        m_targetChanged = false;
        m_targetInfo.Clear();
    }

    public struct TargetInfo
    {
        public Vector3 bearing;
        public float distance;

        public TargetInfo(Vector3 bearing, float distance)
        {
            this.bearing = bearing;
            this.distance = distance;
        }
    }
}

Generally, I'm trying to compare the normalized vector of directional input to the normalized vector from the origin to each target before SwitchTarget(). The input method here is Gamepad axis x and y as Horizontal and Vertical.

Reposting this question since a provided answer was very far from the question and marked as duplicate(Given answer was about finding gameObject by distance only, this question is about direction and distance portion is to compare second-handedly when multiple items were found in the direction)

Edit

After some trials with dot product now I'm sure this is much likely where I want to head. There are much inconsistency I need to get on with, though.
Here's my most recent attempt:

private void Update()
{
    UpdateBearing();

    Vector3 input = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);

    if (input != Vector3.zero)
    {
        SwitchTarget();
    }
}

public void UpdateBearing(GameObject origin)
{
    m_origin.position = origin.transform.position;

    foreach (GameObject target in m_collector.m_targetList)
    {
        Vector3 dir = (target.transform.position - origin.transform.position).normalized;
        if (!m_targetInfo.ContainsKey(target))
        {
            m_targetInfo.Add(target, dir);
        }
    }
}

public void SwitchTarget()
{
    GameObject oldTarget = m_collector.m_target;

    if (!m_targetChanged)
    {
        Vector3 dir = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0).normalized;
        Debug.DrawRay(m_origin.position, dir * 100, Color.yellow, 0.5f);

        foreach (KeyValuePair<GameObject, Vector3> possibleTarget in m_targetInfo)
        {
            float dot = Vector3.Dot(dir, possibleTarget.Value);

            if (dot > 0.5f) // Compare DP difference of added dot and input dot
            {
                GameObject newTarget = possibleTarget.Key;

                if (oldTarget != newTarget)
                {
                    Debug.Log(possibleTarget.Value + " // " + dot);

                    m_target = newTarget;
                    m_collector.m_target = newTarget;
                    m_targetChanged = true;
                }
            }
        }
    }
}

With this, I'm kind of getting gameObject selection without raycasting and missing any targets. However, I'm sure I need better case comparison than if(dot > 0.5f). Also, my rough assumption is that if I don't update the value of the dictionary m_targetInfo for each Key I'd have another inconsistency if those targets ever move. Anyways, I'm still confused how properly utilize this to achieve my end goal.

Body:
Since you have all the desired game objects in the area you can create a for loop and check the angle between your look direction and their position, if it is lower than some value (you can make it super low so it's precise or a little bit higher to allow for some margin of error) put it in a list of gameobjects and if there's more than one object there get the closest one.

The code for getting closest object in angle would look something like this:

GameObject CheckObjects()
{
    List<GameObject> InAngle = new List<GameObject>();

    for(int i = 0; i < YourObjectsList.Count; i++)
    {
        GameObject tested = YourObjectsList[i];

        Vector3 dir = tested.transform.position - origin.transform.forward;

        // I'm assuming here that youre rotating your origin with the
        directional input, not then instead of origin.transform.forward
        place there your directional vector3

        float angle = Vector3.Angle(dir, tested.transform.position);

        if(angle <= desiredAngle)
        {
            InAngle.Add(tested);
        }
    }

    GameObject closest = null;

    for(int j = 0; j < InAngle.Count; i++)
    {
        GameObject tested = InAngle[i];

        Vector3 dir1 = tested.transform.position - origin.transform.position;
        Vector3 dir2 = closest.transform.position - origin.transform.position;

        if(!closest)
        {
            closest = tested;
        }
        else
        {
            if(dir2.sqrMagnitude > dir1.sqrMagnitude)
            {
                closest = tested;
            }
        }
    }

    return closest;
}