问:
Grouping visits by a number ID
I want to group visits by certain id number because every id represents a different client (think of a subdomain or something like that), for example:

```<code>http://site.com/234/home
http://site.com/234/search/something
</code>```

are URL's for client 234, while...

```<code>http://site.com/155/home
http://site.com/155/search/something
</code>```

are URL's for client 155.

I'm a total noob on this, thx!

答:
Well one way permanent way to do this that that doesn't require you to change the tracking code in your markup is Advanced Segments.

Advantages of this technique in your case:

You can create each segment and given
them descriptive names (e.g., client
id);

Unlike, for instance, using an
Advanced Filter, the Advanced
Segments are active immediately (as
soon as you create them) and they
don't permanently alter your data.

Advanced Segments are simple to configure. This Post by the GA Team is an excellent step-by-step guide, or you can follow these two consecutive screen shots below:

Step 1: click Advanced Segments in the upper right-hand corner from the Dashboard view then click Create a new advanced segment when you see the view below:

There are a number of ways to configure your Advanced Segment; here i've chosen the Page Dimension from Content then selected Condition Contains then just key in a value for a path that distinguishes each client ID.

Title: Grouping visits by a number ID

Body:
I want to group visits by certain id number because every id represents a different client (think of a subdomain or something like that), for example:

http://site.com/234/home
http://site.com/234/search/something

are URL's for client 234, while...

http://site.com/155/home
http://site.com/155/search/something

are URL's for client 155.

I'm a total noob on this, thx!


来源: stackexchange

问:
Enable button only if atleast one row is selected in ui-grid angular
I have a ui grid with set of rows in it and a button below that.I want to disable button when no row is relected and enable it if atleast one row is selected.
Below is the plunker of ui grid

http://embed.plnkr.co/nAJ6h07ksn1MIYcHpQ0Q/

I tried to disable button this way

```<code><input class="button" name="submit" type="button" value="Find Flights"
      ng-click="postdata()" ng-disabled="gridApi.grid.selection.selectedCount !== 0 ">
</code>```

But this it is not getting enabled when a select a grid how can we achieve this

答:
It should be the other way around. So when you select one item, then it should be enabled. So your condition should be ng-disabled="gridApi.grid.selection.selectedCount == 0 " which means none have been selected(so disable it).

```<code><input class="button" name="submit" type="button" value="Find Flights"
      ng-click="postdata()" ng-disabled="gridApi.grid.selection.selectedCount == 0 ">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a ui grid with set of rows in it and a button below that.I want to disable button when no row is relected and enable it if atleast one row is selected.
Below is the plunker of ui grid

http://embed.plnkr.co/nAJ6h07ksn1MIYcHpQ0Q/

I tried to disable button this way

<input class="button" name="submit" type="button" value="Find Flights"
      ng-click="postdata()" ng-disabled="gridApi.grid.selection.selectedCount !== 0 ">

But this it is not getting enabled when a select a grid how can we achieve this

Body:
It should be the other way around. So when you select one item, then it should be enabled. So your condition should be ng-disabled="gridApi.grid.selection.selectedCount == 0 " which means none have been selected(so disable it).

<input class="button" name="submit" type="button" value="Find Flights"
      ng-click="postdata()" ng-disabled="gridApi.grid.selection.selectedCount == 0 ">


问:
R data.table and STRING_ELT() error: How to fix 'character vector' vs 'char' error?
After updating from R 3.3 to R 3.4 I have this error when using data.table package:

```<code>STRING_ELT() can only be applied to a 'character vector', not a 'char'
</code>```

Has anyone experienced the same? I'm thinking about downgrading to "fix" this.

This is my session information:

```<code>> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.2 LTS

Matrix products: default
BLAS: /usr/lib/libblas/libblas.so.3.6.0
LAPACK: /usr/lib/lapack/liblapack.so.3.6.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8
 [4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C
[10] LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] bindrcpp_0.2      purrrlyr_0.0.2    readxl_1.0.0      stringr_1.2.0
 [5] bit64_0.9-7       bit_1.1-12        dtplyr_0.0.2      data.table_1.10.4
 [9] dplyr_0.7.1       purrr_0.2.2.2     readr_1.1.1       tidyr_0.6.3
[13] tibble_1.3.3      ggplot2_2.2.1     tidyverse_1.1.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.11     cellranger_1.1.0 compiler_3.4.0   plyr_1.8.4       bindr_0.1
 [6] forcats_0.2.0    tools_3.4.0      jsonlite_1.5     lubridate_1.6.0  nlme_3.1-131
[11] gtable_0.2.0     lattice_0.20-35  pkgconfig_2.0.1  rlang_0.1.1      psych_1.7.5
[16] parallel_3.4.0   haven_1.0.0      xml2_1.1.1       httr_1.2.1       hms_0.3
[21] grid_3.4.0       glue_1.1.1       R6_2.2.2         foreign_0.8-69   modelr_0.1.0
[26] reshape2_1.4.2   magrittr_1.5     scales_0.4.1     rvest_0.3.2      assertthat_0.2.0
[31] mnormt_1.5-5     colorspace_1.3-2 stringi_1.1.5    lazyeval_0.2.0   munsell_0.4.3
[36] broom_0.4.2
</code>```

答:
Totally stupid solution:

Uninstall everything with apt-get uninstall + apt-get autoclean.

Remove other conflicting R versions such as MRAN.

Remove all user packages directories.

Reinstall R base again.

It works !

Body:
After updating from R 3.3 to R 3.4 I have this error when using data.table package:

STRING_ELT() can only be applied to a 'character vector', not a 'char'

Has anyone experienced the same? I'm thinking about downgrading to "fix" this.

This is my session information:

> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.2 LTS

Matrix products: default
BLAS: /usr/lib/libblas/libblas.so.3.6.0
LAPACK: /usr/lib/lapack/liblapack.so.3.6.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8
 [4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C
[10] LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] bindrcpp_0.2      purrrlyr_0.0.2    readxl_1.0.0      stringr_1.2.0
 [5] bit64_0.9-7       bit_1.1-12        dtplyr_0.0.2      data.table_1.10.4
 [9] dplyr_0.7.1       purrr_0.2.2.2     readr_1.1.1       tidyr_0.6.3
[13] tibble_1.3.3      ggplot2_2.2.1     tidyverse_1.1.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.11     cellranger_1.1.0 compiler_3.4.0   plyr_1.8.4       bindr_0.1
 [6] forcats_0.2.0    tools_3.4.0      jsonlite_1.5     lubridate_1.6.0  nlme_3.1-131
[11] gtable_0.2.0     lattice_0.20-35  pkgconfig_2.0.1  rlang_0.1.1      psych_1.7.5
[16] parallel_3.4.0   haven_1.0.0      xml2_1.1.1       httr_1.2.1       hms_0.3
[21] grid_3.4.0       glue_1.1.1       R6_2.2.2         foreign_0.8-69   modelr_0.1.0
[26] reshape2_1.4.2   magrittr_1.5     scales_0.4.1     rvest_0.3.2      assertthat_0.2.0
[31] mnormt_1.5-5     colorspace_1.3-2 stringi_1.1.5    lazyeval_0.2.0   munsell_0.4.3
[36] broom_0.4.2


问:
Find index value of a dataframe by comparing with another series
I am having problem while extracting index value from a data frame by comparing a dataframe column values with another list.</p>

```<code>list=[a,b,c,d]

  data frame
by comparing list with column X
   X Y Z
0  a r t
1  e t y
2  c f h
3  d r t
4  b g q
this should return the index values like

  X
0 a
4 b
2 c
3 d
I tried this method

