问:
angularJS ng repeat field and special characters
I want to display all of the batters and their stats on my team from a json file into a table using angularjs.

HTML:

```<code><table class="table" ng-controller="players">
      <tr ng-repeat="x in player | orderBy:orderByField:reverseSort">
        <td>{{x.player_name}}</td>
        <td>{{x.components.B_OBP}}</td>
        <td>{{x.components.B_K%}}</td>
      </tr>
 </table>
</code>```

JS:

```<code>var baseballApp = angular.module('baseballApp', []);

baseballApp.controller('Players', function ($scope, $http) {
    $scope.message = 'Players';
    $http.get('http://example.com/myteam.json').then(function (response) {
        $scope.player = response.data;
    });
});
</code>```

JSON:

```<code>{

    "player_name": "Mookie Betts",
    "positions": {
        "PR": 0,
        "LF": 0,
        "C": 0,
        "DH": 0,
        "SS": 0,
        "CF": 0,
        "P": 0,
        "RF": 53,
        "1B": 0,
        "2B": 0,
        "3B": 0,
        "PH": 0
    },
    "handedness": {
        "bats": "R",
        "throws": "R"
    },
    "player_type": "b",
    "components": {
        "B_OPS": ".882",
        "B_SLG": ".516",
        "B_BSR": "3.6",
        "B_TEAM": "",
        "B_PA": "643",
        "B_3B": "4",
        "B_RBI": "94",
        "B_AB": "581",
        "B_R": "95",
        "B_2B": "38",
        "B_BB": "51",
        "B_ISO": ".206",
        "B_UBR": "3.5",
        "B_WOBA": ".375",
        "B_GDP": "",
        "B_H": "180",
        "B_SEASON": "2017",
        "B_SO": "71",
        "B_SH": "3",
        "B_WGDP": "",
        "B_SPD": "5.5",
        "B_SF": "5",
        "B_IBB": "1",
        "B_SB": "21",
        "B_G": "145",
        "B_WSB": "0.1",
        "B_BB/K": "0.72",
        "B_AVG": ".310",
        "B_CS": "9",
        "B_OFF": "28.4",
        "B_WRC+": "132",
        "B_HR": "25",
        "B_K%": "0.111",
        "B_WAR": "5.6",
        "B_BB%": "0.08",
        "B_BABIP": ".317",
        "B_1B": "113",
        "B_HBP": "3",
        "B_WRAA": "30.2",
        "B_WRC": "106",
        "B_DEF": "4.1",
        "B_OBP": ".366"
    },
    "player_id": "13611"

},
</code>```

I am able to show most stats correctly until i get to a stat with a special character such as B_K% or B_WRC+

I keep on receiving this error: ```Unexpected end of expression: x.components.B_K%```

Im not totally sure how to escape the character as ```{{x.components.["B_K%"]}}``` doesn't seem to help

Does anyone have an idea?

答: Try doing {{x.components["B_K%"]}}

Body:
I want to display all of the batters and their stats on my team from a json file into a table using angularjs.

HTML:

        {{x.player_name}}
        {{x.components.B_OBP}}
        {{x.components.B_K%}}

JS:

var baseballApp = angular.module('baseballApp', []);

baseballApp.controller('Players', function ($scope, $http) {
    $scope.message = 'Players';
    $http.get('http://example.com/myteam.json').then(function (response) {
        $scope.player = response.data;
    });
});

JSON:

{

    "player_name": "Mookie Betts",
    "positions": {
        "PR": 0,
        "LF": 0,
        "C": 0,
        "DH": 0,
        "SS": 0,
        "CF": 0,
        "P": 0,
        "RF": 53,
        "1B": 0,
        "2B": 0,
        "3B": 0,
        "PH": 0
    },
    "handedness": {
        "bats": "R",
        "throws": "R"
    },
    "player_type": "b",
    "components": {
        "B_OPS": ".882",
        "B_SLG": ".516",
        "B_BSR": "3.6",
        "B_TEAM": "",
        "B_PA": "643",
        "B_3B": "4",
        "B_RBI": "94",
        "B_AB": "581",
        "B_R": "95",
        "B_2B": "38",
        "B_BB": "51",
        "B_ISO": ".206",
        "B_UBR": "3.5",
        "B_WOBA": ".375",
        "B_GDP": "",
        "B_H": "180",
        "B_SEASON": "2017",
        "B_SO": "71",
        "B_SH": "3",
        "B_WGDP": "",
        "B_SPD": "5.5",
        "B_SF": "5",
        "B_IBB": "1",
        "B_SB": "21",
        "B_G": "145",
        "B_WSB": "0.1",
        "B_BB/K": "0.72",
        "B_AVG": ".310",
        "B_CS": "9",
        "B_OFF": "28.4",
        "B_WRC+": "132",
        "B_HR": "25",
        "B_K%": "0.111",
        "B_WAR": "5.6",
        "B_BB%": "0.08",
        "B_BABIP": ".317",
        "B_1B": "113",
        "B_HBP": "3",
        "B_WRAA": "30.2",
        "B_WRC": "106",
        "B_DEF": "4.1",
        "B_OBP": ".366"
    },
    "player_id": "13611"

},

I am able to show most stats correctly until i get to a stat with a special character such as B_K% or B_WRC+

I keep on receiving this error:
Unexpected end of expression: x.components.B_K%

Im not totally sure how to escape the character as
{{x.components.["B_K%"]}}
 doesn't seem to help

Does anyone have an idea?

Body: Try doing {{x.components["B_K%"]}}


来源: stackexchange

问:
Create Visio Database Diagram from Excel Table and Field List
I have an Excel worksheet, which has the following columns:
Table Name
Field Name
Data Type

My goal is to import this into Visio, and have it generate the table shapes, for each table, filling them with each field/data type.

I can then draw the relationship lines and arrange everything.

I've seen posts here and on other sites, about importing Excel, but it seems to be the data, not the data plan.

Anyone know how to do this?  Please let me know if you need more info.

I'm using Office 2010.

Thank you!

答:
From what I read, you're trying to create an entity relationship diagram. There's a template for these diagrams but I think only the professional version.
Here's a first link: https://support.office.com/en-us/article/Create-a-Database-Model-also-known-as-Entity-Relationship-diagram-7042e719-384a-4b41-b29c-d1b35719fc93</p>

ContentLicense: CC BY-SA 3.0


问:
decoding json string with json.loads in python
I have string like that:

jstring = {"label":"2017-06-01","value1":"250.730000"},{"label":"2017-06-02","value1":"250.730000"}

end if I use json.loads(jstring) I got this error:

```<code>Traceback (most recent call last):
  File "Funds.py", line 44, in <module>
    data  = json.loads(array)
  File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 367, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 45 - line 1 column 54951 (char 44 - 54950)
</code>```

What should I do with it?

答:
If you have the whole thing as on string like this:

```<code>jstring = '{"label":"2017-06-01","value1":"250.730000"},{"label":"2017-06-02","value1":"250.730000"}'
</code>```

then the dumps process sees this as two differnt objects and it can't process the information correctly. you need to put your string in a single object like this:

```<code>jstring = '{"first":{"label":"2017-06-01","value1":"250.730000"},"second":{"label":"2017-06-02","value1":"250.730000"}}'
</code>```

or like this:

```<code>jstring = '[{"label":"2017-06-01","value1":"250.730000"},{"label":"2017-06-02","value1":"250.730000"}]'
</code>```

that way the parser sees only one object

Body:
I have string like that:

jstring = {"label":"2017-06-01","value1":"250.730000"},{"label":"2017-06-02","value1":"250.730000"}

end if I use json.loads(jstring) I got this error:

Traceback (most recent call last):
  File "Funds.py", line 44, in <module>
    data  = json.loads(array)
  File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 367, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 45 - line 1 column 54951 (char 44 - 54950)

What should I do with it?

Body:
If you have the whole thing as on string like this:

jstring = '{"label":"2017-06-01","value1":"250.730000"},{"label":"2017-06-02","value1":"250.730000"}'

then the dumps process sees this as two differnt objects and it can't process the information correctly. you need to put your string in a single object like this:

jstring = '{"first":{"label":"2017-06-01","value1":"250.730000"},"second":{"label":"2017-06-02","value1":"250.730000"}}'

or like this:

jstring = '[{"label":"2017-06-01","value1":"250.730000"},{"label":"2017-06-02","value1":"250.730000"}]'

that way the parser sees only one object


问:
SQLDependency thread
i am in the process implementing SQLdepenency i would like to know in case of Dependency Handler exeuctues will it spun a different thred from main Process ? What will happen when the event handler triggers? Do i need to worry about any multithreds issues?</p>

```<code>public void CreateSqlDependency()
{
    try
    {
        using (SqlConnection connection = (SqlConnection)DBFactory.GetDBFactoryConnection(Constants.SQL_PROVIDER_NAME))
        {
            SqlCommand command = (SqlCommand)DBFactory.GetCommand(Constants.SQL_PROVIDER_NAME);
            command.CommandText = watchQuery;
            command.CommandType = CommandType.Text;
            SqlDependency dependency = new SqlDependency(command);
            //Create the callback object
            dependency.OnChange += new OnChangeEventHandler(this.QueueChangeNotificationHandler);
            SqlDependency.Start(connectionString);

            DataTable dataTable = DBFactory.ExecuteSPReDT(command);
        }

    }
    catch (SqlException sqlExp)
    {
        throw sqlExp;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

public void QueueChangeNotificationHandler(object caller, SqlNotificationEventArgs e)
{
    if(e.Info == SqlNotificationInfo.Insert)
        Fire();
}
</code>```

答: It works in a separate thread, but there is only one such thread for all notifications. Have a look at the SQLDependency section in this article </p>

ContentLicense: CC BY-SA 2.5

Title: SQLDependency thread

Body:
i am in the process implementing SQLdepenency i would like to know in case of Dependency Handler exeuctues will it spun a different thred from main Process ? What will happen when the event handler triggers? Do i need to worry about any multithreds issues?

