问:
Swift, use function UIView.removeFromSuperview as an argument in forEach function over array of views
I would like to change following code

```<code>    let views: [UIView] = []
    views.forEach {
        $0.removeFromSuperview()
    }
</code>```

to some other way, in which I pass function UIView.removeFromSuperview as an argument to the forEach function.
Something similar to

```<code>        let views: [UIView] = []
        views.map {  /* transform views to be passed further */ }
            .forEach(UIView.removeFromSuperview)
</code>```

Is it possible somehow?

UPDATE

Based on the answer below and some comments, I can sum up feedback for this question for myself a bit.

Instance Methods are “Curried” Functions in Swift (By Ole Begemann)

Flattening the function type of unapplied method references (Swift Evolution)

Based on the latter, Chris Lattner has mentioned some flip function in a paragraph Impact on existing code.

My assumption about its implementation is something following

```<code>func flip<T>(_ function: @escaping (T) -> () -> Void) -> (T) -> Void {
    return { object in function(object)() }
}
</code>```

Thus, we can rewrite initial code like

```<code>views.forEach(flip(UIView.removeFromSuperview))
</code>```

答:
It's easy enough to just call the method on $0:

```<code>views.forEach {
    $0.removeFromSuperview()
}
</code>```

(And you can name the argument if you like.)

But you could also wrap it into a method:

```<code>extension Sequence {
    func onEach(_ invoke: (Iterator.Element) -> () -> Void) {
        self.forEach { invoke($0)() }
    }
}
</code>```

This works because instance methods can be represented as functions that take an instance of their type and return a function that has their "top-level" signature.

One downside here is that you can't include the rethrows annotation that's present on forEach, because rethrows only applies if the function argument itself is throwing.

Body:
I would like to change following code

    let views: [UIView] = []
    views.forEach {
        $0.removeFromSuperview()
    }

to some other way, in which I pass function UIView.removeFromSuperview as an argument to the forEach function.
Something similar to

        let views: [UIView] = []
        views.map {  /* transform views to be passed further */ }
            .forEach(UIView.removeFromSuperview)

Is it possible somehow?

UPDATE

Based on the answer below and some comments, I can sum up feedback for this question for myself a bit.

Instance Methods are “Curried” Functions in Swift (By Ole Begemann)

Flattening the function type of unapplied method references (Swift Evolution)

Based on the latter, Chris Lattner has mentioned some flip function in a paragraph Impact on existing code.

My assumption about its implementation is something following

func flip<T>(_ function: @escaping (T) -> () -> Void) -> (T) -> Void {
    return { object in function(object)() }
}

Thus, we can rewrite initial code like

views.forEach(flip(UIView.removeFromSuperview))

Body:
It's easy enough to just call the method on $0:

views.forEach {
    $0.removeFromSuperview()
}

(And you can name the argument if you like.)

But you could also wrap it into a method:

extension Sequence {
    func onEach(_ invoke: (Iterator.Element) -> () -> Void) {
        self.forEach { invoke($0)() }
    }
}

This works because instance methods can be represented as functions that take an instance of their type and return a function that has their "top-level" signature.

One downside here is that you can't include the rethrows annotation that's present on forEach, because rethrows only applies if the function argument itself is throwing.


来源: stackexchange

问:
Java Generics - method which accept different generic interfaces
Say I have this code:

```<code>IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...
</code>```

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

```<code>void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}
</code>```

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.

答:
There is no established design pattern which will help you here.

Your problem is in your declaration of these variables:

```<code>IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;
</code>```

By using the wildcard, you are effectively telling the compiler "I do not care about the type". That's not true. Eventually you do care about the type.

Fundamentally, your method is attempting to do too much and that's what's causing you problems. Break it down into multiple methods and it becomes much easier:

```<code>switch (OPERATION_TYPE) {
   case TYPE_1:
      typeOne();
   case TYPE_2:
      typeTwo();
}

private void typeOne()
{
    IOperation<Type1> parameter1 = new MyOperation<>();
    ITotallyDifferentOperation<Type1> parameter2 = new MyTotallyDifferentOperation<>();

    doTheChecks(parameter1, parameter2);
    databaseStuff(parameter1, parameter2);
}

private void typeTwo() /*identical to above, except the types*/
{
    IOperation<Type2> parameter1 = new MyOperation<>();
    ITotallyDifferentOperation<Type2> parameter2 = new MyTotallyDifferentOperation<>();

    doTheChecks(parameter1, parameter2);
    databaseStuff(parameter1, parameter2);
}

<T> void doTheChecks(IOperation<T> param1, ITotallyDifferentOperation<T> param2)
{
    ...
}

<T> void databaseStuff(IOperation<T> param1, ITotallyDifferentOperation<T> param2)
{
    switch (DB_OPERATION_TYPE) {
        case DB_TYPE_1:
            myMethod(param1, param2);
            break;
        case DB_TYPE_2:
            myOtherMethod(param1, param2);
            break;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Say I have this code:

IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.

Body:
There is no established design pattern which will help you here.

Your problem is in your declaration of these variables:

IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

By using the wildcard, you are effectively telling the compiler "I do not care about the type". That's not true. Eventually you do care about the type.

Fundamentally, your method is attempting to do too much and that's what's causing you problems. Break it down into multiple methods and it becomes much easier:

switch (OPERATION_TYPE) {
   case TYPE_1:
      typeOne();
   case TYPE_2:
      typeTwo();
}

private void typeOne()
{
    IOperation<Type1> parameter1 = new MyOperation<>();
    ITotallyDifferentOperation<Type1> parameter2 = new MyTotallyDifferentOperation<>();

    doTheChecks(parameter1, parameter2);
    databaseStuff(parameter1, parameter2);
}

private void typeTwo() /*identical to above, except the types*/
{
    IOperation<Type2> parameter1 = new MyOperation<>();
    ITotallyDifferentOperation<Type2> parameter2 = new MyTotallyDifferentOperation<>();

    doTheChecks(parameter1, parameter2);
    databaseStuff(parameter1, parameter2);
}

<T> void doTheChecks(IOperation<T> param1, ITotallyDifferentOperation<T> param2)
{
    ...
}

<T> void databaseStuff(IOperation<T> param1, ITotallyDifferentOperation<T> param2)
{
    switch (DB_OPERATION_TYPE) {
        case DB_TYPE_1:
            myMethod(param1, param2);
            break;
        case DB_TYPE_2:
            myOtherMethod(param1, param2);
            break;
    }
}


问:
Is it worth creating an interface for a trivial return type?
Consider the following interfaces:

```<code>public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

and the associated implementations:

```<code>public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?

答: If you plan on creating mockups for unit testing, this might be worthwhile. In this particular case, it might be worth mocking the IPlayerRepository, but probably not the IPlayerInfo.

ContentLicense: CC BY-SA 2.5

Body:
Consider the following interfaces:

public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

and the associated implementations:

public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?


问:
Sending a caret with System.Windows.Forms.SendKeys.Send() will send & (ampersand)
When using SendKeys.Send() of System.Windows.Forms to send a caret ^

```<code>SendKeys.Send ("{^}")
</code>```

it will send an ampersand & instead.

Why?

答:
According to

https://www.experts-exchange.com/questions/28994144/SendKeys-caret-sends-ampersand.html

it's a localization issue.

Changing the keyboard layout from german layout to english layout should help.

ContentLicense: CC BY-SA 4.0

Body:
When using SendKeys.Send() of System.Windows.Forms to send a caret ^

SendKeys.Send ("{^}")

it will send an ampersand & instead.

Why?


问:
hortonworks Ambari + nifi selectHiveQL
we use hortonworks' ambari packone and nifi, then we encountered a problem like this:

when the log shows that

2017-10-26 13:06:14,031 WARN [main] org.apache.nifi.nar.ExtensionManager Controller Service org.apache.nifi.dbcp.hive.HiveConnectionPool is bundled with its supporting APIs org.apache.nifi.dbcp.hive.HiveDBCPService. The service APIs should not be bundled with the implementations.

2017-10-26 13:06:14,031 ERROR [main] org.apache.nifi.nar.ExtensionManager Skipping Controller Service org.apache.nifi.dbcp.hive.HiveConnectionPool because it is bundled with its supporting APIs and requires instance class loading.

2017-10-26 13:06:14,050 WARN [main] org.apache.nifi.nar.ExtensionManager Component org.apache.nifi.processors.hive.SelectHiveQL is bundled with its referenced Controller Service APIs org.apache.nifi.dbcp.hive.HiveDBCPService. The service APIs should not be bundled with component implementations that reference it.

I searched source code and found in line 167 of sourceCodeUrl like this:

"Skipping component %s because it is bundled with its referenced Controller Service APIs and requires instance class loading.", extensionType.getName()));

Thank the first one who answered me, i think you are right, and i post pictures below of all files in the lib, in which some nar files are developed by our own. thank you very much.

allFilesInLib

allFilesInBootStrap

could anyone help me?

thank you very much

one of my workmates searched a webpage :
brokenPipesURL

i have tried it. May it can be useful for my first error.

答:
The error in the UI is unrelated to the error you showed from the logs.

The error in the UI is showing a socket exception which likely means there is some network connectivity issue between NiFi and the hosts where Hive processes are running.

The error in the log is an error that should have been fixed in the HDF 3.x release line. It would be helpful if you could show a listing of everything in /usr/hdf/current/nifi/lib

Title: hortonworks Ambari + nifi selectHiveQL


问:
How to set property values in new object from object from List and get a new List of the same objects in which properties are set using java 8?
For example here is my code :

```<code>   List<EmployeeDto> employees = new ArrayList<>();
   if(CollectionUtils.isNotEmpty(employeeListFromUI)){
        for(EmployeeVO employee : employeeListFromUI){
            EmployeeDto employeeDto =  new EmployeeDto();
            employeeDto.setName(employee.getName());
            employeeDto.setAddressLine1(employee.getAddressLine1());
            if(employee.getAddressLine2()!=null && employee.getAddressLine2()!=""){
            employeeDto.setAddressLine2(employee.getAddressLine2());
            }
            employeeDto.setCity(employee.getCity());
            employeeDto.setState(employee.getState());
            employeeDto.setZip(employee.getZip());
            employees.add(employeeDto);
        }
    }
