问:
AndroidTv and Smartphone in one app / Different launcher
I am writing an application that will serve for tv and smartphone. For now I just want to differentiate the main screen depending on the device.
I have placed fragments, and that are therefore arranged differently according to the device.
But when I launch the application on TV, it is not tvActivity that is launched but the mainActivity

Also, i have 2 launcher in the manifest, one

```<code><action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
</code>```

and the other

```<code><action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
</code>```

Here is my code :

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jamesp.fragmenttest">

    <uses-feature android:name="android.software.leanback"
        android:required="false" />

    <!--Unsupported TV hardware features-->
    <uses-feature android:name="android.hardware.touchscreen"
        android:required="false"/>
    <uses-feature android:name="android.hardware.faketouch"
        android:required="false"/>
    <uses-feature android:name="android.hardware.telephony"
        android:required="false"/>
    <uses-feature android:name="android.hardware.camera"
        android:required="false"/>
    <uses-feature android:name="android.hardware.nfc"
        android:required="false"/>
    <uses-feature android:name="android.hardware.location.gps"
        android:required="false"/>
    <uses-feature android:name="android.hardware.microphone"
        android:required="false"/>
    <uses-feature android:name="android.hardware.sensor"
        android:required="false"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:banner="@mipmap/ic_launcher">

        <activity android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".TvActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.Leanback">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>
</code>```

TvActivity :

```<code>public class TvActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tv);

    }
}
</code>```

MainActivity :

```<code>public class MainActivity extends AppCompatActivity {
    public static final String TAG = "TAG";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE);
         if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) {
            Log.d(TAG, "Running on a TV Device");
            setContentView(R.layout.activity_tv);
        } else {
            setContentView(R.layout.activity_main);
            Log.d(TAG, "Running on a non-TV Device");
        }
    }
}
</code>```

With this test I can differentiate and therefore choose the right layout, but I don't understand why Tv is launching MainActivity.

Thanks

答:
Use this as your manifest. It will work.

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/Theme.Leanback">
    <activity
        android:name=".MainActivity"
        android:banner="@drawable/app_icon_your_company"
        android:icon="@drawable/app_icon_your_company"
        android:label="@string/app_name"
        android:logo="@drawable/app_icon_your_company"
        android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".DetailsActivity" />
    <activity android:name=".PlaybackOverlayActivity" />
    <activity android:name=".BrowseErrorActivity" />
</application>
</code>```

Body:
I am writing an application that will serve for tv and smartphone. For now I just want to differentiate the main screen depending on the device.
I have placed fragments, and that are therefore arranged differently according to the device.
But when I launch the application on TV, it is not tvActivity that is launched but the mainActivity

Also, i have 2 launcher in the manifest, one

<action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />

and the other

<action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />

Here is my code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jamesp.fragmenttest">

    <uses-feature android:name="android.software.leanback"
        android:required="false" />

    <uses-feature android:name="android.hardware.touchscreen"
        android:required="false"/>
    <uses-feature android:name="android.hardware.faketouch"
        android:required="false"/>
    <uses-feature android:name="android.hardware.telephony"
        android:required="false"/>
    <uses-feature android:name="android.hardware.camera"
        android:required="false"/>
    <uses-feature android:name="android.hardware.nfc"
        android:required="false"/>
    <uses-feature android:name="android.hardware.location.gps"
        android:required="false"/>
    <uses-feature android:name="android.hardware.microphone"
        android:required="false"/>
    <uses-feature android:name="android.hardware.sensor"
        android:required="false"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:banner="@mipmap/ic_launcher">

        <activity android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".TvActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.Leanback">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

TvActivity :

public class TvActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tv);

    }
}

MainActivity :

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "TAG";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE);
         if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) {
            Log.d(TAG, "Running on a TV Device");
            setContentView(R.layout.activity_tv);
        } else {
            setContentView(R.layout.activity_main);
            Log.d(TAG, "Running on a non-TV Device");
        }
    }
}

With this test I can differentiate and therefore choose the right layout, but I don't understand why Tv is launching MainActivity.

Thanks

Body:
Use this as your manifest. It will work.

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/Theme.Leanback">
    <activity
        android:name=".MainActivity"
        android:banner="@drawable/app_icon_your_company"
        android:icon="@drawable/app_icon_your_company"
        android:label="@string/app_name"
        android:logo="@drawable/app_icon_your_company"
        android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".DetailsActivity" />
    <activity android:name=".PlaybackOverlayActivity" />
    <activity android:name=".BrowseErrorActivity" />
</application>


来源: stackexchange

问:
How can I create specialized builders for semantic layout in rails?
This is how I'd like to write markup in say index.html.erb

```<code><%= page_for "Super Cool Page" do |p| %>
    <%= p.header do %>
        Ruby is Cool
    <% end %>
    <%= p.body do %>
        Witty discourse on Ruby.
    <% end %>
    <% if page.has_sidebar? %>
        <%= p.sidebar do %>
            <ul><li>Option 1</li></ul>
        <% end %>
    <% end %>
<% end %>
</code>```

Which would output

```<code><div class="page">
    <header><h1>Super Cool Page</h1></header>
    <section>
    Witty discourse on Ruby.
    </section>
</div>
</code>```

and when page.has_sidebar? is true

```<code><div class="page">
    <header><h1>Super Cool Page</h1></header>
    <asside><ul><li>Option 1</li></ul></asside>
    <section>
    Witty discourse on Ruby.
    </section>
</div>
</code>```

I've taken a look at the FormHelper class in rails for guidance, but it seems like I'd have to duplicate a lot of work which I'm trying to avoid. I'm really just trying to figure out where to hang the classes/modules/methods in the framework and whit kind of object |p| should be.

My first inclination was to create a PageBuilder class that implements header, body and sidebar methods. But I got stuck on the rendering pipeline to get everything output just right.

Is there a gem that already provides this type of semantic generation? If not I'd love any insight on how to set this up.

答:
Not exactly what you are asking for, but have you tried looking at Haml?

It has a much more succinct syntax so the example you suggested might be written as:

```<code>.page
  %header
    %h1 Super Cool Page
  %asside
    %ul
      %li Option 1
  %section
    Witty Discourse on Ruby
</code>```

As you can see structure in Haml is provided using indentation which helps with reading
Haml source too.

If on the other hand you are attempting this as a learning exercise on how to build a template parser yourself then maybe look into the source of Haml or one of the other templating engines.

ContentLicense: CC BY-SA 2.5

Body:
This is how I'd like to write markup in say index.html.erb

<%= page_for "Super Cool Page" do |p| %>
    <%= p.header do %>
        Ruby is Cool
    <% end %>
    <%= p.body do %>
        Witty discourse on Ruby.
    <% end %>
    <% if page.has_sidebar? %>
        <%= p.sidebar do %>

Option 1

        <% end %>
    <% end %>
<% end %>

Which would output

Super Cool Page

    Witty discourse on Ruby.

and when page.has_sidebar? is true

Super Cool Page

    <asside>

Option 1

</asside>

    Witty discourse on Ruby.

I've taken a look at the FormHelper class in rails for guidance, but it seems like I'd have to duplicate a lot of work which I'm trying to avoid. I'm really just trying to figure out where to hang the classes/modules/methods in the framework and whit kind of object |p| should be.

My first inclination was to create a PageBuilder class that implements header, body and sidebar methods. But I got stuck on the rendering pipeline to get everything output just right.

Is there a gem that already provides this type of semantic generation? If not I'd love any insight on how to set this up.

Body:
Not exactly what you are asking for, but have you tried looking at Haml?

It has a much more succinct syntax so the example you suggested might be written as:

.page
  %header
    %h1 Super Cool Page
  %asside
    %ul
      %li Option 1
  %section
    Witty Discourse on Ruby

As you can see structure in Haml is provided using indentation which helps with reading
Haml source too.

If on the other hand you are attempting this as a learning exercise on how to build a template parser yourself then maybe look into the source of Haml or one of the other templating engines.


问:
Uninstalling Systrack from CMD
So I'm trying to remotely uninstall the application SysTrack using:

```<code> wmic product where "description='Systems Management Agent' " uninstall
</code>```

but for some reason it can't find the product. Doing a

```<code> product get name
</code>```

from the wmic:root console, I don't see it listed. I'm wondering why the wmic can't get all the list of installed programs? It shows up on programs and features list, but now when I run that wmi command. I am a domain admin so the credentials should be a problem (the folder in the Program Files(x86) folder for SysTrack does have a lock on it though, but I can access)

Side note: I really wish there was a way to remotely just view that programs and features menu. Would be incredibly handy for the tasks I've been doing lately.

答:
try;

wmic product where "name like 'Systems Management Agent'" call uninstall /nointeractive

it should work.

ContentLicense: CC BY-SA 3.0

Title: Uninstalling Systrack from CMD

Body:
So I'm trying to remotely uninstall the application SysTrack using:

 wmic product where "description='Systems Management Agent' " uninstall

but for some reason it can't find the product. Doing a

 product get name

from the wmic:root console, I don't see it listed. I'm wondering why the wmic can't get all the list of installed programs? It shows up on programs and features list, but now when I run that wmi command. I am a domain admin so the credentials should be a problem (the folder in the Program Files(x86) folder for SysTrack does have a lock on it though, but I can access)

Side note: I really wish there was a way to remotely just view that programs and features menu. Would be incredibly handy for the tasks I've been doing lately.


问:
Java new time API compiles and break at run time
I am trying to use consistently the Java 8 date time API, I am looking for explications behind this behaviour :