public void CreateSqlDependency()
{
    try
    {
        using (SqlConnection connection = (SqlConnection)DBFactory.GetDBFactoryConnection(Constants.SQL_PROVIDER_NAME))
        {
            SqlCommand command = (SqlCommand)DBFactory.GetCommand(Constants.SQL_PROVIDER_NAME);
            command.CommandText = watchQuery;
            command.CommandType = CommandType.Text;
            SqlDependency dependency = new SqlDependency(command);
            //Create the callback object
            dependency.OnChange += new OnChangeEventHandler(this.QueueChangeNotificationHandler);
            SqlDependency.Start(connectionString);

            DataTable dataTable = DBFactory.ExecuteSPReDT(command);
        }

    }
    catch (SqlException sqlExp)
    {
        throw sqlExp;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

public void QueueChangeNotificationHandler(object caller, SqlNotificationEventArgs e)
{
    if(e.Info == SqlNotificationInfo.Insert)
        Fire();
}


问:
Case statements: multiple variables with multiple possibilities for each variable
At first I thought this syntax worked but it seems when will only check the first value of the groups, if any of the first values fail it will return locked. to bad the or operand doesn't work here.

```<code>def lock(a,b,c,d)
  case [a,b,c,d]
    when[(3||5||7), 2, (5||6), (8||9||0)]
      "unlocked"
    else
      "locked"
  end
end

lock(3, 2, 5, 8)
lock(5, 2, 5, 0)
lock(5, 2, 6, 8)
lock(7, 2, 5, 8)
lock(7, 2, 6, 9)
</code>```

I could do an if else statement for each variable, but i was hoping there was a way to do a case statement without having to make multiple when statements.

答:
I'll opt to loop the array instead of using a case statement, like this:

```<code>def lock(a,b,c,d)
  combination = [[3,5,7], [2], [5,6], [8,9,0]]
  attempt     = [a,b,c,d]

  combination.each_with_index do |position, i|
    return "locked" unless position.include?(attempt[i])
  end

  "unlocked"
end
</code>```

Outputs:

```<code>lock(3, 2, 5, 8)
#=> "unlocked"

lock(5, 2, 5, 0)
#=> "unlocked"

lock(5, 2, 6, 8)
#=> "unlocked"

lock(7, 2, 5, 8)
#=> "unlocked"

lock(7, 2, 6, 9)
#=> "unlocked"

lock(1, 2, 3, 4)
#=> "locked"
</code>```

Why your solution fails?

Just as Hamms pointed out in his comment, the when with [(3||5||7), 2, (5||6), (8||9||0)] evaluates to [3, 2, 5, 8]. That is because each expression in parenthesis is evaluated first, so, breaking it down, it would be:

```<code>(3 || 5 || 7)
#=> 3

2
#=> 2

(5 || 6)
#=> 5

(8 || 9 || 0)
#=> 8
</code>```

This is because || is evaluating if value is truthy, that is, is neither nil nor false. As soon as the expression gets to a truthy value, it will return that value and look no further. So any number will evaluate as truthy, and you will always get the first number of each expression as a result.

Back to your case statement, it is the exact same thing as writing it like:

```<code>case [a,b,c,d]
when [3, 2, 5, 8]
  "unlocked"
else
  "locked"
end
</code>```

Now consider that a case statement will evaluate if the object in case is equal with the one in each when. So in, your case will be something like:

```<code>[a,b,c,d] === [3, 2, 5, 8]
</code>```

Which will return true (and "unlocked") only when you call lock(3, 2, 5, 8).

Also consider that you could use multiple values with when, so using something like this will work:

```<code>case [a,b,c,d]
when [3, 2, 5, 8], [5, 2, 5, 0] then "unlocked"
else "locked"
end
</code>```

In which when will be equivalent to doing:

```<code>[a,b,c,d] === [3, 2, 5, 8] || [5, 2, 5, 0]
</code>```

Body:
At first I thought this syntax worked but it seems when will only check the first value of the groups, if any of the first values fail it will return locked. to bad the or operand doesn't work here.

def lock(a,b,c,d)
  case [a,b,c,d]
    when[(3||5||7), 2, (5||6), (8||9||0)]
      "unlocked"
    else
      "locked"
  end
end

lock(3, 2, 5, 8)
lock(5, 2, 5, 0)
lock(5, 2, 6, 8)
lock(7, 2, 5, 8)
lock(7, 2, 6, 9)

I could do an if else statement for each variable, but i was hoping there was a way to do a case statement without having to make multiple when statements.

Body:
I'll opt to loop the array instead of using a case statement, like this:

def lock(a,b,c,d)
  combination = [[3,5,7], [2], [5,6], [8,9,0]]
  attempt     = [a,b,c,d]

  combination.each_with_index do |position, i|
    return "locked" unless position.include?(attempt[i])
  end

  "unlocked"
end

Outputs:

lock(3, 2, 5, 8)
#=> "unlocked"

lock(5, 2, 5, 0)
#=> "unlocked"

lock(5, 2, 6, 8)
#=> "unlocked"

lock(7, 2, 5, 8)
#=> "unlocked"

lock(7, 2, 6, 9)
#=> "unlocked"

lock(1, 2, 3, 4)
#=> "locked"

Why your solution fails?

Just as Hamms pointed out in his comment, the when with [(3||5||7), 2, (5||6), (8||9||0)] evaluates to [3, 2, 5, 8]. That is because each expression in parenthesis is evaluated first, so, breaking it down, it would be:

(3 || 5 || 7)
#=> 3

2
#=> 2

(5 || 6)
#=> 5

(8 || 9 || 0)
#=> 8

This is because || is evaluating if value is truthy, that is, is neither nil nor false. As soon as the expression gets to a truthy value, it will return that value and look no further. So any number will evaluate as truthy, and you will always get the first number of each expression as a result.

Back to your case statement, it is the exact same thing as writing it like:

case [a,b,c,d]
when [3, 2, 5, 8]
  "unlocked"
else
  "locked"
end

Now consider that a case statement will evaluate if the object in case is equal with the one in each when. So in, your case will be something like:

[a,b,c,d] === [3, 2, 5, 8]

Which will return true (and "unlocked") only when you call lock(3, 2, 5, 8).

Also consider that you could use multiple values with when, so using something like this will work:

case [a,b,c,d]
when [3, 2, 5, 8], [5, 2, 5, 0] then "unlocked"
else "locked"
end

In which when will be equivalent to doing:

[a,b,c,d] === [3, 2, 5, 8] || [5, 2, 5, 0]


问:
Lose data in long strings when transfering values using ranges
So, I'm working on a project and at one point I copy data from one workbook to another by setting a range on the one workbook and then setting the range on the destination workbook equal to it. This works great in general, but I have one field that under some circumstances has data that is five digit numbers separated by commas. Zip codes essentially, separated by commas and possibly spaces as well. (Although there aren't supposed to be spaces in that data it is very possible that there are.)

So for example the cell being copied will look like this:
11111,22222,33333,44444,55555,66666,77777,88888,99999

and will transfer as this:
1.11112222233333E+44 or
111,112,222,233,333,000,000,000,000,000,000,000,000,000,000

This is obviously not what I want. How do I fix this?

Here is the relevant code. The column that has the problem data is column F of the Service Areas worksheet.

```<code>Dim MainWB As Workbook
Set MainWB = Workbooks("SATemplate Data Compile.xlsm")
Dim MDSAT As Range

'Setting the range I want to transfer
Set MDSAT = wb.Worksheets("Service Areas").Range("A13:G13", wb.Worksheets("Service Areas").Range("A13:G13").End(xlDown).End(xlDown).End(xlUp))

'Transferring the range values
MainWB.Sheets("SATemplates").Range("A" & Rows.count).End(xlUp).Offset(1).Resize(MDSAT.Rows.count, MDSAT.Columns.count).Cells.Value = MDSAT.Cells.Value
</code>```

Is this a problem with setting the new range equal to the cell values? Would I have to split this up into multiple parts so that a different range will grab the data in column F?

答: Format the cells as text not numbers.... </p>

Body:
So, I'm working on a project and at one point I copy data from one workbook to another by setting a range on the one workbook and then setting the range on the destination workbook equal to it. This works great in general, but I have one field that under some circumstances has data that is five digit numbers separated by commas. Zip codes essentially, separated by commas and possibly spaces as well. (Although there aren't supposed to be spaces in that data it is very possible that there are.)

So for example the cell being copied will look like this:
11111,22222,33333,44444,55555,66666,77777,88888,99999

and will transfer as this:
1.11112222233333E+44 or
111,112,222,233,333,000,000,000,000,000,000,000,000,000,000

This is obviously not what I want. How do I fix this?

Here is the relevant code. The column that has the problem data is column F of the Service Areas worksheet.

Dim MainWB As Workbook
Set MainWB = Workbooks("SATemplate Data Compile.xlsm")
Dim MDSAT As Range

'Setting the range I want to transfer
Set MDSAT = wb.Worksheets("Service Areas").Range("A13:G13", wb.Worksheets("Service Areas").Range("A13:G13").End(xlDown).End(xlDown).End(xlUp))

'Transferring the range values
MainWB.Sheets("SATemplates").Range("A" & Rows.count).End(xlUp).Offset(1).Resize(MDSAT.Rows.count, MDSAT.Columns.count).Cells.Value = MDSAT.Cells.Value

Is this a problem with setting the new range equal to the cell values? Would I have to split this up into multiple parts so that a different range will grab the data in column F?


问:
Machine learning concepts clarification (linear regression)
I'm pretty new to machine learning and after watching some videos i wanted to make sure i understood a few concepts:

When it comes to linear regression, we can find the intercept and the coefficients using several methods such as: Gradient Descent, Normal Equation and Least Squares.

Then, to measure the accuracy of our hypothesis function derived from the step above, we can use methods such as R-Square or  Square Error.