</code>```

instead of this much of code using java 8 stream and forEach is it possible to write the above code in few lines.

答:
Optional + flatMap + map:

```<code>Optional.ofNullable(employeeListFromUI)
    .flatMap(employeeList-> employeeList
    .stream.map(e -> mapToEmployeeDto(e))).collect(Collectors.toList());
</code>```

Example

Body:
For example here is my code :

   List<EmployeeDto> employees = new ArrayList<>();
   if(CollectionUtils.isNotEmpty(employeeListFromUI)){
        for(EmployeeVO employee : employeeListFromUI){
            EmployeeDto employeeDto =  new EmployeeDto();
            employeeDto.setName(employee.getName());
            employeeDto.setAddressLine1(employee.getAddressLine1());
            if(employee.getAddressLine2()!=null && employee.getAddressLine2()!=""){
            employeeDto.setAddressLine2(employee.getAddressLine2());
            }
            employeeDto.setCity(employee.getCity());
            employeeDto.setState(employee.getState());
            employeeDto.setZip(employee.getZip());
            employees.add(employeeDto);
        }
    }

instead of this much of code using java 8 stream and forEach is it possible to write the above code in few lines.

Body:
Optional + flatMap + map:

Optional.ofNullable(employeeListFromUI)
    .flatMap(employeeList-> employeeList
    .stream.map(e -> mapToEmployeeDto(e))).collect(Collectors.toList());

Example


问:
Visual Studio 2017 SSDT offline install
I require an offline install for SSDT for Visual Studio 2017.  Or how to hack the online download.  (note not VS itself I have that offline install).  I have used the online download to obtain the .vsix files but I need a way to install them.

Double click doesn't work,

Rename to .zip and extract and place them
in the folder doesn't work.

There is an ISO available but it's only
for 2015

Any help would be appreciated

答:
You can download the offline layout using /layout input.

```<code>SSDT-Setup-ENU.exe /layout c:\vs2017ssdt
</code>```

You can find out what parameters can be sent in, if you enter

```<code>SSDT-Setup-ENU.exe /?
</code>```

Once you have the offline layout of ssdt installer, you can copy it to a machine that doesnt have internet access and install there.

Title: Visual Studio 2017 SSDT offline install

Body:
You can download the offline layout using /layout input.

SSDT-Setup-ENU.exe /layout c:\vs2017ssdt

You can find out what parameters can be sent in, if you enter

SSDT-Setup-ENU.exe /?

Once you have the offline layout of ssdt installer, you can copy it to a machine that doesnt have internet access and install there.


问:
Can Laravel using join table to get data?
Just some random thought, can laravel using join table rather than using eloquent relationship. Because most of answers that i read in here suggest to using relationship like belongstoMany, belongsto and other eloquent relationship. If can, it should be nice if u guys giving me some sample code about how to do that. Sorry for the silly question. Thank you</p>

答:
yes you can use the join as per your requirement if you don't want to add relationship like this

```<code>user::select('in_user_id', 'st_first_name', 'st_last_name',
'in_contact_no', 'email', 'tbl_city.st_city_name',
'tbl_usertype_master.st_usertype_name', 'tbl_center.st_center_name',
'is_active')->leftjoin('tbl_city', 'tbl_city.in_city_id',
'tbl_user.in_city_id')->
leftjoin('tbl_usertype_master','tbl_usertype_master.in_usertype_id',
'tbl_user.in_usertype_id')->leftjoin('tbl_center',
'tbl_center.in_center_id', 'tbl_user.in_center_id');
</code>```

in this manner you can use join in laravel here i use for display user from User table

Hope this helps you

Thank You

Body:
yes you can use the join as per your requirement if you don't want to add relationship like this

user::select('in_user_id', 'st_first_name', 'st_last_name',
'in_contact_no', 'email', 'tbl_city.st_city_name',
'tbl_usertype_master.st_usertype_name', 'tbl_center.st_center_name',
'is_active')->leftjoin('tbl_city', 'tbl_city.in_city_id',
'tbl_user.in_city_id')->
leftjoin('tbl_usertype_master','tbl_usertype_master.in_usertype_id',
'tbl_user.in_usertype_id')->leftjoin('tbl_center',
'tbl_center.in_center_id', 'tbl_user.in_center_id');

in this manner you can use join in laravel here i use for display user from User table

Hope this helps you

Thank You


问:
genymotion does not make any sound
there.
I'm using Genymotion for test.
I'm developing an android application.
This application can make a sound.
then
I tried to test my android application.
But,it would not make a sound.

My environment is Macbook.
and
Virtual box is 5.1.
and
VMDevice is Google Nexus 4 with API level 22.
this would not make any sound even if i could change the volume of sound on genymotion.

And my virtual device setting is here.

答:
I also had no sound when using Windows 10 1709, VirtualBox 5.1.26 and Genymotion 2.11.0.

I noticed this line in VBox.log:

Audio: Skipping to create input stream "[LUN#0] ac97.mc", as the host
  audio backend reached its maximum of concurrent audio input streams

What solved my no audio issue was to activate the "Stereomix" in the recording devices in Windows Sound settings. For an unknown reason this was deactivated.

Title: genymotion does not make any sound


问:
Reordering nodes in increasing order in pandas dataframe
```<code>data1 = { 'node1': [2,2,3,6],
     'node2': [6,7,7,28],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])
</code>```

I want to rename the node1 and node 2 in the data1 according in increasing order.
Nodes are 2 3 6 7 28 so they become 1 2 3 4 5 respectively.

So the dataframe becomes-

```<code>data1 = { 'node1': [1,1,2,3],
     'node2': [3,4,4,5],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])
</code>```

The data looked like this before

but now looks like this

答:
Factorizing by sorting and assigning by reshaping i.e </p>

```<code>df1[['node1','node2']] = (pd.factorize(np.sort(df1[['node1','node2']].values.reshape(-1)))[0]+1).reshape(-1,len(df1)).T

    node1  node2  weight
0      1      3       1
1      1      4       2
2      2      4       1
3      3      5       1
</code>```

<p>Another approach with melt and factorize and renaming with dict </p>

```<code>vals = pd.factorize(df1[['node1','node2']].melt().sort_values('value')['value'])

to_rename = dict(zip(vals[1],np.unique(vals[0]+1)))
# {2: 1, 3: 2, 6: 3, 7: 4, 28: 5}

df1[['node1','node2']] = df1[['node1','node2']].apply(lambda x : x.map(to_rename))
# Also df1[['node1','node2']] = df1[['node1','node2']].replace(to_rename) Thanks @jezrael

  node1  node2  weight
0      1      3       1
1      1      4       2
2      2      4       1
3      3      5       1
</code>```

Body:
data1 = { 'node1': [2,2,3,6],
     'node2': [6,7,7,28],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])

I want to rename the node1 and node 2 in the data1 according in increasing order.
Nodes are 2 3 6 7 28 so they become 1 2 3 4 5 respectively.

So the dataframe becomes-

data1 = { 'node1': [1,1,2,3],
     'node2': [3,4,4,5],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])

The data looked like this before

but now looks like this

Body:
Factorizing by sorting and assigning by reshaping i.e

df1[['node1','node2']] = (pd.factorize(np.sort(df1[['node1','node2']].values.reshape(-1)))[0]+1).reshape(-1,len(df1)).T

    node1  node2  weight
0      1      3       1
1      1      4       2
2      2      4       1
3      3      5       1

Another approach with melt and factorize and renaming with dict

vals = pd.factorize(df1[['node1','node2']].melt().sort_values('value')['value'])

to_rename = dict(zip(vals[1],np.unique(vals[0]+1)))
# {2: 1, 3: 2, 6: 3, 7: 4, 28: 5}

df1[['node1','node2']] = df1[['node1','node2']].apply(lambda x : x.map(to_rename))
# Also df1[['node1','node2']] = df1[['node1','node2']].replace(to_rename) Thanks @jezrael

  node1  node2  weight
0      1      3       1
1      1      4       2
2      2      4       1
3      3      5       1


问:
How can I retrieve all values for a column key in a multidimensional ArrayTable?
I'm trying to retrieve all matrix values from a multidimensional array table, using Google's Guava tables package. Right now, I can get all elements for a specific column key as follows:

```<code>import java.util.List;
import java.util.Map;

import com.google.common.collect.ArrayTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;

public class createMatrixTable {

    public static void main(String[] args) {

        // Setup table just like a matrix in R
        List<String> universityRowTable = Lists.newArrayList("Mumbai", "Harvard");
        List<String> courseColumnTables = Lists.newArrayList("Chemical", "IT", "Electrical");
        Table<String, String, Integer> universityCourseSeatTable = ArrayTable.create(universityRowTable, courseColumnTables);

        // Populate the values of the table directly
        universityCourseSeatTable.put("Mumbai", "Chemical", 120);
        universityCourseSeatTable.put("Mumbai", "IT", 60);
        universityCourseSeatTable.put("Harvard", "Electrical", 60);
        universityCourseSeatTable.put("Harvard", "IT", 120);

        // Get all of the elements of a specific column
        Map<String, Integer> courseSeatMap = universityCourseSeatTable.column("IT");

        // Print out those elements
        System.out.println(courseSeatMap);

    }

}
</code>```

Which returns the following in the console:

```<code>{Mumbai=60, Harvard=120}
</code>```

How can I assign just the values (60 and 120) to an array variable without the row keys?

```<code>List<Integer> courseSeatValuesIT = new ArrayList<Integer>();
</code>```

Such that if I were to print the list, it would return the following:

```<code>// Print out the variable with just values
System.out.println(courseSeatValuesIT);