```<code>Instant.from(LocalDateTime.of(2017,01,01,0,0,0,0))
</code>```

Compiles just fine but yields to :

```<code>Exception in thread "main" java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: 2017-01-01T00:00 of type java.time.LocalDateTime
</code>```

My question is :if these types are not compatible why did the API let me code that and compile it without screaming ?

答:
It compiles fine because Instant.from(TemporalAccessor temporal) accepts a TemporalAccessor and LocalDateTime is a subclass from TemporalAccessor.

At runtime you get an exception because to create a Instant the TemporalAccessor must have the fields INSTANT_SECONDS and NANO_OF_SECOND, but LocalDateTime doesn't provide INSTANT_SECONDS only NANO_OF_SECOND.

To create an Instant from a LocalDateTime better use (for example):

```<code>LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zoneId).toInstant();
</code>```

or

```<code>LocalDateTime localDateTime = LocalDateTime.now();
Instant instant = localDateTime.toInstant(ZoneOffset.ofHours(0));
</code>```

Body:
I am trying to use consistently the Java 8 date time API, I am looking for explications behind this behaviour :

Instant.from(LocalDateTime.of(2017,01,01,0,0,0,0))

Compiles just fine but yields to :

Exception in thread "main" java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: 2017-01-01T00:00 of type java.time.LocalDateTime

My question is :if these types are not compatible why did the API let me code that and compile it without screaming ?

Body:
It compiles fine because Instant.from(TemporalAccessor temporal) accepts a TemporalAccessor and LocalDateTime is a subclass from TemporalAccessor.

At runtime you get an exception because to create a Instant the TemporalAccessor must have the fields INSTANT_SECONDS and NANO_OF_SECOND, but LocalDateTime doesn't provide INSTANT_SECONDS only NANO_OF_SECOND.

To create an Instant from a LocalDateTime better use (for example):

LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zoneId).toInstant();

or

LocalDateTime localDateTime = LocalDateTime.now();
Instant instant = localDateTime.toInstant(ZoneOffset.ofHours(0));


问:
VB script delete files creation date + exception
i want to use a VB script to Delete files and folders older then 60 days.

How can i exclude specific folders in my script?

```<code>' Global FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Start at the root
DoFolder "H:\Werk\Testfolder"

' Recursive function
Sub DoFolder(strFolder)

With objFSO.GetFolder(strFolder)

    For Each objFile In .Files
        If objFile.DateCreated < Date - 60 Then objFile.Delete
    Next

    For Each objFolder In .SubFolders
        DoFolder objFolder.Path
    Next

    ' Checked every file and subfolder. If this folder is empty, remove it...
   If .Files.Count = 0 Then If .SubFolders.Count = 0 Then .Delete

End With

End Sub
</code>```

I want to exclude the following:

H:\Werk\Testfolder\Favorieten
and

H:\Werk\Testfolder\OneNote-notitieblokken

How can i  do this?

答:
```<code>For Each objFolder In .SubFolders
    If objfolder.path <> "c:\whatever\whatever.ext" then
        DoFolder objFolder.Path
    End If
Next
</code>```

Is how you do it.

Body:
i want to use a VB script to Delete files and folders older then 60 days.

How can i exclude specific folders in my script?

' Global FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Start at the root
DoFolder "H:\Werk\Testfolder"

' Recursive function
Sub DoFolder(strFolder)

With objFSO.GetFolder(strFolder)

    For Each objFile In .Files
        If objFile.DateCreated < Date - 60 Then objFile.Delete
    Next

    For Each objFolder In .SubFolders
        DoFolder objFolder.Path
    Next

    ' Checked every file and subfolder. If this folder is empty, remove it...
   If .Files.Count = 0 Then If .SubFolders.Count = 0 Then .Delete

End With

End Sub

I want to exclude the following:

H:\Werk\Testfolder\Favorieten
and

H:\Werk\Testfolder\OneNote-notitieblokken

How can i  do this?

Body:
For Each objFolder In .SubFolders
    If objfolder.path <> "c:\whatever\whatever.ext" then
        DoFolder objFolder.Path
    End If
Next

Is how you do it.


问:
Container crashes after one hour due to OOM
i'm running spark using docker on DC/OS. When i submit the spark jobs, using the following memory configurations

Driver 2 Gb

Executor 2 Gb

Number of executors are 3.

The spark submit works fine, after 1 hour the docker container(worker container) crashes due to OOM (exit code 137). but my spark logs shows that 1Gb+ of memory is available.

The strange thing is the same jar which is running in the container , runs normally for almost 20+ hours in the standalone mode.

Is it the normal behaviour of the Spark contianers, or is there Something im doing wrong.Or are there any extra configuraton do I need to use for the docker container.

Thanks

答:
It looks like I have a similar issue. Have you looked at the cache/buffer memory usage on the OS?

Using the command below you can get some info on the type of memory usage on the OS:

```<code>free -h
</code>```

In my case the buffer / cache kept on growing until there was no more memory available in the Container. In my case the VM was a CentOS machine running on AWS and it crashed entirely when this happened.

Body:
It looks like I have a similar issue. Have you looked at the cache/buffer memory usage on the OS?

Using the command below you can get some info on the type of memory usage on the OS:

free -h

In my case the buffer / cache kept on growing until there was no more memory available in the Container. In my case the VM was a CentOS machine running on AWS and it crashed entirely when this happened.


问:
Ember JS - Add select box option to URL string via Query Param
I have a Select Box in my form and I would like to be able to use the selection as a Query Param so that I can refresh a model based on its selection. The Select Box is from this ember add-on.

```<code>{{#select-box/native value=sb name=module on-select=(action 'selected') class="form-control" as |sb| }}
          {{sb.option value='Select a Module:'}} {{sb.option value='Option1'}} {{sb.option value="Option2" }} {{sb.option value="Option3" }} {{sb.option value="option4" }}
        {{/select-box/native}}
</code>```

The 'selected' action simply adds the option to a variable so that I can use it later in a switch statement:

```<code>selected(x) {
  module = x
},
</code>```

I'd like to have the selection (or a representation of the selection) in my URL string but I can'tt work out how. I have other inputs building into the URL string but none of them are select boxes.

I have a 'module' item in the QueryParams on my route but it doesn't do anything, I suspect I'll have to do something in the 'selected' action but I'm not sure what.

答:
I haven't used the add-on you mentioned, but here is how you can do it using normal <select>, so just bridge the gap between normal <select> and the add-on you are using in terms of making sure that the status variable in the example below changes depending on what you select in your select box - Ember will do the rest.

Here's a configuration that works if you want to filter a list of users based on the status value you select from a dropdown:

```<code>// app/models/user.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    status: DS.attr('string')
});

// app/templates/users.hbs

<select onchange={{action (mut status) value="target.value"}}>
    <option value="" selected={{eq status ''}}>- All users -</option>
    <option value="active" selected={{eq status 'active'}}>Active</option>
    <option value="inactive" selected={{eq status 'inactive'}}>Inactive</option>
</select>

<ul>
    {{#each model as |user|}}
        <li>{{user.name}}, {{user.status}}</li>
    {{/each}}
</ul>

// app/controllers/users.js

import Controller from '@ember/controller';

export default Controller.extend({
    queryParams: ['status'],
    status: ''
});

// app/routes/users.js

import Route from '@ember/routing/route';

export default Route.extend({
    queryParams: {
        status: {
            refreshModel: true
        }
    },

    model(params) {
        var options = {};
        if (params.status) {
            options.status = params.status;
        }
        return this.get('store').query('user', options);
    }
});
</code>```

How does it work?

In the controller you define a property status, which you also indicate to be a query parameter (in the URL). Then in the route, you also define status to be a query parameter which refreshes the model. In the model() hook you extract the parameter and use it for Ember Data Store's query() to fetch the model every time you change the value of status. Your route URL will have ?status=... appended to it, and your server will receive a request similar to example.com/api/users?status=.... Of course, you can configure options in the model() hook differently to format the request URL for the server, but I kept it like this for the sake of simplicity.

The only thing that might be confusing is the template file. Apart from the {{eq status '...'}} syntax, which is a truth helper that simply determines whether the option is selected, the rest of the selecting simply aims to change the status variable (explained in depth here).

Body:
I have a Select Box in my form and I would like to be able to use the selection as a Query Param so that I can refresh a model based on its selection. The Select Box is from this ember add-on.

{{#select-box/native value=sb name=module on-select=(action 'selected') class="form-control" as |sb| }}
          {{sb.option value='Select a Module:'}} {{sb.option value='Option1'}} {{sb.option value="Option2" }} {{sb.option value="Option3" }} {{sb.option value="option4" }}
        {{/select-box/native}}

The 'selected' action simply adds the option to a variable so that I can use it later in a switch statement:

selected(x) {
  module = x
},

I'd like to have the selection (or a representation of the selection) in my URL string but I can'tt work out how. I have other inputs building into the URL string but none of them are select boxes.

I have a 'module' item in the QueryParams on my route but it doesn't do anything, I suspect I'll have to do something in the 'selected' action but I'm not sure what.

Body:
I haven't used the add-on you mentioned, but here is how you can do it using normal <select>, so just bridge the gap between normal <select> and the add-on you are using in terms of making sure that the status variable in the example below changes depending on what you select in your select box - Ember will do the rest.

Here's a configuration that works if you want to filter a list of users based on the status value you select from a dropdown:

// app/models/user.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    status: DS.attr('string')
});

// app/templates/users.hbs

