问:
How do I split file removals into a separate changeset in git
I have a massive git changeset on a local branch. It contains file additions, file modifications and file deletions.

How do I split the file deletions into a separate subsequent changeset? (To make the additions and modifications easier to review.)

(In case it matters, this is git-cinnabar, not plain git.)

答:
All of this assumes that the changes are uncommitted, unstaged, and simply in your work tree.  If that is not the case comment with the current state of things and I can update with revised procedures (which will boil down to getting back to the previous commit if need be, unstaging any changes, ...).

When you say "file deletions", I take that to mean you completely removed some files and want to separate that from files you updated (as opposed to wanting to separate deleted lines from added/updated lines within a single file).

If that's the case, you can pick and choose which files you add without having to use git add -p.  (The -p puts you in the "patch" submenu of "interactive mode", where you can pick individual line changes to stage or unstage; it's probably overkill here.)

So all you really would need is to supply the filenames of the deleted files when you do your git add.

```<code>git clone someRepo
rm file1
touch file2
vi file3
rm someDir/file4
git add file1
git add someDir/file4
git commit -mDeletions
git add .
git commit -m"Changes And Additions"
</code>```

If a bunch of deletions are in someDirectory, and there are no additions or edits in someDirectory, then you can git add someDirectory to stage all of them.  If this would catch one or two additions, you can stage the directory then use git reset HEAD -- someDirectory/addedFile to unstage the file you didn't want.

If the files are scattered throughout the work tree alongside changes you don't want to stage, use something based on git status |grep deleted to get the filenames for the first commit and feed them to a script to stage them.

Or an interactive add certainly can do the job

```<code>git add -i
</code>```

but as long as you're picking files and not individual changes within a file, you don't need the patch mode.

Body:
All of this assumes that the changes are uncommitted, unstaged, and simply in your work tree.  If that is not the case comment with the current state of things and I can update with revised procedures (which will boil down to getting back to the previous commit if need be, unstaging any changes, ...).

When you say "file deletions", I take that to mean you completely removed some files and want to separate that from files you updated (as opposed to wanting to separate deleted lines from added/updated lines within a single file).

If that's the case, you can pick and choose which files you add without having to use git add -p.  (The -p puts you in the "patch" submenu of "interactive mode", where you can pick individual line changes to stage or unstage; it's probably overkill here.)

So all you really would need is to supply the filenames of the deleted files when you do your git add.

git clone someRepo
rm file1
touch file2
vi file3
rm someDir/file4
git add file1
git add someDir/file4
git commit -mDeletions
git add .
git commit -m"Changes And Additions"

If a bunch of deletions are in someDirectory, and there are no additions or edits in someDirectory, then you can git add someDirectory to stage all of them.  If this would catch one or two additions, you can stage the directory then use git reset HEAD -- someDirectory/addedFile to unstage the file you didn't want.

If the files are scattered throughout the work tree alongside changes you don't want to stage, use something based on git status |grep deleted to get the filenames for the first commit and feed them to a script to stage them.

Or an interactive add certainly can do the job

git add -i

but as long as you're picking files and not individual changes within a file, you don't need the patch mode.


来源: stackexchange

问:
Call angular service in another js file
I have some javascript and html files: User.js, index.html, Door.js

I want use any function in User.js file.

My user.js file

My door.js file

I call getUserInfo in user.Js from Door.js file in function
doorApplicationLoginPage.service

Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- PerioMainController

```<code>var doorApplicationLoginPage = angular.module("PerioLoginPage", []);

doorApplicationLoginPage.service('UserService', function () {

    this.getUserInfo = function () {
        alert("getUserInfo");
    }

    this.reLoginUser = function () {
        alert("reLoginUser");
    }

});

var doorApplication = angular.module("PerioDoorApplication", []);

doorApplication.controller("PerioMainController", function ($scope, $http, $sce, UserService) {

    UserService.getUserInfo();

});
</code>```

Thank you.

答:
You are injecting a service which is not referenced to your module.

See:

The UserService service is referenced in PerioLoginPage module
The PerioMainController controller is referenced in PerioDoorApplication module.

You've got either to:

reference the service in the same module as your controller.

inject the module where service is referenced to the module where controller is referenced.

ContentLicense: CC BY-SA 3.0

Title: Call angular service in another js file

Body:
I have some javascript and html files: User.js, index.html, Door.js

I want use any function in User.js file.

My user.js file

My door.js file

I call getUserInfo in user.Js from Door.js file in function
doorApplicationLoginPage.service

Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- PerioMainController

var doorApplicationLoginPage = angular.module("PerioLoginPage", []);

doorApplicationLoginPage.service('UserService', function () {

    this.getUserInfo = function () {
        alert("getUserInfo");
    }

    this.reLoginUser = function () {
        alert("reLoginUser");
    }

});

var doorApplication = angular.module("PerioDoorApplication", []);

doorApplication.controller("PerioMainController", function ($scope, $http, $sce, UserService) {

    UserService.getUserInfo();

});

Thank you.


问:
Help in sql query
I have a table:

```<code>ID  Title   Date
30   1     10/10/2010
20   1     10/11/2010
40   2     01/01/2010
</code>```

i need a way to select distinct titles with max dates.

so when title is 1, i should have the second row selected since the date in the 1st row is smaller than the date in the second row.

as a result the query should return:

```<code>20 1 10/11/2010
40 2 01/01/2010
</code>```

答:
Your data set is unclear; do you want the minimum ID and the maximum date?

```<code>SELECT ID=MIN(ID), Title, [Date] = MAX([Date])
FROM Table
GROUP By Title
</code>```

Or was it a typo, and you want the row with the maximum date (assuming that the dates may not follow the ID value)?

```<code>SELECT  a.ID
      , a.Title
      , a.Dt
FROM    Table a
        JOIN ( SELECT   b.Title
                      , Dt = MAX(Dt)
               FROM     Table b
               GROUP BY Title
             ) c ON a.Dt = c.Dt
                    AND a.Title = c.Title
</code>```

ContentLicense: CC BY-SA 2.5

Title: Help in sql query

Body:
I have a table:

ID  Title   Date
30   1     10/10/2010
20   1     10/11/2010
40   2     01/01/2010

i need a way to select distinct titles with max dates.

so when title is 1, i should have the second row selected since the date in the 1st row is smaller than the date in the second row.

as a result the query should return:

20 1 10/11/2010
40 2 01/01/2010

Body:
Your data set is unclear; do you want the minimum ID and the maximum date?

SELECT ID=MIN(ID), Title, [Date] = MAX([Date])
FROM Table
GROUP By Title

Or was it a typo, and you want the row with the maximum date (assuming that the dates may not follow the ID value)?

SELECT  a.ID
      , a.Title
      , a.Dt
FROM    Table a
        JOIN ( SELECT   b.Title
                      , Dt = MAX(Dt)
               FROM     Table b
               GROUP BY Title
             ) c ON a.Dt = c.Dt
                    AND a.Title = c.Title


问:
Mouse look turns right side towards mouse pointer
Im trying to get my GameObject to point towards the mouse. It has a child object with a sprite. The childs rotation is set to 0 on all zxis. The sprite points upwards (positive X) at start. The GameObject rotates with the mouse pointer but its always turning its right side towards the mouse pointer. Also when i add force forward it accelerates at the same direction the sprite is pointing which as stated before is not the direction the mouse is. What is my code missing?</p>

```<code>  var cam = Camera.main;

    // Distance from camera to object.  We need this to get the proper calculation.
    float camDistance = cam.transform.position.y - transform.position.y;

    // Get the mouse position in world space. Using camDis for the Z axis.
    Vector3 mouse = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, camDistance));

    float AngleRad = Mathf.Atan2(mouse.y - transform.position.y, mouse.x - transform.position.x);
    float angle = (180 / Mathf.PI) * AngleRad;

    rb2d.rotation = angle;
</code>```

答:
Your shape is rotated by 90 degrees due to the way that your calculations resolve the angle, you can account for this by using:</p>

```<code>rb2.rotation = angle - 90;
</code>```

Body:
Im trying to get my GameObject to point towards the mouse. It has a child object with a sprite. The childs rotation is set to 0 on all zxis. The sprite points upwards (positive X) at start. The GameObject rotates with the mouse pointer but its always turning its right side towards the mouse pointer. Also when i add force forward it accelerates at the same direction the sprite is pointing which as stated before is not the direction the mouse is. What is my code missing?

  var cam = Camera.main;

    // Distance from camera to object.  We need this to get the proper calculation.
    float camDistance = cam.transform.position.y - transform.position.y;

    // Get the mouse position in world space. Using camDis for the Z axis.
    Vector3 mouse = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, camDistance));

    float AngleRad = Mathf.Atan2(mouse.y - transform.position.y, mouse.x - transform.position.x);
    float angle = (180 / Mathf.PI) * AngleRad;

    rb2d.rotation = angle;

Body:
Your shape is rotated by 90 degrees due to the way that your calculations resolve the angle, you can account for this by using:

rb2.rotation = angle - 90;


问:
How to force int to string in Laravel JSON?
I've recently updated my server to a newer version of MySQL and PHP 7 for various reasons. On my previous instance, running PHP 5.5, Laravel's response()->json() always converted tinyint's into a string. Now running newer server software, it's returning me int's -as it should...

I'd have to change a lots of my codebase to either cast types / convert them into a string manually, whic I'm trying to avoid at the moment.

Is there a way to somehow force response()->json() to return int's as string's?

答:
There is a way to cast integer into string in laravel

in your model you can cast id to string. Its as follows

```<code>protected $casts = [ 'id' => 'string' ];
</code>```

But the downside is that you would have to do that for all Models.

Body:
There is a way to cast integer into string in laravel

in your model you can cast id to string. Its as follows

protected $casts = [ 'id' => 'string' ];

But the downside is that you would have to do that for all Models.


问:
Detecting a shift + click with Jquery on Chrome
I'm trying to detect a shift click with javascript but for some reason it only works on IE

```<code>.click(function (e) {
    if (e.shiftKey) {
        Rain();
    }
});
</code>```

this is the code that work for me in IE, how can I detect it on Chrome

答:
I don't think there is a defined combo, but you could make it yourself. A (crude) example:

```<code><div id="someElement">
    Click me for an alert!
</div>

<script>
var shiftPressed = false;
$(document).keydown(function(event) {
    shiftPressed = event.keyCode==16;
});
$(document).keyup(function(event) {
    if( event.keyCode==16 ){ shiftPressed = false; }
});

$('#someElement').on('click', function(e){
    if( shiftPressed ){
        alert("Shift and click!");
    }
    else{ alert("Nope"); }

});
</script>
</code>```