[60,120]
</code>```

Thanks to any Java rock stars who take the time to help out a new guy!!

答:
If you want only values from specified column, just use .values() on returned map:

```<code>Collection<Integer> courseSeatValuesIT = courseSeatMap.values();
System.out.println(courseSeatValuesIT);
</code>```

If you need list, copy it to new one:

```<code>List<Integer> courseSeatValuesIT = new ArrayList<>(courseSeatMap.values());
</code>```

Note that you're using ArrayTable here, which is fixed-size and requires allowed row and column keys must be supplied when the table is created. If you ever want to add new row / column (ex. "Oxford" -> "Law" -> value), you should use HashBasedTable in first place.

Body:
I'm trying to retrieve all matrix values from a multidimensional array table, using Google's Guava tables package. Right now, I can get all elements for a specific column key as follows:

import java.util.List;
import java.util.Map;

import com.google.common.collect.ArrayTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;

public class createMatrixTable {

    public static void main(String[] args) {

        // Setup table just like a matrix in R
        List<String> universityRowTable = Lists.newArrayList("Mumbai", "Harvard");
        List<String> courseColumnTables = Lists.newArrayList("Chemical", "IT", "Electrical");
        Table<String, String, Integer> universityCourseSeatTable = ArrayTable.create(universityRowTable, courseColumnTables);

        // Populate the values of the table directly
        universityCourseSeatTable.put("Mumbai", "Chemical", 120);
        universityCourseSeatTable.put("Mumbai", "IT", 60);
        universityCourseSeatTable.put("Harvard", "Electrical", 60);
        universityCourseSeatTable.put("Harvard", "IT", 120);

        // Get all of the elements of a specific column
        Map<String, Integer> courseSeatMap = universityCourseSeatTable.column("IT");

        // Print out those elements
        System.out.println(courseSeatMap);

    }

}

Which returns the following in the console:

{Mumbai=60, Harvard=120}

How can I assign just the values (60 and 120) to an array variable without the row keys?

List<Integer> courseSeatValuesIT = new ArrayList<Integer>();

Such that if I were to print the list, it would return the following:

// Print out the variable with just values
System.out.println(courseSeatValuesIT);

[60,120]

Thanks to any Java rock stars who take the time to help out a new guy!!

Body:
If you want only values from specified column, just use .values() on returned map:

Collection<Integer> courseSeatValuesIT = courseSeatMap.values();
System.out.println(courseSeatValuesIT);

If you need list, copy it to new one:

List<Integer> courseSeatValuesIT = new ArrayList<>(courseSeatMap.values());

Note that you're using ArrayTable here, which is fixed-size and requires allowed row and column keys must be supplied when the table is created. If you ever want to add new row / column (ex. "Oxford" -> "Law" -> value), you should use HashBasedTable in first place.


问:
how to calculate the length of a string without spaces in java
this calculate the whole length of the string eg i am a man= 7 letter and 9 characters i just want the amount of the total letters</p>

```<code>import java.util.Scanner;
public class AssignmentProgramming {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter a string");

        String input = sc.nextLine();

        System.out.println(input);

        String str = input;
        String[] myString = str.split(" ");
        int length = str.length();
        System.out.println(length);
    }

}
</code>```

答:
Let me know if this helps you out !!</p>

```<code>import java.util.*;
public class CountCharacters
{
public static void main(String[] args)
{
System.out.println("Entered a string ");
Scanner sc= new Scanner(System.in);
String originalString=sc.nextLine();
System.out.println("Entered string is "+originalString);
String newString=originalString.replaceAll(" ", "");
System.out.println("New string after removing spaces is "+newString);
System.out.println("Number of characters in string are "+newString.length());
}
}
</code>```

Body:
this calculate the whole length of the string eg i am a man= 7 letter and 9 characters i just want the amount of the total letters

import java.util.Scanner;
public class AssignmentProgramming {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter a string");

        String input = sc.nextLine();

        System.out.println(input);

        String str = input;
        String[] myString = str.split(" ");
        int length = str.length();
        System.out.println(length);
    }

}

Body:
Let me know if this helps you out !!

import java.util.*;
public class CountCharacters
{
public static void main(String[] args)
{
System.out.println("Entered a string ");
Scanner sc= new Scanner(System.in);
String originalString=sc.nextLine();
System.out.println("Entered string is "+originalString);
String newString=originalString.replaceAll(" ", "");
System.out.println("New string after removing spaces is "+newString);
System.out.println("Number of characters in string are "+newString.length());
}
}


问:
Can I split a .net DLL without having to recompile other DLLs that reference the original one?
I have a C# project that builds into a single DLL with two classes, ClassA and ClassB. For project management reasons, I'd like to move ClassB into a separate DLL, leaving the original DLL with ClassA only.

The problem is that I have other DLLs (also compiled from C#) that reference ClassA and ClassB in their original DLL. ClassA is fine but calling ClassB ends up with a TypeLoadException.

(I could recompile all of those other DLLs with their new project references, but I'd rather not do that, again for project management reasons.)

Is there a way I could deploy my new split DLLs and have the other DLLs continue to work? Or, do I really need to bite the proverbial bullet and plan to deploy new versions of all these files?

答:
You achieve this using Type forwarding. This enables moving a type to another assembly. In the original assembly, you add a TypeForwardedTo-attribute to signal that the type has been moved.

See this link for detailed information.


问:
Instant run - Android studio
Google announced instant run a year ago, and until this time I can't use it.

I tried more than 10,000 times for many android studio versions,
it works for the first run but the second, it always build failed because it can't delete some files or whatever.

And every time I have to clean the project then run again, which means there is no added value to turn on the instant run.

What is the problem? what's going on with google? They just announce the features without any test. Come on guys.

Any advice guys?

Error:
java.lang.RuntimeException: java.io.IOException: Could not delete path '/**/**/**/**/app/build/intermediates/instant-run-support/**/debug/package_directories/dex-renamer-state.txt'.

答: Sadly, No More instance run :(</p>

Title: Instant run - Android studio

Body: Sadly, No More instance run :(


问:
Elmah webconfig error 500 on Window2008r2 MVC2 Project
Just found out that i don't need httpHandler and the httpHandlers in the system.web and it still running

I have tried to integrate Elmah to my MVC2 Project and it works fine on my local, But when I upload it to the Web, which is window2008-r2. There i get "500 - Internal server error."

When i remove the httpHandler and the httpHandlers from the webconfig the the error is gone but elmah is not running.

Please help, how you I get it running on the 2008RC?

Here is what in my webconfig file:

```<code>  <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"/>
  <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
  <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
  <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
  <section name="errorTweet" requirePermission="false" type="Elmah.ErrorTweetSectionHandler, Elmah"/>
</sectionGroup>
</code>```

...

...

```<code><httpModules>
  <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
  <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
</httpModules>

<customErrors mode="RemoteOnly" defaultRedirect="/content/error.htm" />
</code>```

...

...

```<code><modules runAllManagedModulesForAllRequests="true">
  <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
  <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
</modules>

<handlers>
  <add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
  <remove name="UrlRoutingHandler"/>
</handlers>
</code>```

...

```<code><security allowRemoteAccess="0" />

<!--
  quickest log method
  -->
<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/Content/ErrorLog" />
</code>```

...

答: whether or not httpHandlers is required in system.web is determined by whether you are on IIS6....It is better you keep both pieces as shown in the example by odyth so that it works fine for both IIS 6 and 7</p>

Body:
Just found out that i don't need httpHandler and the httpHandlers in the system.web and it still running

I have tried to integrate Elmah to my MVC2 Project and it works fine on my local, But when I upload it to the Web, which is window2008-r2. There i get "500 - Internal server error."

When i remove the httpHandler and the httpHandlers from the webconfig the the error is gone but elmah is not running.

Please help, how you I get it running on the 2008RC?

Here is what in my webconfig file:

</sectionGroup>

...

...

<httpModules>
  <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
  <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
</httpModules>

<customErrors mode="RemoteOnly" defaultRedirect="/content/error.htm" />

...

...

<modules runAllManagedModulesForAllRequests="true">
  <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
  <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
</modules>

<handlers>
  <add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
  <remove name="UrlRoutingHandler"/>
</handlers>

...

<security allowRemoteAccess="0" />

<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/Content/ErrorLog" />

...


问:
how can I tell cmake to find Windows Media Foundation?
To get cmake to link to (for example) boost::thread I can write:

```<code>find_package(Boost REQUIRED COMPONENTS thread)
</code>```

and then:

```<code>target_link_librarie(${target}
    PRIVATE
    Boost::thread
)
</code>```

How do I do this with Windows Media Foundation libraries?

答:
There are three basic ways of handling dependencies with CMake:

CMake ships with a bunch of find modules for finding external libraries. Your call to find_package(Boost ...) is handled by the FindBoost module.

Alternatively, your dependency might ship with a config script that can be found by find_package. This is the approach that is used for finding eg. Qt5.

In your case, unfortunately, none of those apply, which leaves us with the last remaining option: Write your own find script! You can take a look at the source code for some of the modules that ship with CMake as examples. The Boost one is quite complicated, but FindVulkan for instance is reasonably simple.

You mainly need a find_path call for the include path and a find_library call for the .lib file. The MSDN page for the Windows Media Foundation tells you what to search for. If you are lucky, the SDK installer set an environment variable that you can use as a hint for the find_* calls, in which case your script will be fully automatic. If not, you will have to manually specify the location when running CMake.

While this approach might seem cumbersome, it is very flexible and allows managing any kind of third-party dependency. If you want to step outside of the realm of pure CMake, you can also take look at package managers like vcpkg or conan for handling dependencies, which offer additional features and comfort.

Body:
To get cmake to link to (for example) boost::thread I can write:

find_package(Boost REQUIRED COMPONENTS thread)

and then:

target_link_librarie(${target}
    PRIVATE
    Boost::thread
)

How do I do this with Windows Media Foundation libraries?


问:
Django: jQuery autocomplete with multiple queryset
I am trying to code an autocomplete for django which would display multiple queryset instead of a single list, an example of another site that have this implementation can be found here: https://www.uala.it/

Now i was able to send in a queryset the objects of two model:

```<code>def multi_autocomplete(request):
    if request.is_ajax():
        # In base a cosa sta scrivendo l'utente mostro un set di aziende.
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query)
        treatments = Treatment.objects.filter(name__icontains=query)
        results = []
        for company in companies:
            place_json = company.name
            results.append(place_json)
        for treatment in treatments:
            place_json = treatment.name
            results.append(place_json)
        data = json.dumps(results)
    return HttpResponse(data, "application/json")