<select onchange={{action (mut status) value="target.value"}}>
    <option value="" selected={{eq status ''}}>- All users -</option>
    <option value="active" selected={{eq status 'active'}}>Active</option>
    <option value="inactive" selected={{eq status 'inactive'}}>Inactive</option>
</select>

<ul>
    {{#each model as |user|}}
        <li>{{user.name}}, {{user.status}}</li>
    {{/each}}
</ul>

// app/controllers/users.js

import Controller from '@ember/controller';

export default Controller.extend({
    queryParams: ['status'],
    status: ''
});

// app/routes/users.js

import Route from '@ember/routing/route';

export default Route.extend({
    queryParams: {
        status: {
            refreshModel: true
        }
    },

    model(params) {
        var options = {};
        if (params.status) {
            options.status = params.status;
        }
        return this.get('store').query('user', options);
    }
});

How does it work?

In the controller you define a property status, which you also indicate to be a query parameter (in the URL). Then in the route, you also define status to be a query parameter which refreshes the model. In the model() hook you extract the parameter and use it for Ember Data Store's query() to fetch the model every time you change the value of status. Your route URL will have ?status=... appended to it, and your server will receive a request similar to example.com/api/users?status=.... Of course, you can configure options in the model() hook differently to format the request URL for the server, but I kept it like this for the sake of simplicity.

The only thing that might be confusing is the template file. Apart from the {{eq status '...'}} syntax, which is a truth helper that simply determines whether the option is selected, the rest of the selecting simply aims to change the status variable (explained in depth here).


问:
Executing query with condition in java (response = Illegal operation on empty result set)
I have a problem, I want to execute query based on the condition. The concept is if the result is null, then execute another query. But when I try it, the result is an error

Illegal operation on empty result set`

My code:

```<code>String strSQL = "SELECT * FROM user WHERE userid=? AND password=? LIMIT 1;";

PreparedStatement pst=null;
pst = con.prepareStatement(strSQL);
pst.setString(1, userid);
pst.setString(2, password);

rs = pst.executeQuery();

if(rs.getString(1) == null && rs.getString(2) == null) {
   String strSQL = "SELECT userid FROM user WHERE userid=?;";
}

if(rs.next())
{
    yoyo yo = new yoyo();
    yo.SetUserid(rs.getString(1));
    yo.SetUsername(rs.getString(2));
    yo.SetPosisi(rs.getString(5));
    lstLogin = yo;
}
</code>```

答:
At this line you will get the result set

```<code>rs = pst.executeQuery();
</code>```

Now we want know that the rs is not null and also not empty. So we will give condition like this

```<code>if (rs != null && !rs.isBeforeFirst() ) {
    String strSQL = "SELECT userid FROM user WHERE userid=?;";
}
</code>```

Check this link for reference Check result set is empty or not

In your code it is not checking whether the ResultSet is empty or not.

Body:
I have a problem, I want to execute query based on the condition. The concept is if the result is null, then execute another query. But when I try it, the result is an error

Illegal operation on empty result set`

My code:

String strSQL = "SELECT * FROM user WHERE userid=? AND password=? LIMIT 1;";

PreparedStatement pst=null;
pst = con.prepareStatement(strSQL);
pst.setString(1, userid);
pst.setString(2, password);

rs = pst.executeQuery();

if(rs.getString(1) == null && rs.getString(2) == null) {
   String strSQL = "SELECT userid FROM user WHERE userid=?;";
}

if(rs.next())
{
    yoyo yo = new yoyo();
    yo.SetUserid(rs.getString(1));
    yo.SetUsername(rs.getString(2));
    yo.SetPosisi(rs.getString(5));
    lstLogin = yo;
}

Body:
At this line you will get the result set

rs = pst.executeQuery();

Now we want know that the rs is not null and also not empty. So we will give condition like this

if (rs != null && !rs.isBeforeFirst() ) {
    String strSQL = "SELECT userid FROM user WHERE userid=?;";
}

Check this link for reference Check result set is empty or not

In your code it is not checking whether the ResultSet is empty or not.


问:
scaffolding viewmodels based on database tables
Is there anything that would aid us in designing/scaffolding View models from SQL Server database tables but would result in very lean classes? I know something like that exists for Rails, maybe there's something similar in ASP.NET MVC?

I like what EF wizard creates but it's too heavy - too much attributes, constraints, events and everything is attached to the entities so you can't actually use them as View models (actually you can but it quickly becomes a pain).

答:
I think you could use a POCO generator for your EF4 model instead of the default one. This is a link explaining how. LINK
I hope you can adapt it to fill your needs.

A POCO Class(Plain Old CLR Objects) is by definition a lightweight class, that is (maybe) what you're looking for.


问:
How to move nested divs containers to the left if content increases
I have a div that has a dropdown menu and a label with a button on it.like follows

```<code><div class="container ">
  <div id="User">
    <div id="BtnUser">
      <div id="dropMe">
        <div class="dropdown">
          <a onclick="UserdropDownDetails()">
            <div class="triangle"></div>
          </a>
          <div id="myDropdown" class="dropdown-content ">
            <ul>
              <span class="dropDownMenu">hello <span class="ColonGreen">:</span> hi</span>
              <span class="dropDownMenu Availability">Availablility <span class="ColonGreen">:</span></span>
              <span class="dropDownMenu">helloooo <span class="ColonGreen">:</span></span>

            </ul>

          </div>
        </div>
      </div>
      <div id=UserDetails><label>tessssttt tessssssssssst</label></div>
      <div id="logoutDiv"><button id="btnLogout" name="btnLogout">Log out</button></div>
    </div>
  </div>
</div>
</code>```

https://jsfiddle.net/g9tdcrxh/2/

The problem I am having is when the text tessssst grows it moves to the left which I want.but it's blocking the triangle dropdown. How do I get the BtnUser div to expand and the triangle to move left when the text grows?

This is what it's doing

I need the position of the triangle to stay where it is, only when the text grows then can it move. The logout button should also stay where it is.

I want it to grow like this

What am I doing wrong? Your guidance will be highly appreciated, can you do it in jQuery?

答:
I made a lot of changes. If you right-click elements in your browser, you should be able to select "inspect element" and hovering them in the list that appears, you can see their sizes/margins/paddings..

```<code><div class="container">
    <button id="btnLogout" name="btnLogout">Log out</button>
    <div class="user">
        <div class="userDetails">teshrthrtrthrthtrhtrhabcdefghijklteshrthrtrthrthtrhtrhabcdefghijklteshrthrtrthrthtrhtrhabcdefghijklteshrthrtrthrthtrhtrhabcdefghijkl</div>
        <div class="dropMe">
            <div class="dropdown">
                <a onclick="UserdropDownDetails()">
                    <div class="triangle"></div>
                </a>
                <div class="myDropdown" class="dropdown-content ">
                    <ul>
                        <span class="dropDownMenu">hello <span class="ColonGreen">:</span> hi</span>
                        <span class="dropDownMenu Availability">Availablility <span class="ColonGreen">:</span></span>
                        <span class="dropDownMenu">helloooo <span class="ColonGreen">:</span></span>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

body {
    margin: 5px;
}

.container {
    overflow: hidden;
}

.user {
    overflow: hidden;

    margin-right: 95px;

    min-width: 500px;
    max-width: calc(100% - 100px);
    float: right;

    height: 30px;
    background-color: rgba(0,0,0,.75);
    text-align: center;
    color: #fff !important;
    cursor: pointer;
    right: 0;
    border-bottom-left-radius: .5em;
    display: block;
    box-shadow: inset 0 0 0 1px rgba(0,0,0,.08);
    padding-top: 0;
    border-radius: 1px;
    background-color: #1c1c1c;
    box-shadow: inset 0 10px 20px #333;
}

#btnLogout {
    width: 90px;
    background: linear-gradient(to bottom, #74be43 0%,#3a953e 64%,#3a953e 64%,#0f773b 100%);
    border: 1px solid #BFE1A7;
    box-shadow: none;
    border-radius: 4px;
    color: #FFF;
    border-left: 1px solid #ECF5EC;
    border-right: 1px solid #ECF5EC;
    line-height: 20px;

    position: absolute;
    top: 9px;
    right: 5px;
}

.dropMe {
    width: 10px;
    /*margin-top: -26px;*/
    /*margin-left: 110px;*/
    float:right;
    margin-left:10px;
}

.userDetails {
    /*margin-top: -20px;*/
    /*margin-left: -220px;*/
    text-transform: uppercase;
    font-size: 10px;
    color: #cecece;

    text-align: left;
    height: 22px;
    line-height: 22px;
    float:right;
    min-width: 376px; /* 600px - 110px (left margin) - 20px (arrow) - 90px (button) - 4px (button margin) */
    max-width: calc(100% - 20px); /* 20px (arrow) */
    overflow: hidden;
}
</code>```

https://jsfiddle.net/g9tdcrxh/9/

Body:
I have a div that has a dropdown menu and a label with a button on it.like follows

              hello : hi
              Availablility :
              helloooo :

tessssttt tessssssssssst

<button id="btnLogout" name="btnLogout">Log out</button>

https://jsfiddle.net/g9tdcrxh/2/

The problem I am having is when the text tessssst grows it moves to the left which I want.but it's blocking the triangle dropdown. How do I get the BtnUser div to expand and the triangle to move left when the text grows?

This is what it's doing

I need the position of the triangle to stay where it is, only when the text grows then can it move. The logout button should also stay where it is.

I want it to grow like this

What am I doing wrong? Your guidance will be highly appreciated, can you do it in jQuery?

Body:
I made a lot of changes. If you right-click elements in your browser, you should be able to select "inspect element" and hovering them in the list that appears, you can see their sizes/margins/paddings..

<div class="container">
    <button id="btnLogout" name="btnLogout">Log out</button>
    <div class="user">
        <div class="userDetails">teshrthrtrthrthtrhtrhabcdefghijklteshrthrtrthrthtrhtrhabcdefghijklteshrthrtrthrthtrhtrhabcdefghijklteshrthrtrthrthtrhtrhabcdefghijkl</div>
        <div class="dropMe">
            <div class="dropdown">
                <a onclick="UserdropDownDetails()">
                    <div class="triangle"></div>
                </a>
                <div class="myDropdown" class="dropdown-content ">
                    <ul>
                        <span class="dropDownMenu">hello <span class="ColonGreen">:</span>&nbsp;hi</span>
                        <span class="dropDownMenu Availability">Availablility <span class="ColonGreen">:</span></span>
                        <span class="dropDownMenu">helloooo <span class="ColonGreen">:</span></span>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

body {
    margin: 5px;
}

.container {
    overflow: hidden;
}

.user {
    overflow: hidden;

    margin-right: 95px;

    min-width: 500px;
    max-width: calc(100% - 100px);
    float: right;

    height: 30px;
    background-color: rgba(0,0,0,.75);
    text-align: center;
    color: #fff !important;
    cursor: pointer;
    right: 0;
    border-bottom-left-radius: .5em;
    display: block;
    box-shadow: inset 0 0 0 1px rgba(0,0,0,.08);
    padding-top: 0;
    border-radius: 1px;
    background-color: #1c1c1c;
    box-shadow: inset 0 10px 20px #333;
}

#btnLogout {
    width: 90px;
    background: linear-gradient(to bottom, #74be43 0%,#3a953e 64%,#3a953e 64%,#0f773b 100%);
    border: 1px solid #BFE1A7;
    box-shadow: none;
    border-radius: 4px;
    color: #FFF;
    border-left: 1px solid #ECF5EC;
    border-right: 1px solid #ECF5EC;
    line-height: 20px;

    position: absolute;
    top: 9px;
    right: 5px;
}

.dropMe {
    width: 10px;
    /*margin-top: -26px;*/
    /*margin-left: 110px;*/
    float:right;
    margin-left:10px;
}

.userDetails {
    /*margin-top: -20px;*/
    /*margin-left: -220px;*/
    text-transform: uppercase;
    font-size: 10px;
    color: #cecece;

    text-align: left;
    height: 22px;
    line-height: 22px;
    float:right;
    min-width: 376px; /* 600px - 110px (left margin) - 20px (arrow) - 90px (button) - 4px (button margin) */
    max-width: calc(100% - 20px); /* 20px (arrow) */
    overflow: hidden;
}

https://jsfiddle.net/g9tdcrxh/9/


问:
MVC how to change dropdownlist item names
Been googling for a while, but I can't seem to get any closer.

I'm using MVC with an EF Database structure.

I want the dropdownlist items in the View to show up with different names than what they come up with.

Right now, the lambda query returns a list().
I want each item to get a string name depending on their current name.  Eventually, the selected field needs to be used in another lambda as the Byte that it was.

Edit

```<code>//view
<p>
@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
    @Html.DropDownList("vbType", (SelectList)ViewBag.Type, "" , new { onchange = "form.submit();" })

....

//controller
var typeLst = new List<byte>();
var typeQry = from t in db.model1
       orderby t.TYPE
       select t.TYPE;
typeLst.AddRange(typeQry.Distinct());
ViewBag.vbType = new SelectList(typeLst);

....
</code>```

Thanks in advance.

答:
You need to make use of dropdownlist's Value property. Make your list a type of SelectListItem.

Assign Text= [Your Required Text] and Value = [Current Name]

Body:
Been googling for a while, but I can't seem to get any closer.

I'm using MVC with an EF Database structure.

I want the dropdownlist items in the View to show up with different names than what they come up with.

Right now, the lambda query returns a list().
I want each item to get a string name depending on their current name.  Eventually, the selected field needs to be used in another lambda as the Byte that it was.

Edit

//view

@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{

    @Html.DropDownList("vbType", (SelectList)ViewBag.Type, "" , new { onchange = "form.submit();" })

....

//controller
var typeLst = new List<byte>();
var typeQry = from t in db.model1
       orderby t.TYPE
       select t.TYPE;
typeLst.AddRange(typeQry.Distinct());
ViewBag.vbType = new SelectList(typeLst);

....

Thanks in advance.


问:
how to parcel Object type in Parcelable class in Java
How this class implements parcelable right. i cant do parcel Object type.String, Double,Integer,.. variables types sets to the Object type.</p>

```<code>public class MyClass implements Parcelable {
    public String Name;
    public Object Value; //variables type to set

    protected MyClass(Parcel in) {
        Name = in.readString();
        //Value = in.?
    }

    public static final Creator<MyClass> CREATOR = new Creator<MyClass>() {
        @Override
        public MyClass createFromParcel(Parcel in) {
            return new MyClass(in);
        }

        @Override
        public MyClass[] newArray(int size) {
            return new MyClass[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(Name);
        //dest.
    }
}
</code>```

答:
The Parcel documentation is quite explicit about what you can do, here is some idea.

You have the methods writeParcelable to do that, but you can't parcel an Object because Object doesn't implement Parcelable.

You need to define a class that implements Parcelable for your value.

```<code>public class MyClass implements Parcelable {
    public String name;
    public ParcelableValue value; //variables type to set
    ...

}

public class ParcelableValue implements Parcelable {
    ...
}
</code>```

For a complete implementation, see Write a sub class of Parcelable to another Parcel

You also have writeValue but this still have some condition :

Any object that implements Serializable (but see writeSerializable(Serializable) for caveats). Note that all of the previous types have relatively efficient implementations for writing to a Parcel; having to rely on the generic serialization approach is much less efficient and should be avoided whenever possible.*

For the complete list, see the doc of the method

Body:
How this class implements parcelable right. i cant do parcel Object type.String, Double,Integer,.. variables types sets to the Object type.

public class MyClass implements Parcelable {
    public String Name;
    public Object Value; //variables type to set

    protected MyClass(Parcel in) {
        Name = in.readString();
        //Value = in.?
    }

    public static final Creator<MyClass> CREATOR = new Creator<MyClass>() {
        @Override
        public MyClass createFromParcel(Parcel in) {
            return new MyClass(in);
        }

        @Override
        public MyClass[] newArray(int size) {
            return new MyClass[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(Name);
        //dest.
    }
}

Body:
The Parcel documentation is quite explicit about what you can do, here is some idea.

You have the methods writeParcelable to do that, but you can't parcel an Object because Object doesn't implement Parcelable.

You need to define a class that implements Parcelable for your value.

public class MyClass implements Parcelable {
    public String name;
    public ParcelableValue value; //variables type to set
    ...

}

public class ParcelableValue implements Parcelable {
    ...
}

For a complete implementation, see Write a sub class of Parcelable to another Parcel

You also have writeValue but this still have some condition :

Any object that implements Serializable (but see writeSerializable(Serializable) for caveats). Note that all of the previous types have relatively efficient implementations for writing to a Parcel; having to rely on the generic serialization approach is much less efficient and should be avoided whenever possible.*

For the complete list, see the doc of the method


问:
Is it better to have lots of Azure Functions in one project or many?
I have written eight different Azure Functions in one .NET project.  They work great but I was wondering if it makes more sense from a performance optimization standpoint to put each function in it's own project.  Any ideas in this would regard would be most appreciated... </p>

答:
I don't see any reason why it could have an impact on performance. It could be a difference when you put them all in the same appservice plan.
A reason to put them in separate projects can be that you want to deploy and evolve them independently. We try to make them as independent as possible putting them in seperate projects or even in a different git repo with separate pipelines will make it easier to evolve them independent.</p>


问:
Condition on a map key in update using datastax cassandra driver
I want to create a query like

UPDATE foo set map_clm['bar'] = 'biz' where id = 7 if map_clm['boo'] = 'bang';

using QueryBuilder of Datastax's java driver for cassandra. I can create Assignment using something like QueryBuilder.put("map_clm", "bar", "biz"), but I am stuck in  creating a clause for IF Condition map_clm['boo'] = 'bang'. Is there anyway to do that ?

答: IMHO, most straightforward way will be to use raw function and put your if condition into it. But you need to be careful with escaping of arguments if you aren't using bindings.


问:
Browser.inputBox is not working in doPost in app scripting for spreadsheets
```<code>Browser.inputBox('Enter your name', Browser.Buttons.OK_CANCEL)
</code>```

Above Code is working fine in sendSurvey function.

But I am trying to use it in doPost method in app scripting for spreadSheets. It is not working there.

Can anyone tell me why it is not woking?

but I am not getting my input box.

答:
See the answer here: browserbox-sheets

You can use the input box in the context of a Google Spreadsheet, or a custom function within the Google Apps UI. When you're making a POST() request, that is invalid since the context is serving the request directly, with a text or html output. You can't have a inputbox popup with that.

Body:
Browser.inputBox('Enter your name', Browser.Buttons.OK_CANCEL)

Above Code is working fine in sendSurvey function.

But I am trying to use it in doPost method in app scripting for spreadSheets. It is not working there.

Can anyone tell me why it is not woking?

but I am not getting my input box.


问:
Angular2 Firebase : Response for preflight has invalid HTTP status code 405
I am new to Angular2. While trying to get the values from Firebase API , I am getting below Error:

```<code>OPTIONS https://udemy-ng-http.firebaseio.com/data 405 (Method Not Allowed)

Failed to load https://udemy-ng-http.firebaseio.com/data: Response for preflight has

invalid HTTP status code 405
</code>```

But I am able to post the data to Firebase API Endpoint.

I also tried other solutions provided on this community but it did not help. Below is my code.

Code:

```<code> getServer(){
    let headers = new Headers();
    headers.append('Access-Control-Allow-Headers', 'Content-Type');
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Content-Type', 'application/json') ;
    headers.append('charset','UTF-8');
    headers.append('Accept','application/json');
    let options = new RequestOptions({ headers: headers });

    return this.http.get('https://udemy-ng-http.firebaseio.com/data',options)
        .map(
            (response: Response) => {
                const data = response.json();
                for (const server of data) {
                  server.name = 'FETCHED_' + server.name;
                }
                return data;
            }
        )
        .catch(
            (error: Response) => {
              return Observable.throw('Something went wrong');
            }
        );
}
</code>```

答:
Try removing headers.append('Access-Control-Allow-Origin', '*');

There are two sample functions provided by the Firebase team that demonstrate the use of CORS:

Time server with date formatting

HTTPS endpoint requiring Authentication

The second sample uses a different way of working with cors than you're currently using.

Also, consider importing like this, as shown in the samples:

```<code>const cors = require('cors')({origin: true});
</code>```

Body:
I am new to Angular2. While trying to get the values from Firebase API , I am getting below Error:

OPTIONS https://udemy-ng-http.firebaseio.com/data 405 (Method Not Allowed)

Failed to load https://udemy-ng-http.firebaseio.com/data: Response for preflight has

invalid HTTP status code 405

But I am able to post the data to Firebase API Endpoint.

I also tried other solutions provided on this community but it did not help. Below is my code.

Code:

 getServer(){
    let headers = new Headers();
    headers.append('Access-Control-Allow-Headers', 'Content-Type');
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Content-Type', 'application/json') ;
    headers.append('charset','UTF-8');
    headers.append('Accept','application/json');
    let options = new RequestOptions({ headers: headers });

    return this.http.get('https://udemy-ng-http.firebaseio.com/data',options)
        .map(
            (response: Response) => {
                const data = response.json();
                for (const server of data) {
                  server.name = 'FETCHED_' + server.name;
                }
                return data;
            }
        )
        .catch(
            (error: Response) => {
              return Observable.throw('Something went wrong');
            }
        );
}

Body:
Try removing headers.append('Access-Control-Allow-Origin', '*');

There are two sample functions provided by the Firebase team that demonstrate the use of CORS:

Time server with date formatting

HTTPS endpoint requiring Authentication

The second sample uses a different way of working with cors than you're currently using.

Also, consider importing like this, as shown in the samples:

const cors = require('cors')({origin: true});


问:
Recommended architechture for multiple wordpress installations with a shared database
I'd like to create a several Wordpress websites with a unique relationship between them:

- There will be one main WP site - main.com with several categories for posts.

- There will be several WP sites installed under subdomains: daughter1.main.com , daughter2.main.com

- The daughter sites need to pull posts from several categories (not all of them, and each might pull from different categories) of the main site, but they still need to have independent posts on categories of their own (unique for them).

How would you suggest to approach that?

Please note that the daughter sites will be used as a sub domain of different sites (e.g daughter1.main.com will actually be a subdomain of random.com (somedomain.random.com)). But this can probably be done via simple DNS mapping.

Thanks,

Roy

答:
Alright, I believe I solved this by myself. Here is how I'm going to approach this:

Setup WP 3.0 with Netword/MultiSite configuration

Setup the daughter sites as subdomains (part of the network)

Add FeedWordPress plugin to daughter sites

Add the RSS feeds of the relevant categories in the FeedWordPress settings

Install WordPress MU Domain Mapping on the daughter sites and map the sites properly

I hope others will find this useful.


问:
VisualStudio | summary with keyword 'null'
I have a property which can be null. I want to documentate this in the summary and here is my problem.

cref

```<code>/// <summary>
/// Can be <see cref="null"/>.
/// </summary>
public object FooProperty;
</code>```

ReSharper says, there is a Syntax Error, but the highlighting is working as expected!

cref nested

```<code>/// <summary>
/// Can be <see><cref>null</cref></see>.
/// </summary>
public object FooProperty;
</code>```

When formating it to nested, the highligghting is not working anymore.

langword

```<code>/// <summary>
/// Can be <see langword="null"/>.
/// </summary>
public object FooProperty;
</code>```

langword is working, but there is no intelliSense in VisualStudio.

Can someone please tell me what is the right way to documentate these keywords and IntelliSense support would be nice!

solution approach

VisualStudio | CodeSnippet for inside comment/summary block (IntelliSense)

答:
The langword is the way to go. You are right, there's no Intellisense support for this. It's probably because it's not officially recommended XML comment tag attribute. But the tools that can generate documentation from your comments, e.g. Sandcastle Help File Builder or VSdocman (disclaimer, I'm the developer of VSdocman) will recognize this syntax and will generate a special text. For example, VSdocman generates:

null reference (Nothing in Visual Basic)

The same applies to other reserved words, such as true, abstract, etc.

While Intellisense will not help you, VSdocman has a WYSIWYG comment editor which can assist you with more complex comments.

One more note to <see cref="null"/>. This will create a link to the class,  method or property named null. This is not directly possible in C#, where you need to prepend @ before the name that is a reserved word:

```<code>/// <summary>
/// <see cref="@null"/>
/// </summary>
public class MyClass
{
    public void @null() {}
}
</code>```

But this is perfectly valid in VB .NET:

```<code>''' <summary>
''' <see cref="null"/>
''' </summary>
Public Class MyClass
    ReadOnly Property null As String
End Class
</code>```

Body:
I have a property which can be null. I want to documentate this in the summary and here is my problem.

cref

///
/// Can be <see cref="null"/>.
///
public object FooProperty;

ReSharper says, there is a Syntax Error, but the highlighting is working as expected!

cref nested

///
/// Can be <see><cref>null</cref></see>.
///
public object FooProperty;

When formating it to nested, the highligghting is not working anymore.

langword

///
/// Can be <see langword="null"/>.
///
public object FooProperty;

langword is working, but there is no intelliSense in VisualStudio.

Can someone please tell me what is the right way to documentate these keywords and IntelliSense support would be nice!

solution approach

VisualStudio | CodeSnippet for inside comment/summary block (IntelliSense)

Body:
The langword is the way to go. You are right, there's no Intellisense support for this. It's probably because it's not officially recommended XML comment tag attribute. But the tools that can generate documentation from your comments, e.g. Sandcastle Help File Builder or VSdocman (disclaimer, I'm the developer of VSdocman) will recognize this syntax and will generate a special text. For example, VSdocman generates:

null reference (Nothing in Visual Basic)

The same applies to other reserved words, such as true, abstract, etc.

While Intellisense will not help you, VSdocman has a WYSIWYG comment editor which can assist you with more complex comments.

One more note to <see cref="null"/>. This will create a link to the class,  method or property named null. This is not directly possible in C#, where you need to prepend @ before the name that is a reserved word:

/// <summary>
/// <see cref="@null"/>
/// </summary>
public class MyClass
{
    public void @null() {}
}

But this is perfectly valid in VB .NET:

''' <summary>
''' <see cref="null"/>
''' </summary>
Public Class MyClass
    ReadOnly Property null As String
End Class


问:
Why doesn't HTML5 read my css?
No matter what i tried or changed it didnt work. My CSS file is in the same folder as my HTML. Here's the code:

```<code> <!DOCTYPE html>
    <html>
     <head>
      <link rel="stylesheet" type="text/css" href="style.css">
       <title>Photos'r'us</title>
      <div="header">
         <img id="banner" src="https://i.imgur.com/iTt5U3E.jpg" alt:"pic">
          <ul id="navigation">
             <li>Home</li>
             <li>About</li>
             <li>Portfolio</li>
             <li>Contact</li>
              </ul>
        </div>
      </head>
      <body>
      </body>
       </html>
</code>```

and this is the CSS:

```<code>@charset "UTF-8";

#header {
height: 230px;
background-image: url(https://i.imgur.com/iTt5U3E.jpg);
background-repeat: no-repeat;
font-family: 'Ariel', sans-serif;
}
#banner {
float: left;
width: 100px;
height: 400px;
margin: 20px;
}
#navigation {
display: inline;
}
</code>```

please help.

答:
Put your all the elements into the body tag not in the head and correct this line
 to
.

For more help on html read this: The global structure of an HTML document

@charset "UTF-8";
#header {
  height: 230px;
  background-image: url(https://i.imgur.com/iTt5U3E.jpg);
  background-repeat: no-repeat;
  font-family: 'Ariel', sans-serif;
}

#banner {
  float: left;
  width: 100px;
  height: 400px;
  margin: 20px;
}

#navigation {
  display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Photos'r'us</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
  <div id="header">
    <img id="banner" src="https://i.imgur.com/iTt5U3E.jpg" alt="pic">
    <ul id="navigation">
      <li>Home</li>
      <li>About</li>
      <li>Portfolio</li>
      <li>Contact</li>
    </ul>
  </div>
</body>

</html></code>```

Title: Why doesn't HTML5 read my css?

Body:
No matter what i tried or changed it didnt work. My CSS file is in the same folder as my HTML. Here's the code:

 <!DOCTYPE html>

      <link rel="stylesheet" type="text/css" href="style.css">
       <title>Photos'r'us</title>

Home

About

Portfolio

Contact

and this is the CSS:

@charset "UTF-8";

#header {
height: 230px;
background-image: url(https://i.imgur.com/iTt5U3E.jpg);
background-repeat: no-repeat;
font-family: 'Ariel', sans-serif;
}
#banner {
float: left;
width: 100px;
height: 400px;
margin: 20px;
}
#navigation {
display: inline;
}

please help.

Body:
Put your all the elements into the body tag not in the head and correct this line <div="header"> to <div id="header">.

For more help on html read this: The global structure of an HTML document

@charset "UTF-8";
#header {
  height: 230px;
  background-image: url(https://i.imgur.com/iTt5U3E.jpg);
  background-repeat: no-repeat;
  font-family: 'Ariel', sans-serif;
}

#banner {
  float: left;
  width: 100px;
  height: 400px;
  margin: 20px;
}

#navigation {
  display: inline;
}

<!DOCTYPE html>
<html>

<head>
  <title>Photos'r'us</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
  <div id="header">
    <img id="banner" src="https://i.imgur.com/iTt5U3E.jpg" alt="pic">
    <ul id="navigation">
      <li>Home</li>
      <li>About</li>
      <li>Portfolio</li>
      <li>Contact</li>
    </ul>
  </div>
</body>

</html>


问:
webrtc each step success but no video share
chrome version: 62.0.3202.94;
firefox version: 57.0.1;

I write a simple demo use webrtc and socket.io.
It works with pages. For example, I open one page to connect socket, and waiting for PeerConnection info from the main page(which get the local media). When I open the main, I create ice and sdp and then exchange them by socket.io to create connection.
Here is the code.

// The server side:
const express = require('express')
const app = express()
const path = require('path')

app.use(express.static(path.join(__dirname, 'public')))

app.get('/phone', function(req, res) {
  res.sendfile(__dirname + '/phone.html')
})

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html')
})

const server = require('http').createServer(app)
const io = require('socket.io')(server)
let clients = []

io.on('connection', function(socket) {

  clients.push(socket)
  const referer = socket.handshake.headers.referer

  // socket connect from '/phone'
  if (referer.match('/phone')) {
    // send the ice from phone to others
    socket.on('phone_ice_candidate', function(res) {
      socket.broadcast.emit('pc_add_ice', {
        ice: res.ice
      })
    })

    // send the sdp from phone to others
    socket.on('send_phone_sdp', function(data) {
      socket.broadcast.emit('set_pc_remote_sdp', {
        desc: data.desc
      })
    })
  }

  // phone add ice from web
  socket.on('remote_ice_candidate', function(ice) {
    socket.to(getId(clients, '/phone')).emit('send_ice_to_pc', {
      ice: ice
    })
  })

  // phone add sdp from web
  socket.on('send_pc_sdp', function(data) {
    // send to phone
    socket.to(getId(clients, '/phone')).emit('set_phone_remote_sdp', {
      desc: data
    })
  })

  // socket disconnect and remove it from clients
  socket.on('disconnect', () => {
    let id = socket.id
    clients.forEach((client, index) => {
      if (client.id === id) {
        clients.splice(index, 1)
      }
    })
  })
})

// get the socket id to emit
function getId(sockets, exp) {
  let id
  sockets.forEach(socket => {
    if (socket.handshake.headers.referer.match(exp)) {
      id = socket.id
    }
  })
  return id
}

server.listen(3000, function() {
  console.log('port listening at 3000')
})```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// --------------------------------------------- //
// web.js
var socket = io();
var server = {
    // "iceServers": [{
    //     "url": "stun:stun.l.google.com:19302"
    // }]
  },
  pc = new RTCPeerConnection(null),
  v = document.querySelector('#video2')
// web onicecandidate
pc.onicecandidate = function(event) {
  if (event.candidate) {
    socket.emit('remote_ice_candidate', {
      ice: event.candidate
    })
  }
}
// web addIceCandidate
socket.on('pc_add_ice', function(event) {
  pc.addIceCandidate(new RTCIceCandidate(event.ice))
})

// didn't trigger
pc.ontrack = function(e) {
  // v.srcObject = e.streams[0];
  console.log(e, 'pc.ontrack')
}

// web setRemoteDescription and createAnswer
socket.on('set_pc_remote_sdp', function(e) {
  pc.setRemoteDescription(e.desc).then(
    function() {
      console.log('remote setRemoteDescription success')

      pc.createAnswer().then(function(desc) {
        pc.setLocalDescription(desc).then(
          function() {
            socket.emit('send_pc_sdp', {
              desc: desc
            })
          },
          function(err) {
            console.log(err)
          }
        );
      })
    },
    function() {
      console.log('pc setLocalDescription error')
    }
  )

})

// web iceConnectionState
pc.oniceconnectionstatechange = function() {
  console.log('web oniceconnectionstatechange', pc.iceConnectionState)
  // log  checking -> connected
};</code>```

//---------------------------------------------//
// phone.js
var socket = io();
var server = {
    // "iceServers": [{
    //     "url": "stun:stun.l.google.com:19302"
    // }]
  },
  pc = new RTCPeerConnection(null),
  v = document.querySelector('#video1')

// phone onicecandidate
pc.onicecandidate = function(event) {
  if (event.candidate) {
    socket.emit('phone_ice_candidate', {
      ice: event.candidate
    })
  }
}

// phone addIceCandidate
socket.on('send_ice_to_pc', function(event) {
  pc.addIceCandidate(new RTCIceCandidate(event.ice.ice))
})

// getUserMedia
navigator.mediaDevices.getUserMedia({
    video: {
      width: 400,
      height: 300
    },
    audio: false
  })
  .then(function(stream) {
    v.src = window.URL.createObjectURL(stream);
    pc.addStream(stream);
  })
  .then(function() {
    // create offer
    pc.createOffer({
      offerToReceiveVideo: 1
    }).then(function(e) {
      // pc setLocalDescription
      pc.setLocalDescription(e).then(
        function() {
          socket.emit('send_phone_sdp', {
            desc: e
          })
        },
        function() {
          console.log('pc setLocalDescription error')
        }
      )
    });
  })
  .catch(function(err) {
    console.log(err.name + ": " + err.message);
  })

// phone setRemoteDescription
socket.on('set_phone_remote_sdp', function(e) {
  pc.setRemoteDescription(e.desc.desc).then(
    function() {
      console.log('pc setRemoteDescription success')
    },
    function(err) {
      console.log(err)
    })
})
// phone iceConnectionState
pc.oniceconnectionstatechange = function() {
  console.log('phone oniceconnectionstatechange', pc.iceConnectionState)
  // log checking -> connected -> completed
};```

When i use firefox to open it, there is an error ICE failed, add a STUN server and see about:webrtc for more details in console.
In chrome the 'phone iceConnectionState' changed checking -> connected -> completed, the 'web iceConnectionState' changed checking -> connected.

答: PTAL at https://www.html5rocks.com/en/tutorials/webrtc/basics/#toc-signaling and compare your code to the example and see if you can figure it out.</p>

Body:
chrome version: 62.0.3202.94;
firefox version: 57.0.1;

I write a simple demo use webrtc and socket.io.
It works with pages. For example, I open one page to connect socket, and waiting for PeerConnection info from the main page(which get the local media). When I open the main, I create ice and sdp and then exchange them by socket.io to create connection.
Here is the code.

// The server side:
const express = require('express')
const app = express()
const path = require('path')

app.use(express.static(path.join(__dirname, 'public')))

app.get('/phone', function(req, res) {
  res.sendfile(__dirname + '/phone.html')
})

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html')
})

const server = require('http').createServer(app)
const io = require('socket.io')(server)
let clients = []

io.on('connection', function(socket) {

  clients.push(socket)
  const referer = socket.handshake.headers.referer

  // socket connect from '/phone'
  if (referer.match('/phone')) {
    // send the ice from phone to others
    socket.on('phone_ice_candidate', function(res) {
      socket.broadcast.emit('pc_add_ice', {
        ice: res.ice
      })
    })

    // send the sdp from phone to others
    socket.on('send_phone_sdp', function(data) {
      socket.broadcast.emit('set_pc_remote_sdp', {
        desc: data.desc
      })
    })
  }

  // phone add ice from web
  socket.on('remote_ice_candidate', function(ice) {
    socket.to(getId(clients, '/phone')).emit('send_ice_to_pc', {
      ice: ice
    })
  })

  // phone add sdp from web
  socket.on('send_pc_sdp', function(data) {
    // send to phone
    socket.to(getId(clients, '/phone')).emit('set_phone_remote_sdp', {
      desc: data
    })
  })

  // socket disconnect and remove it from clients
  socket.on('disconnect', () => {
    let id = socket.id
    clients.forEach((client, index) => {
      if (client.id === id) {
        clients.splice(index, 1)
      }
    })
  })
})

// get the socket id to emit
function getId(sockets, exp) {
  let id
  sockets.forEach(socket => {
    if (socket.handshake.headers.referer.match(exp)) {
      id = socket.id
    }
  })
  return id
}

server.listen(3000, function() {
  console.log('port listening at 3000')
})

// --------------------------------------------- //
// web.js
var socket = io();
var server = {
    // "iceServers": [{
    //     "url": "stun:stun.l.google.com:19302"
    // }]
  },
  pc = new RTCPeerConnection(null),
  v = document.querySelector('#video2')
// web onicecandidate
pc.onicecandidate = function(event) {
  if (event.candidate) {
    socket.emit('remote_ice_candidate', {
      ice: event.candidate
    })
  }
}
// web addIceCandidate
socket.on('pc_add_ice', function(event) {
  pc.addIceCandidate(new RTCIceCandidate(event.ice))
})

// didn't trigger
pc.ontrack = function(e) {
  // v.srcObject = e.streams[0];
  console.log(e, 'pc.ontrack')
}

// web setRemoteDescription and createAnswer
socket.on('set_pc_remote_sdp', function(e) {
  pc.setRemoteDescription(e.desc).then(
    function() {
      console.log('remote setRemoteDescription success')

      pc.createAnswer().then(function(desc) {
        pc.setLocalDescription(desc).then(
          function() {
            socket.emit('send_pc_sdp', {
              desc: desc
            })
          },
          function(err) {
            console.log(err)
          }
        );
      })
    },
    function() {
      console.log('pc setLocalDescription error')
    }
  )

})

// web iceConnectionState
pc.oniceconnectionstatechange = function() {
  console.log('web oniceconnectionstatechange', pc.iceConnectionState)
  // log  checking -> connected
};

//---------------------------------------------//
// phone.js
var socket = io();
var server = {
    // "iceServers": [{
    //     "url": "stun:stun.l.google.com:19302"
    // }]
  },
  pc = new RTCPeerConnection(null),
  v = document.querySelector('#video1')

// phone onicecandidate
pc.onicecandidate = function(event) {
  if (event.candidate) {
    socket.emit('phone_ice_candidate', {
      ice: event.candidate
    })
  }
}

// phone addIceCandidate
socket.on('send_ice_to_pc', function(event) {
  pc.addIceCandidate(new RTCIceCandidate(event.ice.ice))
})

// getUserMedia
navigator.mediaDevices.getUserMedia({
    video: {
      width: 400,
      height: 300
    },
    audio: false
  })
  .then(function(stream) {
    v.src = window.URL.createObjectURL(stream);
    pc.addStream(stream);
  })
  .then(function() {
    // create offer
    pc.createOffer({
      offerToReceiveVideo: 1
    }).then(function(e) {
      // pc setLocalDescription
      pc.setLocalDescription(e).then(
        function() {
          socket.emit('send_phone_sdp', {
            desc: e
          })
        },
        function() {
          console.log('pc setLocalDescription error')
        }
      )
    });
  })
  .catch(function(err) {
    console.log(err.name + ": " + err.message);
  })

// phone setRemoteDescription
socket.on('set_phone_remote_sdp', function(e) {
  pc.setRemoteDescription(e.desc.desc).then(
    function() {
      console.log('pc setRemoteDescription success')
    },
    function(err) {
      console.log(err)
    })
})
// phone iceConnectionState
pc.oniceconnectionstatechange = function() {
  console.log('phone oniceconnectionstatechange', pc.iceConnectionState)
  // log checking -> connected -> completed
};

When i use firefox to open it, there is an error ICE failed, add a STUN server and see about:webrtc for more details in console.
In chrome the 'phone iceConnectionState' changed checking -> connected -> completed, the 'web iceConnectionState' changed checking -> connected.


问:
XAML fixed banner on top of scrollable area
I'm trying to add a banner that remains fixed in the window to my page and I'm having a tough time.

This is what I am trying to achieve:  I want a banner that floats at the top of the window (for an ad), then I want the rest of the content in a scrollable area.  First item should be a textBlock, then a textBox, then a button.

This is the code I've got now and it looks right except for the scrolling.  Help would be appreciated.

```<code><Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App2"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Universal="using:Microsoft.AdMediator.Universal"
    x:Class="App2.MainPage"
    mc:Ignorable="d" RequestedTheme="Dark">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Grid.RowSpan="3">
            <Universal:AdMediatorControl x:Name="AdMediatorName" Height="90" Id="AdMediator-Id" Margin="10,0"/>
            <ScrollViewer x:Name="myScrollViewer"  VerticalScrollMode="Enabled">
                <StackPanel Grid.RowSpan="2">
                    <TextBlock x:Name ="outputConsole" FontSize="15" RenderTransformOrigin="0.5,0" TextWrapping="WrapWholeWords" Margin="0,0,10,0" FontFamily="Consolas" IsTextSelectionEnabled="True">
                        <TextBlock.RenderTransform>
                            <CompositeTransform/>
                        </TextBlock.RenderTransform>
                        <TextBlock.Projection>
                            <PlaneProjection/>
                        </TextBlock.Projection>
                        <Run/>
                        <LineBreak/>
                        <Run/>
                    </TextBlock>
                    <TextBox x:Name="inputConsole" FontSize="20" KeyUp="inputKeyUp" Margin="0,0,10,0" FontFamily="Consolas" IsTapEnabled="True" IsTextPredictionEnabled="True"/>
                    <Button x:Name="submitButton" Content="Submit" Click="submitButtonClick"/>
                </StackPanel>
            </ScrollViewer>
        </StackPanel>

    </Grid>
</Page>
</code>```

答:
You just answered your question. You have to do something like this,

```<code>    <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <StackPanel Grid.Row="0" Orientation="Horizontal"><TextBlock x:Name ="outputConsole" FontSize="15" RenderTransformOrigin="0.5,0" TextWrapping="WrapWholeWords" Margin="0,0,10,0" FontFamily="Consolas" IsTextSelectionEnabled="True">
                    <TextBlock.RenderTransform>
                        <CompositeTransform/>
                    </TextBlock.RenderTransform>
                    <TextBlock.Projection>
                        <PlaneProjection/>
                    </TextBlock.Projection>
                    <Run/>
                    <LineBreak/>
                    <Run/>
                </TextBlock>
                <TextBox x:Name="inputConsole" FontSize="20" KeyUp="inputKeyUp" Margin="0,0,10,0" FontFamily="Consolas" IsTapEnabled="True" IsTextPredictionEnabled="True"/>
                <Button x:Name="submitButton" Content="Submit" Click="submitButtonClick"/>
    </StackPanel>

    <ScrollViewer Grid.Row="1">

    </ScrollViewer>
</code>```

Body:
I'm trying to add a banner that remains fixed in the window to my page and I'm having a tough time.

This is what I am trying to achieve:  I want a banner that floats at the top of the window (for an ad), then I want the rest of the content in a scrollable area.  First item should be a textBlock, then a textBox, then a button.

This is the code I've got now and it looks right except for the scrolling.  Help would be appreciated.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App2"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Universal="using:Microsoft.AdMediator.Universal"
    x:Class="App2.MainPage"
    mc:Ignorable="d" RequestedTheme="Dark">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Grid.RowSpan="3">
            <Universal:AdMediatorControl x:Name="AdMediatorName" Height="90" Id="AdMediator-Id" Margin="10,0"/>
            <ScrollViewer x:Name="myScrollViewer"  VerticalScrollMode="Enabled">
                <StackPanel Grid.RowSpan="2">
                    <TextBlock x:Name ="outputConsole" FontSize="15" RenderTransformOrigin="0.5,0" TextWrapping="WrapWholeWords" Margin="0,0,10,0" FontFamily="Consolas" IsTextSelectionEnabled="True">
                        <TextBlock.RenderTransform>
                            <CompositeTransform/>
                        </TextBlock.RenderTransform>
                        <TextBlock.Projection>
                            <PlaneProjection/>
                        </TextBlock.Projection>
                        <Run/>
                        <LineBreak/>
                        <Run/>
                    </TextBlock>
                    <TextBox x:Name="inputConsole" FontSize="20" KeyUp="inputKeyUp" Margin="0,0,10,0" FontFamily="Consolas" IsTapEnabled="True" IsTextPredictionEnabled="True"/>
                    <Button x:Name="submitButton" Content="Submit" Click="submitButtonClick"/>
                </StackPanel>
            </ScrollViewer>
        </StackPanel>

    </Grid>
</Page>

Body:
You just answered your question. You have to do something like this,

    <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <StackPanel Grid.Row="0" Orientation="Horizontal"><TextBlock x:Name ="outputConsole" FontSize="15" RenderTransformOrigin="0.5,0" TextWrapping="WrapWholeWords" Margin="0,0,10,0" FontFamily="Consolas" IsTextSelectionEnabled="True">
                    <TextBlock.RenderTransform>
                        <CompositeTransform/>
                    </TextBlock.RenderTransform>
                    <TextBlock.Projection>
                        <PlaneProjection/>
                    </TextBlock.Projection>
                    <Run/>
                    <LineBreak/>
                    <Run/>
                </TextBlock>
                <TextBox x:Name="inputConsole" FontSize="20" KeyUp="inputKeyUp" Margin="0,0,10,0" FontFamily="Consolas" IsTapEnabled="True" IsTextPredictionEnabled="True"/>
                <Button x:Name="submitButton" Content="Submit" Click="submitButtonClick"/>
    </StackPanel>

    <ScrollViewer Grid.Row="1">

    </ScrollViewer>


问:
How to initialize HashSet values by construction?
I need to create a Set with initial values.

```<code>Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
</code>```

Is there a way to do this in one line of code? For instance, it's useful for a final static field.

答:
Using Java 8 we can create HashSet as:

```<code>Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
</code>```

And if we want unmodifiable set we can create a utility method as :

```<code>public static <T, A extends Set<T>> Collector<T, A, Set<T>> toImmutableSet(Supplier<A> supplier) {
        return Collector.of(
                supplier,
                Set::add, (left, right) -> {
                    left.addAll(right);
                    return left;
                }, Collections::unmodifiableSet);
    }
</code>```

This method can be used as :

```<code> Stream.of("A", "B", "C", "D").collect(toImmutableSet(HashSet::new));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to create a Set with initial values.

Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");

Is there a way to do this in one line of code? For instance, it's useful for a final static field.

Body:
Using Java 8 we can create HashSet as:

Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));

And if we want unmodifiable set we can create a utility method as :

public static <T, A extends Set<T>> Collector<T, A, Set<T>> toImmutableSet(Supplier<A> supplier) {
        return Collector.of(
                supplier,
                Set::add, (left, right) -> {
                    left.addAll(right);
                    return left;
                }, Collections::unmodifiableSet);
    }

This method can be used as :

 Stream.of("A", "B", "C", "D").collect(toImmutableSet(HashSet::new));


问:
Is a GKVoiceChat example available for the iPhone SDK?
I am seeking a GKVoiceChat example for the iPhone SDK in 4.0 or later. It will surely help with my iPhone game.</p>

答:
There are two Game Kit samples I've seen that include GKVoiceChat.

Search for GCPing in the Apple dev forums.  (I'm not posting a link because it's not clear the author wants a public link).  This sample is clear and basic, but demonstrates a wide range of working Game Kit multiplayer concepts.  Search back over 'all' time, and look for the 'GCPing WWDC2010 - Updated for iOS 4 GM Seed' post.

multiplayer Pong client. Found here.

Haven't looked into sample 2 much yet, but it looks pretty good.


问:
spring security redirect based on role
i have the following spring-security.xml file :-

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http auto-config="true">
           <intercept-url pattern="/Freelancer/**" access="ROLE_FREELANCE" />
           <intercept-url pattern="/Client/**" access="ROLE_CLIENT" />
           <intercept-url pattern="/Agency/**" access="ROLE_AGENCY" />
           <intercept-url pattern="/Manager/**" access="ROLE_MANAGER" />
           <intercept-url pattern="/User/**" access="ROLE_USER" />
           <form-login default-target-url="/${role}" login-page="/login.jsp" />
           <logout logout-url="/logout" logout-success-url="/" />
    </http>

    <authentication-manager>
           <authentication-provider>
             <jdbc-user-service data-source-ref="dataSource"
               users-by-username-query="select user_name,password, enabled from Users where user_name=?"
               authorities-by-username-query="select u.user_name, u.role from Users u where u.user_name =?"/>
           </authentication-provider>
    </authentication-manager>

</beans:beans>
</code>```

what i want, i want to redirect the user to their workspace, for example if Client login then he will be redirected to the /Client/index.jsp, if Agency login, they will be redirected to the /Agency/index.jsp.

is there any way to access the role before, he will be redirected to their workspace in spring-security.xml file.

```<code><form-login default-target-url="/${role}" login-page="/login.jsp" />
</code>```

I have the directory structure similer to role.

have any idea.

答:
You can use annotation based solution by using custom success handler like this:

```<code>import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    /*
     * This method extracts the roles of currently logged-in user and returns
     * appropriate URL according to his/her role.
     */
    protected String determineTargetUrl(Authentication authentication) {
        String url = "";

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<String> roles = new ArrayList<String>();

        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }

        if (isDba(roles)) {
            url = "/db";
        } else if (isAdmin(roles)) {
            url = "/admin";
        } else if (isUser(roles)) {
            url = "/home";
        } else {
            url = "/accessDenied";
        }

        return url;
    }

    private boolean isUser(List<String> roles) {
        if (roles.contains("ROLE_USER")) {
            return true;
        }
        return false;
    }

    private boolean isAdmin(List<String> roles) {
        if (roles.contains("ROLE_ADMIN")) {
            return true;
        }
        return false;
    }

    private boolean isDba(List<String> roles) {
        if (roles.contains("ROLE_DBA")) {
            return true;
        }
        return false;
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }

    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

}
</code>```

And security config as:

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
        .antMatchers("/", "/home").access("hasRole('USER')")
        .antMatchers("/admin/**").access("hasRole('ADMIN')")
        .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
        .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
        .usernameParameter("ssoId").passwordParameter("password")
        .and().csrf()
        .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }

}
</code>```

Title: spring security redirect based on role

Body:
i have the following spring-security.xml file :-

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http auto-config="true">
           <intercept-url pattern="/Freelancer/**" access="ROLE_FREELANCE" />
           <intercept-url pattern="/Client/**" access="ROLE_CLIENT" />
           <intercept-url pattern="/Agency/**" access="ROLE_AGENCY" />
           <intercept-url pattern="/Manager/**" access="ROLE_MANAGER" />
           <intercept-url pattern="/User/**" access="ROLE_USER" />
           <form-login default-target-url="/${role}" login-page="/login.jsp" />
           <logout logout-url="/logout" logout-success-url="/" />
    </http>

    <authentication-manager>
           <authentication-provider>
             <jdbc-user-service data-source-ref="dataSource"
               users-by-username-query="select user_name,password, enabled from Users where user_name=?"
               authorities-by-username-query="select u.user_name, u.role from Users u where u.user_name =?"/>
           </authentication-provider>
    </authentication-manager>

</beans:beans>

what i want, i want to redirect the user to their workspace, for example if Client login then he will be redirected to the /Client/index.jsp, if Agency login, they will be redirected to the /Agency/index.jsp.

is there any way to access the role before, he will be redirected to their workspace in spring-security.xml file.

<form-login default-target-url="/${role}" login-page="/login.jsp" />

I have the directory structure similer to role.

have any idea.

Body:
You can use annotation based solution by using custom success handler like this:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    /*
     * This method extracts the roles of currently logged-in user and returns
     * appropriate URL according to his/her role.
     */
    protected String determineTargetUrl(Authentication authentication) {
        String url = "";

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<String> roles = new ArrayList<String>();

        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }

        if (isDba(roles)) {
            url = "/db";
        } else if (isAdmin(roles)) {
            url = "/admin";
        } else if (isUser(roles)) {
            url = "/home";
        } else {
            url = "/accessDenied";
        }

        return url;
    }

    private boolean isUser(List<String> roles) {
        if (roles.contains("ROLE_USER")) {
            return true;
        }
        return false;
    }

    private boolean isAdmin(List<String> roles) {
        if (roles.contains("ROLE_ADMIN")) {
            return true;
        }
        return false;
    }

    private boolean isDba(List<String> roles) {
        if (roles.contains("ROLE_DBA")) {
            return true;
        }
        return false;
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }

    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

}

And security config as:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
        .antMatchers("/", "/home").access("hasRole('USER')")
        .antMatchers("/admin/**").access("hasRole('ADMIN')")
        .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
        .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
        .usernameParameter("ssoId").passwordParameter("password")
        .and().csrf()
        .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }

}


问:
TFS2018 exported build definition json looks different from the exported json for the TFS build definition object
Temp solution I exported the build definition json file from the TFS Web interface. And for comparison I exported the build definition object from the API and the json files look different, which is the problem. For now I will use the api object json.

I have TFS2018 installed and I am importing a exported json build file like this:

```<code>var filePath = "builddefinition.json";
                    var buildDef = JsonConvert.DeserializeObject<BuildDefinition>(File.ReadAllText(filePath));
</code>```

The file is imported successfully. However the steps are not imported. Here is part of the exported json file showing the first step. I have in total 7 steps.

```<code>"process": {
        "phases": [
            {
                "steps": [
                    {
                        "environment": {},
                        "enabled": true,
                        "continueOnError": false,
                        "alwaysRun": false,
                        "displayName": "Use NuGet 4.3.0",
                        "timeoutInMinutes": 0,
                        "condition": "succeeded()",
                        "refName": "NuGetToolInstaller1",
                        "task": {
                            "id": "2c645196a-524fd-4a402-92be8-d9d4837b7c5d",
                            "versionSpec": "0.*",
                            "definitionType": "task"
                        },
                        "inputs": {
                            "versionSpec": "4.3.0",
                            "checkLatest": "false"
                        }
                    },
                    {... more steps
</code>```

However if I get the build definition from the api I get all the steps.

```<code>var buildDef = buildClient.GetDefinitionAsync("MyProject", builddefid);
</code>```

Any idea why the steps are not serialized into the object when reading it from the json file?

答:
The contents/format of Json files which exported from Web interface and object API are different.

So you need to Export/Import the build defintion json files in pair. That means Export from web interface then import from web interface, export via API then import it again via API.

This article for your reference : TFS 2015 clone/import/export build definition between team projects

Body:
Temp solution I exported the build definition json file from the TFS Web interface. And for comparison I exported the build definition object from the API and the json files look different, which is the problem. For now I will use the api object json.

I have TFS2018 installed and I am importing a exported json build file like this:

var filePath = "builddefinition.json";
                    var buildDef = JsonConvert.DeserializeObject<BuildDefinition>(File.ReadAllText(filePath));

The file is imported successfully. However the steps are not imported. Here is part of the exported json file showing the first step. I have in total 7 steps.

"process": {
        "phases": [
            {
                "steps": [
                    {
                        "environment": {},
                        "enabled": true,
                        "continueOnError": false,
                        "alwaysRun": false,
                        "displayName": "Use NuGet 4.3.0",
                        "timeoutInMinutes": 0,
                        "condition": "succeeded()",
                        "refName": "NuGetToolInstaller1",
                        "task": {
                            "id": "2c645196a-524fd-4a402-92be8-d9d4837b7c5d",
                            "versionSpec": "0.*",
                            "definitionType": "task"
                        },
                        "inputs": {
                            "versionSpec": "4.3.0",
                            "checkLatest": "false"
                        }
                    },
                    {... more steps

However if I get the build definition from the api I get all the steps.

var buildDef = buildClient.GetDefinitionAsync("MyProject", builddefid);

Any idea why the steps are not serialized into the object when reading it from the json file?