z=dataframe.loc[(dataframe['X'] == list)]
</code>```

答:
You need to use isin:

Make sure your list is a list of strings, then use dropna to get rid of unwanted rows and columns.

```<code>list = ['a','b','c','d']
df[df.isin(list)].dropna(how='all').dropna(axis=1)
</code>```

Or if you only wanted to compare with column X.

```<code>df.X[df.X.isin(list)]
</code>```

Output:

```<code>   X
0  a
2  c
3  d
4  b
</code>```

Body:
I am having problem while extracting index value from a data frame by comparing a dataframe column values with another list.

list=[a,b,c,d]

  data frame
by comparing list with column X
   X Y Z
0  a r t
1  e t y
2  c f h
3  d r t
4  b g q
this should return the index values like

  X
0 a
4 b
2 c
3 d
I tried this method

z=dataframe.loc[(dataframe['X'] == list)]

Body:
You need to use isin:

Make sure your list is a list of strings, then use dropna to get rid of unwanted rows and columns.

list = ['a','b','c','d']
df[df.isin(list)].dropna(how='all').dropna(axis=1)

Or if you only wanted to compare with column X.

df.X[df.X.isin(list)]

Output:

   X
0  a
2  c
3  d
4  b


问:
Resolve error on deep insert of navigation property Dynamics WebAPI
I am using the Microsoft Dynamics Web API to write data to an entity in Microsoft Dynamics 365. When I try to do a deep insert I am receiving the error

An undeclared property 'ccseq_employeeid' which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.

Why am I receiving this error and how can I resolve the error?

JSON

```<code>{
    "ccseq_importdate" : "2017-05-28T04:00:00Z",
    "ccseq_month" : "1",
    "ccseq_year" : "2017",
    "ccseq_name" : "Test",
    "ccseq_status" : "100000000", "ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID" :
    [
        {
          "ccseq_employeeid@odata.bind": "/systemusers(6d2fd71b-32d1-dd11-a4f5-001a6449bbe7)",
          "ccseq_clientid@odata.bind": "/ccseq_clients(663ebd00-73b9-4faf-90ed-f56bb9c2dc9b)",
          "ccseq_navemployeeid" : "11111",
          "ccseq_employeefirstname" : "John"
        }
    ]
}
</code>```

ExpenseTransactionSet is the parent of ExpenseTransaction meaning that ExpenseTransaction has a lookup to ExpenseTransactionSet.  ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID is one to many relationship. systemuser and ccseq_clients are separate entities that are lookups in ExpenseTransaction.

I've also tried the below variations on the "ccseq_employeeid@odata.bind"

objectid_systemuser@odata.bind

objectid_ccseq_employeeid@odata.bind

ccseq_employeeid@data.bind

ccseq_employeeid@odata.bind : systemusers()

ccseq_employeeid_systemusers@odata.bind

systemuserid_systemusers@odata.bind

I have seen this question and this question and tried the suggested resolutions without success.

答:
I discovered the answer reading this thread.  The correct syntax for a Navigation Property in a deep insert is to use the Child Entity Name followed by brackets with the field name.  The json needs to be changed to the below</p>

```<code>{
    "ccseq_importdate" : "2017-05-28T04:00:00Z",
    "ccseq_month" : "1",
    "ccseq_year" : "2017",
    "ccseq_name" : "Test",
    "ccseq_status" : "100000000",
    "ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID" :
    [
        {
          // Next two lines are changed
          "ExpenseTransaction[ccseq_employeeid@odata.bind]": "/systemusers(6d2fd71b-32d1-dd11-a4f5-001a6449bbe7)",
          "ExpenseTransaction[ccseq_clientid@odata.bind]": "/ccseq_clients(663ebd00-73b9-4faf-90ed-f56bb9c2dc9b)",
          "ccseq_navemployeeid" : "11111",
          "ccseq_employeefirstname" : "John"
        }
    ]
}
</code>```

Body:
I am using the Microsoft Dynamics Web API to write data to an entity in Microsoft Dynamics 365. When I try to do a deep insert I am receiving the error

An undeclared property 'ccseq_employeeid' which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.

Why am I receiving this error and how can I resolve the error?

JSON

{
    "ccseq_importdate" : "2017-05-28T04:00:00Z",
    "ccseq_month" : "1",
    "ccseq_year" : "2017",
    "ccseq_name" : "Test",
    "ccseq_status" : "100000000", "ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID" :
    [
        {
          "ccseq_employeeid@odata.bind": "/systemusers(6d2fd71b-32d1-dd11-a4f5-001a6449bbe7)",
          "ccseq_clientid@odata.bind": "/ccseq_clients(663ebd00-73b9-4faf-90ed-f56bb9c2dc9b)",
          "ccseq_navemployeeid" : "11111",
          "ccseq_employeefirstname" : "John"
        }
    ]
}

ExpenseTransactionSet is the parent of ExpenseTransaction meaning that ExpenseTransaction has a lookup to ExpenseTransactionSet.  ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID is one to many relationship. systemuser and ccseq_clients are separate entities that are lookups in ExpenseTransaction.

I've also tried the below variations on the "ccseq_employeeid@odata.bind"

objectid_systemuser@odata.bind

objectid_ccseq_employeeid@odata.bind

ccseq_employeeid@data.bind

ccseq_employeeid@odata.bind : systemusers()

ccseq_employeeid_systemusers@odata.bind

systemuserid_systemusers@odata.bind

I have seen this question and this question and tried the suggested resolutions without success.

Body:
I discovered the answer reading this thread.  The correct syntax for a Navigation Property in a deep insert is to use the Child Entity Name followed by brackets with the field name.  The json needs to be changed to the below

{
    "ccseq_importdate" : "2017-05-28T04:00:00Z",
    "ccseq_month" : "1",
    "ccseq_year" : "2017",
    "ccseq_name" : "Test",
    "ccseq_status" : "100000000",
    "ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID" :
    [
        {
          // Next two lines are changed
          "ExpenseTransaction[ccseq_employeeid@odata.bind]": "/systemusers(6d2fd71b-32d1-dd11-a4f5-001a6449bbe7)",
          "ExpenseTransaction[ccseq_clientid@odata.bind]": "/ccseq_clients(663ebd00-73b9-4faf-90ed-f56bb9c2dc9b)",
          "ccseq_navemployeeid" : "11111",
          "ccseq_employeefirstname" : "John"
        }
    ]
}


问:
OpenRecordset not recognisng query criteria
I have developed an Access Database query which references an object on a form in order to dynamically filter the data. The criteria upon which the query is filtered is as follows:

```<code>[Forms]![frmMain]![NavigationSubform].[Form]![Frame64]
</code>```

Where [frame64] is where the user chooses one of two options on a form.

Whilst this query runs fine in Access, I want to use this query in a piece of VBA code, but the problem is, when I try to open the record set, VBA won't allow me.

```<code>Dim db As Database
Dim rs As Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("qryMergeEzineCompleteMerges", dbOpenDynamic, dbSeeChanges)
</code>```

Through my research, I have discovered that it is because VBA doesn't recognise the query criteria I have defined as it refers to a form.

Can anyone please show me how I can reference this recordset in VBA so that it filters by the criteria I have stipulated in the query itself?

Many thanks

答: This may sound pretty stupid but the easiest way to solve this is to create two constants for the dbOpenDynamic and dbSeeChanges values and set their values to the right integer values. You can of course also just type the relevant integer values in the OpenRecordset call.</p>

Body:
I have developed an Access Database query which references an object on a form in order to dynamically filter the data. The criteria upon which the query is filtered is as follows:

[Forms]![frmMain]![NavigationSubform].[Form]![Frame64]

Where [frame64] is where the user chooses one of two options on a form.

Whilst this query runs fine in Access, I want to use this query in a piece of VBA code, but the problem is, when I try to open the record set, VBA won't allow me.

Dim db As Database
Dim rs As Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("qryMergeEzineCompleteMerges", dbOpenDynamic, dbSeeChanges)

Through my research, I have discovered that it is because VBA doesn't recognise the query criteria I have defined as it refers to a form.

Can anyone please show me how I can reference this recordset in VBA so that it filters by the criteria I have stipulated in the query itself?

Many thanks


问:
How i can optimize Xpath expression?
I need to concat first 5 symbols of string with 4 last and divide them with '_'.
I came up with this, but it looks so ugly. Can it be rewritten better? I am new to Xpath, so maybe its ok(but i dont think so)</p>

```<code>concat(substring(//element1/element2/text(),1,5),"_",substring(//element1/element2/text(),string-length(//element1/element2/text())-4))
</code>```

答:
With XPath v2.0 you may apply the following (to concat first 5 symbols of string with 4 last and divide them with '_') :

```<code>//element1/element2/text()/concat(substring(.,1,5),"_",substring(.,string-length(.)-3))
</code>```

. - points to the current selected node

Note, to extract the last 4 characters you should specify starting position as string-length(.)-3

Title: How i can optimize Xpath expression?

Body:
I need to concat first 5 symbols of string with 4 last and divide them with '_'.
I came up with this, but it looks so ugly. Can it be rewritten better? I am new to Xpath, so maybe its ok(but i dont think so)

concat(substring(//element1/element2/text(),1,5),"_",substring(//element1/element2/text(),string-length(//element1/element2/text())-4))

Body:
With XPath v2.0 you may apply the following (to concat first 5 symbols of string with 4 last and divide them with '_') :

//element1/element2/text()/concat(substring(.,1,5),"_",substring(.,string-length(.)-3))

. - points to the current selected node

Note, to extract the last 4 characters you should specify starting position as string-length(.)-3


问:
xml + xpath, print element
```<code>Notice: Undefined property: DOMNodeList::$id in D:\wamp\www\xml\index.php on line 15
id:

Notice: Undefined property: DOMNodeList::$name in D:\wamp\www\xml\index.php on line 16
name:

<?php
$xml = new DOMDocument();

$xml->load('test.xml');

$xpath = new DOMXPath($xml);

$query = '/people/person[id="33333"]';

$entries = $xpath->query($query);

echo 'id:'. $entries->id.'<br/>';
echo 'name:'.$entries->name.'<br/>';
?>
</code>```

xml file sample:

```<code><people>
...
    <person>
        <phone>33333</phone>
        <name>Aadgar</name>
        <last_name>Adas</last_name>
    </person>
...
</people>
</code>```

答:
First, the id node doesn't exists...

```<code>$query = '/people/person[id="33333"]';
</code>```

I think you want:

```<code>$query = '/people/person[phone="33333"]';
</code>```

Then, you must do:

```<code>$entries = $xpath->query($query);

foreach ($entries as $entry) {
   echo 'name:'. $entry->getElementsByTagName('name')->item(0)->nodeValue.'<br/>';
   echo 'last_name:'.$entry->getElementsByTagName('last_name')->item(0)->nodeValue.'<br/>';
}
</code>```

It seems you are mixing up DOM and SimpleXML syntax.

ContentLicense: CC BY-SA 2.5

Title: xml + xpath, print element

Body:
Notice: Undefined property: DOMNodeList::$id in D:\wamp\www\xml\index.php on line 15
id:

Notice: Undefined property: DOMNodeList::$name in D:\wamp\www\xml\index.php on line 16
name:

<?php
$xml = new DOMDocument();

$xml->load('test.xml');

$xpath = new DOMXPath($xml);

$query = '/people/person[id="33333"]';

$entries = $xpath->query($query);

echo 'id:'. $entries->id.'
';
echo 'name:'.$entries->name.'
';
?>

xml file sample:

<people>
...
    <person>
        <phone>33333</phone>
        <name>Aadgar</name>
        <last_name>Adas</last_name>
    </person>
...
</people>

Body:
First, the id node doesn't exists...

$query = '/people/person[id="33333"]';

I think you want:

$query = '/people/person[phone="33333"]';

Then, you must do:

$entries = $xpath->query($query);

foreach ($entries as $entry) {
   echo 'name:'. $entry->getElementsByTagName('name')->item(0)->nodeValue.'<br/>';
   echo 'last_name:'.$entry->getElementsByTagName('last_name')->item(0)->nodeValue.'<br/>';
}

It seems you are mixing up DOM and SimpleXML syntax.


问:
Application appears to have two session cookies
In my application I'm seeing it's setting two session cookies:

.AspNet.ApplicationCookie

ASP.NET_SessionId

I can understand the requirement for a session cookie but why have two?  What are the specific purposes of each?

I'm using asp.net identity in case that has something to do with it.

答:
Good description of .AspNet.ApplicationCookie.

As others have said, ASP.NET_SessionId is user session.


问:
SQL: Select distinct children ordered by property of related child
I've got a query where I want to retrieve distinct child2 rows, but ordered by a property of child1 rows that are related by a common parent. If I do the following, I get an error because the ORDERBY property is not in the DISTINCT list:

```<code>select
    distinct c2.Id, c2.Foo, c2.Bar
    from Child1 c1
    join Parent p on c1.parentId = p.Id
    join Child2 c2 on c2.parentId = p.Id
    order by c1.Id
</code>```

However, if I add c1.Id to the select list, I will lose distinctness of Child rows, as c1.Id makes them all distinct.

If I use a CTE or subquery to first do the ordering, and then select distinct rows from that, the outer query doesn't guarantee that it will maintain the order of the inner/cte query.

Is there a way to achieve this?

答:
Using Inline table: </p>

```<code>  Select DISTINCT t.foo, t.bar From
  (SELECT
  c.foo, c.bar, p.createdDate
  FROM Parent p
  JOIN Child c on c.parentId = p.id
  )t
  ORDER BY t.createdDate
</code>```

Body:
I've got a query where I want to retrieve distinct child2 rows, but ordered by a property of child1 rows that are related by a common parent. If I do the following, I get an error because the ORDERBY property is not in the DISTINCT list:

select
    distinct c2.Id, c2.Foo, c2.Bar
    from Child1 c1
    join Parent p on c1.parentId = p.Id
    join Child2 c2 on c2.parentId = p.Id
    order by c1.Id

However, if I add c1.Id to the select list, I will lose distinctness of Child rows, as c1.Id makes them all distinct.

If I use a CTE or subquery to first do the ordering, and then select distinct rows from that, the outer query doesn't guarantee that it will maintain the order of the inner/cte query.

Is there a way to achieve this?

Body:
Using Inline table:

  Select DISTINCT t.foo, t.bar From
  (SELECT
  c.foo, c.bar, p.createdDate
  FROM Parent p
  JOIN Child c on c.parentId = p.id
  )t
  ORDER BY t.createdDate


问:
Select drop-down scroll style
Is there any css way to stylize the scroll of the default select drop-down?
Or it`s better just forgot this and use div, ul, li and some javascript ?

```<code><select id="selector">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  ...
</select>
</code>```

Here is a simple demo, of overflown select and div nearby, where only div has applyed scroll style, as expected

答:
You can forgot this beacause they look different in different bowsers and OS. You can use some JQuery plugin to replace system elements.

Check this : https://www.queness.com/post/204/25-jquery-plugins-that-enhance-and-beautify-html-form-elements

Title: Select drop-down scroll style

Body:
Is there any css way to stylize the scroll of the default select drop-down?
Or it`s better just forgot this and use div, ul, li and some javascript ?

<select id="selector">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  ...
</select>

Here is a simple demo, of overflown select and div nearby, where only div has applyed scroll style, as expected


问:
Resolve git merge conflict by renaming one of the files
I'm using Flyway to keep track of database changes, and git for version control.

Flyway depends on migration scripts, which are named with increasing numbers for each migration.

Now I have the following situation: two features were developed on two separate branches (let's call them A and B), both requiring database changes. Both developers created a migration script for the database for their branch. As they branched off master at around the same time, they both assigned the same filename to the migration script: V42__migration.sql.

Now branch A was merged into master. When merging branch B, I got into a merge conflict because of the V42__migration.sql file. The correct solution to solve this conflict would be to rename the migration script of the branch B to V43__migration.sql. However, at time of merging git tries to merge both files in to one, where I actually need both of them untouched, but one renamed.

What's the best way to solve this kind of merge conflicts with git?

答:
You have branches A and B, both containing a file with the same name, that does not exist in master. Merging A into master works fine, when you merge B, you get a merge conflict.

```<code>$ git checkout master
$ git merge A             # OK
$ git merge B             # CONFLICT (add/add): Merge conflict in file
</code>```

Such a merge conflict looks as follows.

```<code><<<<<<< HEAD
AAA
=======
BBB
>>>>>>> B
</code>```

Now instead of merging these files, you can split these files again and rename the file from branch B to V43__migrate.sql. For removing lines between a pattern, sed can be used as follows.

```<code>$ sed '/<<<<<<< HEAD/,/======/d' V42__migration.sql | sed '/>>>>>>> B/d' > V43__migration.sql
$ sed '/======/,/>>>>>>> B/d' V42__migration.sql | sed '/<<<<<<< HEAD/d' > V42__migration.sql
</code>```

Then you can commit those changes.

```<code>$ git add V42__migration.sql V43__migration.sql
$ git commit
</code>```

*NIX Tricks: [sed] Delete the lines lying in between two patterns

Body:
You have branches A and B, both containing a file with the same name, that does not exist in master. Merging A into master works fine, when you merge B, you get a merge conflict.

$ git checkout master
$ git merge A             # OK
$ git merge B             # CONFLICT (add/add): Merge conflict in file

Such a merge conflict looks as follows.

<<<<<<< HEAD
AAA
=======
BBB
>>>>>>> B

Now instead of merging these files, you can split these files again and rename the file from branch B to V43__migrate.sql. For removing lines between a pattern, sed can be used as follows.

$ sed '/<<<<<<< HEAD/,/======/d' V42__migration.sql | sed '/>>>>>>> B/d' > V43__migration.sql
$ sed '/======/,/>>>>>>> B/d' V42__migration.sql | sed '/<<<<<<< HEAD/d' > V42__migration.sql

Then you can commit those changes.

$ git add V42__migration.sql V43__migration.sql
$ git commit

*NIX Tricks: [sed] Delete the lines lying in between two patterns


问:
Error 404 on Angular 2 app when deployed to Azure
I have an angular 2 app with a simple server.js as a node.js BE.

I have deployed my application to Azure and I'm at the point that the application loads and shows me the welcoming page.

When I reach a component that tries to read a local JSON via an HTTP request I'm getting a 404 error (that I don't receive in my local environment).

The code to read the json is the following:

```<code>private ReadFromJson(path: string): Observable<string[]> {
    return this._http.get(path)
        .map((response: Response) => <string[]>response.json())
        .do(data => console.log('All: ' + JSON.stringify(data)))
        .catch(this.handleError);
}
</code>```

where the actual path passed is the one showed in the console.

I have done two things: First I made sure that the file is actually there using the Azure CLI, and it is there as expected.

Secondly, after viewing many posts the only other solution I found was to add the MIME type as suggested here, but that didn't work for me as well.

I would really like some help in understanding and be troubleshooting the problem, any suggestion is welcomed!

答:
I ran into the same problem last week and thought maybe i should share my findings since i got it to work as desired.

I deployed the app developed using angular cli and built using the same. I copied over all files in the /dist folder over to azure and added a web.config (this was a lot of hit and trial) but i learned that a rewrite rule for angular was required which can process the webpack bundled assets and not return a 404.

Here is the web,config and i believe it should work for you as-is:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <httpRuntime maxQueryStringLength="32768" maxUrlLength="65536" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxQueryString="32768" />
      </requestFiltering>
    </security>
    <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url="^(?!.*(.bundle.js|.bundle.map|.bundle.js.gz|.bundle.css|.bundle.css.gz|.png|.jpg|.ico|.svg|.eot|.woff|\.woff2)).*$" />
          <conditions logicalGrouping="MatchAll"></conditions>
          <action type="Rewrite" url="/" appendQueryString="true" />
        </rule>
      </rules>
    </rewrite>
    <staticContent>
      <remove fileExtension=".svg" />
      <remove fileExtension=".eot" />
      <remove fileExtension=".woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff" />
    </staticContent>
  </system.webServer>
</configuration>

```

Body:
I have an angular 2 app with a simple server.js as a node.js BE.

I have deployed my application to Azure and I'm at the point that the application loads and shows me the welcoming page.

When I reach a component that tries to read a local JSON via an HTTP request I'm getting a 404 error (that I don't receive in my local environment).

The code to read the json is the following:

private ReadFromJson(path: string): Observable<string[]> {
    return this._http.get(path)
        .map((response: Response) => <string[]>response.json())
        .do(data => console.log('All: ' + JSON.stringify(data)))
        .catch(this.handleError);
}

where the actual path passed is the one showed in the console.

I have done two things: First I made sure that the file is actually there using the Azure CLI, and it is there as expected.

Secondly, after viewing many posts the only other solution I found was to add the MIME type as suggested here, but that didn't work for me as well.

I would really like some help in understanding and be troubleshooting the problem, any suggestion is welcomed!

Body:
I ran into the same problem last week and thought maybe i should share my findings since i got it to work as desired.

I deployed the app developed using angular cli and built using the same. I copied over all files in the /dist folder over to azure and added a web.config (this was a lot of hit and trial) but i learned that a rewrite rule for angular was required which can process the webpack bundled assets and not return a 404.

Here is the web,config and i believe it should work for you as-is:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <httpRuntime maxQueryStringLength="32768" maxUrlLength="65536" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxQueryString="32768" />
      </requestFiltering>
    </security>
    <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url="^(?!.*(.bundle.js|.bundle.map|.bundle.js.gz|.bundle.css|.bundle.css.gz|.png|.jpg|.ico|.svg|.eot|.woff|\.woff2)).*$" />
          <conditions logicalGrouping="MatchAll"></conditions>
          <action type="Rewrite" url="/" appendQueryString="true" />
        </rule>
      </rules>
    </rewrite>
    <staticContent>
      <remove fileExtension=".svg" />
      <remove fileExtension=".eot" />
      <remove fileExtension=".woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff" />
    </staticContent>
  </system.webServer>
</configuration>
<!--

This is required for the app to work in Azure or an ASP.NET hosting environment because the woff files
are not treated as static content on Azure as well as the routing breaks without the rewrite rule below
and app or rather the server returns a 404.

-->


问:
Oracle APEX - An unexpected error with the following message occurred: application/pdf
I have a pl/sql procedure that that downloads a blob file in pdf format from Jasper Server. In this procedure I have the following code which prompts the browser to download the file to my local drive.

```<code>begin
    v_param_val (1) := 1;
    owa.init_cgi_env (v_param_val);

    htp.flush;
    -- clear the output buffer and reset response state
    htp.init;

    owa_util.mime_header ('application/pdf', false);--,'UTF-8'
    htp.p('Content-length: ' || v_lob_length);
    htp.p('Content-Disposition: attachement; filename="'||v_file||'"' );
    owa_util.http_header_close;

    htp.showpage ();
    wpg_docload.download_file(v_blobref);

exception
    when timeout_on_resource then
        raise_application_error (-00051,'No response from the server.');
    when others then
        htp.p('other error : ' || sqlerrm);
end;
</code>```

The problem is, I have an oracle apex page that I use to call my procedure. The page passes through the values to be used as parameters in the call of the procedure. I have a an apex process that makes this happen...

```<code>declare
    v_report_name reports_data.report_name%type;

begin
    v_report_name := s_reports_data.get_report_name(:P31_AVAILABLE_REPORTS);

    s_reports_data.generate_jasper_report(v_report_name, :P31_DATE_TO,
    :P31_RESEARCH_STATION, :P31_DATE_FROM);
end;
</code>```

No the following error comes up when I try to call the procedure.

An unexpected error with the following message occurred: application/pdf

It seems like the following line is the cause of the error.

```<code>owa_util.mime_header ('application/pdf', false);--,'UTF-8'
</code>```

Or the following line.

```<code>wpg_docload.download_file(v_blobref);
</code>```

答:
Looking in the docs, the function seems to need 3 parameters. Have you tried</p>

```<code>owa_util.mime_header('application/pdf', false, 'UTF-8')
</code>```

Body:
I have a pl/sql procedure that that downloads a blob file in pdf format from Jasper Server. In this procedure I have the following code which prompts the browser to download the file to my local drive.

begin
    v_param_val (1) := 1;
    owa.init_cgi_env (v_param_val);

    htp.flush;
    -- clear the output buffer and reset response state
    htp.init;

    owa_util.mime_header ('application/pdf', false);--,'UTF-8'
    htp.p('Content-length: ' || v_lob_length);
    htp.p('Content-Disposition: attachement; filename="'||v_file||'"' );
    owa_util.http_header_close;

    htp.showpage ();
    wpg_docload.download_file(v_blobref);

exception
    when timeout_on_resource then
        raise_application_error (-00051,'No response from the server.');
    when others then
        htp.p('other error : ' || sqlerrm);
end;

The problem is, I have an oracle apex page that I use to call my procedure. The page passes through the values to be used as parameters in the call of the procedure. I have a an apex process that makes this happen...

declare
    v_report_name reports_data.report_name%type;

begin
    v_report_name := s_reports_data.get_report_name(:P31_AVAILABLE_REPORTS);

    s_reports_data.generate_jasper_report(v_report_name, :P31_DATE_TO,
    :P31_RESEARCH_STATION, :P31_DATE_FROM);
end;

No the following error comes up when I try to call the procedure.

An unexpected error with the following message occurred: application/pdf

It seems like the following line is the cause of the error.

owa_util.mime_header ('application/pdf', false);--,'UTF-8'

Or the following line.

wpg_docload.download_file(v_blobref);

Body:
Looking in the docs, the function seems to need 3 parameters. Have you tried

owa_util.mime_header('application/pdf', false, 'UTF-8')


问:
Failed to reinstall Android APK
I had a small problem with my Android application. I wanted to change the name of the project because I had two of the same name I suppressed one and removed the figure '2' from the one I chose to keep. Now that I want to run it, it shows me an error message. Already two days that I am trying to solve is problem but I am really very very beginner especially on Android.

答:
There are many possibilities to show this message.

1) If you run the application which is already installed in your
  device and then you change application id.