</code>```

As you can see i'm returning the json.dumps with the data from the two models, how can I change the ui to show the values in different columns like in the link i provided?

答:
You need to merge both list and send it in response

```<code>from django.db.models import F

def multi_autocomplete(request):
    if request.is_ajax():
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label')
        treatments = Treatment.objects.filter(name__icontains=query).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label')
        results = list(companies) + list(treatments)
        data = json.dumps(results)
    else:
        data = 'fail'
    return HttpResponse(data, 'application/json')
</code>```

Your autocomplete handler will look like.

```<code>$("#input_element_id").autocomplete({
     source: "{% url 'url name' %}",
     response: function(event, ui) {
        if (!ui.content.length) {
           var noResult = { value: "", label: "No data found" };
           ui.content.push(noResult);
         }
     },
     select: function (e, ui) {
         if (ui.item.value) {
            //do stuff after user selected option from autocomplete
         }
     }
});
</code>```

Update

Check this JsFiddle i think this will help.

Body:
I am trying to code an autocomplete for django which would display multiple queryset instead of a single list, an example of another site that have this implementation can be found here: https://www.uala.it/

Now i was able to send in a queryset the objects of two model:

def multi_autocomplete(request):
    if request.is_ajax():
        # In base a cosa sta scrivendo l'utente mostro un set di aziende.
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query)
        treatments = Treatment.objects.filter(name__icontains=query)
        results = []
        for company in companies:
            place_json = company.name
            results.append(place_json)
        for treatment in treatments:
            place_json = treatment.name
            results.append(place_json)
        data = json.dumps(results)
    return HttpResponse(data, "application/json")

As you can see i'm returning the json.dumps with the data from the two models, how can I change the ui to show the values in different columns like in the link i provided?

Body:
You need to merge both list and send it in response

from django.db.models import F

def multi_autocomplete(request):
    if request.is_ajax():
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label')
        treatments = Treatment.objects.filter(name__icontains=query).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label')
        results = list(companies) + list(treatments)
        data = json.dumps(results)
    else:
        data = 'fail'
    return HttpResponse(data, 'application/json')

Your autocomplete handler will look like.

$("#input_element_id").autocomplete({
     source: "{% url 'url name' %}",
     response: function(event, ui) {
        if (!ui.content.length) {
           var noResult = { value: "", label: "No data found" };
           ui.content.push(noResult);
         }
     },
     select: function (e, ui) {
         if (ui.item.value) {
            //do stuff after user selected option from autocomplete
         }
     }
});

Update

Check this JsFiddle i think this will help.


问:
less than equals in ggplot2 axis label
I am trying to get the <= in the xaxis labels to show up correctly.  I have seen previous posts with expression.  In each of those examples, there was only 1 label which was done explicitly (manually).  In my case, there are several labels with <=.  I read the factor labels from a file.

```<code>faclab <- "value,label
1,<= 1
2,1 < ... <= 2
3,2< ... <= 3
4,>3"
labels.dt <- fread(faclab)

data <- data.table(value=sample(labels.dt[['value']],100,replace=TRUE))

ggplot(data, aes(factor(value))) + geom_bar(aes(y=(..count..)/sum(..count..))) +
   scale_x_discrete(breaks=labels.dt[['value']], labels=labels.dt[['label']])
</code>```

答:
Replace "<=" with the appropriate unicode character "\u2264" ("≤"):

```<code>stringi::stri_replace_all_fixed(
  c("<= 1", ">= 2"),
  c("<=", ">="),
  c("\u2264", "\u2265"),
  vectorize_all = F
)
# [1] "≤ 1" "≥ 2"
</code>```

For example:

```<code>library(tidyverse)
library(data.table)
faclab <- "value,label
1,<= 1
2,1 < ... <= 2
3,2< ... <= 3
4,>3"
labels.dt <- fread(faclab)
data <- data.table(value=sample(labels.dt[['value']],100,replace=TRUE))
ggplot(data, aes(factor(value))) + geom_bar(aes(y=(..count..)/sum(..count..))) +
  scale_x_discrete(
    breaks=labels.dt[['value']],
    labels=stringi::stri_replace_all_fixed(labels.dt[['label']], "<=", "\u2264")
  )
</code>```

Title: less than equals in ggplot2 axis label

Body:
I am trying to get the <= in the xaxis labels to show up correctly.  I have seen previous posts with expression.  In each of those examples, there was only 1 label which was done explicitly (manually).  In my case, there are several labels with <=.  I read the factor labels from a file.

faclab <- "value,label
1,<= 1
2,1 < ... <= 2
3,2< ... <= 3
4,>3"
labels.dt <- fread(faclab)

data <- data.table(value=sample(labels.dt[['value']],100,replace=TRUE))

ggplot(data, aes(factor(value))) + geom_bar(aes(y=(..count..)/sum(..count..))) +
   scale_x_discrete(breaks=labels.dt[['value']], labels=labels.dt[['label']])

Body:
Replace "<=" with the appropriate unicode character "\u2264" ("≤"):

stringi::stri_replace_all_fixed(
  c("<= 1", ">= 2"),
  c("<=", ">="),
  c("\u2264", "\u2265"),
  vectorize_all = F
)
# [1] "≤ 1" "≥ 2"

For example:

library(tidyverse)
library(data.table)
faclab <- "value,label
1,<= 1
2,1 < ... <= 2
3,2< ... <= 3
4,>3"
labels.dt <- fread(faclab)
data <- data.table(value=sample(labels.dt[['value']],100,replace=TRUE))
ggplot(data, aes(factor(value))) + geom_bar(aes(y=(..count..)/sum(..count..))) +
  scale_x_discrete(
    breaks=labels.dt[['value']],
    labels=stringi::stri_replace_all_fixed(labels.dt[['label']], "<=", "\u2264")
  )


问:
How to specify paths in .gitignore?
I am developing a Ruby on Rails application, using git for synchronising code between stakeholders. The application has the ability to send emails. Each stakeholder has his own SMTP provider which is defined in config/initializers/smtp.rb during installation.

```<code>ActionMailer::Base.smtp_settings = {
    address: "smtp.emailme.com",
    port: 587,
    domain: "emailme.com",
    authentication: "plain",
    enable_starttls_auto: true,
    user_name: "me@emailme.com",
    password: "Password"
    }
</code>```

The .gitignore file is defined as:

```<code>*.rbc
capybara-*.html
.rspec
/log
/tmp
/public/system
/coverage/
/spec/tmp
**.orig
rerun.txt
pickle-email-*.html

## Environment normalization:
/.bundle
/vendor/bundle

# these should all be checked in to normalize the environment:
# Gemfile.lock, .ruby-version, .ruby-gemset
Gemfile~

config/initializers/smtp.rb
</code>```

.gitignore files are identical on Github and on my computer. I tried to specify

config/initializers/smtp.rb

or

/config/initializers/smtp.rb

But whatever, the smtp.rb file on my computer gets overwritten with the file on Github. And it's the same the other way round.
What did I miss?

答:
.gitignore will tell git to ignore changes to files that are not currently being tracked by git.

Run git rm --cached config/initializers/smtp.rb to stop git from tracking future changes to the file.

Create a config/initializers/smtp.template.rb with dummy values, and commit + push your changes.

Direct any new stakeholders to run cp config/initializers/smtp.template.rb config/initializers/smtp.rb and update the file when setting up their development environment.

Title: How to specify paths in .gitignore?

Body:
I am developing a Ruby on Rails application, using git for synchronising code between stakeholders. The application has the ability to send emails. Each stakeholder has his own SMTP provider which is defined in config/initializers/smtp.rb during installation.

ActionMailer::Base.smtp_settings = {
    address: "smtp.emailme.com",
    port: 587,
    domain: "emailme.com",
    authentication: "plain",
    enable_starttls_auto: true,
    user_name: "me@emailme.com",
    password: "Password"
    }

The .gitignore file is defined as:

*.rbc
capybara-*.html
.rspec
/log
/tmp
/public/system
/coverage/
/spec/tmp
**.orig
rerun.txt
pickle-email-*.html

## Environment normalization:
/.bundle
/vendor/bundle

# these should all be checked in to normalize the environment:
# Gemfile.lock, .ruby-version, .ruby-gemset
Gemfile~

config/initializers/smtp.rb

.gitignore files are identical on Github and on my computer. I tried to specify

config/initializers/smtp.rb

or

/config/initializers/smtp.rb

But whatever, the smtp.rb file on my computer gets overwritten with the file on Github. And it's the same the other way round.
What did I miss?


问:
Ruby on Rails Could not find "config/databases/sqlite3.yml"
I am having trouble creating a new Rails app, where it used to work fine.

Using mysql or postgres doesn't solve the problem. The output is pretty the same with every database type.

Creating a new app goes with a first warning about sqlite.

```<code>rails new myapp --quiet
Initialized empty Git repository in /home/libros/myapp/.git/
Could not find "config/databases/sqlite3.yml" in any of your source paths. Your current source paths are:
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/generators/rails/app/templates
</code>```

Then trying to do some base things with app causes another errors.

```<code>rails db:create
rails aborted!
Don't know how to build task 'db:create' (see --tasks)
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/commands/rake/rake_command.rb:21:in `block in perform'
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/commands/rake/rake_command.rb:18:in `perform'
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/command.rb:46:in `invoke'
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
(See full trace by running task with --trace)
</code>```