When it comes to regularization - we can use Ridge Regression (for example) to find the coefficients and intercept in addition to help us eliminate overfitting.
After applying Ridge Regression, when we get some coefficients that are 0, that just means they are not "that crucial" for our data and so we could simply remove them from our hypothesis function.

Are all of these statements correct?
Thanks!

答:
All correct.  One slight modification to your rhetoric:

when we get some coefficients that are 0, that just means they are not "that crucial" for our data and so we could simply remove the corresponding features from our hypothesis function.


问:
Prolog - count occurrence of number
I want to write predicate which can count all encountered number:

```<code>count(1, [1,0,0,1,0], X).
X = 2.
</code>```

I tried to write it like:

```<code>count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.
</code>```

Why doesn't work it?

答:
Why doesn't work it?

Prolog is a programming language that often can answer such question directly. Look how I tried out your definition starting with your failing query:

```<code>?- count(1, [1,0,0,1,0], X).
   false.
?- count(1, Xs, X).
   Xs = [], X = 0
;  Xs = [1], X = 1
;  Xs = [1,1], X = 2
;  Xs = [1,1,1], X = 3
;  ... .
?- Xs = [_,_,_], count(1, Xs, X).
   Xs = [1,1,1], X = 3.
</code>```

So first I realized that the query does not work at all, then I generalized the query. I replaced the big list by a variable Xs and said: Prolog, fill in the blanks for me! And Prolog did this and reveals us precisely the cases when it will succeed.

In fact, it only succeeds with lists of 1s only.  That is odd.  Your definition is too restricted - it correctly counts the 1s in lists where there are only ones, but all other lists are rejected. @coder showed you how to extend your definition.

Here is another one using library(reif) for
SICStus|SWI. Alternatively, see tfilter/3.

```<code>count(X, Xs, N) :-
   tfilter(=(X), Xs, Ys),
   length(Ys, N).
</code>```

A definition more in the style of the other definitions:

```<code>count(_, [], 0).
count(E, [X|Xs], N0) :-
   if_(E = X, C = 1, C = 0),
   count(E, Xs, N1),
   N0 is N1+C.
</code>```

And now for some more general uses:

How does a four element list look like that has 3 times a 1 in it?

```<code>?- length(L, 4), count(1, L, 3).
   L = [1,1,1,_A], dif(1,_A)
;  L = [1,1,_A,1], dif(1,_A)
;  L = [1,_A,1,1], dif(1,_A)
;  L = [_A,1,1,1], dif(1,_A)
;  false.
</code>```

So the remaining element must be something different from 1.

That's the fine generality Prolog offers us.

Title: Prolog - count occurrence of number

Body:
I want to write predicate which can count all encountered number:

count(1, [1,0,0,1,0], X).
X = 2.

I tried to write it like:

count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.

Why doesn't work it?

Body:
Why doesn't work it?

Prolog is a programming language that often can answer such question directly. Look how I tried out your definition starting with your failing query:

?- count(1, [1,0,0,1,0], X).
   false.
?- count(1, Xs, X).
   Xs = [], X = 0
;  Xs = [1], X = 1
;  Xs = [1,1], X = 2
;  Xs = [1,1,1], X = 3
;  ... .
?- Xs = [_,_,_], count(1, Xs, X).
   Xs = [1,1,1], X = 3.

So first I realized that the query does not work at all, then I generalized the query. I replaced the big list by a variable Xs and said: Prolog, fill in the blanks for me! And Prolog did this and reveals us precisely the cases when it will succeed.

In fact, it only succeeds with lists of 1s only.  That is odd.  Your definition is too restricted - it correctly counts the 1s in lists where there are only ones, but all other lists are rejected. @coder showed you how to extend your definition.

Here is another one using library(reif) for
SICStus|SWI. Alternatively, see tfilter/3.

count(X, Xs, N) :-
   tfilter(=(X), Xs, Ys),
   length(Ys, N).

A definition more in the style of the other definitions:

count(_, [], 0).
count(E, [X|Xs], N0) :-
   if_(E = X, C = 1, C = 0),
   count(E, Xs, N1),
   N0 is N1+C.

And now for some more general uses:

How does a four element list look like that has 3 times a 1 in it?

?- length(L, 4), count(1, L, 3).
   L = [1,1,1,_A], dif(1,_A)
;  L = [1,1,_A,1], dif(1,_A)
;  L = [1,_A,1,1], dif(1,_A)
;  L = [_A,1,1,1], dif(1,_A)
;  false.

So the remaining element must be something different from 1.

That's the fine generality Prolog offers us.

ContentLicense: CC BY-SA 4.0


问:
Keyboard shortcut to switch between horizontally split windows in Intellij
I've done numerous searches to find out how to switch between two files that are horizontally split but can't seem to find it. I know that you can switch between vertically split files by using the Goto Next Splitter option, but there doesn't seem to exist an option for horizontally split. Has anyone else figured this out? Thanks!

An example of a situation where I can't switch between the top and bottom files:

答:
I just tried this out, and Goto Next Splitter (Option-Tab on mac) works just fine for me on horizontally split panes

Note: Using CLion 2017.1.2

If you have IdeaVim installed, you can use the Control-W - J/K command to switch between Vim split panes. See also How do I switch between panes in split mode in Vim?


问:
Put cursor inside input box onChange in React
I have a component of basic editable list items that operates as such:

My problem is that the cursor does not move into the input box onChange, making a hassle for the user to always click twice. I tried https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js but it did not work. Component looks like:

```<code>import React from 'react';

import MyComponent from '../utils/MyComponent';

export default class BasicList extends MyComponent {

    constructor(props) {
        let custom_methods = ['renderItemOrEditField', 'toggleEditing', 'moveCaretAtEnd'];
        super(props, custom_methods);
        this.state = {editing: null};
    }

    moveCaretAtEnd(e) {
        var temp_value = e.target.value
        e.target.value = ''
        e.target.value = temp_value
    }

    renderItemOrEditField(item) {
        console.log(item);
        if (this.state.editing === item.id) {
            return (
                <input
                  onKeyDown={ this.handleEditField }
                  type="text"
                  className="form-control"
                  ref={ `${item.type}_name_${ item.id }` }
                  name="title"
                  autofocus
                  onFocus={this.moveCaretAtEnd}
                  defaultValue={ item.name }
                />
            );
        } else {
            return (
                <li
                  onClick={this.toggleEditing.bind(null, item.id)}
                  key={item.id}
                  className="list-group-item">
                    {item.name}
                </li>
            );
        }
    }

    toggleEditing(item_id) {
        this.setState({editing: item_id});
    }

    render() {
        let li_elements = null;
        let items = this.props.items;

        if (items.length > 0) {
          li_elements = items.map((item) => {
              return (
                  this.renderItemOrEditField(item)
                //   {/* }<li key={item.id}>
                //       {item.name} -
                //       <button onClick={() => {this.props.deleteCallback(this.props.item_type, item.id, item.name)} }>
                //         Delete
                //       </button>
                //   </li> */}

              );
          });
        }

        return (
          <div>
            <h4>{this.props.title}:</h4>
                <ul className="list-group">
                    {li_elements}
                </ul>
          </div>
        );
    }
}
</code>```

The items I'm working with now only have a name and ID (type denotes a 'role' or 'task')

How can I make the cursor start at the end of the input box text on change?

答: Autofocus triggers when a component is mounted. Not sure that's happening by your conditional render. You could moving your conditional logic to a separate container and that should trigger a mount each time it's shown.</p>

Body:
I have a component of basic editable list items that operates as such:

My problem is that the cursor does not move into the input box onChange, making a hassle for the user to always click twice. I tried https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js but it did not work. Component looks like:

import React from 'react';

import MyComponent from '../utils/MyComponent';

export default class BasicList extends MyComponent {

    constructor(props) {
        let custom_methods = ['renderItemOrEditField', 'toggleEditing', 'moveCaretAtEnd'];
        super(props, custom_methods);
        this.state = {editing: null};
    }

    moveCaretAtEnd(e) {
        var temp_value = e.target.value
        e.target.value = ''
        e.target.value = temp_value
    }

    renderItemOrEditField(item) {
        console.log(item);
        if (this.state.editing === item.id) {
            return (
                <input
                  onKeyDown={ this.handleEditField }
                  type="text"
                  className="form-control"
                  ref={ `${item.type}_name_${ item.id }` }
                  name="title"
                  autofocus
                  onFocus={this.moveCaretAtEnd}
                  defaultValue={ item.name }
                />
            );
        } else {
            return (

                    {item.name}

            );
        }
    }

    toggleEditing(item_id) {
        this.setState({editing: item_id});
    }

    render() {
        let li_elements = null;
        let items = this.props.items;

        if (items.length > 0) {
          li_elements = items.map((item) => {
              return (
                  this.renderItemOrEditField(item)
                //   {/* }

                //       {item.name} -
                //       <button onClick={() => {this.props.deleteCallback(this.props.item_type, item.id, item.name)} }>
                //         Delete
                //       </button>
                //
 */}

              );
          });
        }

        return (

{this.props.title}:

                    {li_elements}

        );
    }
}

The items I'm working with now only have a name and ID (type denotes a 'role' or 'task')

How can I make the cursor start at the end of the input box text on change?


问:
How get your list selected data from database to the class Entity Framework?
I was wondering if someone can help me with this issue, I have Factorform which is a master and detail, I'm trying to get data from the parameter in my constructor, I know a bout master because it is a single select but about the detail, I get a list of data so how I can get it in my class entity?

Here is my code:

```<code>public partial class FactorForm : MetroFramework.Forms.MetroForm
{
        public FactorForm()
        {
            InitializeComponent();
        }

        public FactorForm(Guid _FactorID)
        {
            _FactorMode = (int)Factormode.update;
            FactorID = _FactorID;
            InitializeComponent();
        }
        //==============================================================================
        Factor _Factor;
        int _FactorMode = (int)Factormode.insert;
        Guid _WarhouseID;
        Guid _CustomerID;
        Guid _partref;
        public Guid FactorID { get; set; }

        enum Factormode
        {
            insert=1,
            update
        }
        //==============================================================================
        private void FactorForm_Load(object sender, EventArgs e)
        {
            CustomerGrid.Visible = false;
            WarehouseGrid.Visible = false;
            PartGrid.Visible = false;

            if (_FactorMode != (int)Factormode.insert && FactorID != null)
            {
                using (var context=new FactorEntities())
                {
                    var Factor = context.Factors.FirstOrDefault(f => f.FactorID==FactorID);
                    if (Factor != null)
                    {
                         _Factor.FactorID = Factor.FactorID;
                         _Factor.FactorCode = Factor.FactorCode;
                         _Factor.FactorDate = Factor.FactorDate;
                         _Factor.discount = Factor.discount;
                         _Factor.VAT = Factor.VAT;
                         _Factor.TotalPrice = Factor.TotalPrice;
                         _Factor.WarehouseRef = Factor.WarehouseRef;
                         _Factor.CustomerRef = Factor.CustomerRef;
                    }

                    var FactorItem = context.FactorItems.Where(fi => fi.FactorRef == FactorID);

                    if (FactorItem != null)
                    {
                        _Factor.
                    }
            }
        }
    }
}
</code>```

So what should the code be in this part?

```<code>   if (FactorItem != null)
   {
       _Factor.
   }
</code>```

Thanks in advance.

答:
well I got it .I have to use for each :</p>

```<code>  var FactorItem = context.FactorItems.Where(fi => fi.FactorRef == FactorID);
                if (FactorItem!=null)
                {
                    foreach (var item in FactorItem)
                    {
                        _FactorItems.FactorItemID = item.FactorItemID;
                        _FactorItems.FactorRef = item.FactorRef;
                        _FactorItems.PartCount = item.PartCount;
                        _FactorItems.PartPrice = item.PartPrice;
                        _FactorItems.PartRef = item.PartRef;
                        _FactorItems.Rowno = item.Rowno;

                    }
                }
</code>```

Body:
I was wondering if someone can help me with this issue, I have Factorform which is a master and detail, I'm trying to get data from the parameter in my constructor, I know a bout master because it is a single select but about the detail, I get a list of data so how I can get it in my class entity?

Here is my code:

public partial class FactorForm : MetroFramework.Forms.MetroForm
{
        public FactorForm()
        {
            InitializeComponent();
        }

        public FactorForm(Guid _FactorID)
        {
            _FactorMode = (int)Factormode.update;
            FactorID = _FactorID;
            InitializeComponent();
        }
        //==============================================================================
        Factor _Factor;
        int _FactorMode = (int)Factormode.insert;
        Guid _WarhouseID;
        Guid _CustomerID;
        Guid _partref;
        public Guid FactorID { get; set; }

        enum Factormode
        {
            insert=1,
            update
        }
        //==============================================================================
        private void FactorForm_Load(object sender, EventArgs e)
        {
            CustomerGrid.Visible = false;
            WarehouseGrid.Visible = false;
            PartGrid.Visible = false;

            if (_FactorMode != (int)Factormode.insert && FactorID != null)
            {
                using (var context=new FactorEntities())
                {
                    var Factor = context.Factors.FirstOrDefault(f => f.FactorID==FactorID);
                    if (Factor != null)
                    {
                         _Factor.FactorID = Factor.FactorID;
                         _Factor.FactorCode = Factor.FactorCode;
                         _Factor.FactorDate = Factor.FactorDate;
                         _Factor.discount = Factor.discount;
                         _Factor.VAT = Factor.VAT;
                         _Factor.TotalPrice = Factor.TotalPrice;
                         _Factor.WarehouseRef = Factor.WarehouseRef;
                         _Factor.CustomerRef = Factor.CustomerRef;
                    }

                    var FactorItem = context.FactorItems.Where(fi => fi.FactorRef == FactorID);

                    if (FactorItem != null)
                    {
                        _Factor.
                    }
            }
        }
    }
}

So what should the code be in this part?

   if (FactorItem != null)
   {
       _Factor.
   }

Thanks in advance.

Body:
well I got it .I have to use for each :

  var FactorItem = context.FactorItems.Where(fi => fi.FactorRef == FactorID);
                if (FactorItem!=null)
                {
                    foreach (var item in FactorItem)
                    {
                        _FactorItems.FactorItemID = item.FactorItemID;
                        _FactorItems.FactorRef = item.FactorRef;
                        _FactorItems.PartCount = item.PartCount;
                        _FactorItems.PartPrice = item.PartPrice;
                        _FactorItems.PartRef = item.PartRef;
                        _FactorItems.Rowno = item.Rowno;

                    }
                }


问:
XML for Android Programming
I just picked up the Android Apps for Absolute Beginners and I read the introduction, it turns out you have to know Java.... so I read Sam's Teach Yourself Java And 24 Hours and I thought I was ready to dive into Android programming. When I began reading the book I noticed there was a lot of XML stuff and I don't know XML.. my question is, how much XML do you have to know in order to write Android apps. Can someone recommend a book or resource that has information about XML and Android? I have about three years of Objective-C experience and a couple days of Java experience.

Thanks!

答:
Please be aware that this answer is mostly focused on Android application development using Android Studio and may not be true for other development tools and methods.

XML is a markup language used for styling Android applications, it is generally used as a means of separating the application’s styling from the actual logic - meaning that that the “image” and “functionality” of the application are separate and if one changes, the other does not have to.

To develop an Android application, you don’t need to know XML, On Android's Developer website - it states that you can either style your application at runtime using Java or use XML. Though a basic understanding of XML may come in handy for problem-solving.

And even if you wish to use XML to style your app - you don't need /an in-depth knowledge of it as you can simply use Android Studio’s Layout-Editor (only versions  2.3 or higher can do this) - which will allow you to style your application visually and generate the corresponding XML afterwards which you're free to edit if you please.

Sources

https://developer.android.com/guide/topics/ui/declaring-layout.html

https://developer.android.com/training/basics/firstapp/building-ui.html#strings

Also see:
 - TutorialsPoint's Android tutorial titled "Styles and Themes"
 - W3Schools' XML tutorials.
 - As well as any of the appealing links on Android's developer website, TutorialsPoint and off-course W3Schools websites.

Forgive me for any mistakes in this post and you're free to correct them, forgive me for my inability to provide all the relevant links (due to my low reputation) and I hope this helps at least someone.

Title: XML for Android Programming


问:
Using Timber and Shopify, how can I update the cart preview?
I’m using Timber in a Shopify theme.

I have a POST request to /cart/add on a custom page. The item is added to the cart properly but in my callback, I need to update the cart preview (ajax-cart-template.liquid).

I see that a function already exists in ajax-cart.js to do this, where a Handlebars template is rendered in the private function, buildCart().

I could duplicate the code in the buildCart() function and put it in my callback, but that is obviously redundant. Am I able to somehow call buildCart() outside of that scope?

答:
With a tiny bit of customization this should be doable.

First, make buildCart a public method by adding build: buildCart to:

```<code>module = {
  init: init,
  load: loadCart,
  build: buildCart
};
</code>```

As I write this I realize loadCart is never used publically. Oops. I think my idea here was that if someone wanted to rebuild the cart, they'd call this ajaxCart.loadCart() and it would get the data and build it out.

Since you already have the cart, you can instead do ajaxCart.build(cart_object) and you're good to go.

Body:
With a tiny bit of customization this should be doable.

First, make buildCart a public method by adding build: buildCart to:

module = {
  init: init,
  load: loadCart,
  build: buildCart
};

As I write this I realize loadCart is never used publically. Oops. I think my idea here was that if someone wanted to rebuild the cart, they'd call this ajaxCart.loadCart() and it would get the data and build it out.

Since you already have the cart, you can instead do ajaxCart.build(cart_object) and you're good to go.


问:
pip or pip3 to install packages for Python 3?
I have a Macbook with OS X El Captain. I think that Python 2.7 comes preinstalled on it. However, I installed Python 3.5 too. When I started using Python 3, I read that if I want to install a package, I should type:

```<code>pip3 install some_package
</code>```

Anyway, now when I use

```<code>pip install some_package
</code>```

I get some_package installed for Python 3. I mean I can import it and use it without problems. Moreover, when I type just pip3 in the Terminal. I got this message about the usage:

```<code>Usage:
  pip <command> [options]
</code>```

which is the same message I get when I type just pip.

Does it mean that in previous versions, things were different, and now pip and pip3 can be used interchangeably? If so, and for the sake of argument, how can I install packages for Python 2 instead of Python 3?

答:
If you had python 2.x and then installed python3, your pip will be pointing to pip3.
you can verify that by typing pip --version which would be the same as pip3 --version.

On your system you have now pip, pip2 and pip3.

If you want you can change pip to point to pip2 instead of pip3.

Body:
I have a Macbook with OS X El Captain. I think that Python 2.7 comes preinstalled on it. However, I installed Python 3.5 too. When I started using Python 3, I read that if I want to install a package, I should type:

pip3 install some_package

Anyway, now when I use

pip install some_package

I get some_package installed for Python 3. I mean I can import it and use it without problems. Moreover, when I type just pip3 in the Terminal. I got this message about the usage:

Usage:
  pip <command> [options]

which is the same message I get when I type just pip.

Does it mean that in previous versions, things were different, and now pip and pip3 can be used interchangeably? If so, and for the sake of argument, how can I install packages for Python 2 instead of Python 3?


问:
Any way to differentiate a building from a road in Google Maps?
So if I have a general GPS Lat/Lng point, would it be possible to say, yes this point is in a building, or this point is on a road which a car could travel on?</p>

答:
I do not think you can determine if a point is a road or a building purely with Google Maps data.  To do this I think you would need some additional data source.

However, you may be able to determine if a point is a road by using the Snap point to street technique.

I have re-written the technique to use Google Maps API v3 and added the Haversine function to tell you the distance (in km) between the original clicked point and the corresponding point in the nearest street.

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

rad = function(x) {return x*Math.PI/180;}