2) If you install the Signed APK which is already in your device and
  you try to run the APK which is debug APK that time this dialog show.

3) You uninstall the application using drag and drop and you think
  application is uninstalled but in many devices which run with dual
  account will not remove the apps and it shows in app management but it
  is not showing in the apps list. In that case when you run the
  application you show this message.

To solve 3rd issue manually go to app settings and uninstall the app
  otherwise it won't allow you to install the application.

Title: Failed to reinstall Android APK


问:
Preprocessing data in pyspark
having looked at the kmeans example in the spark/example directory, I am trying to do K-means clustering on a set of latitude and longitude data. I have imported .csv data into a spark dataframe (~1M rows) and attempted to read the dataframe as an input to my k-means model however I keep getting an error.

My spark dataframe looks like:

```<code> ID             col1           col2        Latitude         Longitude
ford            ...            ...           22.2             13.5
landrover       ...            ...           21.4             13.8
mercedes        ...            ...           21.8             14.1
bmw             ...            ...           28.9             18.0
...             ...            ...           ....             ....
</code>```

Here is my code:

```<code>from pyspark.ml.clustering import KMeans
from pyspark.ml.linalg import Vectors

df = spark.read.csv('file.csv')

spark_rdd = df.rdd.sortByKey()
parsedData = spark_rdd.map(lambda x: Vectors.dense(x[3],x[4])).sortByKey()

kmeans = KMeans().setK(2).setSeed(1)
model = kmeans.fit(parsedData)

sum_of_squared_errors = model.computeCost(parsedData)
    print str(sum_of_squared_errors)

centers = model.clusterCenters()

for center in centers:
    print(center)
</code>```