答:
First uninstall sqllite3 and try to install it
again.

unistall
sudo apt-get remove --auto-remove sqlite3
sudo apt-get purge --auto-remove sqlite3

install
sudo add-apt-repository ppa:jonathonf/backports
sudo apt-get update && sudo apt-get install sqlite3

create a file in database.yml inside the config folder

and paste below code

```<code># SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
#
default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3
</code>```

save and restart the application.

Body:
I am having trouble creating a new Rails app, where it used to work fine.

Using mysql or postgres doesn't solve the problem. The output is pretty the same with every database type.

Creating a new app goes with a first warning about sqlite.

rails new myapp --quiet
Initialized empty Git repository in /home/libros/myapp/.git/
Could not find "config/databases/sqlite3.yml" in any of your source paths. Your current source paths are:
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/generators/rails/app/templates

Then trying to do some base things with app causes another errors.

rails db:create
rails aborted!
Don't know how to build task 'db:create' (see --tasks)
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/commands/rake/rake_command.rb:21:in `block in perform'
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/commands/rake/rake_command.rb:18:in `perform'
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/command.rb:46:in `invoke'
/home/libros/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `'
(See full trace by running task with --trace)

Body:
First uninstall sqllite3 and try to install it
again.

unistall
sudo apt-get remove --auto-remove sqlite3
sudo apt-get purge --auto-remove sqlite3

install
sudo add-apt-repository ppa:jonathonf/backports
sudo apt-get update && sudo apt-get install sqlite3

create a file in database.yml inside the config folder

and paste below code

# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
#
default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

save and restart the application.


问:
What's the right pattern? An observer between the viewmodel & service
I am building a WP7 client app that talk to a web service (SOAP like) using Mvvm-Light.

I have a ViewModel that both implements INotifyPropertyChanged and calls RaisePropertryChanged with the broadcast flag set.

Both my view (XAML) and my model (which does  HTTP requests to the web service) subscribe to property changes. XAML, obviously, because of INotifyPropertyChanged, and my model by calling

```<code>Messenger.Default.Register<SysObjectCreatedMessage>(this, (action) => SysObjectCreatedHandler(action.SysObject));
</code>```

This pattern is not going to work, i'm afraid, because of the following:

When I get data back from the web service I  set properties on my ViewModel (using DispatcherHelper.CheckBeginInvokeUI).  I actually use Reflection and my call looks like this:

```<code>GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() => pinfo.SetValue(this, e.Response, null));
</code>```

Here's the problem:  The resultant property set caused by that call to SetValue causes my property set to call RaisePropertryChanged causing me to send the data I just got from the server right back to it.

EDIT - Adding more context Per Jon's suggestion

Here's some of my XAML. My GarageDoorOpener class has a GarageDoorOpened property

On the home control server there are a bunch of garage door objects that have a boolean property representing whether they are open or not.  I can access these using HTTP POSTs of the form:

http://server/sys/Home/Upstairs/Garage/West Garage Door?f??GarageDoorOpened

The the resultant HTTP body will contain either True or False.

The same model applies to other objects in the home with other types (Strings, Integers, etc...).

For now I'm just focusing on the garage door openers.

The View Model for the garage door looks like this:

```<code>public class GarageDoorSensor : SysObject
{
    public static new string SysType = "Garage Door Sensor";
    public const string GarageDoorOpenedPropertyName = "GarageDoorOpened";
    public Boolean _GarageDoorOpened = false;
    [SysProperty]
    public Boolean GarageDoorOpened
    {
        get
        {
            return _GarageDoorOpened;
        }

        set
        {
            if (_GarageDoorOpened == value)
            {
                return;
            }

            var oldValue = _GarageDoorOpened;
            _GarageDoorOpened = value;

            // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
            RaisePropertyChanged(GarageDoorOpenedPropertyName, oldValue, value, true);
        }
    }
}
</code>```

The SysObject class this inherits from looks like this (simplified):

```<code>public class SysObject : ViewModelBase
{
    public static string SysType = "Object";
    public SysObject()
    {
        Messenger.Default.Send<SysObjectCreatedMessage>(new SysObjectCreatedMessage(this));
        }
    }

    protected override void RaisePropertyChanged<T>(string propertyName, T oldValue, T newValue, bool broadcast)
    {
        // When we are initilizing, do not send updates to the server
        // if (UpdateServerWithChange == true)

        // ****************************
        // ****************************
        //
        // HERE IS THE PROBLEM
        //
        // This gets called whenever a property changes (called from set())
        // It both notifies the "server" AND the view
        //
        // I need a pattern for getting the "SendPropertyChangeToServer" out
        // of here so it is only called when properties change based on
        // UI input.
        //
        // ****************************
        // ****************************
        SendPropertyChangeToServer(propertyName, newValue.ToString());

        // Check if we are on the UI thread or not
        if (App.Current.RootVisual == null || App.Current.RootVisual.CheckAccess())
        {
            base.RaisePropertyChanged(propertyName, oldValue, newValue, broadcast);
        }
        else
        {
            // Invoke on the UI thread
            // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
            GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =>
                base.RaisePropertyChanged(propertyName, oldValue, newValue, broadcast));
        }
    }

    private void SendPropertyChangeToServer(String PropertyName, String Value)
    {
          Messenger.Default.Send<SysObjectPropertyChangeMessage>(new SysObjectPropertyChangeMessage(this, PropertyName, Value));
    }

    // Called from PremiseServer when a result has been returned from the server.
    // Uses reflection to set the appropriate property's value
    public void PropertySetCompleteHandler(HttpResponseCompleteEventArgs e)
    {
        // BUGBUG: this is wonky. there is no guarantee these operations will modal. In fact, they likely
        // will be async because we are calling CheckBeginInvokeUI below to wait on the UI thread.

        Type type = this.GetType();
        PropertyInfo pinfo = type.GetProperty((String)e.context);

        // TODO: Genericize this to parse not string property types
        //
        if (pinfo.PropertyType.Name == "Boolean")
        {
            GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() => pinfo.SetValue(this, Boolean.Parse(e.Response), null));
            //pinfo.SetValue(this, Boolean.Parse(e.Response), null);
        }
        else
        {
            GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() => pinfo.SetValue(this, e.Response, null));
            //pinfo.SetValue(this, e.Response, null);
        }
    }
}
</code>```

My "model" is called PremiseServer.  It wraps Http POSTs and handles causing the server to be "queried" for the latest data every once and a while.  I plan on eventually implementing notifications, but for now i am polling.  It uses a bit of Reflection to dynamically translate the HTTP results into property sets.  At it's core it looks like this (i'm pretty proud of myself for this, although I probably should be ashamed instead).

```<code>    protected virtual void OnRequery()
    {
        Debug.WriteLine("OnRequery");
        Type type;

        foreach (SysObject so in sysObjects)
        {
            type = so.GetType();
            PropertyInfo[] pinfos = type.GetProperties();

            foreach (PropertyInfo p in pinfos)
            {
                if (p.IsDefined(typeof(SysProperty),true))
                    SendGetProperty(so.Location, p.Name, so, so.PropertySetCompleteHandler);
            }

        }
    }

    protected delegate void CompletionMethod(HttpResponseCompleteEventArgs e);
    protected void SendGetProperty(string location, string property, SysObject sysobject, CompletionMethod cm)
    {
        String url = GetSysUrl(location.Remove(0, 5));
        Uri uri = new Uri(url + "?f??" + property);
        HttpHelper helper = new HttpHelper(uri, "POST", null, true, property);
        Debug.WriteLine("SendGetProperty: url = <" + uri.ToString() + ">");
        helper.ResponseComplete += new HttpResponseCompleteEventHandler(cm);
        helper.Execute();
    }
</code>```

Note that OnRequery is not the only place I'll eventually be calling SendGetProperty from; it's just there for initialization scaffolding for now. The idea is that I can have a generic piece of code that gets a "message from the server" and translates it into a SysObject.Property.SetValue() call...

END EDIT

I need a pattern that will let me both bind to my data on the XAML side but also on my model side in a thread safe way.

Suggestions?

Thanks!

答:
I re-engaged on this project over the last few weeks and finally came up with a solution. Given the comments and thoughts people posted above, I'm not sure anyone but me understands what I'm trying to do, but I figured it might be worthwhile posting how I solved this. At the minimum, writing it up will ensure I understand it :-).

Summarizing the question again:

I have a home control server that exposes objects in my home via a SOAP interface. Home.LivingRoom.Fireplace, for example is exposed as:

http://server/Home/LivingRoom/Fireplace?property=DisplayName
http://server/Home/LivingRoom/Fireplace?property=PowerState

Doing an HTTP GET against these will result in the HTTP reply containing the property value (e.g. "Living Room Fireplace" and "Off" respectively).

A garage door (e.g. Home.Garage.EastGarageDoor) is exposed as:

http://server/Home/Upstairs/EastGarageDoor?property=DisplayName
http://server/Home/Upstairs/EastGarageDoor?property=GarageDoorOpened
http://server/Home/Upstairs/EastGarageDoor?property=Trigger

Here we have a property that if set causes an action (Trigger). Doing a POST against this with a HTTP body of "True" will cause the door to open/close.

I am building a WP7 app as a front end to this.  I have decided to follow the Mvvm model and am using Mvvm-Light.