distHaversine = function(p1, p2) {
  var R = 6371; // earth's mean radius in km
  var dLat  = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;

  return d.toFixed(3);
}

  var dirn = new google.maps.DirectionsService();
  var map;

  function initialize() {
    var center = new google.maps.LatLng(53.7877, -2.9832);
    var myOptions = {
      zoom:15,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: center
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    google.maps.event.addListener(map, "click", function(event) {
        // == When the user clicks on a the map, get directiobns from that point to itself ==
        var request = {
            origin: event.latLng,
            destination: event.latLng,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        dirn.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
                if(response.routes && response.routes.length > 0){
                    route = response.routes[0];
                    if(route.overview_path && route.overview_path.length > 0){
                        pos = route.overview_path[0];
                        new google.maps.Marker({
                              position: pos,
                              map: map
                        });
                        alert(distHaversine(request.origin, pos));
                    }
                }
          }
        });
    });
  }

</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
</code>```

I hope this is helpful.

Body:
I do not think you can determine if a point is a road or a building purely with Google Maps data.  To do this I think you would need some additional data source.

However, you may be able to determine if a point is a road by using the Snap point to street technique.

I have re-written the technique to use Google Maps API v3 and added the Haversine function to tell you the distance (in km) between the original clicked point and the corresponding point in the nearest street.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

rad = function(x) {return x*Math.PI/180;}

distHaversine = function(p1, p2) {
  var R = 6371; // earth's mean radius in km
  var dLat  = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;

  return d.toFixed(3);
}

  var dirn = new google.maps.DirectionsService();
  var map;

  function initialize() {
    var center = new google.maps.LatLng(53.7877, -2.9832);
    var myOptions = {
      zoom:15,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: center
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    google.maps.event.addListener(map, "click", function(event) {
        // == When the user clicks on a the map, get directiobns from that point to itself ==
        var request = {
            origin: event.latLng,
            destination: event.latLng,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        dirn.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
                if(response.routes && response.routes.length > 0){
                    route = response.routes[0];
                    if(route.overview_path && route.overview_path.length > 0){
                        pos = route.overview_path[0];
                        new google.maps.Marker({
                              position: pos,
                              map: map
                        });
                        alert(distHaversine(request.origin, pos));
                    }
                }
          }
        });
    });
  }

</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>

I hope this is helpful.


问:
Excel formula to find the value where a row stays zero and return column header
I'm trying to create a formula that would be able to find the last zero value in a row by searching a row from right to left. In other words the value where a cell in a row is zero and then all the cells after that are also zero. I've been experimenting with offset, index and lookup but nothing seems to work.

For example, in the data below I would want the formula to come up with the answer "18-Nov-17".

Any suggestions would be greatly appreciated!

here is a sample excel sheet

答:
Use the following array formula:

```<code>=INDEX($P$3:$AI$3,MATCH(2,IF($P$4:$AI$4<>0,1))+1)
</code>```

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.

Body:
Use the following array formula:

=INDEX($P$3:$AI$3,MATCH(2,IF($P$4:$AI$4<>0,1))+1)

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.


问:
Build Failed: Value of optional type '[SFUserAccount]?' not unwrapped
A newbie to native swift development!
Opened the below issue in https://github.com/forcedotcom/SalesforceMobileSDK-iOS/issues/2072

Version of Mobile SDK Used: 5.1.0

Issue found in Native App or Hybrid App: Native App

OS Version: 10.12.5

Device: iPhone 6

Steps to reproduce:

forceios create

Provided application type as native_swift and add other requested details

Open the *.xcworkspace file in Xcode

Build the project

Error: Value id optional type '[SFUserAccount]?' not unwrapped;

```<code>    func handleSdkManagerLogout()
        {
            self.log(.debug, msg: "SFAuthenticationManager logged out.  Resetting app.")
            self.resetViewState { () -> () in
                self.initializeAppViewState()

                // Multi-user pattern:
                // - If there are two or more existing accounts after logout, let the user choose the account
                //   to switch to.
                // - If there is one existing account, automatically switch to that account.
                // - If there are no further authenticated accounts, present the login screen.
                //
                // Alternatively, you could just go straight to re-initializing your app state, if you know
                // your app does not support multiple accounts.  The logic below will work either way.

                var numberOfAccounts : Int;
                let allAccounts = SFUserAccountManager.sharedInstance().allUserAccounts()
                numberOfAccounts = (allAccounts!.count);

                if numberOfAccounts > 1 {
                    let userSwitchVc = SFDefaultUserManagementViewController(completionBlock: {
                        action in
                        self.window!.rootViewController!.dismiss(animated:true, completion: nil)
                    })
                    if let actualRootViewController = self.window!.rootViewController {
                        actualRootViewController.present(userSwitchVc!, animated: true, completion: nil)
                    }
                } else {
                    if (numberOfAccounts == 1) {
                        SFUserAccountManager.sharedInstance().currentUser = allAccounts[0]

// ERROR: Value id optional type '[SFUserAccount]?' not unwrapped;
                    }
                    SalesforceSDKManager.shared().launch()
                }
            }
        }
</code>```

答:
You need to unwrap allAccounts because it's an optional array. And since force unwrapping has been used above to get numberOfAccounts, it's probably safe to use it.

Try this:

```<code>SFUserAccountManager.sharedInstance().currentuser = allAccounts![0]
</code>```

Body:
A newbie to native swift development!
Opened the below issue in https://github.com/forcedotcom/SalesforceMobileSDK-iOS/issues/2072

Version of Mobile SDK Used: 5.1.0

Issue found in Native App or Hybrid App: Native App

OS Version: 10.12.5

Device: iPhone 6

Steps to reproduce:

forceios create

Provided application type as native_swift and add other requested details

Open the *.xcworkspace file in Xcode

Build the project

Error: Value id optional type '[SFUserAccount]?' not unwrapped;

    func handleSdkManagerLogout()
        {
            self.log(.debug, msg: "SFAuthenticationManager logged out.  Resetting app.")
            self.resetViewState { () -> () in
                self.initializeAppViewState()

                // Multi-user pattern:
                // - If there are two or more existing accounts after logout, let the user choose the account
                //   to switch to.
                // - If there is one existing account, automatically switch to that account.
                // - If there are no further authenticated accounts, present the login screen.
                //
                // Alternatively, you could just go straight to re-initializing your app state, if you know
                // your app does not support multiple accounts.  The logic below will work either way.

                var numberOfAccounts : Int;
                let allAccounts = SFUserAccountManager.sharedInstance().allUserAccounts()
                numberOfAccounts = (allAccounts!.count);

                if numberOfAccounts > 1 {
                    let userSwitchVc = SFDefaultUserManagementViewController(completionBlock: {
                        action in
                        self.window!.rootViewController!.dismiss(animated:true, completion: nil)
                    })
                    if let actualRootViewController = self.window!.rootViewController {
                        actualRootViewController.present(userSwitchVc!, animated: true, completion: nil)
                    }
                } else {
                    if (numberOfAccounts == 1) {
                        SFUserAccountManager.sharedInstance().currentUser = allAccounts[0]

// ERROR: Value id optional type '[SFUserAccount]?' not unwrapped;
                    }
                    SalesforceSDKManager.shared().launch()
                }
            }
        }

Body:
You need to unwrap allAccounts because it's an optional array. And since force unwrapping has been used above to get numberOfAccounts, it's probably safe to use it.

Try this:

SFUserAccountManager.sharedInstance().currentuser = allAccounts![0]


问:
Enabling Facebook SDK in an Android Project
I specify the Facebook SDK as a remote dependency in my build.gradle file, however I've also had to import the actual SDK files into my Android project. Isn't that redundant? Or does the specification of the remote dependency and the import of the Facebook SDK files fulfill two different requirements.

If I want to update the SDK version my app uses, is it necessary to update the actual SDK files I previously imported into my project? Or can I just update my dependency in the build.gradle file?

答:
Open your your_app | build.gradle, and add the compile dependency

```<code>dependencies {
  compile 'com.facebook.android:facebook-android-sdk:4.+'
}
</code>```

Build your project. Now you can import com.facebook.FacebookSdk into your app.

It's all what you need to use de Facebook Sdk.  If you want to update facebook sdk version just change de compile dependency and sync gradle.

For more information visit Facebook Docs

Body:
Open your your_app | build.gradle, and add the compile dependency

dependencies {
  compile 'com.facebook.android:facebook-android-sdk:4.+'
}

Build your project. Now you can import com.facebook.FacebookSdk into your app.

It's all what you need to use de Facebook Sdk.  If you want to update facebook sdk version just change de compile dependency and sync gradle.

For more information visit Facebook Docs


问:
Limit the length of a string with AngularJS
I have the following:

```<code><div>{{modal.title}}</div>
</code>```

Is there a way that I could limit the length of the string to say 20 characters?

And an even better question would be is there a way that I could change the string to be truncated and show ... at the end if it's more than 20 characters?

答:
The simplest solution I found for simply limiting the string length was {{ modal.title | slice:0:20 }}, and then borrowing from @Govan above you can use {{ modal.title.length > 20 ? '...' : ''}} to add the suspension points if the string is longer than 20, so the final result is simply:

{{ modal.title | slice:0:20 }}{{ modal.title.length > 20 ? '...' : ''}}

https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html

Body:
I have the following:

{{modal.title}}

Is there a way that I could limit the length of the string to say 20 characters?

And an even better question would be is there a way that I could change the string to be truncated and show ... at the end if it's more than 20 characters?


问:
How to make spark streaming job run perpetually on HD Insights (YARN)?
I am developing a spark application running in HD Insights Cluster (YARN based) with IntelliJ. Currently, I submit jobs through the Azure HD Insights plug-in directly from IntelliJ. This, in turns, use the Livy API to submit the job remotely.

When I am done with developing the code, I would like the streaming job to be run perpetually. Currently, if the job fails five times, the program stops and doesn't restart itself. Is there any way to change this behavior? Or what solution do most people use to make spark restart after failing?

答:
Restart of Yarn Spark jobs is controlled by Yarn settings. So you need to increase number of restarts for the spark application (yarn application master) in yarn. I believe it's: yarn.resourcemanager.am.max-attempts.
In HDInsight go to Ambari UI and change this setting in Yarn -> Config -> Advanced Yarn-site.

In order to submit production job you can use livy APIs directly as described here: https://learn.microsoft.com/en-us/azure/hdinsight/hdinsight-apache-spark-eventhub-streaming#run-the-application-remotely-on-a-spark-cluster-using-livy


问:
How to include CSS file in AMP project
```<code><style amp-custom>
{% include "style.css" %}
</style>
</code>```

I am trying to create a simple AMP-site and got some problem. What is {% %}? It doesn't work for me?

Title: How to include CSS file in AMP project

Body:
{% include "style.css" %} is a twig tag (template). Are you by chance in WordPress or other php base framework ?

You have two possibilities:
 1. Using the include, you replace "style.css" with a reference to your css file to be include.
 2. You paste your css inside the <style amp-custom>, in place of the template tag (e.g. the whole {% include "style.css" %}).

Hope this help


问:
How can I properly bind a React component class's event handlers when converting from createClass to the class keyword?
I'm in the midst of preparing our React components for an upgrade to React 16 with the crux of that process being an update of components that use with React.createClass to use the class keyword instead.

I'm running into trouble when it comes to event handlers that invoke class methods as I keep seeing the Can only update a mounted or mounting component error.

A trivial example...

Original component using React.createClass:

```<code>const Foo = React.createClass({
  getInitialState() {
    return { bar: false };
  },

  onClick() {
    this.setState({ bar: !this.state.bar });
  },

  render() {
    return (
      <div>
        <p>{this.state.bar ? 'YAY' : 'BOO'}</p>
        <button onClick={this.onClick}>CLICK IT</button>
      </div>
    );
  },
});
</code>```

That works as expected. So does this if I'm willing to ignore that a new function object will be created with each call to render:

```<code>class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };
  }

  render() {
    return (
      <div>
        <p>{this.state.bar ? 'YAY' : 'BOO'}</p>
        <button onClick={() => { this.setState({ bar: !this.state.bar }); }}>CLICK IT</button>
      </div>
    );
  }
}
</code>```

However, I can't get the "bind in the constructor" approach to work:

```<code>class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };

    this.onClick = this.onClick.bind(this);
  }

  onClick() {
    this.setState({ bar: !this.state.bar });
  }

  render() {
    return (
      <div>
        <p>{this.state.bar ? 'YAY' : 'BOO'}</p>
        <button onClick={this.onClick}>CLICK IT</button>
      </div>
    );
  }
}
</code>```

Nor can I get the property initializer syntax approach to work:

```<code>class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };
  }

  onClick = () => {
    this.setState({ bar: !this.state.bar });
  }

  render() {
    return (
      <div>
        <p>{this.state.bar ? 'YAY' : 'BOO'}</p>
        <button onClick={this.onClick}>CLICK IT</button>
      </div>
    );
  }
}
</code>```

In both of those cases, whenever I click the button the aforementioned error message shows up in the browser console.

I'm hoping someone has encountered this problem themselves already and has advice on how to deal with it. I imagine that it's just something trivial that I'm completely overlooking. :)

Thanks in advance!

答:
Pshh, do it the easy way and use react-autobind. Binds all component functions to this for you automatically in the constructor.

Super simple and easy to use:

```<code>import autoBind from 'react-autobind';