The error I get is as follows:

```<code>Py4JJavaError                             Traceback (most recent call last)
<ipython-input-32-76d5a466dc4c> in <module>()
      3
      4 spark_rdd = df.rdd.sortByKey()
----> 5 parsedData = spark_rdd.map(lambda x: Vectors.dense(x[3],x[4])).sortByKey()
      6

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in sortByKey(self, ascending, numPartitions, keyfunc)
    660         # the key-space into bins such that the bins have roughly the same
    661         # number of (key, value) pairs falling into them
--> 662         rddSize = self.count()
    663         if not rddSize:
    664             return self  # empty RDD

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in count(self)
   1039         3
   1040         """
-> 1041         return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum()
   1042
   1043     def stats(self):

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in sum(self)
   1030         6.0
   1031         """
-> 1032         return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)
   1033
   1034     def count(self):

 ~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in fold(self, zeroValue, op)
    904         # zeroValue provided to each partition is unique from the one provided
    905         # to the final reduce call
--> 906         vals = self.mapPartitions(func).collect()
    907         return reduce(op, vals, zeroValue)
    908

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in collect(self)
    807         """
    808         with SCCallSiteSync(self.context) as css:
--> 809             port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
    810         return list(_load_from_socket(port, self._jrdd_deserializer))
    811

/usr/local/lib/python2.7/dist-packages/py4j/java_gateway.pyc in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id, self.name)
   1134
   1135         for temp_arg in temp_args:

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/utils.pyc in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/usr/local/lib/python2.7/dist-packages/py4j/protocol.pyc in get_return_value(answer, gateway_client, target_id, name)
    317                 raise Py4JJavaError(
    318                     "An error occurred while calling {0}{1}{2}.\n".
--> 319                     format(target_id, ".", name), value)
    320             else:
    321                 raise Py4JError(

Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 26.0 failed 4 times, most recent failure: Lost task 0.3 in stage 26.0 (TID 139, 10.3.1.31, executor 1): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 174, in main
    process()
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 169, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/serializers.py", line 138, in dump_stream
    for obj in iterator:
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.py", line 1752, in add_shuffle_key
    for k, v in iterator:
ValueError: too many values to unpack
...
</code>```