WP7 does not have a built in way of supporting notifications from REST interfaces, and I am not yet ready to build my own (although it is on my radar). So for the UI to show up-to-date state I need to poll.  The # of entities & amount of data is relatively small and I have now proven that I can make it work well with polling, but there are some optimizations I can do to improve it (including adding smarts to the server to enable a notifcation like system).

In my solution I've blurred the lines between my model & my viewmodel. If you really wanted to be pendantic about it my "Model" is just the low level classes I have for wrapping my Http requests (e.g GetPropertyAsync(objectLocation, propertyName, completionMethod)).

What I ended up doing is defining a generic class for properties. It looks like this:

```<code>namespace Premise.Model
{
    //where T : string, bool, int, float
    public class PremiseProperty<T>
    {
        private T _Value;
        public PremiseProperty(String propertyName)
        {
            PropertyName = propertyName;
            UpdatedFromServer = false;
        }

        public T Value
        {
            get { return _Value; }

            set { _Value = value; }
        }
        public String PropertyName { get; set; }
        public bool UpdatedFromServer { get; set; }
    }
}
</code>```

I then created a ViewModelBase (from Mvvm-Light) derived base class PremiseObject which represents the base class each object in the control system is based on (e.g. which is literally called `Object').

The most important method on PremiseObject is it's override of RaisePropertyChanged:

```<code>    /// </summary>
    protected override void RaisePropertyChanged<T>(string propertyName, T oldValue, T newValue, bool sendToServer)
    {
        if (sendToServer)
            SendPropertyChangeToServer(propertyName, newValue);

        // Check if we are on the UI thread or not
        if (App.Current.RootVisual == null || App.Current.RootVisual.CheckAccess())
        {
            // broadcast == false because I don't know why it would ever be true
            base.RaisePropertyChanged(propertyName, oldValue, newValue, false);
        }
        else
        {
            // Invoke on the UI thread
            // Update bindings
            // broadcast == false because I don't know why it would ever be true
            GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =>
                base.RaisePropertyChanged(propertyName, oldValue, newValue, false));
        }

    }
</code>```

Note a few things:
1) I am over-riding/re-purposing the broadcast parameter. If it is True then a the property change is "sent to the server" (I do an HTTP POST). I don't use broadcast property changes anywhere else (and I'm not actually even sure what I would use it for).
2) I always pass broadcast to False when calling base..

PremiseObject has a set of standard PremiseProperty properties on it: Location (the URL to the object), Name, DisplayName, Value (the value property). DisplayName looks like this:

```<code>    protected PremiseProperty<String> _DisplayName = new PremiseProperty<String>("DisplayName");

    public string DisplayName
    {
        get
        {
            return _DisplayName.Value;
        }

        set
        {
            if (_DisplayName.Value == value)
            {
                return;
            }

            var oldValue = _DisplayName;
            _DisplayName.Value = value;

            // Update bindings and sendToServer change using GalaSoft.MvvmLight.Messenging
            RaisePropertyChanged(_DisplayName.PropertyName,
                   oldValue, _DisplayName, _DisplayName.UpdatedFromServer);
        }
    }
</code>```

So this means anytime .DisplayName changes within my program it gets relayed to all UI and IF AND ONLY IF _DisplayName.UpdatedFromServer is True does it also get sent back to the server.

So how does .UpdatedFromServer get set?  When we get our callback from an async Http request:

```<code>    protected void DisplayName_Get(PremiseServer server)
    {
        String propertyName = _DisplayName.PropertyName;

        _DisplayName.UpdatedFromServer = false;
        server.GetPropertyAsync(Location, propertyName, (HttpResponseArgs) =>
        {
            if (HttpResponseArgs.Succeeded)
            {
                //Debug.WriteLine("Received {0}: {1} = {2}", DisplayName, propertyName, HttpResponseArgs.Response);
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    DisplayName = (String)HttpResponseArgs.Response; // <-- this is the whole cause of this confusing architecture
                    _DisplayName.UpdatedFromServer = true;
                    HasRealData = true;
                });
            }
        });
    }
</code>```

Whenever the UI wants fresh data these XXX_Get functions get called (e.g. on a polling timer, when a view changes, app start, etc...)

I have to duplicate the code above for each property I define which is pretty painful, but I have not yet found a way to genericize it (trust me, I've tried, but my knowledge of C# is just not strong enough and I just keep moving the problem).  But this works, and works well.

To cover all bases, here's an example of the Trigger property on the GarageDoor class:

```<code>    protected PremiseProperty<bool> _Trigger = new PremiseProperty<bool>("Trigger");
    public bool Trigger
    {
        set
        {
            if (value == true)
                RaisePropertyChanged(_Trigger.PropertyName, false, value, true);
        }
    }
</code>```

Note how I force the broadcast parameter to RaisePropertyChanged to true and how this is a "Write only" property? This generates an HTTP POST against the 'GarageDoor.Location' URL + ?propertyName= + value.ToString().

I'm pretty happy with this turned out.  It's a bit of a hack, but I've now implemented several sophisticated views and it works well.  The separation I've created will allow me to change the underling protocol (e.g. batching up requests and having the server only send changed data) and my ViewModels will not have to change.

Thoughts, comments, suggestions?

Body:
I am building a WP7 client app that talk to a web service (SOAP like) using Mvvm-Light.

I have a ViewModel that both implements INotifyPropertyChanged and calls RaisePropertryChanged with the broadcast flag set.

Both my view (XAML) and my model (which does  HTTP requests to the web service) subscribe to property changes. XAML, obviously, because of INotifyPropertyChanged, and my model by calling

Messenger.Default.Register<SysObjectCreatedMessage>(this, (action) => SysObjectCreatedHandler(action.SysObject));

This pattern is not going to work, i'm afraid, because of the following:

When I get data back from the web service I  set properties on my ViewModel (using DispatcherHelper.CheckBeginInvokeUI).  I actually use Reflection and my call looks like this:

GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() => pinfo.SetValue(this, e.Response, null));

Here's the problem:  The resultant property set caused by that call to SetValue causes my property set to call RaisePropertryChanged causing me to send the data I just got from the server right back to it.

EDIT - Adding more context Per Jon's suggestion

Here's some of my XAML. My GarageDoorOpener class has a GarageDoorOpened property

On the home control server there are a bunch of garage door objects that have a boolean property representing whether they are open or not.  I can access these using HTTP POSTs of the form:

http://server/sys/Home/Upstairs/Garage/West Garage Door?f??GarageDoorOpened

The the resultant HTTP body will contain either True or False.

The same model applies to other objects in the home with other types (Strings, Integers, etc...).

For now I'm just focusing on the garage door openers.

The View Model for the garage door looks like this:

public class GarageDoorSensor : SysObject
{
    public static new string SysType = "Garage Door Sensor";
    public const string GarageDoorOpenedPropertyName = "GarageDoorOpened";
    public Boolean _GarageDoorOpened = false;
    [SysProperty]
    public Boolean GarageDoorOpened
    {
        get
        {
            return _GarageDoorOpened;
        }

        set
        {
            if (_GarageDoorOpened == value)
            {
                return;
            }

            var oldValue = _GarageDoorOpened;
            _GarageDoorOpened = value;

            // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
            RaisePropertyChanged(GarageDoorOpenedPropertyName, oldValue, value, true);
        }
    }
}

The SysObject class this inherits from looks like this (simplified):

public class SysObject : ViewModelBase
{
    public static string SysType = "Object";
    public SysObject()
    {
        Messenger.Default.Send<SysObjectCreatedMessage>(new SysObjectCreatedMessage(this));
        }
    }

    protected override void RaisePropertyChanged<T>(string propertyName, T oldValue, T newValue, bool broadcast)
    {
        // When we are initilizing, do not send updates to the server
        // if (UpdateServerWithChange == true)

        // ****************************
        // ****************************
        //
        // HERE IS THE PROBLEM
        //
        // This gets called whenever a property changes (called from set())
        // It both notifies the "server" AND the view
        //
        // I need a pattern for getting the "SendPropertyChangeToServer" out
        // of here so it is only called when properties change based on
        // UI input.
        //
        // ****************************
        // ****************************
        SendPropertyChangeToServer(propertyName, newValue.ToString());

        // Check if we are on the UI thread or not
        if (App.Current.RootVisual == null || App.Current.RootVisual.CheckAccess())
        {
            base.RaisePropertyChanged(propertyName, oldValue, newValue, broadcast);
        }
        else
        {
            // Invoke on the UI thread
            // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
            GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =>
                base.RaisePropertyChanged(propertyName, oldValue, newValue, broadcast));
        }
    }

    private void SendPropertyChangeToServer(String PropertyName, String Value)
    {
          Messenger.Default.Send<SysObjectPropertyChangeMessage>(new SysObjectPropertyChangeMessage(this, PropertyName, Value));
    }

    // Called from PremiseServer when a result has been returned from the server.
    // Uses reflection to set the appropriate property's value
    public void PropertySetCompleteHandler(HttpResponseCompleteEventArgs e)
    {
        // BUGBUG: this is wonky. there is no guarantee these operations will modal. In fact, they likely
        // will be async because we are calling CheckBeginInvokeUI below to wait on the UI thread.

        Type type = this.GetType();
        PropertyInfo pinfo = type.GetProperty((String)e.context);

        // TODO: Genericize this to parse not string property types
        //
        if (pinfo.PropertyType.Name == "Boolean")
        {
            GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() => pinfo.SetValue(this, Boolean.Parse(e.Response), null));
            //pinfo.SetValue(this, Boolean.Parse(e.Response), null);
        }
        else
        {
            GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() => pinfo.SetValue(this, e.Response, null));
            //pinfo.SetValue(this, e.Response, null);
        }
    }
}

My "model" is called PremiseServer.  It wraps Http POSTs and handles causing the server to be "queried" for the latest data every once and a while.  I plan on eventually implementing notifications, but for now i am polling.  It uses a bit of Reflection to dynamically translate the HTTP results into property sets.  At it's core it looks like this (i'm pretty proud of myself for this, although I probably should be ashamed instead).

    protected virtual void OnRequery()
    {
        Debug.WriteLine("OnRequery");
        Type type;

        foreach (SysObject so in sysObjects)
        {
            type = so.GetType();
            PropertyInfo[] pinfos = type.GetProperties();

            foreach (PropertyInfo p in pinfos)
            {
                if (p.IsDefined(typeof(SysProperty),true))
                    SendGetProperty(so.Location, p.Name, so, so.PropertySetCompleteHandler);
            }

        }
    }

    protected delegate void CompletionMethod(HttpResponseCompleteEventArgs e);
    protected void SendGetProperty(string location, string property, SysObject sysobject, CompletionMethod cm)
    {
        String url = GetSysUrl(location.Remove(0, 5));
        Uri uri = new Uri(url + "?f??" + property);
        HttpHelper helper = new HttpHelper(uri, "POST", null, true, property);
        Debug.WriteLine("SendGetProperty: url = <" + uri.ToString() + ">");
        helper.ResponseComplete += new HttpResponseCompleteEventHandler(cm);
        helper.Execute();
    }

Note that OnRequery is not the only place I'll eventually be calling SendGetProperty from; it's just there for initialization scaffolding for now. The idea is that I can have a generic piece of code that gets a "message from the server" and translates it into a SysObject.Property.SetValue() call...

END EDIT

I need a pattern that will let me both bind to my data on the XAML side but also on my model side in a thread safe way.

Suggestions?

Thanks!

Body:
I re-engaged on this project over the last few weeks and finally came up with a solution. Given the comments and thoughts people posted above, I'm not sure anyone but me understands what I'm trying to do, but I figured it might be worthwhile posting how I solved this. At the minimum, writing it up will ensure I understand it :-).

Summarizing the question again:

I have a home control server that exposes objects in my home via a SOAP interface. Home.LivingRoom.Fireplace, for example is exposed as:

http://server/Home/LivingRoom/Fireplace?property=DisplayName
http://server/Home/LivingRoom/Fireplace?property=PowerState

Doing an HTTP GET against these will result in the HTTP reply containing the property value (e.g. "Living Room Fireplace" and "Off" respectively).

A garage door (e.g. Home.Garage.EastGarageDoor) is exposed as:

http://server/Home/Upstairs/EastGarageDoor?property=DisplayName
http://server/Home/Upstairs/EastGarageDoor?property=GarageDoorOpened
http://server/Home/Upstairs/EastGarageDoor?property=Trigger

Here we have a property that if set causes an action (Trigger). Doing a POST against this with a HTTP body of "True" will cause the door to open/close.

I am building a WP7 app as a front end to this.  I have decided to follow the Mvvm model and am using Mvvm-Light.

WP7 does not have a built in way of supporting notifications from REST interfaces, and I am not yet ready to build my own (although it is on my radar). So for the UI to show up-to-date state I need to poll.  The # of entities & amount of data is relatively small and I have now proven that I can make it work well with polling, but there are some optimizations I can do to improve it (including adding smarts to the server to enable a notifcation like system).

In my solution I've blurred the lines between my model & my viewmodel. If you really wanted to be pendantic about it my "Model" is just the low level classes I have for wrapping my Http requests (e.g GetPropertyAsync(objectLocation, propertyName, completionMethod)).

What I ended up doing is defining a generic class for properties. It looks like this:

namespace Premise.Model
{
    //where T : string, bool, int, float
    public class PremiseProperty<T>
    {
        private T _Value;
        public PremiseProperty(String propertyName)
        {
            PropertyName = propertyName;
            UpdatedFromServer = false;
        }

        public T Value
        {
            get { return _Value; }

            set { _Value = value; }
        }
        public String PropertyName { get; set; }
        public bool UpdatedFromServer { get; set; }
    }
}

I then created a ViewModelBase (from Mvvm-Light) derived base class PremiseObject which represents the base class each object in the control system is based on (e.g. which is literally called `Object').