constructor() {
  super();
  autoBind(this);
}
</code>```

Body:
I'm in the midst of preparing our React components for an upgrade to React 16 with the crux of that process being an update of components that use with React.createClass to use the class keyword instead.

I'm running into trouble when it comes to event handlers that invoke class methods as I keep seeing the Can only update a mounted or mounting component error.

A trivial example...

Original component using React.createClass:

const Foo = React.createClass({
  getInitialState() {
    return { bar: false };
  },

  onClick() {
    this.setState({ bar: !this.state.bar });
  },

  render() {
    return (

{this.state.bar ? 'YAY' : 'BOO'}

        <button onClick={this.onClick}>CLICK IT</button>

    );
  },
});

That works as expected. So does this if I'm willing to ignore that a new function object will be created with each call to render:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };
  }

  render() {
    return (

{this.state.bar ? 'YAY' : 'BOO'}

        <button onClick={() => { this.setState({ bar: !this.state.bar }); }}>CLICK IT</button>

    );
  }
}

However, I can't get the "bind in the constructor" approach to work:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };

    this.onClick = this.onClick.bind(this);
  }

  onClick() {
    this.setState({ bar: !this.state.bar });
  }

  render() {
    return (

{this.state.bar ? 'YAY' : 'BOO'}

        <button onClick={this.onClick}>CLICK IT</button>

    );
  }
}

Nor can I get the property initializer syntax approach to work:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };
  }

  onClick = () => {
    this.setState({ bar: !this.state.bar });
  }

  render() {
    return (

{this.state.bar ? 'YAY' : 'BOO'}

        <button onClick={this.onClick}>CLICK IT</button>

    );
  }
}

In both of those cases, whenever I click the button the aforementioned error message shows up in the browser console.

I'm hoping someone has encountered this problem themselves already and has advice on how to deal with it. I imagine that it's just something trivial that I'm completely overlooking. :)

Thanks in advance!

Body:
Pshh, do it the easy way and use react-autobind. Binds all component functions to this for you automatically in the constructor.

Super simple and easy to use:

import autoBind from 'react-autobind';

constructor() {
  super();
  autoBind(this);
}


问:
How to iterate through multiple UILabels
I am looking for an elegant way to iterate through an array and assign each of its values to one or more of five UILabels

This code illustrates what I am trying to do (although it is very long and repetitive)

```<code>    if touches.count >= 1 {
        positionTouch1LBL.text = String(describing: touches[0].location(in: view))
    } else {
        positionTouch1LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 2 {
        positionTouch2LBL.text = String(describing: touches[1].location(in: view))
    } else {
        positionTouch2LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 3 {
        positionTouch3LBL.text = String(describing: touches[2].location(in: view))
    } else {
        positionTouch3LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 4 {
        positionTouch4LBL.text = String(describing: touches[3].location(in: view))
    } else {
        positionTouch4LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 5 {
        positionTouch5LBL.text = String(describing: touches[4].location(in: view))
    } else {
        positionTouch5LBL.text = "0.0 / 0.0"
    }
</code>```

答:
You could put your labels inside another array and iterate through them:

let labelsArray = [positionTouch1LBL, positionTouch2LBL, positionTouch3LBL, positionTouch4BL, positionTouch5LBL]

for i in 0..<labelsArray.count {
    // Get i-th UILabel
    let label = labelsArray[i]
    if touches.count >= (i+1) {
        label.text = String(describing: touches[i].location(in: view))
    }else{
        label.text = "0.0 / 0.0"
    }
}
```

This way you are able to group redundant code

Body:
I am looking for an elegant way to iterate through an array and assign each of its values to one or more of five UILabels

This code illustrates what I am trying to do (although it is very long and repetitive)

    if touches.count >= 1 {
        positionTouch1LBL.text = String(describing: touches[0].location(in: view))
    } else {
        positionTouch1LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 2 {
        positionTouch2LBL.text = String(describing: touches[1].location(in: view))
    } else {
        positionTouch2LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 3 {
        positionTouch3LBL.text = String(describing: touches[2].location(in: view))
    } else {
        positionTouch3LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 4 {
        positionTouch4LBL.text = String(describing: touches[3].location(in: view))
    } else {
        positionTouch4LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 5 {
        positionTouch5LBL.text = String(describing: touches[4].location(in: view))
    } else {
        positionTouch5LBL.text = "0.0 / 0.0"
    }

Body:
You could put your labels inside another array and iterate through them:

let labelsArray = [positionTouch1LBL, positionTouch2LBL, positionTouch3LBL, positionTouch4BL, positionTouch5LBL]

for i in 0..<labelsArray.count {
    // Get i-th UILabel
    let label = labelsArray[i]
    if touches.count >= (i+1) {
        label.text = String(describing: touches[i].location(in: view))
    }else{
        label.text = "0.0 / 0.0"
    }
}

This way you are able to group redundant code


答:
Use Ctrl + Tab or Ctrl + Shift + Tab to switch between opened buffers (or "file editors", if you like). If you have only two buffers like on your screenshot, you can just press Ctrl + Tab and then by pressing Enter the other editor will become focused.

Important addition:

The shortcut varies depending on your keymap. To figure out proper key combination, open File -> Settings -> Keymap and search for "Switcher" keymap in the search field.

Title: Keyboard shortcut to switch between horizontally split windows in Intellij

Body:
I've done numerous searches to find out how to switch between two files that are horizontally split but can't seem to find it. I know that you can switch between vertically split files by using the Goto Next Splitter option, but there doesn't seem to exist an option for horizontally split. Has anyone else figured this out? Thanks!

An example of a situation where I can't switch between the top and bottom files:


问:
php laravel 4.2 protected rule
I want to make phone filed in following code to accept only numbers and limit its length by 10.
    'phone' => 'numeric|min:10',

Above, is not working. Can anyone suggest how to make this working?

thank you

答:
In Laravel 4.2 the syntax looks like that, check if it's not that kind of mistake:

```<code>$validator = Validator::make(
  array('phone' => 'numeric|min:10')
);
</code>```

https://laravel.com/docs/4.2/validation

Title: php laravel 4.2 protected rule

Body:
In Laravel 4.2 the syntax looks like that, check if it's not that kind of mistake:

$validator = Validator::make(
  array('phone' => 'numeric|min:10')
);

https://laravel.com/docs/4.2/validation


问:
Java Spring MVC + Hibernate Class Composition
I am starting a project with Spring MVC and Hibernate. I am concerned about best practices related to class composition. Suppose I had a class called User with an ORM technology like Hibernate.

I am not sure if I should include everything related to the User entity inside of the User class. I know that Hibernate automatically improves performance by lazy loading so it does not retrieve all instance variables when we retrieve a user. However, I feel like if we included too much variables in the User class, it will become very expensive to query User objects.

Consider this example:

```<code>@Entity
@Table(name = "Users")
public class User{

private String username;
private String password;
private long user_id;

private Collection<Transaction> transactions;

}
</code>```

Here the User class stores a collection of transactions. Each transaction represents a purchase that user made on the website. But we do not need to store a transactions collection for every user.

Instead, we can make a transaction table like so:

```<code> @Entity
 @Table(name = "UserTransactions)
 public class Transaction{

    private int user_id;
    private int order_id;
    private double amount_paid;
}
</code>```

With this transaction table, we can still store every transaction every user has made.

This is only an example, there are many more variables that do not need to be stored in the User class and can be represented by their own table. So I am wondering if there is any harm to storing all of these variables in the User class, or should we be careful and be selective of what we include in the User class? What would be the pros/cons of each approach?

Thank you in advance!

答:
It seems that you have a one-to-many relationship between User and UserTransation. A User can have many transactions and a transaction is made by one and only one user.

So I don't understand why you are wondering if you should store everything in User. You cannot. You have to have 2 domain objects User and UserTransaction with a one-to-many relationship (with a User and a (User)Transaction table in the database). Then, when you query a User with Hibernate, by default use "lazy-loading" to not make a join with Transaction. For data access patterns that needs Transaction, explicity make a "fetch join" to get the User and its transactions in a single SQL query.

Body:
I am starting a project with Spring MVC and Hibernate. I am concerned about best practices related to class composition. Suppose I had a class called User with an ORM technology like Hibernate.

I am not sure if I should include everything related to the User entity inside of the User class. I know that Hibernate automatically improves performance by lazy loading so it does not retrieve all instance variables when we retrieve a user. However, I feel like if we included too much variables in the User class, it will become very expensive to query User objects.

Consider this example:

@Entity
@Table(name = "Users")
public class User{

private String username;
private String password;
private long user_id;

private Collection<Transaction> transactions;

}

Here the User class stores a collection of transactions. Each transaction represents a purchase that user made on the website. But we do not need to store a transactions collection for every user.

Instead, we can make a transaction table like so:

 @Entity
 @Table(name = "UserTransactions)
 public class Transaction{

    private int user_id;
    private int order_id;
    private double amount_paid;
}

With this transaction table, we can still store every transaction every user has made.

This is only an example, there are many more variables that do not need to be stored in the User class and can be represented by their own table. So I am wondering if there is any harm to storing all of these variables in the User class, or should we be careful and be selective of what we include in the User class? What would be the pros/cons of each approach?

Thank you in advance!


问:
Change size of markers in scatter3
I want to draw a set of points each with different colors.

Unfortunately the dots become really small. How can I change that?

This is how my code looks right now, but it is not working

```<code>% Draw with different colors
colors = ['b'; 'k'; 'r'; 'g'; 'm'; 'y'; 'c']
hold on;
for i = 1:7
    x = cell2mat(cluster_l(i))
    scatter3(x(:,1),x(:,2),x(:,3), strcat(colors(i), '.'), 'MarkerSize', 12);
end
</code>```

But apparantly there is no MarkerSize property on the Scatter class.

答:
You can specify the size of the marker as fourth argument (S):

```<code>scatter3(x(:,1), x(:,2), x(:,3), 12, strcat(colors(i), '.'));
</code>```

draws each circle with the size specified by S. To plot each circle
  with equal size, specify S as a scalar. To plot each circle with a
  specific size, specify S as a vector.

Title: Change size of markers in scatter3

Body:
I want to draw a set of points each with different colors.

Unfortunately the dots become really small. How can I change that?

This is how my code looks right now, but it is not working

% Draw with different colors
colors = ['b'; 'k'; 'r'; 'g'; 'm'; 'y'; 'c']
hold on;
for i = 1:7
    x = cell2mat(cluster_l(i))
    scatter3(x(:,1),x(:,2),x(:,3), strcat(colors(i), '.'), 'MarkerSize', 12);
end

But apparantly there is no MarkerSize property on the Scatter class.

Body:
You can specify the size of the marker as fourth argument (S):

scatter3(x(:,1), x(:,2), x(:,3), 12, strcat(colors(i), '.'));

draws each circle with the size specified by S. To plot each circle
  with equal size, specify S as a scalar. To plot each circle with a
  specific size, specify S as a vector.


答:
The allUserAccounts property of SFUserAccountManager is nullable.

```<code>- (nullable NSArray <SFUserAccount *> *) allUserAccounts;
</code>```

https://github.com/forcedotcom/SalesforceMobileSDK-iOS/blob/master/libs/SalesforceSDKCore/SalesforceSDKCore/Classes/Security/SFUserAccountManager.h#L188

If you know for a fact that it will exist at the time you are trying to use it, you can perform a force unwrap by typing allAccounts![0]. If you need to handle the case where it may be nil, you need to check for that by doing something like:

```<code>if let accounts = allAccounts
{
   currentUser = accounts[0]
}
else
{
   // does not exist
}
</code>```

What I can't tell you is whether it being nil is actually a valid case that you need to handle, as I am not familiar with the library. You'll need to do the research or ask them yourself.

Title: Build Failed: Value of optional type '[SFUserAccount]?' not unwrapped

Body:
The allUserAccounts property of SFUserAccountManager is nullable.

- (nullable NSArray <SFUserAccount *> *) allUserAccounts;

https://github.com/forcedotcom/SalesforceMobileSDK-iOS/blob/master/libs/SalesforceSDKCore/SalesforceSDKCore/Classes/Security/SFUserAccountManager.h#L188

If you know for a fact that it will exist at the time you are trying to use it, you can perform a force unwrap by typing allAccounts![0]. If you need to handle the case where it may be nil, you need to check for that by doing something like:

if let accounts = allAccounts
{
   currentUser = accounts[0]
}
else
{
   // does not exist
}

What I can't tell you is whether it being nil is actually a valid case that you need to handle, as I am not familiar with the library. You'll need to do the research or ask them yourself.


问:
$state.go not redirecting to page
I am working on a login and registration for somebody who already has a website. Not sure if it matters but index.html is the landing page and I click on login to goto the login page. The rest of the project is not apart of the web app only login and register so far (index.html doesnt have any angularjs code and it is not loading any of the controllers or app.js).

On login a response is returned from the server but it doesn't go to the test page but the url changes from http://express.app/dashboard/login.html#!/ to http://express.app/dashboard/login.html#!/test I have no idea why the #!/ is being added in the first place. However if I look in my network console I can see that test.html is being loaded and if I look at the preview I can see the page.

I have tried many different combos like setting templateURL to dashboard/test.html and just leaving it as /test.html but nothing seems to work. What am I doing wrong?

app.js

```<code>angular.module('app',['angular-jwt','angular-storage', 'ngRoute', 'ui.router'])
  .config(function  ($stateProvider, $urlRouterProvider, jwtInterceptorProvider, $httpProvider, jwtOptionsProvider) {
  $urlRouterProvider.otherwise('/');
  $stateProvider
      .state("login", {
          url:"/login",
          controller: "loginController",
          templateUrl: "dashboard/login.html"
      })
      .state("signup", {
          url:"/signup",
          controller: "signupController",
          templateUrl: "dashboard/register.html"
      })
      .state("test", {
          url:"/test",
          controller: "testController",
          templateUrl: "test.html"
      });

  jwtInterceptorProvider.tokenGetter = function (store) {
      return store.get('jwt');
  };
      jwtOptionsProvider.config({
          whiteListedDomains: ['express.api', 'localhost']
  });

  $httpProvider.interceptors.push('jwtInterceptor');
})
  .run(function($rootScope, $state, store, jwtHelper) {
  $rootScope.$on('$stateChangeStart', function(e, to) {
      if (to.data && to.data.requiresLogin) {
          if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
              e.preventDefault();
              $state.go('login');
          }
      }
});
</code>```

login.Controller.js

```<code>'use strict';

angular.module('app')
  .controller('loginController', function ($scope, $http, $state, store) {
  $scope.user = {};
  $scope.login = function() {
      $http({
          url: 'http://expressapi.com/login',
          method: 'POST',
          data: $scope.user
      }).then(function(response) {
          console.log("res", response.data.token);
          store.set('jwt', response.data.token);
          var test1 = store.get('jwt');
          console.log("get", test1);
          $state.go("test");
      }, function(error) {
          console.log(error);
          alert(error);
      });
  }
});
</code>```

test.js

```<code>'use strict';

angular.module('app')
  .controller('testController', function ($scope, $http, $state, store) {
     console.log("TEst");
      $scope.test = function() {
      }
});
</code>```

login.html

```<code><body class="main" ng-app="app" ng-controller="loginController">
  <div class="form" data-ix="new-interaction-2">
    <label class="field-label" for="Name-2">Email</label>
      <input class="text-field-2 w-input" data-name="name" id="Name-2" maxlength="256" name="name" placeholder="Email" required="required" type="email" ng-model="user.email">
    <label for="Password-2">Password:</label>
      <input class="text-field w-input" data-name="Password" id="Password-2" maxlength="256" name="Password" placeholder="Password" required="required" type="password" ng-model="user.password">
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.6.4/angular-messages.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-storage/0.0.15/angular-storage.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-resource.js" type="text/javascript"></script>
<script src="/app.js"></script>
<script src="/node_modules/angular-jwt/dist/angular-jwt.js"></script>
<script src="/Controllers/loginController.js"></script>
<script src="/Controllers/testController.js"></script>
</code>```

test.html

```<code><body ng-app="app" ng-controller="testController">
Worked!

<script src="../js/express.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.6.4/angular-messages.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-storage/0.0.15/angular-storage.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-resource.js" type="text/javascript"></script>

<script type="application/javascript" src="../app.js"> </script>
<script src="../node_modules/angular-jwt/dist/angular-jwt.js"></script>
<script src="../controllers/loginController.js"></script>
<script src="../controllers/testController.js"></script>
<script src="../controllers/signupController.js"></script>
</body>
</code>```

Folder structure

```<code>/
controllers
 -loginController.js
 -testController.js
app.js
index.html
contact.html
info.html
dashboard
  -login.html
  -test.html
</code>```

答: If you want to use the UI router for a redirect the login.js functionality needs to be moved to the loginController file.  This is the controller the markup in login.html is attached to.</p>

Title: $state.go not redirecting to page

Body:
I am working on a login and registration for somebody who already has a website. Not sure if it matters but index.html is the landing page and I click on login to goto the login page. The rest of the project is not apart of the web app only login and register so far (index.html doesnt have any angularjs code and it is not loading any of the controllers or app.js).

On login a response is returned from the server but it doesn't go to the test page but the url changes from http://express.app/dashboard/login.html#!/ to http://express.app/dashboard/login.html#!/test I have no idea why the #!/ is being added in the first place. However if I look in my network console I can see that test.html is being loaded and if I look at the preview I can see the page.

I have tried many different combos like setting templateURL to dashboard/test.html and just leaving it as /test.html but nothing seems to work. What am I doing wrong?

app.js

angular.module('app',['angular-jwt','angular-storage', 'ngRoute', 'ui.router'])
  .config(function  ($stateProvider, $urlRouterProvider, jwtInterceptorProvider, $httpProvider, jwtOptionsProvider) {
  $urlRouterProvider.otherwise('/');
  $stateProvider
      .state("login", {
          url:"/login",
          controller: "loginController",
          templateUrl: "dashboard/login.html"
      })
      .state("signup", {
          url:"/signup",
          controller: "signupController",
          templateUrl: "dashboard/register.html"
      })
      .state("test", {
          url:"/test",
          controller: "testController",
          templateUrl: "test.html"
      });

  jwtInterceptorProvider.tokenGetter = function (store) {
      return store.get('jwt');
  };
      jwtOptionsProvider.config({
          whiteListedDomains: ['express.api', 'localhost']
  });

  $httpProvider.interceptors.push('jwtInterceptor');
})
  .run(function($rootScope, $state, store, jwtHelper) {
  $rootScope.$on('$stateChangeStart', function(e, to) {
      if (to.data && to.data.requiresLogin) {
          if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
              e.preventDefault();
              $state.go('login');
          }
      }
});

login.Controller.js

'use strict';

angular.module('app')
  .controller('loginController', function ($scope, $http, $state, store) {
  $scope.user = {};
  $scope.login = function() {
      $http({
          url: 'http://expressapi.com/login',
          method: 'POST',
          data: $scope.user
      }).then(function(response) {
          console.log("res", response.data.token);
          store.set('jwt', response.data.token);
          var test1 = store.get('jwt');
          console.log("get", test1);
          $state.go("test");
      }, function(error) {
          console.log(error);
          alert(error);
      });
  }
});

test.js

'use strict';

angular.module('app')
  .controller('testController', function ($scope, $http, $state, store) {
     console.log("TEst");
      $scope.test = function() {
      }
});

login.html

    Email
      <input class="text-field-2 w-input" data-name="name" id="Name-2" maxlength="256" name="name" placeholder="Email" required="required" type="email" ng-model="user.email">
    Password:
      <input class="text-field w-input" data-name="Password" id="Password-2" maxlength="256" name="Password" placeholder="Password" required="required" type="password" ng-model="user.password">

test.html

Worked!

Folder structure

/
controllers
 -loginController.js
 -testController.js
app.js
index.html
contact.html
info.html
dashboard
  -login.html
  -test.html


问:
Spark 2.0.2 doesn't seem to think that "groupBy" is returning a DataFrame
This feels sort of silly, but I am migrating from Spark 1.6.1 to Spark 2.0.2.  I was using the Databrick CSV library, and am now attempting to use the builtin CSV DataFrameWriter.

The following code:

```<code>    // Get an SQLContext
    val sqlContext = new SQLContext(sc)
    import sqlContext.implicits._

    var sTS = lTimestampToSummarize.toString()
    val sS3InputPath = "s3://measurements/" + sTS + "/*"

    // Read all measurements - note that all subsequent ETLs will reuse dfRaw
    val dfRaw = sqlContext.read.json(sS3InputPath)

    // Filter just the user/segment timespent records
    val dfSegments = dfRaw.filter("segment_ts <> 0").withColumn("views", lit(1))

    // Aggregate views and timespent per user/segment tuples
    val dfUserSegments : DataFrame = dfSegments.groupBy("company_id", "division_id", "department_id", "course_id", "user_id", "segment_id")
        .agg(sum("segment_ts").alias("segment_ts_sum"), sum("segment_est").alias("segment_est_sum"), sum("views").alias("segment_views"))

    // The following will write CSV files to the S3 bucket
    val sS3Output = "s3://output/" + sTS + "/usersegment/"
    dfUserSegments.write.csv(sS3Output)
</code>```

Returns this error:

```<code>[error] /home/Spark/src/main/scala/Example.scala:75: type mismatch;
[error]  found   : Unit
[error]  required: org.apache.spark.sql.DataFrame
[error]     (which expands to)  org.apache.spark.sql.Dataset[org.apache.spark.sql.Row]
[error]         dfUserSegments.write.csv(sS3Output)
[error]                                 ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 2 s, completed Jun 5, 2017 5:00:12 PM
</code>```

I know I must be interpreting the error wrong, because I set dfUserSegments to explicitly be a DataFrame, and yet the compiler is telling me that it is of type Unit (no type).

Any help is appreciated.

答: You don't show the whole method. I guess it's because the method return type is DataFrame, but the last statement in this method is dfUserSegments.write.csv(sS3Output), and csv's return type is Unit.

Body:
This feels sort of silly, but I am migrating from Spark 1.6.1 to Spark 2.0.2.  I was using the Databrick CSV library, and am now attempting to use the builtin CSV DataFrameWriter.

The following code:

    // Get an SQLContext
    val sqlContext = new SQLContext(sc)
    import sqlContext.implicits._

    var sTS = lTimestampToSummarize.toString()
    val sS3InputPath = "s3://measurements/" + sTS + "/*"

    // Read all measurements - note that all subsequent ETLs will reuse dfRaw
    val dfRaw = sqlContext.read.json(sS3InputPath)

    // Filter just the user/segment timespent records
    val dfSegments = dfRaw.filter("segment_ts <> 0").withColumn("views", lit(1))

    // Aggregate views and timespent per user/segment tuples
    val dfUserSegments : DataFrame = dfSegments.groupBy("company_id", "division_id", "department_id", "course_id", "user_id", "segment_id")
        .agg(sum("segment_ts").alias("segment_ts_sum"), sum("segment_est").alias("segment_est_sum"), sum("views").alias("segment_views"))

    // The following will write CSV files to the S3 bucket
    val sS3Output = "s3://output/" + sTS + "/usersegment/"
    dfUserSegments.write.csv(sS3Output)

Returns this error:

[error] /home/Spark/src/main/scala/Example.scala:75: type mismatch;
[error]  found   : Unit
[error]  required: org.apache.spark.sql.DataFrame
[error]     (which expands to)  org.apache.spark.sql.Dataset[org.apache.spark.sql.Row]
[error]         dfUserSegments.write.csv(sS3Output)
[error]                                 ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 2 s, completed Jun 5, 2017 5:00:12 PM

I know I must be interpreting the error wrong, because I set dfUserSegments to explicitly be a DataFrame, and yet the compiler is telling me that it is of type Unit (no type).

Any help is appreciated.


问:
How can I change all my links on my Apache site to look for port 8080 instead of 80 after changing my site from 80?
My local Apache environment, on XAMPP, was set up to listen on port 80.  I now changed it to listen to port 8080. my site now works on port 8080. I have to go to mysite.local:8080 to make it work, which is fine. The only problem is when I click a link it goes to mysite.local/page instead of mysite.local:8080/page and the page does not work. Also, some of my pages that use a log in require me to NOT use 8080 in the url so I have to use mysite.local/admin instead of mysite.local:8080/admin so I am constantaly swithing between adding the port number in the url and taking it away for some other pages. Is there a way where I can make it where I don't have to specify port number on any of the pages. This happened after installing IIS by the way.

My vhost page now looks like the below:

```<code><VirtualHost mysite.local:8080>
DocumentRoot "C:\repos\www.mysite.org\web"
ServerName mysite.local
ErrorLog "logs/mysite-error.log"
CustomLog "logs/mysite-access.log" common
<Directory "C:\repos\www.mysite.org\web">
    AllowOverride All
    Order allow,deny
    Allow from all
    Require all granted
</Directory>
</code>```

答:
The problem is, that after you changed Apache to listen on 8080 Apache does not even see traffic on :80 (and that's where default HTTP traffic goes).

As you said that you have IIS listening on :80, the only way to solve your problem is to make IIS act as a reverse proxy that would forward all the traffic that should be meant for Apache to Apache.

Body:
My local Apache environment, on XAMPP, was set up to listen on port 80.  I now changed it to listen to port 8080. my site now works on port 8080. I have to go to mysite.local:8080 to make it work, which is fine. The only problem is when I click a link it goes to mysite.local/page instead of mysite.local:8080/page and the page does not work. Also, some of my pages that use a log in require me to NOT use 8080 in the url so I have to use mysite.local/admin instead of mysite.local:8080/admin so I am constantaly swithing between adding the port number in the url and taking it away for some other pages. Is there a way where I can make it where I don't have to specify port number on any of the pages. This happened after installing IIS by the way.

My vhost page now looks like the below:

<VirtualHost mysite.local:8080>
DocumentRoot "C:\repos\www.mysite.org\web"
ServerName mysite.local
ErrorLog "logs/mysite-error.log"
CustomLog "logs/mysite-access.log" common
<Directory "C:\repos\www.mysite.org\web">
    AllowOverride All
    Order allow,deny
    Allow from all
    Require all granted
</Directory>