Any help would be greatly appreciated. Thanks

EDIT: Thank you for you reply @Duf59 . Please note the dataframe has multiple data points for each ID (eg. 50 data points for 'landrover', 70 datapoints for 'bmw', 80 data points for 'mercedes' etc.

When I use your method, I get the following error:
    ---------------------------------------------------------------------------

```<code>Py4JJavaError                             Traceback (most recent call last)
    <ipython-input-53-37fce322868d> in <module>()
          5
          6 spark_rdd = df.rdd.map(lambda row: (row["ID"], Vectors.dense(row["Latitude"],row["Longitude"])))
    ----> 7 feature_df = spark_rdd.toDF(["ID", "features"])
          8 feature_df.show()
          9

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/session.pyc in toDF(self, schema, sampleRatio)
     55         [Row(name=u'Alice', age=1)]
     56         """
---> 57         return sparkSession.createDataFrame(self, schema, sampleRatio)
     58
     59     RDD.toDF = toDF

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/session.pyc in createDataFrame(self, data, schema, samplingRatio, verifySchema)
    518
    519         if isinstance(data, RDD):
--> 520             rdd, schema = self._createFromRDD(data.map(prepare), schema, samplingRatio)
    521         else:
    522             rdd, schema = self._createFromLocal(map(prepare, data), schema)

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/session.pyc in _createFromRDD(self, rdd, schema, samplingRatio)
    358         """
    359         if schema is None or isinstance(schema, (list, tuple)):
--> 360             struct = self._inferSchema(rdd, samplingRatio)
    361             converter = _create_converter(struct)
    362             rdd = rdd.map(converter)

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/session.pyc in _inferSchema(self, rdd, samplingRatio)
    329         :return: :class:`pyspark.sql.types.StructType`
    330         """
--> 331         first = rdd.first()
    332         if not first:
    333             raise ValueError("The first row in RDD is empty, "

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in first(self)
   1359         ValueError: RDD is empty
   1360         """
-> 1361         rs = self.take(1)
   1362         if rs:
   1363             return rs[0]

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in take(self, num)
   1341
   1342             p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts))
-> 1343             res = self.context.runJob(self, takeUpToNumLeft, p)
   1344
   1345             items += res

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/context.pyc in runJob(self, rdd, partitionFunc, partitions, allowLocal)
    963         # SparkContext#runJob.
    964         mappedRDD = rdd.mapPartitions(partitionFunc)
--> 965         port = self._jvm.PythonRDD.runJob(self._jsc.sc(), mappedRDD._jrdd, partitions)
    966         return list(_load_from_socket(port, mappedRDD._jrdd_deserializer))
    967

/usr/local/lib/python2.7/dist-packages/py4j/java_gateway.pyc in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id, self.name)
   1134
   1135         for temp_arg in temp_args:

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/utils.pyc in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/usr/local/lib/python2.7/dist-packages/py4j/protocol.pyc in get_return_value(answer, gateway_client, target_id, name)
    317                 raise Py4JJavaError(
    318                     "An error occurred while calling {0}{1}{2}.\n".
--> 319                     format(target_id, ".", name), value)
    320             else:
    321                 raise Py4JError(

Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.runJob.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 134.0 failed 4 times, most recent failure: Lost task 0.3 in stage 134.0 (TID 557, 10.3.1.31, executor 1): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 174, in main
    process()
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 169, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/serializers.py", line 268, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.py", line 1339, in takeUpToNumLeft
    yield next(iterator)
  File "<ipython-input-53-37fce322868d>", line 6, in <lambda>
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/ml/linalg/__init__.py", line 790, in dense
    return DenseVector(elements)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/ml/linalg/__init__.py", line 275, in __init__
    ar = np.array(ar, dtype=np.float64)
ValueError: could not convert string to float: Latitude

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)
    at org.apache.spark.api.python.PythonRDD$.runJob(PythonRDD.scala:441)
    at org.apache.spark.api.python.PythonRDD.runJob(PythonRDD.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 174, in main
    process()
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 169, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/serializers.py", line 268, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.py", line 1339, in takeUpToNumLeft
    yield next(iterator)
  File "<ipython-input-53-37fce322868d>", line 6, in <lambda>
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/ml/linalg/__init__.py", line 790, in dense
    return DenseVector(elements)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/ml/linalg/__init__.py", line 275, in __init__
    ar = np.array(ar, dtype=np.float64)
ValueError: could not convert string to float: Latitude

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more
</code>```

答:
Your error is because you apply sortByKey() to a RDD which is not a PairwiseRDD (df.rdd gives you a RDD of Rows, and in your case each Row has 5 values). *byKey methods operate on PairwiseRDDs, that is RDD which contains tuples of length 2 or other structure which can be unpack like k, v = pair.

Apart from that, you are trying to use ml algorithm with RDD. You should feed the kmean model with a dataframe here (by default, kmeans.fit expects a dataframe with a column named features). You can lookup the doc here.

What you can do is :

```<code>spark_rdd = df.rdd.map(lambda row: (row["ID"], Vectors.dense(row["Latitude"],row["Longitude"])))
feature_df = spark_rdd.toDF(["ID", "features"])

kmeans = KMeans().setK(2).setSeed(1)
model = kmeans.fit(feature_df)
</code>```

Title: Preprocessing data in pyspark

Body:
having looked at the kmeans example in the spark/example directory, I am trying to do K-means clustering on a set of latitude and longitude data. I have imported .csv data into a spark dataframe (~1M rows) and attempted to read the dataframe as an input to my k-means model however I keep getting an error.

My spark dataframe looks like:

 ID             col1           col2        Latitude         Longitude
ford            ...            ...           22.2             13.5
landrover       ...            ...           21.4             13.8
mercedes        ...            ...           21.8             14.1
bmw             ...            ...           28.9             18.0
...             ...            ...           ....             ....

Here is my code:

from pyspark.ml.clustering import KMeans
from pyspark.ml.linalg import Vectors

df = spark.read.csv('file.csv')

spark_rdd = df.rdd.sortByKey()
parsedData = spark_rdd.map(lambda x: Vectors.dense(x[3],x[4])).sortByKey()

kmeans = KMeans().setK(2).setSeed(1)
model = kmeans.fit(parsedData)

sum_of_squared_errors = model.computeCost(parsedData)
    print str(sum_of_squared_errors)

centers = model.clusterCenters()

for center in centers:
    print(center)

The error I get is as follows:

Py4JJavaError                             Traceback (most recent call last)
<ipython-input-32-76d5a466dc4c> in <module>()
      3
      4 spark_rdd = df.rdd.sortByKey()
----> 5 parsedData = spark_rdd.map(lambda x: Vectors.dense(x[3],x[4])).sortByKey()
      6

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in sortByKey(self, ascending, numPartitions, keyfunc)
    660         # the key-space into bins such that the bins have roughly the same
    661         # number of (key, value) pairs falling into them
--> 662         rddSize = self.count()
    663         if not rddSize:
    664             return self  # empty RDD

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in count(self)
   1039         3
   1040         """
-> 1041         return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum()
   1042
   1043     def stats(self):

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in sum(self)
   1030         6.0
   1031         """
-> 1032         return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)
   1033
   1034     def count(self):

 ~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in fold(self, zeroValue, op)
    904         # zeroValue provided to each partition is unique from the one provided
    905         # to the final reduce call
--> 906         vals = self.mapPartitions(func).collect()
    907         return reduce(op, vals, zeroValue)
    908

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in collect(self)
    807         """
    808         with SCCallSiteSync(self.context) as css:
--> 809             port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
    810         return list(_load_from_socket(port, self._jrdd_deserializer))
    811

/usr/local/lib/python2.7/dist-packages/py4j/java_gateway.pyc in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id, self.name)
   1134
   1135         for temp_arg in temp_args:

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/utils.pyc in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/usr/local/lib/python2.7/dist-packages/py4j/protocol.pyc in get_return_value(answer, gateway_client, target_id, name)
    317                 raise Py4JJavaError(
    318                     "An error occurred while calling {0}{1}{2}.\n".
--> 319                     format(target_id, ".", name), value)
    320             else:
    321                 raise Py4JError(

Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 26.0 failed 4 times, most recent failure: Lost task 0.3 in stage 26.0 (TID 139, 10.3.1.31, executor 1): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 174, in main
    process()
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 169, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/serializers.py", line 138, in dump_stream
    for obj in iterator:
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.py", line 1752, in add_shuffle_key
    for k, v in iterator:
ValueError: too many values to unpack
...

Any help would be greatly appreciated. Thanks

EDIT: Thank you for you reply @Duf59 . Please note the dataframe has multiple data points for each ID (eg. 50 data points for 'landrover', 70 datapoints for 'bmw', 80 data points for 'mercedes' etc.

When I use your method, I get the following error:
    ---------------------------------------------------------------------------

Py4JJavaError                             Traceback (most recent call last)
    <ipython-input-53-37fce322868d> in <module>()
          5
          6 spark_rdd = df.rdd.map(lambda row: (row["ID"], Vectors.dense(row["Latitude"],row["Longitude"])))
    ----> 7 feature_df = spark_rdd.toDF(["ID", "features"])
          8 feature_df.show()
          9

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/session.pyc in toDF(self, schema, sampleRatio)
     55         [Row(name=u'Alice', age=1)]
     56         """