The most important method on PremiseObject is it's override of RaisePropertyChanged:

    /// </summary>
    protected override void RaisePropertyChanged<T>(string propertyName, T oldValue, T newValue, bool sendToServer)
    {
        if (sendToServer)
            SendPropertyChangeToServer(propertyName, newValue);

        // Check if we are on the UI thread or not
        if (App.Current.RootVisual == null || App.Current.RootVisual.CheckAccess())
        {
            // broadcast == false because I don't know why it would ever be true
            base.RaisePropertyChanged(propertyName, oldValue, newValue, false);
        }
        else
        {
            // Invoke on the UI thread
            // Update bindings
            // broadcast == false because I don't know why it would ever be true
            GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =>
                base.RaisePropertyChanged(propertyName, oldValue, newValue, false));
        }

    }

Note a few things:
1) I am over-riding/re-purposing the broadcast parameter. If it is True then a the property change is "sent to the server" (I do an HTTP POST). I don't use broadcast property changes anywhere else (and I'm not actually even sure what I would use it for).
2) I always pass broadcast to False when calling base..

PremiseObject has a set of standard PremiseProperty properties on it: Location (the URL to the object), Name, DisplayName, Value (the value property). DisplayName looks like this:

    protected PremiseProperty<String> _DisplayName = new PremiseProperty<String>("DisplayName");

    public string DisplayName
    {
        get
        {
            return _DisplayName.Value;
        }

        set
        {
            if (_DisplayName.Value == value)
            {
                return;
            }

            var oldValue = _DisplayName;
            _DisplayName.Value = value;

            // Update bindings and sendToServer change using GalaSoft.MvvmLight.Messenging
            RaisePropertyChanged(_DisplayName.PropertyName,
                   oldValue, _DisplayName, _DisplayName.UpdatedFromServer);
        }
    }

So this means anytime .DisplayName changes within my program it gets relayed to all UI and IF AND ONLY IF _DisplayName.UpdatedFromServer is True does it also get sent back to the server.

So how does .UpdatedFromServer get set?  When we get our callback from an async Http request:

    protected void DisplayName_Get(PremiseServer server)
    {
        String propertyName = _DisplayName.PropertyName;

        _DisplayName.UpdatedFromServer = false;
        server.GetPropertyAsync(Location, propertyName, (HttpResponseArgs) =>
        {
            if (HttpResponseArgs.Succeeded)
            {
                //Debug.WriteLine("Received {0}: {1} = {2}", DisplayName, propertyName, HttpResponseArgs.Response);
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    DisplayName = (String)HttpResponseArgs.Response; // <-- this is the whole cause of this confusing architecture
                    _DisplayName.UpdatedFromServer = true;
                    HasRealData = true;
                });
            }
        });
    }

Whenever the UI wants fresh data these XXX_Get functions get called (e.g. on a polling timer, when a view changes, app start, etc...)

I have to duplicate the code above for each property I define which is pretty painful, but I have not yet found a way to genericize it (trust me, I've tried, but my knowledge of C# is just not strong enough and I just keep moving the problem).  But this works, and works well.

To cover all bases, here's an example of the Trigger property on the GarageDoor class:

    protected PremiseProperty<bool> _Trigger = new PremiseProperty<bool>("Trigger");
    public bool Trigger
    {
        set
        {
            if (value == true)
                RaisePropertyChanged(_Trigger.PropertyName, false, value, true);
        }
    }

Note how I force the broadcast parameter to RaisePropertyChanged to true and how this is a "Write only" property? This generates an HTTP POST against the 'GarageDoor.Location' URL + ?propertyName= + value.ToString().

I'm pretty happy with this turned out.  It's a bit of a hack, but I've now implemented several sophisticated views and it works well.  The separation I've created will allow me to change the underling protocol (e.g. batching up requests and having the server only send changed data) and my ViewModels will not have to change.

Thoughts, comments, suggestions?


问:
Sorting a list of lists based on the third element
I've got an object names x which is a list containing inner lists.

```<code>`x$population`

output
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 11

[[1]][[3]]
[1] 1

[[2]]
[[2]][[1]]
[1] 1

[[2]][[2]]
[1] 20

[[2]][[3]]
[1] 2
</code>```

I want to be able to sort the list based on the third elements:
x$population[[2]][[3]] but I have no idea how to do it.

I have no idea how to start so instead of got some mock code that re-creates the problem:

```<code>z <- list()

z[[1]] <- list(1, 10, 0.5)
z[[2]] <- list(1, 10, 0.87)
</code>```

How would I go about sorting z based on the third elements of each list (0.5, 0.87) such that the larger value is at the top.

Thanks in advance.

答:
1) Pick out the third elements, get their order and subscript the list by that:

```<code>z[order(sapply(z, "[[", 3))]
</code>```

2) Another approach is to represent the data as a matrix a and then sort that:

```<code>a <- sapply(z, unlist)
a[, order(a[3, ])]
</code>```

Body:
I've got an object names x which is a list containing inner lists.

`x$population`

output
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 11

[[1]][[3]]
[1] 1

[[2]]
[[2]][[1]]
[1] 1

[[2]][[2]]
[1] 20

[[2]][[3]]
[1] 2

I want to be able to sort the list based on the third elements:
x$population[[2]][[3]] but I have no idea how to do it.

I have no idea how to start so instead of got some mock code that re-creates the problem:

z <- list()

z[[1]] <- list(1, 10, 0.5)
z[[2]] <- list(1, 10, 0.87)

How would I go about sorting z based on the third elements of each list (0.5, 0.87) such that the larger value is at the top.

Thanks in advance.

Body:
1) Pick out the third elements, get their order and subscript the list by that:

z[order(sapply(z, "[[", 3))]