You could improve it by only binding the .keyup() when the keydown is a shift in order to minimize the number of events. You should add as little logic as possible outside the if statements, as this event gets fired a lot

Body:
I'm trying to detect a shift click with javascript but for some reason it only works on IE

.click(function (e) {
    if (e.shiftKey) {
        Rain();
    }
});

this is the code that work for me in IE, how can I detect it on Chrome

Body:
I don't think there is a defined combo, but you could make it yourself. A (crude) example:

<div id="someElement">
    Click me for an alert!
</div>

<script>
var shiftPressed = false;
$(document).keydown(function(event) {
    shiftPressed = event.keyCode==16;
});
$(document).keyup(function(event) {
    if( event.keyCode==16 ){ shiftPressed = false; }
});

$('#someElement').on('click', function(e){
    if( shiftPressed ){
        alert("Shift and click!");
    }
    else{ alert("Nope"); }

});
</script>

You could improve it by only binding the .keyup() when the keydown is a shift in order to minimize the number of events. You should add as little logic as possible outside the if statements, as this event gets fired a lot


问:
What dangers are there in creating collections which extend native arrays?
I created a Collection based on this article. I found that this runs on chrome, firefox and ie9+.
I assume some things are not going to work or maybe, the ie9 emulator for windows 10 just doesn't give me the real picture.

What could go wrong with this extension?

Test code:

```<code><script>
    function Collection() {
        var collection = Object.create( Array.prototype );

        collection = (Array.apply( collection, arguments ) || collection);

        return collection;
    }

    Collection.prototype =  Object.create(Array.prototype);

    var collection = new Collection();

    collection[0] = 1;

    console.log(collection[0]);
</script>
</code>```

答:
Have a look at http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/.

In particular,

```<code>var collection = Object.create(Array.prototype);
</code>```

creates an object that does inherit from Array.prototype not Collection.prototype. And it creates an object, not an array.

```<code>collection = (Array.apply( collection, arguments ) …
</code>```

Array ignores its this value. And creates an Array instance, not a Collection one.

```<code>… || collection)
</code>```

This is pointless, as Array never returns a falsy value, so collection is simply always ignored.

What could go wrong with this extension?

It creates Arrays, not Collections. There is no extension at all. Try putting some methods at Collection.prototype and invoke them.

Body:
Have a look at http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/.

In particular,

var collection = Object.create(Array.prototype);

creates an object that does inherit from Array.prototype not Collection.prototype. And it creates an object, not an array.

collection = (Array.apply( collection, arguments ) …

Array ignores its this value. And creates an Array instance, not a Collection one.

… || collection)

This is pointless, as Array never returns a falsy value, so collection is simply always ignored.

What could go wrong with this extension?

It creates Arrays, not Collections. There is no extension at all. Try putting some methods at Collection.prototype and invoke them.


问:
How can I trigger Google Spreadsheets script if a specific cell contains a value greater than, say, 10
So I have a script that would launch an e-mail, and I want it to be run when a specific cell (A5) contains a value over 10. Here's the script:

```<code>function onEdit() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rownum = 1; // #of rows
  var rowstart = 2; // where to start row

  // get range of cell
  // column 1 = email, column 2 is first name
  var dataRange = sheet.getRange(rowstart, 1, rownum, 2)

  var data = dataRange.getValues()
  for (i in data) {
    if(sheet.getRange(5,1).getValue()>10){      //change row and column in get range to match what you need
      var row = data[i];
      var emailadr = row[0]; // data select
      var msgcontent = "Hey " + row[1] + ",\n Just:)chilling \n    Sent from my email"; // body
      var sbjt = "You have mail!"; //subject
      MailApp.sendEmail(emailadr, sbjt, msgcontent);}
    }
  }
</code>```

Under Current project's triggers, I have the following:

Run: onEdit

Events: From spreadsheet On edit

Now, when I set cell "A5" to "21", the script doesn't run. What's the issue? I can't seem to figure it out. Thanks.

答:
Using logger it shows that it does work. You can see in example below. You may want to try to use a time based trigger and set it to check every x amount of time and send email. Google may not allow the sendemail to run "onedit"

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rownum = 1; // #of rows
  var rowstart = 2; // where to start row

  // get range of cell
  // column 1 = email, column 2 is first name
  var dataRange = sheet.getRange(rowstart, 1, rownum, 2)

  var data = dataRange.getValues()

 for (i in data) {
   if(sheet.getRange(5,1).getValue()>10){      //change row and column in get range to match what you need
     var row = data[i];
         Logger.log("Yes it is larger than 10");

    //  var emailadr = row[0]; // data select
    //  var msgcontent = "Hey " + row[1] + ",\n Just:)chilling \n    Sent from my email"; // body
    //  var sbjt = "You have mail!"; //subject
    //   MailApp.sendEmail(emailadr, sbjt, msgcontent);
   }
  }
}```

Body:
So I have a script that would launch an e-mail, and I want it to be run when a specific cell (A5) contains a value over 10. Here's the script:

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rownum = 1; // #of rows
  var rowstart = 2; // where to start row

  // get range of cell
  // column 1 = email, column 2 is first name
  var dataRange = sheet.getRange(rowstart, 1, rownum, 2)

  var data = dataRange.getValues()
  for (i in data) {
    if(sheet.getRange(5,1).getValue()>10){      //change row and column in get range to match what you need
      var row = data[i];
      var emailadr = row[0]; // data select
      var msgcontent = "Hey " + row[1] + ",\n Just:)chilling \n    Sent from my email"; // body
      var sbjt = "You have mail!"; //subject
      MailApp.sendEmail(emailadr, sbjt, msgcontent);}
    }
  }

Under Current project's triggers, I have the following:

Run: onEdit

Events: From spreadsheet On edit

Now, when I set cell "A5" to "21", the script doesn't run. What's the issue? I can't seem to figure it out. Thanks.


问:
STM32F4 DMA UART
I'm using STM32F401RE UART with DMA to receive a continuous stream of data and send over BLE. I am using buffer of size 20 or 1023 bytes. I am facing issue  that DMA buffer full interrupt stops working as it start receiving data continuously.
It works perfectly fine when I send data in chunks (20 or 1023 bytes) through PC COM port in non-continuous manner. I am trying to work in debugger mode and it works with PC COM port setup and hits breakpoints in DMA callback function but not on stream of data.
I check the data streaming module its working fine.

Program is getting into  "HAL_UART_ErrorCallback" function and I am reactivating "HAL_UART_Receive_DMA" but still not resolving the issue.

Kindly let me know how to resolve the issue.

Many many thanks.

Kind Regards,
Ghalib

答: Issue got resolved, noise was causing issue on UART signals. </p>

Title: STM32F4 DMA UART


问:
How to return static value from static query
In sql i need to get my own values.
For example :

Select House from dual ( here i need to return H ) from dual union all
select Build from dual ( here i need to return B) ...

I tired with this but i dont get it as  I want

select '18776' as instanceid from dual union all
select '18775' as instanceid from dual

答:
@mikrimouse simply just write hard code in a query like:</p>

```<code>select 'H' from dual
union all
select 'B' from dual
</code>```

Body:
@mikrimouse simply just write hard code in a query like:

select 'H' from dual
union all
select 'B' from dual


问:
Adjust background to text on TextView in android
I'd like to know if anyone could help me with this.

I've got a textView and I want the background just to be applied to the text, according to its size, not to the whole textView.

There is no problem when the text is only one row lenghth, but there is when it takes more than one line...

Maybe this pic helps to understand this all...

top: what I have
bottom: what I want

Thank you :-)

答:
Try using  something like this:

```<code>TextView tv = (TextView) findViewById(R.id.myid);
tv.setText(Html.fromHtml("<span style="background: red;">Text</span>"));
</code>```

It might resolve your issue...

EDIT:

I found the solution here : Set color of TextView span in Android using SpannableString

Body:
Try using  something like this:

TextView tv = (TextView) findViewById(R.id.myid);
tv.setText(Html.fromHtml("<span style="background: red;">Text</span>"));

It might resolve your issue...

EDIT:

I found the solution here : Set color of TextView span in Android using SpannableString


问:
How to extend activerecord and tinytds timeout?
The symptom is:

TinyTds::Error: Adaptive Server connection timed out: EXEC some_stored_procedure

It's execute_procedure a slow stored procedure on a slow MSSQL Server via ActiveRecord over tinytds. If I EXEC the stored procedure in SQL Query Analyzer, it takes 29 to 30 to finish.

So I added:

```<code>timeout = 60
</code>```

in /etc/freetds.conf and:

```<code>read_timeout: 60
write_timeout: 60
</code>```

to database.yml.

The same error still shows up. Is there any other configs I missed?

p.s. I did measure when the timeout error shows up with a timer after hitting return key, it's about 30 seconds. I have a feeling 30 seconds may not be the default timeout of freetds or activerecord  and wonders why the error shows up somewhat close the time for the sql to finish ...

答:
It has been pretty long time but someone may need this. I solved this by passing timeout: option for creating tiny_tds client depend on git doc, see the below:

```<code>client = TinyTds::Client.new username: 'sa', password: 'secret', host: 'mydb.host.net', timeout: 30
</code>```

Body:
The symptom is:

TinyTds::Error: Adaptive Server connection timed out: EXEC some_stored_procedure

It's execute_procedure a slow stored procedure on a slow MSSQL Server via ActiveRecord over tinytds. If I EXEC the stored procedure in SQL Query Analyzer, it takes 29 to 30 to finish.

So I added:

timeout = 60

in /etc/freetds.conf and:

read_timeout: 60
write_timeout: 60

to database.yml.

The same error still shows up. Is there any other configs I missed?

p.s. I did measure when the timeout error shows up with a timer after hitting return key, it's about 30 seconds. I have a feeling 30 seconds may not be the default timeout of freetds or activerecord  and wonders why the error shows up somewhat close the time for the sql to finish ...

Body:
It has been pretty long time but someone may need this. I solved this by passing timeout: option for creating tiny_tds client depend on git doc, see the below:

client = TinyTds::Client.new username: 'sa', password: 'secret', host: 'mydb.host.net', timeout: 30


问:
Newtonsoft.JSON Serialize\Deserialize Datatable with GUID
I have a Web API solution I'm using to work with various databases.  Everything was working until I accessed a table with a GUID number in it.  I finally narrowed down the problem to the Serialize/Deserialize methods.  When the DataTable is serialized to JSON and then subsequently deserialized back to a DataTable, the data type of the column containing the GUID becomes System.String instead of System.Guid like it was originally.

Take this simple example:

```<code>System.Data.DataTable myData = new DataTable();
myData.Columns.Add("ID", typeof(System.Guid));
myData.Columns.Add("Name", typeof(System.String));
myData.Rows.Add(System.Guid.NewGuid(), "Name1");