---> 57         return sparkSession.createDataFrame(self, schema, sampleRatio)
     58
     59     RDD.toDF = toDF

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/session.pyc in createDataFrame(self, data, schema, samplingRatio, verifySchema)
    518
    519         if isinstance(data, RDD):
--> 520             rdd, schema = self._createFromRDD(data.map(prepare), schema, samplingRatio)
    521         else:
    522             rdd, schema = self._createFromLocal(map(prepare, data), schema)

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/session.pyc in _createFromRDD(self, rdd, schema, samplingRatio)
    358         """
    359         if schema is None or isinstance(schema, (list, tuple)):
--> 360             struct = self._inferSchema(rdd, samplingRatio)
    361             converter = _create_converter(struct)
    362             rdd = rdd.map(converter)

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/session.pyc in _inferSchema(self, rdd, samplingRatio)
    329         :return: :class:`pyspark.sql.types.StructType`
    330         """
--> 331         first = rdd.first()
    332         if not first:
    333             raise ValueError("The first row in RDD is empty, "

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in first(self)
   1359         ValueError: RDD is empty
   1360         """
-> 1361         rs = self.take(1)
   1362         if rs:
   1363             return rs[0]

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.pyc in take(self, num)
   1341
   1342             p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts))
-> 1343             res = self.context.runJob(self, takeUpToNumLeft, p)
   1344
   1345             items += res

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/context.pyc in runJob(self, rdd, partitionFunc, partitions, allowLocal)
    963         # SparkContext#runJob.
    964         mappedRDD = rdd.mapPartitions(partitionFunc)
--> 965         port = self._jvm.PythonRDD.runJob(self._jsc.sc(), mappedRDD._jrdd, partitions)
    966         return list(_load_from_socket(port, mappedRDD._jrdd_deserializer))
    967

/usr/local/lib/python2.7/dist-packages/py4j/java_gateway.pyc in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id, self.name)
   1134
   1135         for temp_arg in temp_args:

~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/utils.pyc in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/usr/local/lib/python2.7/dist-packages/py4j/protocol.pyc in get_return_value(answer, gateway_client, target_id, name)
    317                 raise Py4JJavaError(
    318                     "An error occurred while calling {0}{1}{2}.\n".
--> 319                     format(target_id, ".", name), value)
    320             else:
    321                 raise Py4JError(

Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.runJob.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 134.0 failed 4 times, most recent failure: Lost task 0.3 in stage 134.0 (TID 557, 10.3.1.31, executor 1): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 174, in main
    process()
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 169, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/serializers.py", line 268, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.py", line 1339, in takeUpToNumLeft
    yield next(iterator)
  File "<ipython-input-53-37fce322868d>", line 6, in <lambda>
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/ml/linalg/__init__.py", line 790, in dense
    return DenseVector(elements)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/ml/linalg/__init__.py", line 275, in __init__
    ar = np.array(ar, dtype=np.float64)
ValueError: could not convert string to float: Latitude

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)
    at org.apache.spark.api.python.PythonRDD$.runJob(PythonRDD.scala:441)
    at org.apache.spark.api.python.PythonRDD.runJob(PythonRDD.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 174, in main
    process()
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/worker.py", line 169, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/serializers.py", line 268, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/rdd.py", line 1339, in takeUpToNumLeft
    yield next(iterator)
  File "<ipython-input-53-37fce322868d>", line 6, in <lambda>
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/ml/linalg/__init__.py", line 790, in dense
    return DenseVector(elements)
  File "~/Downloads/spark-2.1.0-bin-hadoop2.7/python/pyspark/ml/linalg/__init__.py", line 275, in __init__
    ar = np.array(ar, dtype=np.float64)
ValueError: could not convert string to float: Latitude

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more

Body:
Your error is because you apply sortByKey() to a RDD which is not a PairwiseRDD (df.rdd gives you a RDD of Rows, and in your case each Row has 5 values). *byKey methods operate on PairwiseRDDs, that is RDD which contains tuples of length 2 or other structure which can be unpack like k, v = pair.

Apart from that, you are trying to use ml algorithm with RDD. You should feed the kmean model with a dataframe here (by default, kmeans.fit expects a dataframe with a column named features). You can lookup the doc here.

What you can do is :

spark_rdd = df.rdd.map(lambda row: (row["ID"], Vectors.dense(row["Latitude"],row["Longitude"])))
feature_df = spark_rdd.toDF(["ID", "features"])

kmeans = KMeans().setK(2).setSeed(1)
model = kmeans.fit(feature_df)


问:
Dynamically setting CSS values using ASP.NET
I'm working on a site where the images and other resources will be located on a separate domain from the main content of the site. We will use something like 'www.example.com' for the main site, and then 'images.example.com' for all extra resources for styles, etc.

When developing the site I will keep all of these resources on local dev. machines. The challenge here is keeping CSS references consistent between the production server and development environments.

What I was thinking of doing was creating a web.config key that would store the URL of the images server. Then, when switching from development to production I could just change the web.config value and everything would be done.

Is there any way to add a value to a CSS file, dynamically or otherwise, from some place in a config or C# class? Or am I going about this the wrong way?

Also, I'm limited to using .NET 2.0 if that makes a difference.

UPDATE

To expand on this a little more, I know I can use a web.config setting for server controls' URLs. Those are already generated dynamically. What I'm more interested in is what options I have for modifying (or doing "something") to static CSS files that will allow me to change URLs for things such as background image resources that would be referenced in CSS. Is there anything I can do besides find/replacing the values using my IDE? Perhaps something that can be done automatically with a deployment script?

答:
Is keeping the CSS file on the image server an option? If that it possible, you could make all the image references relative, and then you just need to update the link to the css file.

```<code><link rel="stylesheet" href="<%= ConfigurationManager.AppSettings("css-server") %>style.css" />
</code>```

If you still want to send or generate a css file dynamically:

css files don't have to end in css. aspx is fine. You could do this:

```<code><link rel="stylesheet" href="style.aspx" />
</code>```

and then in your style.aspx page:

```<code>protected void page_load(){
    Response.ContentType = "text/css";
    if (ConfigurationManager.AppSettings("css-server") == "local") {
        Server.Transfer("css/local.css");
    } else {
        Server.Transfer("css/production.css");
    }
}
</code>```

If you still want to dynamically generate a css file, I'd use an HttpHandler, set the contenttype to "text/css", then generate the css with Response.Write. If you insist on having the page end in css, you could always register css to go to asp.net in IIS, then on incoming requests in global.asax application_Begin request, if the file ends in .css, use httpcontext.current.rewritepath to your handler.

This will have a net effect of style.css being dynamically generated at runtime.

OwnerDisplayName: DanHerbert

LastEditorDisplayName: DanHerbert

Body:
Is keeping the CSS file on the image server an option? If that it possible, you could make all the image references relative, and then you just need to update the link to the css file.

<link rel="stylesheet" href="<%= ConfigurationManager.AppSettings("css-server") %>style.css" />

If you still want to send or generate a css file dynamically:

css files don't have to end in css. aspx is fine. You could do this:

<link rel="stylesheet" href="style.aspx" />

and then in your style.aspx page:

protected void page_load(){
    Response.ContentType = "text/css";
    if (ConfigurationManager.AppSettings("css-server") == "local") {
        Server.Transfer("css/local.css");
    } else {
        Server.Transfer("css/production.css");
    }
}

If you still want to dynamically generate a css file, I'd use an HttpHandler, set the contenttype to "text/css", then generate the css with Response.Write. If you insist on having the page end in css, you could always register css to go to asp.net in IIS, then on incoming requests in global.asax application_Begin request, if the file ends in .css, use httpcontext.current.rewritepath to your handler.

This will have a net effect of style.css being dynamically generated at runtime.

OwnerDisplayName: Update

LastEditorDisplayName: Update


问:
Problem using nppToR or Tinn-R
Thanks everybody for the reply! Now I fixed the problem by R 2.12.1 and NpptoR (version 2.5.2), without setting the registry.

After a while of my updating of R from 2.11.1 to 2.12.0, I was now completely unable to pass scripts to R from Notepad++ (working together with nppToR).

when I installed nppToR, I always get the same dialogue of "Could not find the Rgui.exe file. Aborting", and it will not ready for use. I thought it is caused by the updating of R.2.11.1 to R.2.12.0 because the Rgui.exe were located in different location. Then, for a while, the nppToR works after I edit the nppToR.ini file, from this:

```<code>[install]
global=1
</code>```

into this, which is also from the previous version of the nppToR files:

```<code>[executables]
R=C:\Program Files\R\R-2.12.0\bin\i386\Rgui.exe  --max-mem-size=2047M
Rcmdparms=
Npp=
NppConfig=
[hotkeys]
passline=F8
passfile=^F8
evaltocursor=+F8
batchrun=^!F8
rhelp=^F1
[putty]
activateputty=1
puttyline=F9
puttyfile=^F9
[controls]
Rpastewait=50
Rrunwait=10
restoreclipboard=1
appendnewline=1
[silent]
enablesilent=1
silentkey=!F8
[install]
global=1
</code>```

However, in these days, this modification never work for me, even though I uninstalled the R.2.12.0 and installed R.2.11.1. And I really have no idea the reason for that. Is there some one had the same experiences? Or, can some one help me out?

PS.: I also tried Tinn-R as an alternative, but after some time of use, the cursor usually appear in some position just like it is going mad, and when I input the code, each line can have only one single letter, and the cursor will move to the next line automatically.Do any body know why?

Thank in advance~

Best Regards~

Marco

答:
The registry is not necessary if the R home directory is specified in the settings, but the registry is simpler for people who do regular installs.

Right click on the NppToR icon and select settings then specify the R home directory.  There should never be a need to directly edit the ini file.

Update

The new version of NppToR, 2.5.2, tries to fix this exact problem.

Title: Problem using nppToR or Tinn-R

Body:
Thanks everybody for the reply! Now I fixed the problem by R 2.12.1 and NpptoR (version 2.5.2), without setting the registry.

After a while of my updating of R from 2.11.1 to 2.12.0, I was now completely unable to pass scripts to R from Notepad++ (working together with nppToR).

when I installed nppToR, I always get the same dialogue of "Could not find the Rgui.exe file. Aborting", and it will not ready for use. I thought it is caused by the updating of R.2.11.1 to R.2.12.0 because the Rgui.exe were located in different location. Then, for a while, the nppToR works after I edit the nppToR.ini file, from this:

[install]
global=1

into this, which is also from the previous version of the nppToR files:

[executables]
R=C:\Program Files\R\R-2.12.0\bin\i386\Rgui.exe  --max-mem-size=2047M
Rcmdparms=
Npp=
NppConfig=
[hotkeys]
passline=F8
passfile=^F8
evaltocursor=+F8
batchrun=^!F8
rhelp=^F1
[putty]
activateputty=1
puttyline=F9
puttyfile=^F9
[controls]
Rpastewait=50
Rrunwait=10
restoreclipboard=1
appendnewline=1
[silent]
enablesilent=1
silentkey=!F8
[install]
global=1

However, in these days, this modification never work for me, even though I uninstalled the R.2.12.0 and installed R.2.11.1. And I really have no idea the reason for that. Is there some one had the same experiences? Or, can some one help me out?

PS.: I also tried Tinn-R as an alternative, but after some time of use, the cursor usually appear in some position just like it is going mad, and when I input the code, each line can have only one single letter, and the cursor will move to the next line automatically.Do any body know why?

Thank in advance~

Best Regards~

Marco


问:
Convert javascript code to c code
Is there any way to convert C code to JavaScript and from JavaScript to C? I found V8 juice which can generate JavaScript-side classes from C++, but it's only one way (C++ to JavaScript).

I'm not looking for a software.

答:
C language can do hell of lot stuff that javascript or v8 engine can't do, specifically system program such as memory management, direct memory access, interrupts, assembly code, thread management.
So it is not possible to convert c to javascript unless it is very simple code without some of system code. With nodeJS (not v8 javascript) along with system wrapper code do some of system level functions. Again it is complex part of conversion.
Even if we able to convert this simple code the execution of c and converted javascript differs as it it is based on v8 engine.

It is possible to convert javascript to C. Because C can virtually handle any execution stuff including that of interpreters.

Title: Convert javascript code to c code


问:
Why is there no database file created when using Android Room?
I use the Room Persistence Library for my Android app, but after it's creation I can not find .sql file with tables on my device.

When I create database through SQLiteOpenHelper I can see all my tables in folder data on the device, but when I create database through Room there is no file anywhere.

Where can I see the content of all my tables?

Create database code:

```<code>@Provides
@Singleton
PokuponDataBase providePokuponDataBase() {
    return Room.inMemoryDatabaseBuilder(SuperDealApp.getInstance().getApplicationContext(), PokuponDataBase.class, "PokuponRoomDatabase").build();
}
</code>```

答: I found the cause of disappearing my database. It was because I create it incorrectly. I use Room.InMemoryDatabaseBuilder() instead of simple Room.databaseBuilder() and after each application reloading my db was recreated and also inMemory database does not create any files.</p>

Body:
I use the Room Persistence Library for my Android app, but after it's creation I can not find .sql file with tables on my device.

When I create database through SQLiteOpenHelper I can see all my tables in folder data on the device, but when I create database through Room there is no file anywhere.

Where can I see the content of all my tables?

Create database code:

@Provides
@Singleton
PokuponDataBase providePokuponDataBase() {
    return Room.inMemoryDatabaseBuilder(SuperDealApp.getInstance().getApplicationContext(), PokuponDataBase.class, "PokuponRoomDatabase").build();
}


问:
Trash using memcpy
I'm using memcpy to copy a specific number of chars from a char array to a char *. But when I read the char * have always trash in the end.

I'm using libssh2 lib to send commands to my raspberry pi and receive the output.

libssh2_channel_read will return the number of chars of the output int x and the output text will be on the char buffer[32].

Code I'm using:

```<code>char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buffer, x-2); // x - 2 because of "\r\n"
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;
</code>```

Example of output:

```<code>0══²²²²
</code>```

I only want the 0

答:
Use std::string:</p>

```<code>char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
std::string output{ buffer, buffer + x - 2 };
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;
</code>```

Title: Trash using memcpy

Body:
I'm using memcpy to copy a specific number of chars from a char array to a char *. But when I read the char * have always trash in the end.

I'm using libssh2 lib to send commands to my raspberry pi and receive the output.

libssh2_channel_read will return the number of chars of the output int x and the output text will be on the char buffer[32].

Code I'm using:

char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buffer, x-2); // x - 2 because of "\r\n"
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;

Example of output:

0══²²²²

I only want the 0

Body:
Use std::string:

char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
std::string output{ buffer, buffer + x - 2 };
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;


问:
Error 500 Yii framework PHP
Im constantly facing this error
"Error 500 Array to string conversion". Need help guys

JS Controller Function

```<code>$scope.saveSchool=function(){
    $http.post($scope.SchoolCTRLUrl+"/saveSchool" , $scope.schoolObject)
        .success(function(responce){

        })
};
</code>```

Action Method

```<code>public function actionsaveSchool()
{
    $school = file_get_contents("php://input");
    $schoolInfo=json_decode($school,true);
    $schoolTable=new SchoolTable();
    $schoolTable->school_name=$schoolInfo["schoolName"];
    $schoolTable->registration_code=$schoolInfo["registrationCode"];
    $schoolTable->cell_no=$schoolInfo["cellNo"];
    $schoolTable->phone_no=$schoolInfo["phoneNo"];
    $schoolTable->logo=$schoolInfo["logo"];
    $schoolTable->email_address=$schoolInfo["emailAddress"];
    $schoolTable->contact_person=$schoolInfo["contactPerson"];
    $schoolTable->address=$schoolInfo["address"];
    $schoolTable->city=$schoolInfo["city"];
    $schoolTable->district=$schoolInfo["district"];
    $schoolTable->province=$schoolInfo["province"];
    if($schoolTable->save()) {
        $id = $schoolTable->school_id;
        echo $id;
    } else{
        echo $schoolTable->getErrors();
    }
}
</code>```

答:
Please change this line :

echo $schoolTable->getErrors();
with this :

print_r($schoolTable->getErrors());

Title: Error 500 Yii framework PHP

Body:
Im constantly facing this error
"Error 500 Array to string conversion". Need help guys

JS Controller Function

$scope.saveSchool=function(){
    $http.post($scope.SchoolCTRLUrl+"/saveSchool" , $scope.schoolObject)
        .success(function(responce){

        })
};

Action Method

public function actionsaveSchool()
{
    $school = file_get_contents("php://input");
    $schoolInfo=json_decode($school,true);
    $schoolTable=new SchoolTable();
    $schoolTable->school_name=$schoolInfo["schoolName"];
    $schoolTable->registration_code=$schoolInfo["registrationCode"];
    $schoolTable->cell_no=$schoolInfo["cellNo"];
    $schoolTable->phone_no=$schoolInfo["phoneNo"];
    $schoolTable->logo=$schoolInfo["logo"];
    $schoolTable->email_address=$schoolInfo["emailAddress"];
    $schoolTable->contact_person=$schoolInfo["contactPerson"];
    $schoolTable->address=$schoolInfo["address"];
    $schoolTable->city=$schoolInfo["city"];
    $schoolTable->district=$schoolInfo["district"];
    $schoolTable->province=$schoolInfo["province"];
    if($schoolTable->save()) {
        $id = $schoolTable->school_id;
        echo $id;
    } else{
        echo $schoolTable->getErrors();
    }
}


问:
Angular 2 DOM Elements, "Use of Directives and Advantage of Directives over components
I have just started working on angular 2 and i need to know what are directives and what is the difference between and directives and components.
Also i need a basic idea on dom elements in angular 2.</p>

答:
A component is a directive-with-a-template and the @Component decorator is actually a @Directive decorator extended with template-oriented features.

Details : http://www.codeandyou.com/2016/01/difference-between-component-and-directive-in-Angular2.html

Directive vs Component

Components

To register a component we use @Component meta-data annotation.
Component is a directive which uses shadow DOM to create encapsulated visual behavior called components. Components are typically used to create UI widgets.
Component is used to break up the application into smaller components.
Only one component can be present per DOM element.
@View decorator or templateurl template are mandatory in the component.

Directive

To register directives we use @Directive meta-data annotation.
Directive is used to add behavior to an existing DOM element.
Directive is use to design re-usable components.
Many directives can be used per DOM element.
Directive doesn't use View.


问:
rails helper to give a upload file a unique name?
Hey guys
I'm now working on a project that require upload a lot of videos, Does rails have this helper can handle this, like the address of youtube video :

www.youtube.com/watch?v=KYUhtPV_Lk4

Thanks

答:
You can generate a random string like this and use it as the file name:</p>

```<code>Digest::SHA1.hexdigest(Time.now.to_s) # => 800b262b59296b660a4f73e23580809143ed8846
</code>```

Body:
You can generate a random string like this and use it as the file name:

Digest::SHA1.hexdigest(Time.now.to_s) # => 800b262b59296b660a4f73e23580809143ed8846


问:
Google Maps marker icon (symbol) not rotating
I posted a question yesterday which was resolved by a typographical correction, but now I have a problem which is baffling me.

I have a custom marker on a map, using a symbol as the icon so that I can rotate it. When I initialise it I set rotation to be 0, and at some point will call the updateMap() function which should give the marker a new rotation value. And it does, I'm able to see by printing the marker and its icon in the console that the rotation has changed, but the marker remains staunchly pointed north.

Here's my code for initialising and rotating the marker:

```<code>var map;
var marker;

function initMap(position) {
    var map_div = document.getElementById("map");
    map = new google.maps.Map(map_div, {
        zoom: 14,
        center: { lat: position.Latitude, lng: position.Longitude },
        mapTypeId: 'terrain'
    });
    marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        title: "MY MARKER",
        icon: {
            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
            scale: 4,
            strokeColor: '#00F',
            rotation: 0,
        }
    });
}

function updateMap() {
    var bearing = 135;
    console.log(bearing);
    marker.icon.rotation = bearing;
    console.log(marker);
}
</code>```

The console tells me that the rotation of the marker has changed but the marker itself does not change direction.

Things I have tried:

Triggering a resize event at the end of the update map function

Not specifying an original rotation for the icon

Switching the rotations, so starting at 135 and trying to change to 0 (the value of the marker's rotation at marker.icon.rotation after calling updateMap() becomes 0 but the actual marker keeps pointing at 135)

Changing the rotation right at the end of the initMap() function - this does work, which leads me to believe that there's something not right about the updateMap() function. I can't figure out what though, it still executes the function. Logging the marker in the global scope also tells me that the rotation has changed.

Any ideas or suggestions are welcome.

答:
There is no documented icon property of a google.maps.Marker object (while it may "work", using undocumented properties is not recommended).  Use the documented setters and getters to get the value, change it, then set it again:

```<code>function updateMap() {
    var bearing = 135;
    console.log(bearing);
    var icon = marker.getIcon();
    icon.rotation = bearing;
    marker.setIcon(icon);
    console.log(marker);
}
</code>```

proof of concept fiddle

code snippet:

var map;
var marker;

function initMap(position) {
  var map_div = document.getElementById("map");
  map = new google.maps.Map(map_div, {
    zoom: 14,
    center: {
      lat: position.Latitude,
      lng: position.Longitude
    },
    mapTypeId: 'terrain'
  });
  marker = new google.maps.Marker({
    position: map.getCenter(),
    map: map,
    title: "MY MARKER",
    icon: {
      path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
      scale: 4,
      strokeColor: '#00F',
      rotation: 0,
    }
  });
}

function updateMap(bearing) {
  var icon = marker.getIcon();
  icon.rotation = bearing;
  marker.setIcon(icon);
}

function initialize() {
  initMap({
    Latitude: 37.4419,
    Longitude: -122.1419
  });
}
google.maps.event.addDomListener(window, "load", initialize);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}</code>```

<input type="button" value="rotate" onclick="updateMap(parseInt(document.getElementById('rotation').value));" /><input id="rotation" value="135" />

```

Body:
I posted a question yesterday which was resolved by a typographical correction, but now I have a problem which is baffling me.

I have a custom marker on a map, using a symbol as the icon so that I can rotate it. When I initialise it I set rotation to be 0, and at some point will call the updateMap() function which should give the marker a new rotation value. And it does, I'm able to see by printing the marker and its icon in the console that the rotation has changed, but the marker remains staunchly pointed north.

Here's my code for initialising and rotating the marker:

var map;
var marker;

function initMap(position) {
    var map_div = document.getElementById("map");
    map = new google.maps.Map(map_div, {
        zoom: 14,
        center: { lat: position.Latitude, lng: position.Longitude },
        mapTypeId: 'terrain'
    });
    marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        title: "MY MARKER",
        icon: {
            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
            scale: 4,
            strokeColor: '#00F',
            rotation: 0,
        }
    });
}

function updateMap() {
    var bearing = 135;
    console.log(bearing);
    marker.icon.rotation = bearing;
    console.log(marker);
}

The console tells me that the rotation of the marker has changed but the marker itself does not change direction.

Things I have tried:

Triggering a resize event at the end of the update map function

Not specifying an original rotation for the icon

Switching the rotations, so starting at 135 and trying to change to 0 (the value of the marker's rotation at marker.icon.rotation after calling updateMap() becomes 0 but the actual marker keeps pointing at 135)

Changing the rotation right at the end of the initMap() function - this does work, which leads me to believe that there's something not right about the updateMap() function. I can't figure out what though, it still executes the function. Logging the marker in the global scope also tells me that the rotation has changed.

Any ideas or suggestions are welcome.

Body:
There is no documented icon property of a google.maps.Marker object (while it may "work", using undocumented properties is not recommended).  Use the documented setters and getters to get the value, change it, then set it again:

function updateMap() {
    var bearing = 135;
    console.log(bearing);
    var icon = marker.getIcon();
    icon.rotation = bearing;
    marker.setIcon(icon);
    console.log(marker);
}

proof of concept fiddle

code snippet:

var map;
var marker;

function initMap(position) {
  var map_div = document.getElementById("map");
  map = new google.maps.Map(map_div, {
    zoom: 14,
    center: {
      lat: position.Latitude,
      lng: position.Longitude
    },
    mapTypeId: 'terrain'
  });
  marker = new google.maps.Marker({
    position: map.getCenter(),
    map: map,
    title: "MY MARKER",
    icon: {
      path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
      scale: 4,
      strokeColor: '#00F',
      rotation: 0,
    }
  });
}

function updateMap(bearing) {
  var icon = marker.getIcon();
  icon.rotation = bearing;
  marker.setIcon(icon);
}

function initialize() {
  initMap({
    Latitude: 37.4419,
    Longitude: -122.1419
  });
}
google.maps.event.addDomListener(window, "load", initialize);

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" value="rotate" onclick="updateMap(parseInt(document.getElementById('rotation').value));" /><input id="rotation" value="135" />
<div id="map"></div>

ContentLicense: CC BY-SA 4.0


问:
Keep user logged in accross Sites
I'm using Django Sites framework to hadle different sites. They have different domains but same database and same users.

I'd like to add a link to switch between my sites. The thing is I don't want to get redirected to login form. What is the best way to achieve this?

Is it possible to build a view that logs the user in the destination site and then redirect to it?

```<code>class SiteSwitcherView(View):
    def get(self, request, *args, **kwargs):
        site = Site.objects.filter(pk=kwargs.get('site_pk')).first()
        # log request.user in the destination Site
        # ...
        return redirect("http://{0}/dashboard/".format(site.domain))
</code>```

To use authenticate() and login(), I have to pass the user credentials and current request...maybe if I send a post request to login view of the destination site before redirect would work?

答: Please check https://github.com/jbittel/django-mama-cas - this seem to be something you're looking for.</p>

Title: Keep user logged in accross Sites

Body:
I'm using Django Sites framework to hadle different sites. They have different domains but same database and same users.

I'd like to add a link to switch between my sites. The thing is I don't want to get redirected to login form. What is the best way to achieve this?

Is it possible to build a view that logs the user in the destination site and then redirect to it?

class SiteSwitcherView(View):
    def get(self, request, *args, **kwargs):
        site = Site.objects.filter(pk=kwargs.get('site_pk')).first()
        # log request.user in the destination Site
        # ...
        return redirect("http://{0}/dashboard/".format(site.domain))

To use authenticate() and login(), I have to pass the user credentials and current request...maybe if I send a post request to login view of the destination site before redirect would work?