2) Another approach is to represent the data as a matrix a and then sort that:

a <- sapply(z, unlist)
a[, order(a[3, ])]


问:
How should I design the schema to get the last 2 records of each clustering key in Cassandra?
Each row in my table has 4 values product_id, user_id, updated_at, rating.

I'd like to create a table to find out how many users changed rating during a given period.

Currently my schema looks like:

```<code>CREATE TABLE IF NOT EXISTS ratings_by_product (
  product_id  int,
  updated_at timestamp,
  user_id int,
  rating int,
  PRIMARY KEY ((product_id  ), updated_at , user_id ))
WITH CLUSTERING ORDER BY (updated_at DESC, user_id ASC);
</code>```

but I couldn't figure out the way to only get the last 2 rows of each user in a given time window.

Any advice on query or changing the schema would be appreciated.

答:
Cassandra requires a query-based approach to table design.  Which means that typically one table will serve one query.  So to serve the query you are talking about (last two updated rows per user) you should build a table specifically designed to serve it:

```<code>CREATE TABLE ratings_by_user_by_time (
  product_id  int,
  updated_at timestamp,
  user_id int,
  rating int,
  PRIMARY KEY ((user_id  ), updated_at, product_id ))
WITH CLUSTERING ORDER BY (updated_at DESC, product_id ASC );
</code>```

Then you will be able to get the last two updated ratings for a user by doing the following:

```<code>SELECT * FROM ratings_by_user_by_time
WHERE user_id = 'Bob' LIMIT 2;
</code>```

Note that you'll need to keep the two ratings tables in-sync yourself, and using a batch statement is a good way to accomplish that.

Body:
Each row in my table has 4 values product_id, user_id, updated_at, rating.

I'd like to create a table to find out how many users changed rating during a given period.

Currently my schema looks like:

CREATE TABLE IF NOT EXISTS ratings_by_product (
  product_id  int,
  updated_at timestamp,
  user_id int,
  rating int,
  PRIMARY KEY ((product_id  ), updated_at , user_id ))
WITH CLUSTERING ORDER BY (updated_at DESC, user_id ASC);

but I couldn't figure out the way to only get the last 2 rows of each user in a given time window.

Any advice on query or changing the schema would be appreciated.

Body:
Cassandra requires a query-based approach to table design.  Which means that typically one table will serve one query.  So to serve the query you are talking about (last two updated rows per user) you should build a table specifically designed to serve it:

CREATE TABLE ratings_by_user_by_time (
  product_id  int,
  updated_at timestamp,
  user_id int,
  rating int,
  PRIMARY KEY ((user_id  ), updated_at, product_id ))
WITH CLUSTERING ORDER BY (updated_at DESC, product_id ASC );

Then you will be able to get the last two updated ratings for a user by doing the following:

SELECT * FROM ratings_by_user_by_time
WHERE user_id = 'Bob' LIMIT 2;

Note that you'll need to keep the two ratings tables in-sync yourself, and using a batch statement is a good way to accomplish that.


问:
Join two tables and show the retrieved information in thymeleaf
I work with Spring MVC and JPA. I want to join the data out of two classes (tables) and show data out of both tables via thymeleaf html.

These are the two classes I want to join:

```<code>@Entity
@Table(name = "package_aud")
public class PackageAudited {

@Column(name="id")
private Integer id;

@Id
@GeneratedValue
@Column(name="rev")
private Integer rev;

@Column(name="revtype")
private Integer revtype;

@OneToOne
@JoinColumn(name = "rev", nullable=true)
private RevisionInfo info;

... more attributes and getters/setters
</code>```

And

```<code>@Entity
@RevisionEntity(RevListener.class)
@Table(name = "revinfo")
public class RevisionInfo {

@Id
@RevisionNumber
@GeneratedValue
@Column(name="rev")
private Integer rev;

@RevisionTimestamp
@Column(name="revtstmp")
private Date revtstmp;

@Column(name="revuser")
private String revuser;

... getters/setters
</code>```

This is the repository where I try to join the tables with a query:

```<code>public interface PackageAuditedRepository extends
CrudRepository<PackageAudited, Long> {

@Query("SELECT p, c FROM PackageAudited p join p.info c WHERE p.id =:id AND p.rev = c.rev")
List<PackageAudited> findById(@Param("id") Integer id);
</code>```

Controller entry for the html template:

```<code>@PostMapping("/listSelectedPackage")
public String selectedPackage(@RequestParam("packageId") Integer packageId, Model model) {
        Iterable<PackageAudited> specificPackageHistory = this.packageAuditedRepository.findById(packageId);
        model.addAttribute("specificPackageHistory", specificPackageHistory);
        return "/package/listSelectedPackage";
}
</code>```

Html template to show the joined data:

```<code><table class ="center">
<thead>
    <tr>
        ...
    </tr>
</thead>
<tbody>
    <tr th:each="package : ${specificPackageHistory}">
        <td th:text="${package.rev}"> </td>
        <td th:text="${package.id}"> </td>
        <td th:text="${package.revuser}"></td>
        <td th:text="${package.revtstmp}"></td>
    </tr>
</tbody>
</table>
</code>```

My code works when I try to show only the data from the PackageAudited class. My query doesn't get me any results and I'm also not sure if ${package.revuser} and ${package.revtstmp} works.

答:
Put only the PackageAudited as the query result:

```<code>@Query("SELECT p FROM PackageAudited p join fetch p.info c WHERE p.id =:id")
List<PackageAudited> findById(@Param("id") Integer id);
</code>```

Then change the way you refer on the page:

```<code><tr th:each="package : ${specificPackageHistory}">
    <td th:text="${package.info.rev}"> </td>
    <td th:text="${package.id}"> </td>
    <td th:text="${package.info.revuser}"></td>
    <td th:text="${package.info.revtstmp}"></td>
</tr>
</code>```

Body:
I work with Spring MVC and JPA. I want to join the data out of two classes (tables) and show data out of both tables via thymeleaf html.

These are the two classes I want to join:

@Entity
@Table(name = "package_aud")
public class PackageAudited {

@Column(name="id")
private Integer id;

@Id
@GeneratedValue
@Column(name="rev")
private Integer rev;

@Column(name="revtype")
private Integer revtype;

@OneToOne
@JoinColumn(name = "rev", nullable=true)
private RevisionInfo info;

... more attributes and getters/setters

And

@Entity
@RevisionEntity(RevListener.class)
@Table(name = "revinfo")
public class RevisionInfo {

@Id
@RevisionNumber
@GeneratedValue
@Column(name="rev")
private Integer rev;

@RevisionTimestamp
@Column(name="revtstmp")
private Date revtstmp;

@Column(name="revuser")
private String revuser;

... getters/setters

This is the repository where I try to join the tables with a query:

public interface PackageAuditedRepository extends
CrudRepository<PackageAudited, Long> {

@Query("SELECT p, c FROM PackageAudited p join p.info c WHERE p.id =:id AND p.rev = c.rev")
List<PackageAudited> findById(@Param("id") Integer id);

Controller entry for the html template:

@PostMapping("/listSelectedPackage")
public String selectedPackage(@RequestParam("packageId") Integer packageId, Model model) {
        Iterable<PackageAudited> specificPackageHistory = this.packageAuditedRepository.findById(packageId);
        model.addAttribute("specificPackageHistory", specificPackageHistory);
        return "/package/listSelectedPackage";
}

Html template to show the joined data:

        ...

My code works when I try to show only the data from the PackageAudited class. My query doesn't get me any results and I'm also not sure if ${package.revuser} and ${package.revtstmp} works.

Body:
Put only the PackageAudited as the query result:

@Query("SELECT p FROM PackageAudited p join fetch p.info c WHERE p.id =:id")
List<PackageAudited> findById(@Param("id") Integer id);

Then change the way you refer on the page:

<tr th:each="package : ${specificPackageHistory}">
    <td th:text="${package.info.rev}"> </td>
    <td th:text="${package.id}"> </td>
    <td th:text="${package.info.revuser}"></td>
    <td th:text="${package.info.revtstmp}"></td>
</tr>


问:
Changing CSS attribute with JQuery
Today I was shown a really simple way to change the font-size  of an element using jQuery.
It looked very similar to the following:

```<code><script  type="text/javascript">
    jQuery(document.body) ({font-size:5em;});
</script>
</code>```

This obviously doesn't work, but I was wondering what's missing? I remember it being just one line of code.

Note: I have tried jQuery(document.body).css({font-size:5em;}); as well, without success.

Thanks.

答:
Quote key names and values in JavaScript object literals, and separate them with commas, don't terminate them with semi-colons.</p>

```<code>{
    "font-size": "5em"
}
</code>```

Title: Changing CSS attribute with JQuery

Body:
Today I was shown a really simple way to change the font-size  of an element using jQuery.
It looked very similar to the following:

This obviously doesn't work, but I was wondering what's missing? I remember it being just one line of code.

Note: I have tried jQuery(document.body).css({font-size:5em;}); as well, without success.

Thanks.

Body:
Quote key names and values in JavaScript object literals, and separate them with commas, don't terminate them with semi-colons.

{
    "font-size": "5em"
}


问:
Materialize icon in Phonegap/Android didn't work
i'm currently using "materialize design" for my app, using phonegap, i followed the steps detailed here: http://google.github.io/material-design-icons/#icon-font-for-the-web "Setup Method 2. Self hosting" but when i run it on diferents android's versions, the icons doesn't show...

I read something like if i have differents android's versions i have to hide some files (the ones who has woff,ttf, woff2 extention).

答:
I had same issue in android 4.X , and solved my problem by using via Google Web Fonts:

```<code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</code>```

add this line to index.html.
you can see more details in Material Icons Guide

Body:
I had same issue in android 4.X , and solved my problem by using via Google Web Fonts:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

add this line to index.html.
you can see more details in Material Icons Guide