// Reports: System.Guid
System.Diagnostics.Debug.Write(myData.Columns["ID"].DataType.FullName);

string mySerializedString = Newtonsoft.Json.JsonConvert.SerializeObject(myData);
myData = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(mySerializedString);

// Reports: System.String
System.Diagnostics.Debug.Write(myData.Columns["ID"].DataType.FullName);
</code>```

This is a generic API so I have no idea if the table(s) being passed around have columns containing GUIDs or any other data types that may cause issues with JSON.

Hopefully it's just because I'm missing something stupid and it's just a simple fix?

**** Update ****

Thanks for the tips all. In the meantime I have run into yet another problem that may just be the end of it all.

When you initially load a table from the database, every rowstate = unchanged. However going through the Serialize process, the result is every rowstate becomes "Added".

So take for example I query 1 record, modify that record and send it back. The DataTable has now flagged that record as "Added" which then breaks the primary key constraint and it blows up.

This sucks!

I'm basically looking at some sort of huge kludge job on both ends where I would have to pass a Dictionary of all the properties that I discover get hosed via the JSON process and then Rebuild it all on the other end.

All while trying to be generic and not knowing what kind of data I'm supposed to be dealing with.

&*(^% it!

答:
There's no way in JSON to indicate that something is a GUID.

From json.org:

A value can be a string in double quotes, or a number, or true or
  false or null, or an object or an array. These structures can be
  nested.

Because you are not deserializing back into something with a defined type, there's no way for the deserializer to know that it should attempt to convert the "GUID as a string" back into an actual GUID.

If you were deserializing back to an object that had a property with a type of GUID, it would attempt to parse the string into a GUID for that property, but the structure of the datatable is not part of the transmitted JSON.

Body:
I have a Web API solution I'm using to work with various databases.  Everything was working until I accessed a table with a GUID number in it.  I finally narrowed down the problem to the Serialize/Deserialize methods.  When the DataTable is serialized to JSON and then subsequently deserialized back to a DataTable, the data type of the column containing the GUID becomes System.String instead of System.Guid like it was originally.

Take this simple example:

System.Data.DataTable myData = new DataTable();
myData.Columns.Add("ID", typeof(System.Guid));
myData.Columns.Add("Name", typeof(System.String));
myData.Rows.Add(System.Guid.NewGuid(), "Name1");

// Reports: System.Guid
System.Diagnostics.Debug.Write(myData.Columns["ID"].DataType.FullName);

string mySerializedString = Newtonsoft.Json.JsonConvert.SerializeObject(myData);
myData = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(mySerializedString);

// Reports: System.String
System.Diagnostics.Debug.Write(myData.Columns["ID"].DataType.FullName);

This is a generic API so I have no idea if the table(s) being passed around have columns containing GUIDs or any other data types that may cause issues with JSON.

Hopefully it's just because I'm missing something stupid and it's just a simple fix?

**** Update ****

Thanks for the tips all. In the meantime I have run into yet another problem that may just be the end of it all.

When you initially load a table from the database, every rowstate = unchanged. However going through the Serialize process, the result is every rowstate becomes "Added".

So take for example I query 1 record, modify that record and send it back. The DataTable has now flagged that record as "Added" which then breaks the primary key constraint and it blows up.

This sucks!

I'm basically looking at some sort of huge kludge job on both ends where I would have to pass a Dictionary of all the properties that I discover get hosed via the JSON process and then Rebuild it all on the other end.

All while trying to be generic and not knowing what kind of data I'm supposed to be dealing with.

&*(^% it!


问:
Normalizr and recursive nested structure
I'm using normalizr to flatten a structure like the following one:

```<code>{
  "fields":[{
    "id":"29",
    "text": "something"
  }, {
    "id":"16",
    "text": "something"
    "fields":[{
      "id":"17",
      "text": "something"
    }]
  }, {
    "id":"18",
    "text": "something"
  }
}
</code>```

My structure has an array of fields and a field may also have nested fields. There's only one level of nesting allowed.

What I'm trying to do is this:

```<code>const block = new schema.Entity('fields')
const blockList = new schema.Array(block)

block.define({
  fields: blockList
})

const normalizedData = normalize(originalData, blockList)
</code>```

After running this snippet, normalizedData has a results property and it only has the first level of field ids, even though entities has all the fields normalized, including the nested ones.

I'd like to have in the results array all the ids, including the nested ones. What am I missing?

答:
I'd like to have in the results array all the ids, including the nested ones. What am I missing?

This is how Normalizr works. The returned result is always in the same format of the input data. You won't be able to get what you are asking for from Normalizr.

If, however, you're just looking for a list of blocks, pull that from the entities:

```<code>const blockIds = Object.keys(normalizedData.entities.blocks);
</code>```

Body:
I'm using normalizr to flatten a structure like the following one:

{
  "fields":[{
    "id":"29",
    "text": "something"
  }, {
    "id":"16",
    "text": "something"
    "fields":[{
      "id":"17",
      "text": "something"
    }]
  }, {
    "id":"18",
    "text": "something"
  }
}

My structure has an array of fields and a field may also have nested fields. There's only one level of nesting allowed.

What I'm trying to do is this:

const block = new schema.Entity('fields')
const blockList = new schema.Array(block)

block.define({
  fields: blockList
})

const normalizedData = normalize(originalData, blockList)

After running this snippet, normalizedData has a results property and it only has the first level of field ids, even though entities has all the fields normalized, including the nested ones.

I'd like to have in the results array all the ids, including the nested ones. What am I missing?

Body:
I'd like to have in the results array all the ids, including the nested ones. What am I missing?

This is how Normalizr works. The returned result is always in the same format of the input data. You won't be able to get what you are asking for from Normalizr.

If, however, you're just looking for a list of blocks, pull that from the entities:

const blockIds = Object.keys(normalizedData.entities.blocks);


问:
When to use Class methods over Activities?
I'm getting introduced to Android programming and want to understand Activities a bit more (I'm coming in with basic-advanced java knowledge, basic knowledge in GUIs).

I currently assume that all methods will be contained in their respective activity, or in some helper class--whose methods wouldn't be shown to the user, (unless an activity used it), but whose methods could perhaps be used in multiple activities.

Are these assumptions correct?

When are helper classes even required?

Any good online resources regarding (specifically) classes vs activity use cases?

Any examples of a fairly simple, complete APK where I could look through and dissect the code, including XML?  Hopefully something I could just import into Android Studio.

Thanks!

答:
Try android programming the big nerd ranch guide , its very useful for beginners
And try youtube channel "wiseass"
He has good videos on mvp architecture </p>


问:
Compostions and mixins in JS
I got some trouble with compostions and mixin.
For examples, lets imagine that we have a AHero and Hero1 object.
All heroes can move, so AHero.move() is a thing.
And now, at a moment of the dev, I want to add the possibility to stun and beStunned. So I make a new object that look like this ( called stunTrait)  :

```<code>{
stunned : false,
stun(),
beStun,
}
</code>```

And I decide to give to possiblity to heroes to stun and beStunned. So I do a mixin :
class AHero extends stunTrait(superclass).

Now I want that a stunned hero can not move.
So in Ahero :

```<code>move(){
if(this.stunned) return;
...
}
</code>```

Later I find out stun was a bad idea, so I decide to stop implementing the stunTrait. And now I must find all stunned things  in my Ahero class, and this can be sometimes hard, and even harder if child class did some other things with this stun stuff.

Is there a way to avoid that ? A better design ?

```<code>class Object{
  constructor(x,y){
    this.x = x
    this.y = y
  }
}

class AHero extends stunTrait(Object){
  constructor(x,y,moveSpeed){
    this.moveSpeed = moveSpeed;
  }

  move(){
    super.move();
    this.speed = moveSpeed;
  }
}

class hero1 extends AHero{
  constructor(x,y,moveSpeed){ }
}

let stunTrait = function(object){
  return class extends object{
    constructor(...args) {
      super(...args);

      this.stunned = false;
    }

    move(){
      if(this.stunned) this.speed = 0;
    }
  }
}

let hero = new hero1(40, 50, 100);
hero.stunned = true;
hero.move();
// This work, bcs AHero.move() is called before stunTrait.move()
// but if for some reason, I decide that only hero1 should have stunTrait
// So : class hero1 extends stunTrait(AHero)
// stunTrait.move() will be called after, so stunned will not be applied
// How make compostion without breaking inheritance ?
</code>```

答:
The OP's given design decision targets the modification of the move behavior that already has been implemented from the class side.

Thus a stun behavior is not only responsible for implementing its stun specific state handling, it also has to decide whether and/or how to change a move behavior's control flow.

For this it relies on existing implementations not only of move but also on setSpeed.

The concept of mixins really does not fit with the OP's approach for it just mixes additional behavior into other objects. But the given special case has to handle the naming conflict of move too. And that's something what traits are for.

If, in JavaScript, there once was a real support for applicable types which have to be capable of both kinds of composition trait- and object-composition, as well as of method modification, a possible solution might look similar to the next provided one.

const withStunBehavior = Trait.create(function (use, applicator) {

  function moveInterceptor(proceedMove, interceptor, argsArray) {
  //console.log("withStunBehavior::moveInterceptor - this.isStunned() : ", this.isStunned());
    if (this.isStunned()) {

      this.setSpeed(0);
    }/* else {
      return proceedMove.call(this);
    }*/
    return proceedMove.call(this);
  }

  applicator(function (isStunnedValue) {
    isStunnedValue = !!isStunnedValue;
  //console.log("withStunBehavior::applicator - isStunnedValue : ", isStunnedValue);

    this.beStun = function beStun () {
      isStunnedValue = true;
    };
    this.unban = function unban () {
      isStunnedValue = false;
    };
    this.isStunned = function isStunned () {
      return isStunnedValue;
    };

  }).requires([

    "setSpeed",
    "move"

  ]).around(

    "move", moveInterceptor
  );
});

class AHero {
  constructor(stateValue) {
    var
      aHero = this;

    aHero.getSpeed = function getSpeed () {
      return stateValue.moveSpeed;
    };
    aHero.setSpeed = function setSpeed (speedValue) {
      return (stateValue.moveSpeed = speedValue);
    };

    // withStunBehavior.call(aHero);
  }
  move() {
    var
      speedValue = this.getSpeed();

    if (speedValue === 0) {
      console.log("Hero does not move at all. Its speed is " + speedValue + ".");
    } else {
      console.log("Hero moves with speed " + speedValue + ".");
    }
    return speedValue;
  }
}

class AHeroWithStunBehavior extends AHero {

  constructor(stateValue) {
    super(stateValue);

    withStunBehavior.call(this);
  }
}

var
  hero = new AHero({ x: 0, y: 0, moveSpeed: 200 });

console.log("\n");
console.log("hero.getSpeed() : ", hero.getSpeed());
console.log("hero.move() : ", hero.move());
console.log("\n");
console.log("hero.setSpeed(0) : ", hero.setSpeed(0));
console.log("hero.getSpeed() : ", hero.getSpeed());
console.log("hero.move() : ", hero.move());
console.log("\n");
console.log("hero.setSpeed(100) : ", hero.setSpeed(100));
console.log("hero.getSpeed() : ", hero.getSpeed());
console.log("hero.move() : ", hero.move());
console.log("\n");
console.log("hero.isStunned : ", hero.isStunned);
console.log("hero.beStun : ", hero.beStun);
console.log("hero.unban : ", hero.unban);

var
  stunningHero = new AHeroWithStunBehavior({ x: 40, y: 50, moveSpeed: 130 });

console.log("\n");
console.log("stunningHero.isStunned : ", stunningHero.isStunned);
console.log("stunningHero.beStun : ", stunningHero.beStun);
console.log("stunningHero.unban : ", stunningHero.unban);
console.log("\n");
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.setSpeed(0) : ", stunningHero.setSpeed(0));
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.setSpeed(90) : ", stunningHero.setSpeed(90));
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.beStun() : ", stunningHero.beStun());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.setSpeed(160) : ", stunningHero.setSpeed(160));
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.unban() : ", stunningHero.unban());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.setSpeed(160) : ", stunningHero.setSpeed(160));
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100%!important; top: 0; }</code>```

```

Title: Compostions and mixins in JS

Body:
I got some trouble with compostions and mixin.
For examples, lets imagine that we have a AHero and Hero1 object.
All heroes can move, so AHero.move() is a thing.
And now, at a moment of the dev, I want to add the possibility to stun and beStunned. So I make a new object that look like this ( called stunTrait)  :

{
stunned : false,
stun(),
beStun,
}

And I decide to give to possiblity to heroes to stun and beStunned. So I do a mixin :
class AHero extends stunTrait(superclass).

Now I want that a stunned hero can not move.
So in Ahero :

move(){
if(this.stunned) return;
...
}

Later I find out stun was a bad idea, so I decide to stop implementing the stunTrait. And now I must find all stunned things  in my Ahero class, and this can be sometimes hard, and even harder if child class did some other things with this stun stuff.

Is there a way to avoid that ? A better design ?

class Object{
  constructor(x,y){
    this.x = x
    this.y = y
  }
}

class AHero extends stunTrait(Object){
  constructor(x,y,moveSpeed){
    this.moveSpeed = moveSpeed;
  }

  move(){
    super.move();
    this.speed = moveSpeed;
  }
}

class hero1 extends AHero{
  constructor(x,y,moveSpeed){ }
}

let stunTrait = function(object){
  return class extends object{
    constructor(...args) {
      super(...args);

      this.stunned = false;
    }

    move(){
      if(this.stunned) this.speed = 0;
    }
  }
}

let hero = new hero1(40, 50, 100);
hero.stunned = true;
hero.move();
// This work, bcs AHero.move() is called before stunTrait.move()
// but if for some reason, I decide that only hero1 should have stunTrait
// So : class hero1 extends stunTrait(AHero)
// stunTrait.move() will be called after, so stunned will not be applied
// How make compostion without breaking inheritance ?

Body:
The OP's given design decision targets the modification of the move behavior that already has been implemented from the class side.

Thus a stun behavior is not only responsible for implementing its stun specific state handling, it also has to decide whether and/or how to change a move behavior's control flow.

For this it relies on existing implementations not only of move but also on setSpeed.

The concept of mixins really does not fit with the OP's approach for it just mixes additional behavior into other objects. But the given special case has to handle the naming conflict of move too. And that's something what traits are for.

If, in JavaScript, there once was a real support for applicable types which have to be capable of both kinds of composition trait- and object-composition, as well as of method modification, a possible solution might look similar to the next provided one.

const withStunBehavior = Trait.create(function (use, applicator) {

  function moveInterceptor(proceedMove, interceptor, argsArray) {
  //console.log("withStunBehavior::moveInterceptor - this.isStunned() : ", this.isStunned());
    if (this.isStunned()) {

      this.setSpeed(0);
    }/* else {
      return proceedMove.call(this);
    }*/
    return proceedMove.call(this);
  }

  applicator(function (isStunnedValue) {
    isStunnedValue = !!isStunnedValue;
  //console.log("withStunBehavior::applicator - isStunnedValue : ", isStunnedValue);

    this.beStun = function beStun () {
      isStunnedValue = true;
    };
    this.unban = function unban () {
      isStunnedValue = false;
    };
    this.isStunned = function isStunned () {
      return isStunnedValue;
    };

  }).requires([

    "setSpeed",
    "move"

  ]).around(

    "move", moveInterceptor
  );
});

class AHero {
  constructor(stateValue) {
    var
      aHero = this;

    aHero.getSpeed = function getSpeed () {
      return stateValue.moveSpeed;
    };
    aHero.setSpeed = function setSpeed (speedValue) {
      return (stateValue.moveSpeed = speedValue);
    };

    // withStunBehavior.call(aHero);
  }
  move() {
    var
      speedValue = this.getSpeed();

    if (speedValue === 0) {
      console.log("Hero does not move at all. Its speed is " + speedValue + ".");
    } else {
      console.log("Hero moves with speed " + speedValue + ".");
    }
    return speedValue;
  }
}

class AHeroWithStunBehavior extends AHero {

  constructor(stateValue) {
    super(stateValue);

    withStunBehavior.call(this);
  }
}

var
  hero = new AHero({ x: 0, y: 0, moveSpeed: 200 });

console.log("\n");
console.log("hero.getSpeed() : ", hero.getSpeed());
console.log("hero.move() : ", hero.move());
console.log("\n");
console.log("hero.setSpeed(0) : ", hero.setSpeed(0));
console.log("hero.getSpeed() : ", hero.getSpeed());
console.log("hero.move() : ", hero.move());
console.log("\n");
console.log("hero.setSpeed(100) : ", hero.setSpeed(100));
console.log("hero.getSpeed() : ", hero.getSpeed());
console.log("hero.move() : ", hero.move());
console.log("\n");
console.log("hero.isStunned : ", hero.isStunned);
console.log("hero.beStun : ", hero.beStun);
console.log("hero.unban : ", hero.unban);

var
  stunningHero = new AHeroWithStunBehavior({ x: 40, y: 50, moveSpeed: 130 });

console.log("\n");
console.log("stunningHero.isStunned : ", stunningHero.isStunned);
console.log("stunningHero.beStun : ", stunningHero.beStun);
console.log("stunningHero.unban : ", stunningHero.unban);
console.log("\n");
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.setSpeed(0) : ", stunningHero.setSpeed(0));
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.setSpeed(90) : ", stunningHero.setSpeed(90));
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.beStun() : ", stunningHero.beStun());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.setSpeed(160) : ", stunningHero.setSpeed(160));
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.unban() : ", stunningHero.unban());
console.log("stunningHero.move() : ", stunningHero.move());
console.log("\n");
console.log("stunningHero.setSpeed(160) : ", stunningHero.setSpeed(160));
console.log("stunningHero.getSpeed() : ", stunningHero.getSpeed());
console.log("stunningHero.move() : ", stunningHero.move());

.as-console-wrapper { max-height: 100%!important; top: 0; }

<script>(function(r){function g(a){var c="none",b;Y(a)&&(ta(a)?c=ua:(b=Z(a),t("^class\\s+"+a.name+"\\s+\\{").test(b)?c=va:t("\\([^)]*\\)\\s+=>\\s+\\(").test(b)?c=wa:z(a)&&(c=xa(a)?ya:za(a)||Aa(a)||Ba(a)?Ca:aa)));return c===aa}function C(a){return["^\\[object\\s+",a,"\\]$"].join("")}function v(a,c){var b=Da[c];return!!b&&0<=b.indexOf(a)}function M(a,c,b){return function(){var d=arguments;c.apply(b,d);return a.apply(b,d)}}function N(a,c,b){return function(){var d=arguments,e=a.apply(b,d);c.apply(b,d);return e}}function Ea(a,c,b,d){return function(){var e=arguments;c.call(b,e,d);return a.apply(b,e)}}function Fa(a,c,b,d){return function(){var e=arguments,f=a.apply(b,e);c.call(b,e,d);return f}}function Ga(a,c,b,d){return function(){var e=arguments,f=a.apply(b,e);c.call(b,f,e,d);return f}}function Ha(a,c,b,d){return function(){var e=arguments,f;try{f=a.apply(b,e)}catch(l){c.call(b,l,e,d)}return f}}function Ia(a,c,b,d){return function(){var e=arguments,f,g;try{f=a.apply(b,e)}catch(m){g=m}c.call(b,g||f,e,d);return f}}function Ja(a,c,b,d){return function(){return c.call(b,a,c,arguments,d)}}function Ka(a,c){return function(){var b=this[a];g(b)||(b=u);this[a]=M(b,c,this)}}function La(a,c){return function(){var b=this[a];g(b)||(b=u);this[a]=N(b,c,this)}}function Ma(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ea(d,c,this,b)}}function Na(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Fa(d,c,this,b)}}function Oa(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ga(d,c,this,b)}}function Pa(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ha(d,c,this,b)}}function Qa(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ia(d,c,this,b)}}function Ra(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ja(d,c,this,b)}}function ba(a,c,b){a.useTraits.rules.push(new A({type:"without",traitList:c,methodNameList:b}))}function ca(a,c,b,d){a.useTraits.rules.push(new A({type:"as",trait:c,methodName:b,methodAlias:d}))}function da(a){return ea(p(a)).reduce(function(a,b){q(b)&&a.push(F(b));return a},[])}function fa(){var a,c,b,d,e;if(O(this))if(d=this.valueOf(),e=d.parentLink,w(e))if(b=e.getSetup(),a=b.chainData,c=a.recentCalleeName,v(c,"without"))if(c=da(arguments),1<=c.length)a.recentCalleeName="without",ba(b,d.traitList,c);else throw new h("Not even a single <String> type was passed to 'without' as to be excluded method name.");else{a=["\u2026 invalid chaining of '",c,"().without()'"].join("");if("applyBehavior"==c)throw new n([a," in case of excluding one or more certain behaviors."].join(""));throw new n(a);}else throw new k("Please do not spoof the context of 'use'.");else throw new k("Please do not spoof the context of 'apply'.");return e}function P(a,c){var b=a.getSetup();if(Sa(c,a.valueOf().traitList))b.chainData.recentCalleeName="applyTraits",b=new Q({traitList:c,parentLink:a}),a.putChild(b);else throw new h("Any trait that got passed to 'apply' needs to be registered before via 'use'.");return b}function Sa(a,c){return a.every(function(a){return 0<=c.indexOf(a)})}function Ta(){var a;a=this.getSetup();var c=this.valueOf().traitList;I(this,a,a.chainData.recentCalleeName);a=P(this,c);return fa.apply(a,arguments)}function Ua(){var a=this.getSetup(),c=this.valueOf().traitList;I(this,a,a.chainData.recentCalleeName);return P(this,c)}function ga(){var a,c,b;b=p(arguments);if(w(this))if(a=this.getSetup(),c=a.chainData,c=c.recentCalleeName,I(this,a,c),a=["\u2026 invalid chaining of '",c,"().apply()'"].join(""),v(c,"apply"))if(x(b[0]))if(q(b[1]))if(v(c,"applyBehavior")){c=b[0];b=F(b[1]);a=this.getSetup();var d;if(0<=this.valueOf().traitList.indexOf(c))if(d={},c.call(d),g(d[b]))a.chainData.recentCalleeName="applyBehavior",b=new R({trait:c,methodName:b,parentLink:this}),this.putChild(b);else throw new k(["The requested '",b,"' method has not been implemented by the trait that got passed to 'apply'."].join(""));else throw new h("Any trait that got passed to 'apply' needs to be registered before via 'use'.");}else throw new n([a," in case of applying just a certain behavior."].join(""));else if(p(b).every(x))if(v(c,"applyTraits"))b=P(this,b);else throw new n([a," in case of applying from one or more traits."].join(""));else throw new h("'apply(\u2026)' excepts either, as its 2nd delimiting argument, just a 'String' type or exclusively one or more 'Trait' and 'Function' types.");else throw new h("'apply(<Trait|Function>, \u2026)' excepts as its 1st argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(a);else throw new k("'use(\u2026).apply(\u2026)' only works within a validly chained context, please do not try spoofing the latter.");return b}function ha(){var a;a=this;if(O(a)||G(a))a=a.valueOf(),a=a.parentLink,a=ga.apply(a,arguments);else throw new k("Please do not spoof the context of 'apply'.");return a}function I(a,c,b){var d,e;a&&!c.chainData.isTerminated&&(d=a.getChild())&&(e=d.valueOf())&&("applyTraits"==b&&O(d)?ba(c,e.traitList,[]):"applyBehavior"==b&&G(d)&&(a=e.methodName,ca(c,e.trait,a,a)));c.chainData.recentCalleeName="apply"}function R(a){this.valueOf=function(){return{trait:a.trait,methodName:a.methodName,parentLink:a.parentLink}};this.toString=function(){return["ApplyLink::singleBehavior :: ",S.stringify(a)].join("")};return this}function G(a){var c;return null!=a&&(a instanceof R||g(a.as)&&g(a.after)&&g(a.before)&&g(a.valueOf)&&(c=a.valueOf())&&x(c.trait)&&q(c.methodName)&&w(c.parentLink))}function Q(a){this.valueOf=function(){return{traitList:a.traitList,parentLink:a.parentLink}};this.toString=function(){return["ApplyLink::fromTraits :: ",S.stringify(a)].join("")};return this}function O(a){var c;return null!=a&&(a instanceof Q||g(a.without)&&g(a.valueOf)&&(c=a.valueOf())&&T(c.traitList)&&w(c.parentLink))}function U(a,c){var b=null;this.getSetup=function(){return c};this.deleteChild=function(){b=null};this.putChild=function(a){b=a};this.getChild=function(){return b};this.valueOf=function(){return{traitList:p(a.traitList)}};this.toString=function(){return["UseRoot :: ",S.stringify(a)].join("")};this.apply=ga.bind(this);this.apply.all=Ua.bind(this);this.apply.all.without=Ta.bind(this);return this}function w(a){var c;return null!=a&&(a instanceof U||g(a.apply)&&g(a.valueOf)&&g(a.getSetup)&&(c=a.valueOf())&&T(c.traitList)&&(c=a.getSetup())&&ia(c))}function Va(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Ka(a,c));else throw new h("'before(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'before(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function Wa(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Ma(a,c));else throw new h("'before.stateful(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'before.stateful(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function Xa(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(La(a,c));else throw new h("'after(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'after(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function Ya(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Na(a,c));else throw new h("'after.stateful(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'after.stateful(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function Za(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Oa(a,c));else throw new h("'afterReturning(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'afterReturning(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function $a(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Pa(a,c));else throw new h("'afterThrowing(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'afterThrowing(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function ab(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Qa(a,c));else throw new h("'afterFinally(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'afterFinally(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function bb(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Ra(a,c));else throw new h("'around(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'around(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function cb(){var a=this.applicator,c=a.root,b=a.didRequire;if(a.canRequire)if(a.canRequire=!1,a.didRequire=!0,b=da(arguments),1<=b.length)a.requires=b;else throw new h("Not even a single <String> type was passed to 'requires' as method name that a trait, at its apply time, expects to be present at least.");else{if(b)throw new n("'requires' can be invoked exactly once, right after having executed a trait's 'applicator' method.");throw new n("'requires' can not bee invoked after a modifier method, but has to be the direct follower of a trait's 'applicator' method.");}return c}function db(a){I(this.useTraits.root,this,this.chainData.recentCalleeName);this.chainData.isTerminated=!0;var c=this.applicator,b=this.useTraits.rules,d=0>=b.length;if(!d&&!ja(b))throw new k("The trait composition language's rule set does not result in applicable behavior. This happens e.g. if all behavior has been deleted via 'without'.");if(null!=a)if(g(a=F(a)))c.body=a,a.call(c.proxy);else throw new h("The applicator should either stay empty or receive a sole applicable type like a 'Trait' or a 'Function' type.");else d&&0>=c.modifiers.length&&D.warn("The trait descriptor till now did neither receive an applicable function via the 'applicator' method nor any composition rule via 'use(\u2026).apply(\u2026)' nor any method modifier.");return c.root}function eb(){var a;a=ea(p(arguments)).filter(function(a){return x(a)});if(1<=a.length)a=new U({traitList:a},this);else throw new h("Not even a single valid 'Trait' or 'Function' type has been provided to 'use(<Trait|Function>[, \u2026])'.");return this.useTraits.root=a}function y(a,c){return a.findIndex(function(a){return a.trait===c})}function ka(a){return{type:a.type,trait:a.trait,methodName:a.methodName}}function la(a){return{type:a.type,trait:a.trait,fromTrait:a.fromTrait,methodName:a.methodName}}function A(a){this.valueOf=function(){return fb[a.type](a)}}function ja(a){var c=!0;if(1<=a.length){var b={},c=ma(a),d=na(c);d.forEach(function(a){a.trait.call(a.proxy)});a.forEach(function(a){a.execute(b,d)});c=1<=J(b).length}return c}function gb(a,c,b){var d;if(b[0]!==oa&&(d=c.reduce(function(b,c){g(a[c])||b.push(c);return b},[]),1<=d.length))throw new h("The type misses following required method(s) \u2026 '"+d.join("', '")+"'.");return d}function hb(a,c,b){a.forEach(function(a){a.call(c,b)})}function ib(a){this.call=function(){var c=p(arguments),b;b=c.shift();b=null!=b&&b||null;a.apply(b,c);return b};this.apply=function(c,b){null==b&&(b=[]);c=null!=c&&c||null;a.apply(c,b);return c};return this}function jb(a){this.requires=function(){return p(a)};return this}function kb(a){var c=[],b={};a.call(b,oa);c=J(b).sort(function(a,b){return a<b&&-1||a>b&&1||0});b=null;this.keys=function(){return p(c)};return this}function pa(a,c){this.toString=function(){return"[object Trait]"};this.valueOf=function(){return a};ib.call(this,a);jb.call(this,c);kb.call(this,a);return this}function qa(a){var c;if(c=!!a)(c=a instanceof pa)||(c="object"==typeof a&&g(a.call)&&g(a.apply)&&g(a.valueOf)&&g(a.valueOf()));return c}function x(a){return qa(a)||g(a)}function ma(a){return a.reduce(function(a,b){var c=b.valueOf(),e=c.trait,f=c.fromTrait;e&&0>a.indexOf(e)&&a.push(e);f&&0>a.indexOf(f)&&a.push(f);(c.traitList||[]).forEach(function(b){0>a.indexOf(b)&&a.push(b)});return a},[])}function na(a){return a.map(function(a){return{trait:a,proxy:{}}})}function lb(a,c,b,d){var e=[],f={};if(!(0>=c.length||ja(c)))throw new k("The trait composition language's rule set does not result in applicable behavior. This happens e.g. if all behavior has been deleted via 'without'.");g(b)&&(b.call(f),e=J(f));return[a,c,e,d].some(function(a){return 1<=a.length})}function mb(a){var c,b=a.useTraits.rules,d=a.applicator;a=d.body;var e=d.requires,d=d.modifiers,f=ma(b);lb(f,b,a,d)&&(d=function(a,b,c,d,e){return function(){var f=this,h=p(arguments),l=na(a);l.forEach(function(a){a.trait.apply(a.proxy,h)});b.forEach(function(a){a.execute(f,l)});gb(f,c,h);g(d)&&d.apply(f,h);hb(e,f,h);return f}}(f,b,e,a,d),c=new pa(d,e));return c}var V=r.Function,H=r.Object,B=r.Array,t=r.RegExp,S=r.JSON,h=r.TypeError,k=r.ReferenceError,n=r.SyntaxError,nb=V.prototype,K=H.prototype,ra=U.prototype,sa=Q.prototype,L=R.prototype,oa={},aa="applicable-function",ya="buildin-constructor",va="class-constructor",wa="arrow-function",ua="generator-function",Ca="interface-type",Da={without:["apply","applyTraits"],as:["apply","applyBehavior"],after:["apply","applyBehavior","after","before"],before:["apply","applyBehavior","after","before"],apply:"apply applyBehavior applyTraits without as after before use".split(" "),applyTraits:"apply applyBehavior applyTraits without as after before use".split(" "),applyBehavior:"apply applyBehavior applyTraits without as after before use".split(" ")},fb={beforeWrap:ka,afterWrap:ka,beforeApply:la,afterApply:la,without:function(a){return{type:a.type,traitList:p(a.traitList),methodNameList:p(a.methodNameList)}},as:function(a){return{type:a.type,trait:a.trait,methodName:a.methodName,methodAlias:a.methodAlias}}},ob={beforeWrap:function(a,c,b){var d=y(b,a.trait);b=b[d];a=a.methodName;c[a]=M((b&&b.proxy||{})[a],c[a],c)},afterWrap:function(a,c,b){var d=y(b,a.trait);b=b[d];a=a.methodName;c[a]=N((b&&b.proxy||{})[a],c[a],c)},beforeApply:function(a,c,b){var d=y(b,a.trait),e=y(b,a.fromTrait),d=b[d],e=b[e];b=d&&d.proxy||{};e=e&&e.proxy||{};a=a.methodName;a in c&&delete c.methodName;c[a]=M(b[a],e[a],c)},afterApply:function(a,c,b){var d=y(b,a.trait),e=y(b,a.fromTrait),d=b[d],e=b[e];b=d&&d.proxy||{};e=e&&e.proxy||{};a=a.methodName;a in c&&delete c.methodName;c[a]=N(b[a],e[a],c)},without:function(a,c,b){var d=a.traitList,e=a.methodNameList.reduce(function(a,b){a[b]=null;return a},{});d.forEach(function(a){a=y(b,a);var d=(a=b[a])&&a.proxy||{};J(d).forEach(function(a){a in e||(a in c&&delete c.methodName,c[a]=function(a,b){return function(){return a.apply(b,arguments)}}(d[a],c))})});a=b=d=e=null},as:function(a,c,b){var d=y(b,a.trait);b=(b=b[d])&&b.proxy||{};d=a.methodAlias;a=a.methodName;d in c&&delete c.methodAlias;c[d]=function(a,b){return function(){return a.apply(b,arguments)}}(b[a],c);a=b=d=b=b=d=a=null}},F=function(a,c){return function(b){return b==c?b:a.call(b).valueOf()}}(K.valueOf,null),E=function(a){return function(c){return a.call(c)}}(K.toString),Z=function(a){return function(c){return a.call(c)}}(nb.toString),pb=function(a){try{a.call(null,"length"),a=function(a,b){return function(c,e){return c!=b&&a.call(c,e)}}(a,null)}catch(c){a=function(a,c){return function(b,d){var e=b!=c;if(e)try{e=a.call(b,d)}catch(m){e=!0}return e}}(a,null)}return a}(K.propertyIsEnumerable),Y=function(a){return function(c){return typeof c==a}}(typeof V),z=function(a){return function(c){return Y(c)&&typeof c.call==a&&typeof c.apply==a}}(typeof V),qb=function(a){return function(c){return t(a).test(E(c))}}(C("Function")),ia=function(a){return function(c){return t(a).test(E(c))}}(C("Object")),rb=z(H.getPrototypeOf)&&H.getPrototypeOf||function(a){var c=a&&a.__proto__;return c||null===c?c:qb(a.constructor)?a.constructor.prototype:a instanceof H?K:null},W=function(a){return function(c){return(c=t(a).exec(Z(c)))&&c[1]}}("^function\\s+([^(]+)\\("),xa=function(a){return function(c){return t(a).test(W(c))}}("^(?:Array|ArrayBuffer|AsyncFunction|Atomics|Boolean|DataView|Date|Error|EvalError|Float32Array|Float64Array|Function|Generator|GeneratorFunction|Int16Array|Int32Array|Int8Array|InternalError|Collator|DateTimeFormat|NumberFormat|Iterator|Map|Number|Object|Promise|Proxy|RangeError|ReferenceError|RegExp|Bool16x8|Bool32x4|Bool64x2|Bool8x16|Float32x4|Float64x2|Int16x8|Int32x4|Int8x16|Uint16x8|Uint32x4|Uint8x16|Set|SharedArrayBuffer|StopIteration|String|Symbol|SyntaxError|TypeError|TypedArray|URIError|Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|WeakMap|WeakSet)$"),X=function(a,c){var b=t(c);return b.test(W(a))||b.test(W(rb(a)))},za=function(a){return function(c){return X(c,a)}}("^(?:Node|CharacterData|Event|DOMError|DOMException|DOMImplementation|DOMStringList|DOMTokenList|EventTarget|HTMLCollection|MutationObserver|MutationRecord|NodeFilter|NodeIterator|NodeList|Range|TreeWalker|URL|Document)$"),Aa=function(a){return function(c){return X(c,a)}}("^(?:HTMLElement|HTMLMediaElement|Element)$"),Ba=function(a){return function(c){return X(c,a)}}("^(?:CanvasRenderingContext2D|CanvasGradient|CanvasPattern|TextMetrics|ImageData|DOMStringMap|MediaError|HTMLCollection|NodeList)$"),ta=function(a){return function(c){return t(a).test(E(c))}}(C("GeneratorFunction")),q=function(a){return function(c){return t(a).test(E(c))}}(C("String")),T=z(B.isArray)&&B.isArray||function(a){return function(c){return t(a).test(E(c))}}(C("Array")),sb=z(B.isArguments)&&B.isArguments||function(a,c){var b=function(b){return t(a).test(E(b))};b(arguments)||(b=function(a){return ia(a)&&"number"==typeof a.length&&c(a.length)&&!pb(a,"length")});return b}(C("Arguments"),r.Number.isFinite),p=z(B.from)&&B.from||function(a){return function(c){return a.call(c)}}(B.prototype.slice),ea=function c(b){b=sb(b)&&p(b)||b;T(b)&&(b=b.reduce(function(b,e){return b.concat(c(e))},[]));return b},J=H.keys,u=function(){},D;D=(D=r.console)&&z(D.warn)&&z(D.log)&&D||{warn:u,log:u};L.as=function(c){var b,d,e,f,g;if(G(this))if(f=this.valueOf(),g=f.parentLink,w(g))if(e=g.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"as"))if(q(c=F(c)))if(b=f.trait,f=f.methodName,f!==c)d.recentCalleeName="as",ca(e,b,f,c);else throw new h("Using identical method names in case of aliasing is considered to be a rule violating contradiction.");else throw new h("'as(<String>)' excepts as its sole argument just a 'String' type.");else{c=["\u2026 invalid chaining of '",b,"().as()'"].join("");if("applyTraits"==b)throw new n([c," in case of aliasing just a certain behavior."].join(""));throw new n(c);}else throw new k("Please do not spoof the context of 'use'.");else throw new k("Please do not spoof the context of 'apply'.");return g};L.after=function(c){var b,d,e,f,l,m;if(G(this))if(f=this.valueOf(),m=f.parentLink,w(m))if(e=m.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"after"))if(x(c))if(b=m.valueOf(),b=b.traitList,0<=b.indexOf(c))if(b=f.trait,b!==c)if(l=f.methodName,f={},c.call(f),g(f[l]))d.recentCalleeName="after",e.useTraits.rules.push(new A({type:"afterApply",trait:c,fromTrait:b,methodName:l}));else throw new k(["Please consider applying '",l,"' directly. This expected behavior has not been implemented by the trait that got passed to 'after'."].join(""));else throw new k("Passing identical trait references to both 'apply' and 'after' is a contradiction that violates the composition rules.");else throw new h("Any trait passed to 'after' has to be registered before via 'use'.");else throw new h("'after(<Trait|Function>)' excepts as its sole argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(["\u2026 invalid chaining of '",b,"().after()'"].join(""));else throw new k("Please do not spoof the context of 'use'.");else throw new k("Please do not spoof the context of 'apply'.");return m};L.before=function(c){var b,d,e,f,l,m;if(G(this))if(f=this.valueOf(),m=f.parentLink,w(m))if(e=m.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"before"))if(x(c))if(b=m.valueOf(),b=b.traitList,0<=b.indexOf(c))if(b=f.trait,b!==c)if(l=f.methodName,f={},c.call(f),g(f[l]))d.recentCalleeName="before",e.useTraits.rules.push(new A({type:"beforeApply",trait:c,fromTrait:b,methodName:l}));else throw new k(["Please consider applying '",l,"' directly. This expected behavior has not been implemented by the trait that got passed to 'before'."].join(""));else throw new k("Passing identical trait references to both 'apply' and 'before' is a contradiction that violates the composition rules.");else throw new h("Any trait passed to 'before' has to be registered before via 'use'.");else throw new h("'before(<Trait|Function>)' excepts as its sole argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(["\u2026 invalid chaining of '",b,"().before()'"].join(""));else throw new k("Please do not spoof the context of 'use'.");else throw new k("Please do not spoof the context of 'apply'.");return m};L.apply=ha;sa.without=fa;sa.apply=ha;ra.after=function(c){var b,d,e,f;if(w(this))if(e=this.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"after"))if(x(c))if(b=this.valueOf(),b=b.traitList,0<=b.indexOf(c))if(b=this.getChild(),f=b.valueOf(),b=f.trait,b!==c)if(f=f.methodName,b={},c.call(b),g(b[f]))d.recentCalleeName="after",e.useTraits.rules.push(new A({type:"afterWrap",trait:c,methodName:f}));else throw new k(["Please consider applying '",f,"' directly. This expected behavior has not been implemented by the trait that got passed to 'after'."].join(""));else throw new k("Passing identical trait references to both 'apply' and 'after' is a contradiction that violates the composition rules.");else throw new h("Any trait passed to 'after' has to be registered before via 'use'.");else throw new h("'after(<Trait|Function>)' excepts as its sole argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(["\u2026 invalid chaining of '",b,"().after()'"].join(""));else throw new k("Please do not spoof the context of 'use'.");return this};ra.before=function(c){var b,d,e,f;if(w(this))if(e=this.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"before"))if(x(c))if(b=this.valueOf(),b=b.traitList,0<=b.indexOf(c))if(b=this.getChild(),f=b.valueOf(),b=f.trait,b!==c)if(f=f.methodName,b={},c.call(b),g(b[f]))d.recentCalleeName="before",e.useTraits.rules.push(new A({type:"beforeWrap",trait:c,methodName:f}));else throw new k(["Please consider applying '",f,"' directly. This expected behavior has not been implemented by the trait that got passed to 'before'."].join(""));else throw new k("Passing identical trait references to both 'apply' and 'before' is a contradiction that violates the composition rules.");else throw new h("Any trait passed to 'before' has to be registered before via 'use'.");else throw new h("'before(<Trait|Function>)' excepts as its sole argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(["\u2026 invalid chaining of '",b,"().before()'"].join(""));else throw new k("Please do not spoof the context of 'use'.");return this};A.prototype.execute=function(c,b){var d=this.valueOf();ob[d.type](d,c,b)};return r.Trait={create:function(c){var b,d,e;g(c=F(c))&&(e={chainData:{isTerminated:!1,recentCalleeName:"use"},useTraits:{root:null,rules:[]},applicator:{body:null,proxy:{},root:{},modifiers:[],requires:[],canRequire:!0,didRequire:!1}},b=e.applicator.root,b.requires=cb.bind(e),b.before=Va.bind(e),b.after=Xa.bind(e),b.before.stateful=Wa.bind(e),b.after.stateful=Ya.bind(e),b.afterReturning=Za.bind(e),b.afterThrowing=$a.bind(e),b.afterFinally=ab.bind(e),b.around=bb.bind(e),b=eb.bind(e),d=db.bind(e),c(b,d),e=mb(e));return e},isTrait:qa,isApplicable:x}})(Function("return this")());</script>


问:
Adding 'CASE WHEN' to codeigniter CI_DB_mysql_driver object's ar_select key
I need to add a case when statement to CI_DB_mysql_driver object. I tried the following code

```<code>$this->db->select("CASE WHEN colum1 >0 THEN 'sl' ELSE colum1 END AS colum1");
</code>```

When I run it query is generated as

```<code>`CASE` WHEN colum1 >0 THEN 'sl' ELSE colum1 END AS colum1
</code>```

and it generates sql error.

答:
Try turning off automatic query escaping.</p>

```<code>$this->db->select("CASE WHEN colum1 >0 THEN 'sl' ELSE colum1 END AS colum1", FALSE);
</code>```

Body:
I need to add a case when statement to CI_DB_mysql_driver object. I tried the following code

$this->db->select("CASE WHEN colum1 >0 THEN 'sl' ELSE colum1 END AS colum1");

When I run it query is generated as

`CASE` WHEN colum1 >0 THEN 'sl' ELSE colum1 END AS colum1

and it generates sql error.

Body:
Try turning off automatic query escaping.

$this->db->select("CASE WHEN colum1 >0 THEN 'sl' ELSE colum1 END AS colum1", FALSE);


问:
Generating string in code when one of a group of properties change
I am seeking advice on how to be notified when one of many properties change.

For example, lets say I want to bind a control's text to a FullAddress property in my WPF ViewModel that I can calculate on the fly whenever one of a set of properties changes, such as StreetNumber, StreetName, Suburb, PostCode etc.

I am thinking that I need to bind my displaying control to the FullAddress property, but how do I have it automatically update whenever one of the dependent properties changes? Can I bind the property's codebehind to multiple other properties on the same ViewModel? If so how? Is there a better way?

答:
Assuming your class implements INotifyPropertyChanged then you can notify within any property setter. E.g</p>

```<code>    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            Address.BeginEdit();
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion

    public string FirstLine
    {
        get { return firstLine; }
        set
        {
            firstLine = value;
            OnPropertyChanged("FirstLine");
            OnPropertyChanged("FullAddress");
        }
    }

    public string SecondLine
    {
        get { return secondLine; }
        set
        {
            secondLine= value;
            OnPropertyChanged("SecondLine");
            OnPropertyChanged("FullAddress");
        }
    }

    public string FullAddress
    {
        get { return firstLine + secondLine; }
    }
</code>```

Body:
Assuming your class implements INotifyPropertyChanged then you can notify within any property setter. E.g

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            Address.BeginEdit();
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion

    public string FirstLine
    {
        get { return firstLine; }
        set
        {
            firstLine = value;
            OnPropertyChanged("FirstLine");
            OnPropertyChanged("FullAddress");
        }
    }

    public string SecondLine
    {
        get { return secondLine; }
        set
        {
            secondLine= value;
            OnPropertyChanged("SecondLine");
            OnPropertyChanged("FullAddress");
        }
    }

    public string FullAddress
    {
        get { return firstLine + secondLine; }
    }


问:
How to disable user accounts on firebase authentication automatically?
I am currently working on an android application which uses Google Firebase as the back end server.

One function I want to implement is disabling user accounts as they register through the application but I don't know how to do it.

Does anyone know how to implement this into the android code itself?

答:
There's no method to disable a user account from the Android client SDK.

You have to use Firebase Admin SDK for this.

```<code>admin.auth().updateUser(uid, {
    disabled: true
});
</code>```

Guide link: Firebase Admin - Update a user

EDIT: Thanks @FrankvanPuffelen

You can also trigger this function when a Firebase user is created on Firebase Cloud Function.

read more here

Body:
There's no method to disable a user account from the Android client SDK.

You have to use Firebase Admin SDK for this.

admin.auth().updateUser(uid, {
    disabled: true
});

Guide link: Firebase Admin - Update a user

EDIT: Thanks @FrankvanPuffelen

You can also trigger this function when a Firebase user is created on Firebase Cloud Function.

read more here


问:
What is the rule of import with curly braces in React / Redux?
I thought the line:

```<code>import { FETCH_WEATHER } from "../actions/index";
</code>```

means: we don't import the whole object, but import the obj.FETCH_WEATHER from the file ../actions/index.js

One example is, we use

```<code>import React, { Component } from "react";
</code>```

And it is like, we import from "react", let's call it here as obj, and name it React in our own file, and obj.Component, we name it as Component in our own file.

(1) is that true?

(2) in the file ../actions/index.js, the content is actually:

```<code>export const FETCH_WEATHER = "FETCH_WEATHER";
</code>```

so there is no object, and no key / value pair to speak of. So what does import { FETCH_WEATHER } mean?

答:
The module may export one default object and many named items.

It is default module export:

```<code>const MyClass = (props) => (
  <div/>
)

export default MyClass
</code>```

We can import it like this:

```<code>import MyClass from "../actions"
</code>```

The curly braces allows to export named items, so if we have such exports:

```<code>const myConst = "The Text"
const myHelper = (num) => 2*num

export default MyClass
export {myHelper, myConst}
</code>```

We can import its like this:

```<code>import MyClass, {myHelper, myConst} from "../actions"
</code>```

There is not need to add index at path - it is add by default. So write "../actions" enough instead of "../actions/index"

Body:
I thought the line:

import { FETCH_WEATHER } from "../actions/index";

means: we don't import the whole object, but import the obj.FETCH_WEATHER from the file ../actions/index.js

One example is, we use

import React, { Component } from "react";

And it is like, we import from "react", let's call it here as obj, and name it React in our own file, and obj.Component, we name it as Component in our own file.

(1) is that true?

(2) in the file ../actions/index.js, the content is actually:

export const FETCH_WEATHER = "FETCH_WEATHER";

so there is no object, and no key / value pair to speak of. So what does import { FETCH_WEATHER } mean?

Body:
The module may export one default object and many named items.

It is default module export:

const MyClass = (props) => (
  <div/>
)

export default MyClass

We can import it like this:

import MyClass from "../actions"

The curly braces allows to export named items, so if we have such exports:

const myConst = "The Text"
const myHelper = (num) => 2*num

export default MyClass
export {myHelper, myConst}

We can import its like this:

import MyClass, {myHelper, myConst} from "../actions"

There is not need to add index at path - it is add by default. So write "../actions" enough instead of "../actions/index"


问:
Call angular service in another js file
I have some javascript and html files: User.js, index.html, Door.js

I want use any function in User.js file.

My user.js file

My door.js file

I call getUserInfo in user.Js from Door.js file in function
doorApplicationLoginPage.service

Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- PerioMainController

```<code>var doorApplicationLoginPage = angular.module("PerioLoginPage", []);

doorApplicationLoginPage.service('UserService', function () {

    this.getUserInfo = function () {
        alert("getUserInfo");
    }

    this.reLoginUser = function () {
        alert("reLoginUser");
    }

});

var doorApplication = angular.module("PerioDoorApplication", []);

doorApplication.controller("PerioMainController", function ($scope, $http, $sce, UserService) {

    UserService.getUserInfo();

});
</code>```

Thank you.

答:
In this case I can see you have two modules Periodicloginpage and periodicdoorapplication. So two services are defined in two modules. So you have to put the Periodicloginpage as dependency of periodicdoorapplication.</p>

```<code>var doorApplication = angular.module("PerioDoorApplication", ["PerioLoginPage"]);
</code>```

Title: Call angular service in another js file

Body:
I have some javascript and html files: User.js, index.html, Door.js

I want use any function in User.js file.

My user.js file

My door.js file

I call getUserInfo in user.Js from Door.js file in function
doorApplicationLoginPage.service

Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- PerioMainController

var doorApplicationLoginPage = angular.module("PerioLoginPage", []);

doorApplicationLoginPage.service('UserService', function () {

    this.getUserInfo = function () {
        alert("getUserInfo");
    }

    this.reLoginUser = function () {
        alert("reLoginUser");
    }

});

var doorApplication = angular.module("PerioDoorApplication", []);

doorApplication.controller("PerioMainController", function ($scope, $http, $sce, UserService) {

    UserService.getUserInfo();

});

Thank you.

Body:
In this case I can see you have two modules Periodicloginpage and periodicdoorapplication. So two services are defined in two modules. So you have to put the Periodicloginpage as dependency of periodicdoorapplication.

var doorApplication = angular.module("PerioDoorApplication", ["PerioLoginPage"]);


问:
Is there any pre implemented routing algorithm that I can use to find the shortest path between 2 airports using waypoints as nodes
What I need is a pre implemented routing algorithm that finds the shortest route between 2 airports with nodes as waypoint. The airports and waypoints are saved as a JSON files with lang and lat information. Once the shortest path is calculated the path is shown on google maps api as markers. I have a json file with approximately 30000 waypoints across europe and asia as well as the airports for europe and asia.
PS this is needed for my final year computer science project. </p>

<p>Does anyone know if a template algorithm exists in php or js to help sort this problem. </p>

答:
write a function that calculates the distance between 2 waypoints based on lon/lat (shouldn't be too hard) and convert the json into a graph (e.g a 2X2 matrix with the i,j entree being the distance between waypoint i and j (0 in case no way) - than all you need to do is run Dijkstra (make sure your algorithm returns the set of nodes in the shortest path and not only the distance). </p>

<p>Note: Dijkstra algorithm assumes no negative values for edges, which I believe is the case here. </p>

ContentLicense: CC BY-SA 4.0

Body:
What I need is a pre implemented routing algorithm that finds the shortest route between 2 airports with nodes as waypoint. The airports and waypoints are saved as a JSON files with lang and lat information. Once the shortest path is calculated the path is shown on google maps api as markers. I have a json file with approximately 30000 waypoints across europe and asia as well as the airports for europe and asia.
PS this is needed for my final year computer science project.

Does anyone know if a template algorithm exists in php or js to help sort this problem.

Body:
write a function that calculates the distance between 2 waypoints based on lon/lat (shouldn't be too hard) and convert the json into a graph (e.g a 2X2 matrix with the i,j entree being the distance between waypoint i and j (0 in case no way) - than all you need to do is run Dijkstra (make sure your algorithm returns the set of nodes in the shortest path and not only the distance).

Note: Dijkstra algorithm assumes no negative values for edges, which I believe is the case here.


问:
PowerShell receive vs. get verbs
I've seen quite a few discussions on which verbs to use in your own PowerShell functions, but I haven't seen a clarification on using Receive vs. Get. They mean roughly the same thing to me, but Receive is supposed to be used specifically in situations involving communications (just type Get-Verb to see this).  Get, however, is in the Common group, so I'm really not sure which one to use.

I have a function that basically wraps a RESTful API and gets data from it (I use parameter sets for the different methods of the service). Right now the function is called Get-FooData. However, I'm thinking that I should possibly rename it to Receive-FooData since it is doing some communication.

I think I'm being too literal here in wanting to use Receive. My personal feeling is that Get sounds better, but I think that's just because I'm used to using it. What are your thoughts?

答:
Use the noun to decide.  If your noun is the object that is being retrieved then use "GET".  If the noun is the mechanism by which you retrieve something, then use "RECEIVE".

e.g.

GET-BOOK -via REST

RECEIVE-REST -object book

Title: PowerShell receive vs. get verbs


问:
Using execute command in Page Objects in Nightwatch JS
I have a problem with implementing Page Object in Nightwatch. Let's say that I have a login scenario. I need to scroll to the element - I'm using for thar execute function.

```<code>module.exports = {
   'Login' : function (browser) {
    browser.url(this.launchUrl)
       .setValue('input[name=username]', 'admin')
       .setValue('input[name=password]', 'password')
       .execute(function () {
            document.querySelector('input[type=submit]').scrollIntoView();
        }, [])
       .click('input[type=submit]');
    browser.end();
    }
}
</code>```

I'd like to refactor this login code into Page Object like that

```<code>module.exports = {
  url: function() {
    return this.api.launchUrl;
  },
  commands: [scrolling],
  elements: {
    usernameField: {
      selector: 'input[name=username]'
    },
    passwordField: {
      selector: 'input[name=password]'
    },
    submit: {
     selector: 'input[type=submit]'
  }
  }
};
</code>```

I'd like to 'hide' also this execute command and pack it into commands, like that:

```<code>var scrolling = {
  scroll: function(){
    return this.execute(function () {
      document.querySelector(input[type=submit]').scrollIntoView();
    }, []);
  }
};
</code>```

Unfortunately it seems that execute command doesn't work with Page Object.

How I can overcome this issue with executing JavaScript code when I want to use Page  Object? How can I encapsulate it?

答:
The answer was very simple
1) There was a quotation mark missing in a selector.
2) Using execute() in Object Pattern it is needed to run it using this.api :</p>

```<code>this.api.execute(function () {
             document.querySelector('input[type=submit]').scrollIntoView();
          }, []);
</code>```

Body:
I have a problem with implementing Page Object in Nightwatch. Let's say that I have a login scenario. I need to scroll to the element - I'm using for thar execute function.

module.exports = {
   'Login' : function (browser) {
    browser.url(this.launchUrl)
       .setValue('input[name=username]', 'admin')
       .setValue('input[name=password]', 'password')
       .execute(function () {
            document.querySelector('input[type=submit]').scrollIntoView();
        }, [])
       .click('input[type=submit]');
    browser.end();
    }
}

I'd like to refactor this login code into Page Object like that

module.exports = {
  url: function() {
    return this.api.launchUrl;
  },
  commands: [scrolling],
  elements: {
    usernameField: {
      selector: 'input[name=username]'
    },
    passwordField: {
      selector: 'input[name=password]'
    },
    submit: {
     selector: 'input[type=submit]'
  }
  }
};

I'd like to 'hide' also this execute command and pack it into commands, like that:

var scrolling = {
  scroll: function(){
    return this.execute(function () {
      document.querySelector(input[type=submit]').scrollIntoView();
    }, []);
  }
};

Unfortunately it seems that execute command doesn't work with Page Object.

How I can overcome this issue with executing JavaScript code when I want to use Page  Object? How can I encapsulate it?

Body:
The answer was very simple
1) There was a quotation mark missing in a selector.
2) Using execute() in Object Pattern it is needed to run it using this.api :

this.api.execute(function () {
             document.querySelector('input[type=submit]').scrollIntoView();
          }, []);


问:
ElasticSearch - add\update SearchTemplate using NEST (.net)
i got this elasticsearch instance, and im trying to implement something like a "dynamic" searchtemplate.

Case:
I got a userinterface where we can adjust the boosting of certain types.
ex. "Boost hits in Articles by 10", "Boost hits on the product page by 20"

Today:
I can write up the query itself using fluent DSL, which would be generated everytime someone searches.

Future:
I would love to have this in a searchtemplate that would just get updated everytime a change is made, thereby just passing in the template name and a query string - instead of having to look up the current boosting values on every request.

My research:
So the nest client supports adding searchtemplates to the ES instance, but it seems like it only supports "inline" scripts and i cant seem to find a way to parse my existing query written in "Fluent DSL" to the JSON equivalent.

Fallback idea:
Writing the script manually using json \ query DSL.

Any ideas \ solutions out there? :)

答:
Version: ElasticSearch\ElasticSearch.NET\NEST v5.2

As pointed out in the comments, there is a serializer on the NEST client, you can also use the NewtonSoft JSON library as pointet out in this answer - but as also stated, to get the exact JSON use the Nest Client serializer, which wraps NewtonSoft JSON with the correct configuration.

Here is an example on the implementation i did using Object initializer syntax, as the one stated in the answer mentioned above uses an old library.

```<code>var searchRequest = new SearchRequest()
        {
            Query = query
        };
        var myBytes = _client.Serializer.SerializeToBytes(searchRequest);
        var jsonSearchTemplate = Encoding.UTF8.GetString(myBytes);
</code>```

As extra information, this is how you add it to your cluster:

```<code>//Define your template ID, this is later used when doing the search.
var templateRequest = new PutSearchTemplateDescriptor("my_template");

//Add your parsed json as the inline script
templateRequest.Template(jsonSearchTemplate);

var response = _client.PutSearchTemplate(templateRequest);
</code>```

How to query using the template: (I also got multiple parameters that needs to be sent in)

```<code>var response =
            _client.SearchTemplate<MyIndexObject>(
                e =>
                    e.Index($"myIndex")
                        .Id("my_template")
                        .Params(new Dictionary<string, object>()
                        {
                            {"query_string", "Obamacare"},
                            {"min_should_match", "70%"}
                        }));
</code>```

Hope this helps anyone else out there struggling with the same thing.

Body:
Version: ElasticSearch\ElasticSearch.NET\NEST v5.2

As pointed out in the comments, there is a serializer on the NEST client, you can also use the NewtonSoft JSON library as pointet out in this answer - but as also stated, to get the exact JSON use the Nest Client serializer, which wraps NewtonSoft JSON with the correct configuration.

Here is an example on the implementation i did using Object initializer syntax, as the one stated in the answer mentioned above uses an old library.

var searchRequest = new SearchRequest()
        {
            Query = query
        };
        var myBytes = _client.Serializer.SerializeToBytes(searchRequest);
        var jsonSearchTemplate = Encoding.UTF8.GetString(myBytes);

As extra information, this is how you add it to your cluster:

//Define your template ID, this is later used when doing the search.
var templateRequest = new PutSearchTemplateDescriptor("my_template");

//Add your parsed json as the inline script
templateRequest.Template(jsonSearchTemplate);

var response = _client.PutSearchTemplate(templateRequest);

How to query using the template: (I also got multiple parameters that needs to be sent in)

var response =
            _client.SearchTemplate<MyIndexObject>(
                e =>
                    e.Index($"myIndex")
                        .Id("my_template")
                        .Params(new Dictionary<string, object>()
                        {
                            {"query_string", "Obamacare"},
                            {"min_should_match", "70%"}
                        }));

Hope this helps anyone else out there struggling with the same thing.


问:
Why is mod_rewrite adding var/www/html to the resulting url
I am trying to make my service backward compatible, since I have moved the service to a new path internaly, I still want the users to access it with the old url as not all of them have knowledge of this change.

I can accomplish what I want if I add [R] flag at the end of  my rewrite rule but it redirects the url on the client side, which I don't want.

My rewrite code:

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^/old-path(.*)$ /new-path/$ [L]
</IfModule>
</code>```

Although this rule results in the following url:

/var/www/html/new-path

Sample request looks something like:

https://host-name/old-path/param1/param2/param3/param4

and rewrite rule should just replace old-path with the new-path.

Can anyone give me some clues about what am I doing wrong? and how can I fix it?

Thanks in advance!

答:
If your are aiming for 'hiding' the rewrite, try this:

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^/old-path/(.*)$ /new-path/$1 [P,L]
</IfModule>
</code>```

And if you REALLY want to extract the hostname:

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} (.*)
  RewriteRule ^/old-path/(.*)$ http://%1/new-path/$1 [P,L]
</IfModule>
</code>```

Since %1 references the first bracket of RewriteCond-line...
If you want customers to be rewritten to the new URI and see that:

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^/old-path/(.*)$ https://host-name/new-path/$1 [R=301,L]
</IfModule>
</code>```

or in short, and without even using a rewrite:

```<code>RedirectMatch ^/old-path/(.*)$ /new-path/$1
</code>```

To avoid 'https://host-name/' change your DocumentRoot to the parent-directory of 'old-path' and especially 'new-path'.

Body:
I am trying to make my service backward compatible, since I have moved the service to a new path internaly, I still want the users to access it with the old url as not all of them have knowledge of this change.

I can accomplish what I want if I add [R] flag at the end of  my rewrite rule but it redirects the url on the client side, which I don't want.

My rewrite code:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^/old-path(.*)$ /new-path/$ [L]
</IfModule>

Although this rule results in the following url:

/var/www/html/new-path

Sample request looks something like:

https://host-name/old-path/param1/param2/param3/param4

and rewrite rule should just replace old-path with the new-path.

Can anyone give me some clues about what am I doing wrong? and how can I fix it?

Thanks in advance!

Body:
If your are aiming for 'hiding' the rewrite, try this:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^/old-path/(.*)$ /new-path/$1 [P,L]
</IfModule>

And if you REALLY want to extract the hostname:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} (.*)
  RewriteRule ^/old-path/(.*)$ http://%1/new-path/$1 [P,L]
</IfModule>

Since %1 references the first bracket of RewriteCond-line...
If you want customers to be rewritten to the new URI and see that:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^/old-path/(.*)$ https://host-name/new-path/$1 [R=301,L]
</IfModule>

or in short, and without even using a rewrite:

RedirectMatch ^/old-path/(.*)$ /new-path/$1

To avoid 'https://host-name/' change your DocumentRoot to the parent-directory of 'old-path' and especially 'new-path'.