问:
mySQL Query select / join not working as expected
let me preface that I've done a good bit of searching to see if this issue can be resolved but have yet to find an answer that relates, so I'll ask now.  I have a query that works (mostly) to pull from two separate tables to show a total amount of pc models in each of four locations(these locations are in a single column, so I'm trying to select them as their own columns through aliases).  The query pulls all required info, but not as I was hoping it would.

Expectation:

```<code>model | loc1 | loc2 | loc3 | loc4
5530  | 3    | 2    | 1    | 0
6440  | 10   | 0    | 3    | 20
</code>```

Reality:

```<code>model | loc1 | loc2 | loc3 | loc4
5530  | 3    | null | null | null
5530  | null | 2    | null | null
5530  | null | null | 1    | null
</code>```

etc..

Here is my query, any help to make the reality match the expectation if possible would be appreciated.

```<code>SELECT
      a.model,
      (select COUNT(a.model)
             WHERE a.location = 'AoC-Reno') AS Reno,
      (select count(a.model)
             where a.location = 'AoC-Fargo') AS Fargo,
      (select count(a.model)
              where a.location = 'EoC') AS EoC,
      (select count(a.model)
              where a.location = 'APoC') as APoC
FROM assets AS a
join models m on m.model = a.model
WHERE m.type IN ('Desktop','Laptop')
AND a.model = m.model
AND a.status != 'Recycled'
GROUP BY m.model, a.location
ORDER BY m.model
</code>```

答:
Use conditional aggregation:

```<code>SELECT a.model,
       SUM(a.location = 'AoC-Reno') AS Reno,
       SUM(a.location = 'AoC-Fargo') AS Fargo,
       SUM(a.location = 'EoC') AS EoC,
       SUM(a.location = 'APoC') as APoC
FROM models m JOIN
     assets a
     on m.model = a.model
WHERE m.type IN ('Desktop', 'Laptop') and a.status <> 'Recycled'
GROUP BY m.model
ORDER BY m.model;
</code>```

Your query has multiple issues:

You are using a "subquery", but there is no FROM clause.

You are aggregating by both model and location, but you want only one row per model.

The JOIN condition is both in the ON clause and repeated in the WHERE clause.

Body:
let me preface that I've done a good bit of searching to see if this issue can be resolved but have yet to find an answer that relates, so I'll ask now.  I have a query that works (mostly) to pull from two separate tables to show a total amount of pc models in each of four locations(these locations are in a single column, so I'm trying to select them as their own columns through aliases).  The query pulls all required info, but not as I was hoping it would.

Expectation:

model | loc1 | loc2 | loc3 | loc4
5530  | 3    | 2    | 1    | 0
6440  | 10   | 0    | 3    | 20

Reality:

model | loc1 | loc2 | loc3 | loc4
5530  | 3    | null | null | null
5530  | null | 2    | null | null
5530  | null | null | 1    | null

etc..

Here is my query, any help to make the reality match the expectation if possible would be appreciated.

SELECT
      a.model,
      (select COUNT(a.model)
             WHERE a.location = 'AoC-Reno') AS Reno,
      (select count(a.model)
             where a.location = 'AoC-Fargo') AS Fargo,
      (select count(a.model)
              where a.location = 'EoC') AS EoC,
      (select count(a.model)
              where a.location = 'APoC') as APoC
FROM assets AS a
join models m on m.model = a.model
WHERE m.type IN ('Desktop','Laptop')
AND a.model = m.model
AND a.status != 'Recycled'
GROUP BY m.model, a.location
ORDER BY m.model

Body:
Use conditional aggregation:

SELECT a.model,
       SUM(a.location = 'AoC-Reno') AS Reno,
       SUM(a.location = 'AoC-Fargo') AS Fargo,
       SUM(a.location = 'EoC') AS EoC,
       SUM(a.location = 'APoC') as APoC
FROM models m JOIN
     assets a
     on m.model = a.model
WHERE m.type IN ('Desktop', 'Laptop') and a.status <> 'Recycled'
GROUP BY m.model
ORDER BY m.model;

Your query has multiple issues:

You are using a "subquery", but there is no FROM clause.

You are aggregating by both model and location, but you want only one row per model.

The JOIN condition is both in the ON clause and repeated in the WHERE clause.


来源: stackexchange

答:
You can do a conditional aggregation (count)

SELECT a.model,
       SUM(CASE WHEN a.location = 'AoC-Reno' THEN 1 END)  reno,
       SUM(CASE WHEN a.location = 'AoC-Fargo' THEN 1 END)  farggo,
       SUM(CASE WHEN a.location = 'EoC' THEN 1 END)  eoc,
       SUM(CASE WHEN a.location = 'APoC' THEN 1 END)  apoc
  FROM assets AS a JOIN models m
    ON m.model = a.model
 WHERE m.type IN ('Desktop','Laptop')
   AND a.status != 'Recycled'
GROUP BY m.model
ORDER BY m.model
```

ContentLicense: CC BY-SA 3.0

Title: mySQL Query select / join not working as expected


问:
How to do HTTP-request/call with JSON payload from command-line?
What's the easiest way to do a JSON call from the command-line? I have a website that does a JSON call to retrieve additional data.

The Request Payload as shown in Google Chrome looks like this:

```<code>{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }
</code>```

It's about doing the call from (preferably) linux command line and retrieving the JSON content, not about parsing the incoming JSON data.

答:
Have you looked at curl? It's very good at facilitating HTTP GET/POST requests via the command line.

e.g. (for a GET request):

```<code>C:\WINDOWS>curl "http://search.twitter.com/search.json?q=twitterapi&result_type=
popular"
{"results":[{"from_user_id_str":"32316068","profile_image_url":"http://a2.twimg.
com/profile_images/351010682/twitblock_profile_normal.png","created_at":"Thu, 25
 Nov 2010 14:37:46 +0000","from_user":"twitblockapp","id_str":"7805146834669569"
,"metadata":{"result_type":"popular","recent_retweets":10},"to_user_id":null,"te
xt":"blocking and reporting functions are currently failing. @TwitterAPI have be
en notified. http://j.mp/id5w3m","id":7805146834669569,"from_user_id":32316068,"
geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href=&q
uot;http://twitter.com" rel="nofollow">Tweetie for Mac</a&g
t;"}],"max_id":9607558079713280,"since_id":0,"refresh_url":"?since_id=9607558079
713280&q=twitterapi","results_per_page":15,"page":1,"completed_in":0.012698,"sin
ce_id_str":"0","max_id_str":"9607558079713280","query":"twitterapi"}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What's the easiest way to do a JSON call from the command-line? I have a website that does a JSON call to retrieve additional data.

The Request Payload as shown in Google Chrome looks like this:

{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }

It's about doing the call from (preferably) linux command line and retrieving the JSON content, not about parsing the incoming JSON data.

Body:
Have you looked at curl? It's very good at facilitating HTTP GET/POST requests via the command line.

e.g. (for a GET request):

C:\WINDOWS>curl "http://search.twitter.com/search.json?q=twitterapi&result_type=
popular"
{"results":[{"from_user_id_str":"32316068","profile_image_url":"http://a2.twimg.
com/profile_images/351010682/twitblock_profile_normal.png","created_at":"Thu, 25
 Nov 2010 14:37:46 +0000","from_user":"twitblockapp","id_str":"7805146834669569"
,"metadata":{"result_type":"popular","recent_retweets":10},"to_user_id":null,"te
xt":"blocking and reporting functions are currently failing. @TwitterAPI have be
en notified. http://j.mp/id5w3m","id":7805146834669569,"from_user_id":32316068,"
geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"&lt;a href=&q
uot;http://twitter.com&quot; rel=&quot;nofollow&quot;&gt;Tweetie for Mac&lt;/a&g
t;"}],"max_id":9607558079713280,"since_id":0,"refresh_url":"?since_id=9607558079
713280&q=twitterapi","results_per_page":15,"page":1,"completed_in":0.012698,"sin
ce_id_str":"0","max_id_str":"9607558079713280","query":"twitterapi"}


问:
Using CSS or JS to hide text inside the a href tag
I have a list in this format:

```<code><ul>
    <li><a href="link">Part 1</a></li>
    <li><a href="link">Part 2</a></li>
    <li><a href="link">Part 3</a></li>
</ul>
</code>```

I am using css :before to display something instead of the text inside the a href tag and I want to hide the text. I just want to hide Part 1, Part 2, Part 3 text and leave a href tag there.

If I use display:none; then everything is hidden, how can I just hide the text inside the href tag?

答:
You can use the visibility attribute, it will collapse (hide) the contents of your href tag but keep the tag inline.

css

```<code>ul li a {
    visibility: collapse;
}
</code>```

html

```<code><ul>
    <li><a href="link">Part 1</a></li>
    <li><a href="link">Part 2</a></li>
    <li><a href="link">Part 3</a></li>
</ul>
</code>```

To show the contents at a later stage use

```<code>ul li a {
    visibility: visible;
}
</code>```

Body:
I have a list in this format:

Part 1

Part 2

Part 3

I am using css :before to display something instead of the text inside the a href tag and I want to hide the text. I just want to hide Part 1, Part 2, Part 3 text and leave a href tag there.

If I use display:none; then everything is hidden, how can I just hide the text inside the href tag?

Body:
You can use the visibility attribute, it will collapse (hide) the contents of your href tag but keep the tag inline.

css

ul li a {
    visibility: collapse;
}

html

<ul>
    <li><a href="link">Part 1</a></li>
    <li><a href="link">Part 2</a></li>
    <li><a href="link">Part 3</a></li>
</ul>

To show the contents at a later stage use

ul li a {
    visibility: visible;
}


问:
Change color of items in appbar
I want to change the color of my app name, search icon and overflow menu in the appbar to white. I used textColorPrimary but its not working, it is all black.

Here is my code

colors.xml

```<code><resources>
    <color name="colorPrimary">#9C27B0</color>
    <color name="colorPrimaryDark">#CE93D8</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#FFFFFF</color>
    <color name="colorAccent">#FF80AB</color>
</resource>
</code>```

styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="textColorPrimary">@color/textColorPrimary</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
</code>```

AndroidManifest.xml

```<code>     <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme"
        android:label="@string/title_activity_welcome">
    </activity>
</code>```

menumain.xml

```<code>   <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="always" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />

    </menu>
</code>```

This is what I want - A white text(app name), search icon(fixed,i used a white search icon so no problem) and white overflow menu

答:
Create this style and set to Toolbar:

```<code><style name="AppTheme.Toolbar" parent="ThemeOverlay.AppCompat.ActionBar">
    <!-- Customize color of navigation drawer icon and back arrow -->
    <item name="colorControlNormal">@color/textColorPrimary</item>
</style>

<style name="AppTheme.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
    <!-- Set proper title size -->
    <item name="android:textSize">@dimen/abc_text_size_title_material_toolbar</item>
    <!-- Set title color -->
    <item name="android:textColor">@color/textColorPrimary</item>
</style>
</code>```

Toolbar code:

```<code><android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:background="@color/toolbar_bg"
    app:theme="@style/AppTheme.Toolbar"
    app:titleTextAppearance="@style/AppTheme.Toolbar.Title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"/>
</code>```

Title: Change color of items in appbar

Body:
I want to change the color of my app name, search icon and overflow menu in the appbar to white. I used textColorPrimary but its not working, it is all black.

Here is my code

colors.xml

<resources>
    <color name="colorPrimary">#9C27B0</color>
    <color name="colorPrimaryDark">#CE93D8</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#FFFFFF</color>
    <color name="colorAccent">#FF80AB</color>
</resource>

styles.xml

AndroidManifest.xml

     <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme"
        android:label="@string/title_activity_welcome">
    </activity>

menumain.xml

   <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="always" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />

    </menu>

This is what I want - A white text(app name), search icon(fixed,i used a white search icon so no problem) and white overflow menu

Body:
Create this style and set to Toolbar:

<style name="AppTheme.Toolbar" parent="ThemeOverlay.AppCompat.ActionBar">
    <!-- Customize color of navigation drawer icon and back arrow -->
    <item name="colorControlNormal">@color/textColorPrimary</item>
</style>

<style name="AppTheme.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
    <!-- Set proper title size -->
    <item name="android:textSize">@dimen/abc_text_size_title_material_toolbar</item>
    <!-- Set title color -->
    <item name="android:textColor">@color/textColorPrimary</item>
</style>

Toolbar code:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:background="@color/toolbar_bg"
    app:theme="@style/AppTheme.Toolbar"
    app:titleTextAppearance="@style/AppTheme.Toolbar.Title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"/>


问:
Using CSS in Laravel views?
I've just began learning Laravel, and can do the basics of a controller and routing.

My OS is Mac OS X Lion, and it's on a MAMP server.

My code from routes.php:

```<code>Route::get('/', function() {
    return View::make('home.index');
});

Route::get('businesses', function() {
    return View::make('businesses.index');
});

Route::get('testing', function() {
    return View::make('testing.index');
});

Route::get('hello', function() {
    return "<h3>Hello world!</H3>";
});
</code>```

That works, the views display perfectly, ''however'' what I want to try and do is include CSS within the views, I tried adding in a link to a stylesheet within the directory but the page displayed it as the default browser font even though the css was in the HTML!

This is index.php from businesses within the views folder:

```<code><head>
   <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

<p>Business is a varied term. My content here.
</code>```

I tried using the Blade template engine in my other views folder (testing) to display CSS but again the CSS did not show despite it being in the testing folder!

How can I overcome this problem, and get better - as I'm slowly learning this framework.

答:
For Laravel 5.4 and if you are using mix helper, use</p>

```<code>    <link href="{{ mix('/css/app.css') }}" rel="stylesheet">
    <script src="{{ mix('/js/app.js') }}"></script>
</code>```

Title: Using CSS in Laravel views?

Body:
I've just began learning Laravel, and can do the basics of a controller and routing.

My OS is Mac OS X Lion, and it's on a MAMP server.

My code from routes.php:

Route::get('/', function() {
    return View::make('home.index');
});

Route::get('businesses', function() {
    return View::make('businesses.index');
});

Route::get('testing', function() {
    return View::make('testing.index');
});

Route::get('hello', function() {
    return "
Hello world!
";
});

That works, the views display perfectly, ''however'' what I want to try and do is include CSS within the views, I tried adding in a link to a stylesheet within the directory but the page displayed it as the default browser font even though the css was in the HTML!

This is index.php from businesses within the views folder:

   <link rel="stylesheet" type="text/css" href="mystyle.css">

Business is a varied term. My content here.

I tried using the Blade template engine in my other views folder (testing) to display CSS but again the CSS did not show despite it being in the testing folder!

How can I overcome this problem, and get better - as I'm slowly learning this framework.

Body:
For Laravel 5.4 and if you are using mix helper, use

    <link href="{{ mix('/css/app.css') }}" rel="stylesheet">
    <script src="{{ mix('/js/app.js') }}"></script>


问:
Why do Guava classes provide so many factory methods instead of just one that takes varargs?

Possible Duplicate:

  Why does Guava's ImmutableList have so many overloaded of() methods?

Looking at Guava's ImmutableList (and some other classes), you'll find plenty of overloaded of convenience methods ("Returns an immutable list containing the given elements, in order.") that take a different number of parameters:

```<code>...
public static <E> ImmutableList<E> of(E e1, E e2, E e3)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
...
</code>```

All the way to this one:

```<code>public static <E> ImmutableList<E> of(E e1,
                                      E e2,
                                      E e3,
                                      E e4,
                                      E e5,
                                      E e6,
                                      E e7,
                                      E e8,
                                      E e9,
                                      E e10,
                                      E e11,
                                      E e12,
                                      E... others)
</code>```

Some colleagues of mine consider this silly, wondering why there's isn't just one method: of(E... elements).  They suspect it's an ill-guided performance "optimisation" that falls into the category "do you think you're smarter than compiler", or something like that.

My hunch is that Kevin Bourrillion et al. put these methods in there for a real reason. Can anyone explain (or speculate) what that reason might be?

答:
The comment in the source says:

```<code>// These go up to eleven. After that, you just get the varargs form, and
// whatever warnings might come along with it. :(
</code>```

So, this was done because varargs methods produce a warning with generic arguments.

Body:
Possible Duplicate:

  Why does Guava's ImmutableList have so many overloaded of() methods?

Looking at Guava's ImmutableList (and some other classes), you'll find plenty of overloaded of convenience methods ("Returns an immutable list containing the given elements, in order.") that take a different number of parameters:

...
public static <E> ImmutableList<E> of(E e1, E e2, E e3)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
...

All the way to this one:

public static <E> ImmutableList<E> of(E e1,
                                      E e2,
                                      E e3,
                                      E e4,
                                      E e5,
                                      E e6,
                                      E e7,
                                      E e8,
                                      E e9,
                                      E e10,
                                      E e11,
                                      E e12,
                                      E... others)

Some colleagues of mine consider this silly, wondering why there's isn't just one method: of(E... elements).  They suspect it's an ill-guided performance "optimisation" that falls into the category "do you think you're smarter than compiler", or something like that.

My hunch is that Kevin Bourrillion et al. put these methods in there for a real reason. Can anyone explain (or speculate) what that reason might be?

Body:
The comment in the source says:

// These go up to eleven. After that, you just get the varargs form, and
// whatever warnings might come along with it. :(

So, this was done because varargs methods produce a warning with generic arguments.


问:
How come so different while using same Tahoma font representing same snippet of code in SciTE and PHPDesigner?
How come so different while using same Tahoma font representing same snippet of code in SciTE and PHPDesigner?
Here is a screenshot.
Why so much difference?

答:
Why so much difference?

From what I can see in the provided pictures the answer to this question is:

on the left side you see the mono-space font variant, where on the right side you see the proportional font variant

the sizes of the font vary between the left and right side

on the right side you see the italics font variant

This site ( fontfeed.com: styles-weights-widths-it’s-all-in-the-type-family ) gives some insight into the subject of different variants of the "same" font.

In addition to the issue with fonts where it is even possible that the font with the same name looks different (you can't prevent the case that someone creates a font and give it a name of another one - in other words you can't be 100% sure the font is the same except you use the same file from which the font is loaded) further reason for differences in what you see are different settings for the syntax highlighting (in SciTe and PHPDesigner). Such settings are highly customizable, so you will witness  differences between users of the same editor even in case of same font used.

To see it for yourself what it is all about play a bit around with settings related to fonts and to syntax highlighting in your text editor(s).

In addition to already mentioned causes of differences in how you see the same font displayed each modern operating system allows also to change how the fonts are rendered to the screen (choosing a method for antialiasing), but the differences in how a font is displayed caused by this are only small ones.


问:
Taking second-by-second data and transforming it into hour-by-hour?
So, I have a dataset that contains values sampled every second.

I would like to transform the above dataset that has the second-by-second data, so that it is indexed every hour.  And the value at each hour is the running sum total through the day.

I haven't been able to find anything similar in my searches, so if anyone could point me in the best direction to find out the best method to accomplish this; it would be greatly appreciated!

答:
It really depends on what you are using to implement this as well as the greater context of your application, but generally a running sum is fairly simple in most cases.  For instance, if you are using a language such as the one in Matlab, there are functions that allow you to sum all of the contents in an array (as you would in Excel).  Other languages have libraries or packages you can call on to do this also, and I recommend looking it up if you are using anything higher level than, say, C.

However, let's assume you want to write your own function to do this.  The way that jumps to my mind is a single iteration through your data array.  Say your array has n elements in it.  With your loop, designate a variable, and in each loop iteration, increase the value via a sum, for example:

my $sum = $dataArray[0];     # running sum tracker, initialize to first value
for ($i=1; $i < <length of your array>; $i++) {
  $sum += $dataArray[$i];
}

In the end, this loop would have complexity O(n).  I would also then add a conditional in the loop to throw the sum for index $i into some other data structure and index it with $i when $i is a multiple of seconds in an hour (3600 samples).  My favorite way to do that would probably a hash or associative array to map $i => $sum pairs as this would allow me to track EXACTLY where cut off each running sum. But there's no reason a plain old array can't suffice if you are willing to write the code to convert your 1:n indices into "time" and just assume they correspond to "hour 0, hour 1, hour 2 ....".

WARNING:  If you do this, I caution you that there is no substitute for having timestamps with your data.  Sampling rate can have hardware drift or approximation error while scripting, and this can lead to significant skew in time vs. data accounting if you are not careful.


问:
Open directions func not opening apple maps programmatically
I am working on a project right now and am stuck on the final part. I have designed an app with 20 custom annotations to be used by our wedding guests to find nearby restaurants, bars, coffee shops, etc. There are various custom annotation to identify what each location is. It also asks for users current location so they can find things nearby. I would like to be able to click on the annotations and have our friends and family be able to get directions from their current location to the annotation. It seems like the best way to do this is by opening up the apple maps app with my latitude and longitude coordinates in my custom point annotations. My code though does not seem to open that maps app at all. I have added a right call out, I have looked through every since question old and new asking about this and can not find a solution. Any advice will be much appreciated as this is my first real swift app. Below is my current open directions function. Thank you in advance for any help or insight.</p>

```<code>    func openDirections(_ address :String?) {

    self.geocoder.geocodeAddressString(address!, completionHandler: { (placemarks :[CLPlacemark]?, error :NSError?) -> Void in

        let placemark = placemarks![0] as CLPlacemark

        let destinationPlacemark = MKPlacemark(coordinate: placemark.location!.coordinate, addressDictionary: placemark.addressDictionary as? [String:NSObject])

        let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: placemark.location!.coordinate, addressDictionary:nil))
        mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving])

        let startingMapItem = MKMapItem.forCurrentLocation()
        let destinationMapItem = MKMapItem(placemark: destinationPlacemark)

        let directionsRequest = MKDirectionsRequest()
        directionsRequest.transportType = .automobile
        directionsRequest.source = startingMapItem
        directionsRequest.destination = destinationMapItem

        let directions = MKDirections(request: directionsRequest)

        directions.calculate(completionHandler: { (response :MKDirectionsResponse?, error :NSError?) -> Void in

            let route = response!.routes[0] as MKRoute

            if route.steps.count > 0 {

                for step in route.steps {

                    print(step.instructions)

                }
            }

            self.mapView!.add((route.polyline), level: MKOverlayLevel.aboveRoads)
            } as! MKDirectionsHandler)
        } as! CLGeocodeCompletionHandler)
}
</code>```

答:
Go ahead and delete everything you wrote and do some research on how to write a new, better, cleaner function. Here is what worked for me and I hope it helps someone else.</p>

```<code>    func mapView(_ mapView: MKMapView, annotationView view:MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    let placemark = MKPlacemark(coordinate: view.annotation!.coordinate, addressDictionary: nil)
    let mapItem = MKMapItem(placemark: placemark)
    let launchOptions = [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit]
    self.title = title
    mapItem.name = title
    mapItem.openInMaps(launchOptions: launchOptions)
}
</code>```

Body:
I am working on a project right now and am stuck on the final part. I have designed an app with 20 custom annotations to be used by our wedding guests to find nearby restaurants, bars, coffee shops, etc. There are various custom annotation to identify what each location is. It also asks for users current location so they can find things nearby. I would like to be able to click on the annotations and have our friends and family be able to get directions from their current location to the annotation. It seems like the best way to do this is by opening up the apple maps app with my latitude and longitude coordinates in my custom point annotations. My code though does not seem to open that maps app at all. I have added a right call out, I have looked through every since question old and new asking about this and can not find a solution. Any advice will be much appreciated as this is my first real swift app. Below is my current open directions function. Thank you in advance for any help or insight.

    func openDirections(_ address :String?) {

    self.geocoder.geocodeAddressString(address!, completionHandler: { (placemarks :[CLPlacemark]?, error :NSError?) -> Void in

        let placemark = placemarks![0] as CLPlacemark

        let destinationPlacemark = MKPlacemark(coordinate: placemark.location!.coordinate, addressDictionary: placemark.addressDictionary as? [String:NSObject])

        let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: placemark.location!.coordinate, addressDictionary:nil))
        mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving])

        let startingMapItem = MKMapItem.forCurrentLocation()
        let destinationMapItem = MKMapItem(placemark: destinationPlacemark)

        let directionsRequest = MKDirectionsRequest()
        directionsRequest.transportType = .automobile
        directionsRequest.source = startingMapItem
        directionsRequest.destination = destinationMapItem

        let directions = MKDirections(request: directionsRequest)

        directions.calculate(completionHandler: { (response :MKDirectionsResponse?, error :NSError?) -> Void in

            let route = response!.routes[0] as MKRoute

            if route.steps.count > 0 {

                for step in route.steps {

                    print(step.instructions)

                }
            }

            self.mapView!.add((route.polyline), level: MKOverlayLevel.aboveRoads)
            } as! MKDirectionsHandler)
        } as! CLGeocodeCompletionHandler)
}

Body:
Go ahead and delete everything you wrote and do some research on how to write a new, better, cleaner function. Here is what worked for me and I hope it helps someone else.

    func mapView(_ mapView: MKMapView, annotationView view:MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    let placemark = MKPlacemark(coordinate: view.annotation!.coordinate, addressDictionary: nil)
    let mapItem = MKMapItem(placemark: placemark)
    let launchOptions = [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit]
    self.title = title
    mapItem.name = title
    mapItem.openInMaps(launchOptions: launchOptions)
}


问:
XML ElementTree - indexing tags
I have a XML file:

```<code><sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I've been to this restaurant over a dozen times with no complaints to date.</text>
</sentence>
</code>```

Using XML ElementTree, I would like to insert a tag <Opinion> that has an attribute category=. Say I have a list of chars list = ['a', 'b', 'c'], is it possible to incrementally asign them to each text so I have:

```<code><sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
   <Opinion category='a' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
   <Opinion category='b' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I've been to this restaurant over a dozen times with no complaints to date.</text>
   <Opinion category='c' />
</sentence>
</code>```

I am aware I can use the sentence id attribute but this would require a lot of restructuring of my code. Basically, I'd like to be able to index each sentence entry to align with my list index.

答:
You can use the SubElement factory function to add elements to the tree.
Assuming your XML data is in a variable called data, this will add the elements to your document tree:

```<code>import xml.etree.ElementTree as ET
tree = ET.XML(data)
for elem, category in zip(tree.findall('sentence'), ['a', 'b', 'c']):
    Opinion  = ET.SubElement(elem, 'Opinion')
    Opinion.set('category', category)

ET.dump(tree)  # prints the tree; tree.write('output.xml') is another option
</code>```

Title: XML ElementTree - indexing tags

Body:
I have a XML file:

<sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I've been to this restaurant over a dozen times with no complaints to date.</text>
</sentence>

Using XML ElementTree, I would like to insert a tag <Opinion> that has an attribute category=. Say I have a list of chars list = ['a', 'b', 'c'], is it possible to incrementally asign them to each text so I have:

<sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
   <Opinion category='a' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
   <Opinion category='b' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I've been to this restaurant over a dozen times with no complaints to date.</text>
   <Opinion category='c' />
</sentence>

I am aware I can use the sentence id attribute but this would require a lot of restructuring of my code. Basically, I'd like to be able to index each sentence entry to align with my list index.

Body:
You can use the SubElement factory function to add elements to the tree.
Assuming your XML data is in a variable called data, this will add the elements to your document tree:

import xml.etree.ElementTree as ET
tree = ET.XML(data)
for elem, category in zip(tree.findall('sentence'), ['a', 'b', 'c']):
    Opinion  = ET.SubElement(elem, 'Opinion')
    Opinion.set('category', category)

ET.dump(tree)  # prints the tree; tree.write('output.xml') is another option


问:
Multiple compiled libraries in one Function App
is it possible to have more than one compiled library in one Function App?
I'm wondering with "Function Proxies" if that would still be applicable with a compiled C# library?!

Or is there 1 Function App == 1 compiled library ?

Cheers

David

答:
You can have multiple C# libraries per function app, just use a different value for "scriptFile" and "entryPoint".

The best way to do this would be to have 2 class library projects and one Web project for deployment.

Example layout:

FirstClassLibrary

SecondClassLibrary

WebProject: references class libraries above and contains function.json files

FirstFunc/function.json would contain:

"scriptFile": "..\\bin\\First.dll",
 "entryPoint": "Namespace.MyFunction"

Second/function.json would contain:

"scriptFile": "..\\bin\\Second.dll",
 "entryPoint": "Namespace.MyOtherGreatFunction"

To check the Kudu build, try msbuild for the solution from the command line. If that works, Kudu should also work.


问:
Selecting random records for use on a web page
HI Guys,

I own a website I have a section called "mobile Section" this section contain many catagories (Nameoftheobject + a picture + little description and a download link)
Now the section is considered as an internal section. I want to view random records from that section on the first page (I dont know Like RSS but not Rss) showing
the name of the object and to which subcategories it belong and its picture if possible.
I hope any one understand what I'm trying to say.

This is my website HERE and this the link of the internal page HERE check the block that say Mobile Section Its kinda a mess.
is there any script or a tech to view it in a proper way to view it show me examples if possible

I'm using php and MySQL

Thanx in advance

答: This idea sort of steals from David Thomas Garcia. What you could do is in your database implement a field that would keep track of views of a product (or you could eschew this and just keep track of purchases) and you can select the items from your database as "Top Sellers" or "Hot Products" to then display on your site.</p>

OwnerDisplayName: shicosvnki

LastEditorDisplayName: Tom Anderson

OwnerDisplayName: TheTXI


问:
AVCapturePhotoOutput isFlashScene Key-Value-Observing
I am following Apple's latest sample code AVCam Swift, which is updated to use AVCapturePhotoOutput.

var isFlashScene: Bool { get }

A Boolean value indicating whether the scene currently being previewed
  by the camera warrants use of the flash. This property’s value changes
  depending on the scene currently visible to the camera. For example,
  you might use this property to highlight the flash control in your
  app’s camera UI, indicating to the user that the scene is dark enough
  that enabling the flash might be desirable. If the photo capture
  output’s supportedFlashModes value is off, this property’s value is
  always false. This property supports Key-value observing.

I am trying to Key-value observe this so when Auto Flash Mode indicates that this is a scene that flash will fire (Just like the stock iOS Camera App), So I can change the UI, just like the documentation notes.

So I set it up like this:

```<code>private let photoOutput = AVCapturePhotoOutput()

private var FlashSceneContext = 0

self.addObserver(self, forKeyPath: "photoOutput.isFlashScene", options: .new, context: &FlashSceneContext)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  if context == & FlashSceneContext {
     print ("Flash Scene Changed")
  }
}
</code>```

Above never shows a change.  Even if I put a log in to check

```<code>print (self.photoOutput.isFlashScene)
</code>```

This comes out as False all the time though out the app.

I also tried :

```<code>self.photoOutput.addObserver(self, forKeyPath: "isFlashScene", options: .new, context: &FlashSceneContext)
</code>```

.... still no change is Flash Scene, it's stuck on False.

答:
```<code>self.photoOutput.addObserver(self, forKeyPath: "isFlashScene", options: .new, context: &FlashSceneContext)
</code>```

Above was the proper way to setup the KVO.

photoSettingsForSceneMonitoring has to be implemented:

```<code>let photoSettings = AVCapturePhotoSettings()
photoSettings.flashMode = .auto
photoSettings.isAutoStillImageStabilizationEnabled = true
self.photoOutput.photoSettingsForSceneMonitoring = photoSettings
</code>```

Works!

Body:
I am following Apple's latest sample code AVCam Swift, which is updated to use AVCapturePhotoOutput.

var isFlashScene: Bool { get }

A Boolean value indicating whether the scene currently being previewed
  by the camera warrants use of the flash. This property’s value changes
  depending on the scene currently visible to the camera. For example,
  you might use this property to highlight the flash control in your
  app’s camera UI, indicating to the user that the scene is dark enough
  that enabling the flash might be desirable. If the photo capture
  output’s supportedFlashModes value is off, this property’s value is
  always false. This property supports Key-value observing.

I am trying to Key-value observe this so when Auto Flash Mode indicates that this is a scene that flash will fire (Just like the stock iOS Camera App), So I can change the UI, just like the documentation notes.

So I set it up like this:

private let photoOutput = AVCapturePhotoOutput()

private var FlashSceneContext = 0

self.addObserver(self, forKeyPath: "photoOutput.isFlashScene", options: .new, context: &FlashSceneContext)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  if context == & FlashSceneContext {
     print ("Flash Scene Changed")
  }
}

Above never shows a change.  Even if I put a log in to check

print (self.photoOutput.isFlashScene)

This comes out as False all the time though out the app.

I also tried :

self.photoOutput.addObserver(self, forKeyPath: "isFlashScene", options: .new, context: &FlashSceneContext)

.... still no change is Flash Scene, it's stuck on False.

Body:
self.photoOutput.addObserver(self, forKeyPath: "isFlashScene", options: .new, context: &FlashSceneContext)

Above was the proper way to setup the KVO.

photoSettingsForSceneMonitoring has to be implemented:

let photoSettings = AVCapturePhotoSettings()
photoSettings.flashMode = .auto
photoSettings.isAutoStillImageStabilizationEnabled = true
self.photoOutput.photoSettingsForSceneMonitoring = photoSettings

Works!


问:
Converting 3 seperate arrays of dictionaries into 1 struct array?
I am currently using 3 separate arrays to populate a sectioned UITableView and I'd like to use just a single array for filtering purposes but still maintain the sections within my table.

The data is fed by a single JSON string which I then iterate through to create a dictionary of a single 'Event' and then based on the value of 'Event Status', it is added to one of three arrays (open, closed and deferred). These arrays are then uses to populate each section of a UITableView.

```<code>let myDictionary: [String: String] = [
      "EventID" : item["EventID"] as! String,
      "EventTitle" : item["EventTitle"] as! String,
      "EventSummary" : item["EventSummary"] as! String,
      "EventStatus" : item["Status"] as! String
      ]

 if (item["Status"] as! String == "Open") {
     self.openEvents.append(myDictionary as AnyObject)
 }
 if (item["Status"] as! String == "Closed") {
     self.closedEvents.append(myDictionary as AnyObject)
 }
 if (item["Status"] as! String == "") {
     self.deferredEvents.append(myDictionary as AnyObject)
 }
</code>```

Then in cellForRowAt:

```<code>var tmpDict: [String: String] = ["":""]

if sectionHeaders[indexPath.section] == "Open" {
    tmpDict = openEvents[indexPath.row] as! [String : String]
}

if sectionHeaders[indexPath.section] == "Closed" {
    tmpDict = closedEvents[indexPath.row] as! [String : String]
}

if sectionHeaders[indexPath.section] == "Deferred" {
    tmpDict = deferredEvents[indexPath.row] as! [String : String]
}
</code>```

Problem is that in order to allow filtering of this data, I'd have to run the filter against three different arrays which means three different 'filtered data' arrays. Which is far from ideal.

What I'd like to achieve is to have a single array of structured data (as opposed to dictionaries) that the user can filter through and the result returned to a single 'filtered data' array. I am doing this elsewhere with good effect, however, that is for a single list, not sectioned.

I have a struct setup and adding items to it as follows:

```<code>let data = EventItem(EventID: item["EventID"] as! String, EventTitle: item["EventTitle"] as! String, EventSummary: item["EventSummary"] as! String, EventStatus: item["Status"] as! String)

self.eventList.append(data)
</code>```

and filtering using:

```<code>filteredData = eventList.filter() {
   ($0.EventTitle.lowercased() as NSString).contains(searchText.lowercased()) || ($0.EventSummary.lowercased() as NSString).contains(searchText.lowercased())
}

eventsTable.reloadData()
</code>```

Is it possible to split this single array over different sections in a TableView? if so, how?

答:
I would suggest giving a little more responsibility to your EventItem struct to help with the data source response. The you can then use a two dimensional array to manage both the section and row contents.

For example:

```<code>struct EventItem
{
      var EventID        = ""
      var EventTitle     = ""
      var EventSummary   = ""
      var EventStatus    = ""

      func matches(_ searchText:String) -> Bool
      {
         return EventTitle.lowercased().contains(searchText.lowercased())
             || EventSummary.lowercased().contains(searchText.lowercased())
      }

      var section:Int
      {
         return EventStatus == "Opened"  ?  0
              : EventStatus == "Closed"  ?  1
              :                             2
      }
}

// you can maintain an "master" array of events (or build them from the dictionary as needed)
// I' using an array to keep the example simple

var eventList:[EventItem] = []

// This 2D array in your controller will serve as the store for your table view data source
var sectionData:[[EventItem]] = []

// applying filter is one line once you've added utility functions to your struct
sectionData = Array(0..<3).map{ section in return eventList.filter{$0.section == section && $0.matches(searchText)} }

// responding to tableview data source protocol only requires one line
// (which will not change even if you break down your data into more sections)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{ return sectionData[section].count }

// getting to the data to populate the table view cell will be quite straightforward
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let rowData = sectionData[indexPath.section][indexPath.row]
    // setup cell ...
}
</code>```

Body:
I am currently using 3 separate arrays to populate a sectioned UITableView and I'd like to use just a single array for filtering purposes but still maintain the sections within my table.

The data is fed by a single JSON string which I then iterate through to create a dictionary of a single 'Event' and then based on the value of 'Event Status', it is added to one of three arrays (open, closed and deferred). These arrays are then uses to populate each section of a UITableView.

let myDictionary: [String: String] = [
      "EventID" : item["EventID"] as! String,
      "EventTitle" : item["EventTitle"] as! String,
      "EventSummary" : item["EventSummary"] as! String,
      "EventStatus" : item["Status"] as! String
      ]

 if (item["Status"] as! String == "Open") {
     self.openEvents.append(myDictionary as AnyObject)
 }
 if (item["Status"] as! String == "Closed") {
     self.closedEvents.append(myDictionary as AnyObject)
 }
 if (item["Status"] as! String == "") {
     self.deferredEvents.append(myDictionary as AnyObject)
 }

Then in cellForRowAt:

var tmpDict: [String: String] = ["":""]

if sectionHeaders[indexPath.section] == "Open" {
    tmpDict = openEvents[indexPath.row] as! [String : String]
}

if sectionHeaders[indexPath.section] == "Closed" {
    tmpDict = closedEvents[indexPath.row] as! [String : String]
}

if sectionHeaders[indexPath.section] == "Deferred" {
    tmpDict = deferredEvents[indexPath.row] as! [String : String]
}

Problem is that in order to allow filtering of this data, I'd have to run the filter against three different arrays which means three different 'filtered data' arrays. Which is far from ideal.

What I'd like to achieve is to have a single array of structured data (as opposed to dictionaries) that the user can filter through and the result returned to a single 'filtered data' array. I am doing this elsewhere with good effect, however, that is for a single list, not sectioned.

I have a struct setup and adding items to it as follows:

let data = EventItem(EventID: item["EventID"] as! String, EventTitle: item["EventTitle"] as! String, EventSummary: item["EventSummary"] as! String, EventStatus: item["Status"] as! String)

self.eventList.append(data)

and filtering using:

filteredData = eventList.filter() {
   ($0.EventTitle.lowercased() as NSString).contains(searchText.lowercased()) || ($0.EventSummary.lowercased() as NSString).contains(searchText.lowercased())
}

eventsTable.reloadData()

Is it possible to split this single array over different sections in a TableView? if so, how?

Body:
I would suggest giving a little more responsibility to your EventItem struct to help with the data source response. The you can then use a two dimensional array to manage both the section and row contents.

For example:

struct EventItem
{
      var EventID        = ""
      var EventTitle     = ""
      var EventSummary   = ""
      var EventStatus    = ""

      func matches(_ searchText:String) -> Bool
      {
         return EventTitle.lowercased().contains(searchText.lowercased())
             || EventSummary.lowercased().contains(searchText.lowercased())
      }

      var section:Int
      {
         return EventStatus == "Opened"  ?  0
              : EventStatus == "Closed"  ?  1
              :                             2
      }
}

// you can maintain an "master" array of events (or build them from the dictionary as needed)
// I' using an array to keep the example simple

var eventList:[EventItem] = []

// This 2D array in your controller will serve as the store for your table view data source
var sectionData:[[EventItem]] = []

// applying filter is one line once you've added utility functions to your struct
sectionData = Array(0..<3).map{ section in return eventList.filter{$0.section == section && $0.matches(searchText)} }

// responding to tableview data source protocol only requires one line
// (which will not change even if you break down your data into more sections)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{ return sectionData[section].count }

// getting to the data to populate the table view cell will be quite straightforward
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let rowData = sectionData[indexPath.section][indexPath.row]
    // setup cell ...
}


问:
How do I reference values in an List, excluding the current element
So this is something that should be easy to get around but I can't quite figure out. (I'm using XNA for Visual Studios 2015. I know it's a bit outdated)

What I have is a List of Enemies (from an Enemy class). Each enemy is assigned a collision rectangle, and if one enemy intersects another enemy's collision box, they stop moving.
I'd like to use something similar to a for loop.

```<code>for (int i = 0; i < spawnAmount; i++)
{
    if (enemies[i].collisionRect.Intersects(enemies[].collisionRect))
        enemies[i].allActive = false;
}
</code>```

So in the blank space (where enemies[] should have a value), is there any way to use all of the values from the enemies List (i.e enemies[1, 2, 3, 4, 5]) minus enemies[i]? Otherwise the enemy detects its own collision box and stops anyway. It doesn't have to be confined to a few lines but the less complicated the better.

答:
Nested loops...

```<code>for (int i = 0; i < spawnAmount - 1; i++)
{
   for (int j = i + 1; j < spawnAmount; j++)
   {
       if (enemies[i].collisionRect.Intersects(enemies[j].collisionRect))
       {
           enemies[i].allActive = false;
       }
   }
}
</code>```

So you start going through enemies. Let's say spawnAmount is 5.

So for i = 0, you compare 0 -> 1, 0 -> 2, 0 -> 3 and 0 -> 4.

i = 1, you compare 1 -> 2, 1 -> 3, 1 -> 4

i = 2, you compare 2 -> 3, 2 -> 4

i = 3, you compare 3 -> 4

You don't need to compare any for i=4, because you'll have covered them all anyway, and because for each iteration you start j at i+1, they will never be the same anyway.

Body:
So this is something that should be easy to get around but I can't quite figure out. (I'm using XNA for Visual Studios 2015. I know it's a bit outdated)

What I have is a List of Enemies (from an Enemy class). Each enemy is assigned a collision rectangle, and if one enemy intersects another enemy's collision box, they stop moving.
I'd like to use something similar to a for loop.

for (int i = 0; i < spawnAmount; i++)
{
    if (enemies[i].collisionRect.Intersects(enemies[].collisionRect))
        enemies[i].allActive = false;
}

So in the blank space (where enemies[] should have a value), is there any way to use all of the values from the enemies List (i.e enemies[1, 2, 3, 4, 5]) minus enemies[i]? Otherwise the enemy detects its own collision box and stops anyway. It doesn't have to be confined to a few lines but the less complicated the better.

Body:
Nested loops...

for (int i = 0; i < spawnAmount - 1; i++)
{
   for (int j = i + 1; j < spawnAmount; j++)
   {
       if (enemies[i].collisionRect.Intersects(enemies[j].collisionRect))
       {
           enemies[i].allActive = false;
       }
   }
}

So you start going through enemies. Let's say spawnAmount is 5.

So for i = 0, you compare 0 -> 1, 0 -> 2, 0 -> 3 and 0 -> 4.

i = 1, you compare 1 -> 2, 1 -> 3, 1 -> 4

i = 2, you compare 2 -> 3, 2 -> 4

i = 3, you compare 3 -> 4

You don't need to compare any for i=4, because you'll have covered them all anyway, and because for each iteration you start j at i+1, they will never be the same anyway.


答:
how can I just hide the text inside the href tag?

simply set the font-size to 0.

<!DOCTYPE html>

    <title>Page Title</title>

Part 1

Part 2

Part 3

```

Title: Using CSS or JS to hide text inside the a href tag

Body:
I have a list in this format:

Part 1

Part 2

Part 3

I am using css :before to display something instead of the text inside the a href tag and I want to hide the text. I just want to hide Part 1, Part 2, Part 3 text and leave a href tag there.

If I use display:none; then everything is hidden, how can I just hide the text inside the href tag?

Body:
how can I just hide the text inside the href tag?

simply set the font-size to 0.

<!DOCTYPE html>
<html>
  <head>
    <title>Page Title</title>
    <style>
    a{
      font-size: 0;
    }
    </style>
  </head>
<body>

<ul>
    <li><a href="link">Part 1</a></li>
    <li><a href="link">Part 2</a></li>
    <li><a href="link">Part 3</a></li>
</ul>

</body>
</html>


问:
PowerShell dir /ah not working?
When I try dir /ah under Windows 10 I get the following:

```<code>PS C:\Users\Robert\dev\fiedz> dir /ah
dir : Cannot find path 'C:\ah' because it does not exist.
At line:1 char:1
+ dir /ah
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\ah:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
</code>```

Any idea why ?

答:
Dir is only an alias to Get-ChildItem in PowerShell.

Since the path separator / is also accepted you got that error msg.

To resemble cmd dir behavior use the -force parameter

To select only files with a given Attribute check with a piped where:

```<code>Gci c:\ -force|Where Attributes -like '*Hidden*'
</code>```

Edit Just remembered there also is a shortcut, you can use

```<code>ls c:\ -ah
</code>```

Title: PowerShell dir /ah not working?

Body:
When I try dir /ah under Windows 10 I get the following:

PS C:\Users\Robert\dev\fiedz> dir /ah
dir : Cannot find path 'C:\ah' because it does not exist.
At line:1 char:1
+ dir /ah
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\ah:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Any idea why ?

Body:
Dir is only an alias to Get-ChildItem in PowerShell.

Since the path separator / is also accepted you got that error msg.

To resemble cmd dir behavior use the -force parameter

To select only files with a given Attribute check with a piped where:

Gci c:\ -force|Where Attributes -like '*Hidden*'

Edit Just remembered there also is a shortcut, you can use

ls c:\ -ah


问:
XSLT : recursive string concatenation from parent/child structure
I'd like some help on a topic I cannot find a solution to (and I'm a tad on the rush...)
I'm average in XSLT and this point is beyond my skills.

My source XML has got a tree structure organized as Child/Parent, already sorted with top nodes up.

EDITED : added top enclosing for Department nodes.
Here's an example :

```<code><AllDepartments>
 <Department>
  <Code>1</Code>
  <ParentCode></ParentCode>
  <Label>IT</Label>
 </Department>
 <Department>
  <Code>2</Code>
  <ParentCode>1</ParentCode>
  <Label>Security</Label>
 </Department>
 <Department>
  <Code>3</Code>
  <ParentCode>2</ParentCode>
  <Label>SSO</Label>
 </Department>
</AllDepartments>
</code>```

I'd like the output to be formatted as :

```<code><AllDepartments>
 <Department>
    <Code>1</Code>
    <ParentCode></ParentCode>
    <Label>IT</Label>
  </Department>
  <Department>
    <Code>2</Code>
    <ParentCode>1</ParentCode>
    <Label>Security</Label>
  </Department>
  <Department>
    <Code>3</Code>
    <ParentCode>1.2</ParentCode>
    <Label>SSO</Label>
  </Department>
</AllDepartments>
</code>```

It means that, as soon as I reach the 3rd level, ParentCode should be a concatenation of all ParentCode ancestors (including ParentCode itself), with a dot as separator.
The maximum depth of level is 7, thus I was looking for a recursive concatenation algorithm.

I've tried some XSL I'm too ashamed to show (trying call-template, apply-template)...
I've looked for similar topics, found some but not as "simple" as my case.

Any help would be appreciated (XSLT 2.0 allowed).

答:
First, you will need a well-formed XML input, with a single root element such as:

XML

```<code><Departments>
   <Department>
      <Code>1</Code>
      <ParentCode/>
      <Label>IT</Label>
   </Department>
   <Department>
      <Code>2</Code>
      <ParentCode>1</ParentCode>
      <Label>Security</Label>
   </Department>
   <Department>
      <Code>3</Code>
      <ParentCode>2</ParentCode>
      <Label>SSO</Label>
   </Department>
</Departments>
</code>```

Then you can use:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:key name="parent" match="Department" use="Code" />

<xsl:template match="ParentCode">
    <xsl:copy>
        <xsl:apply-templates select="key('parent', .)" mode="parent"/>
        <xsl:value-of select="."/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Department" mode="parent">
    <xsl:if test="string(ParentCode)">
        <xsl:apply-templates select="key('parent', ParentCode)" mode="parent"/>
        <xsl:value-of select="ParentCode"/>
        <xsl:text>.</xsl:text>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>
</code>```

to get:

Result

```<code><?xml version="1.0" encoding="UTF-8"?>
<Departments>
   <Department>
      <Code>1</Code>
      <ParentCode/>
      <Label>IT</Label>
   </Department>
   <Department>
      <Code>2</Code>
      <ParentCode>1</ParentCode>
      <Label>Security</Label>
   </Department>
   <Department>
      <Code>3</Code>
      <ParentCode>1.2</ParentCode>
      <Label>SSO</Label>
   </Department>
</Departments>
</code>```

Body:
I'd like some help on a topic I cannot find a solution to (and I'm a tad on the rush...)
I'm average in XSLT and this point is beyond my skills.

My source XML has got a tree structure organized as Child/Parent, already sorted with top nodes up.

EDITED : added top enclosing for Department nodes.
Here's an example :

<AllDepartments>
 <Department>
  1
  <ParentCode></ParentCode>
  IT
 </Department>
 <Department>
  2
  <ParentCode>1</ParentCode>
  Security
 </Department>
 <Department>
  3
  <ParentCode>2</ParentCode>
  SSO
 </Department>
</AllDepartments>

I'd like the output to be formatted as :

<AllDepartments>
 <Department>
    1
    <ParentCode></ParentCode>
    IT
  </Department>
  <Department>
    2
    <ParentCode>1</ParentCode>
    Security
  </Department>
  <Department>
    3
    <ParentCode>1.2</ParentCode>
    SSO
  </Department>
</AllDepartments>

It means that, as soon as I reach the 3rd level, ParentCode should be a concatenation of all ParentCode ancestors (including ParentCode itself), with a dot as separator.
The maximum depth of level is 7, thus I was looking for a recursive concatenation algorithm.

I've tried some XSL I'm too ashamed to show (trying call-template, apply-template)...
I've looked for similar topics, found some but not as "simple" as my case.

Any help would be appreciated (XSLT 2.0 allowed).

Body:
First, you will need a well-formed XML input, with a single root element such as:

XML

<Departments>
   <Department>
      <Code>1</Code>
      <ParentCode/>
      <Label>IT</Label>
   </Department>
   <Department>
      <Code>2</Code>
      <ParentCode>1</ParentCode>
      <Label>Security</Label>
   </Department>
   <Department>
      <Code>3</Code>
      <ParentCode>2</ParentCode>
      <Label>SSO</Label>
   </Department>
</Departments>

Then you can use:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:key name="parent" match="Department" use="Code" />

<xsl:template match="ParentCode">
    <xsl:copy>
        <xsl:apply-templates select="key('parent', .)" mode="parent"/>
        <xsl:value-of select="."/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Department" mode="parent">
    <xsl:if test="string(ParentCode)">
        <xsl:apply-templates select="key('parent', ParentCode)" mode="parent"/>
        <xsl:value-of select="ParentCode"/>
        <xsl:text>.</xsl:text>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

to get:

Result

<?xml version="1.0" encoding="UTF-8"?>
<Departments>
   <Department>
      <Code>1</Code>
      <ParentCode/>
      <Label>IT</Label>
   </Department>
   <Department>
      <Code>2</Code>
      <ParentCode>1</ParentCode>
      <Label>Security</Label>
   </Department>
   <Department>
      <Code>3</Code>
      <ParentCode>1.2</ParentCode>
      <Label>SSO</Label>
   </Department>
</Departments>


答:
You want to use the Except LINQ extension (from System.Linq).

The only catch is that you need to pass it a collection, so your code would be something like:

```<code>Enemy[] exclusionList = new Enemy[1]; //Construct outside of loop for efficiency
for (int i = 0; i < spawnAmount; i++)
{
    Enemy currentEnemy = enemies[i];
    exclusionList[0] = currentEnemy;
    if (enemies.Except(exclusionList).Any(e => e.collisionRect.Intersects(currentEnemy.collisionRect))
        enemies[i].allActive = false;
}
</code>```

You might be able to replace the for loop entirely with some clever LINQ, and should also consider adding far away enemies to the exclusion list, as you obviously aren't colliding with them.

@MattWhitfields answer is actually more efficient, as this code will comare enemy 1 to enemy 0 and vice versa, which is definitely not required. You could build a more clever exclusion list to accommodate this problem, or use the for loops he describes.

Title: How do I reference values in an List, excluding the current element

Body:
You want to use the Except LINQ extension (from System.Linq).

The only catch is that you need to pass it a collection, so your code would be something like:

Enemy[] exclusionList = new Enemy[1]; //Construct outside of loop for efficiency
for (int i = 0; i < spawnAmount; i++)
{
    Enemy currentEnemy = enemies[i];
    exclusionList[0] = currentEnemy;
    if (enemies.Except(exclusionList).Any(e => e.collisionRect.Intersects(currentEnemy.collisionRect))
        enemies[i].allActive = false;
}

You might be able to replace the for loop entirely with some clever LINQ, and should also consider adding far away enemies to the exclusion list, as you obviously aren't colliding with them.

@MattWhitfields answer is actually more efficient, as this code will comare enemy 1 to enemy 0 and vice versa, which is definitely not required. You could build a more clever exclusion list to accommodate this problem, or use the for loops he describes.


问:
Timer creates a new Window on Start
My timer is creating a new window with non-working buttons when I hit the start button. The change in display only happens in the new window but the start/stop functionality only works in the old window. I'm not sure what's going on here. Can someone help me figure out how to stop it from creating a new window when start is pressed?

I have three classes I'm working with. The first runs the timer.

```<code>package timer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.event.*;

public class TaskTimer extends TaskTimerWindow {

    int seconds = 0;
    int minutes = 0;
    int hours = 0;
    final int UNIT = 1000;
    boolean stopped = false;
    Timer timer;

    public TaskTimer() {

        ActionListener go = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                count();
            }
        };

        timer = new Timer(UNIT, go);
        timer.start();
    }

    public void resume() {
        if(stopped) {
            seconds = 0;
            minutes = 0;
            hours = 0;
        }
    }

    public void end() {
        timer.stop();
    }

    public void count() {
        if(seconds < 59) {
            seconds++;
        } else if(minutes < 59) {
            seconds = 0;
            minutes++;
        } else {
            seconds = 0;
            minutes = 0;
            hours++;
        }
        changeDisplay(String.format("%02d", hours) + ":"
             + String.format("%02d", minutes)  + ":"
             + String.format("%02d", seconds));
    }
}
</code>```

The second creates and updates the display.

```<code>package timer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TaskTimerWindow extends JFrame {

    JLabel timeDisplay;
    JButton start, stop, pause;

    public TaskTimerWindow() {

        JPanel timerWindow = new JPanel();
        JPanel buttonSpace = new JPanel();

        timeDisplay = new JLabel("00:00:00");
        timeDisplay.setHorizontalAlignment((int) CENTER_ALIGNMENT);
        timeDisplay.setFont(new Font("Arial", Font.PLAIN, 48));

        timeDisplay.setBackground(Color.WHITE);

        timerWindow.add(timeDisplay);

        start = new JButton("Start");
        stop = new JButton("Stop");
        pause = new JButton("Pause");

        buttonSpace.add(start);
        buttonSpace.add(stop);
        buttonSpace.add(pause);

        getContentPane().add(timerWindow, BorderLayout.NORTH);
        getContentPane().add(buttonSpace);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setLocationRelativeTo(null);
        setTitle("Task Timer");
        pack();
    }

    public JLabel getText() {
        return timeDisplay;
    }

    public void changeDisplay(String time) {
        getText().setText(time);
    }

}
</code>```

And the third is the controller.

```<code>package timer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ControlTimer {
    boolean stopped = false;
    boolean paused = false;
    TaskTimer timer;

    public ControlTimer() {
        TaskTimerWindow window = new TaskTimerWindow();
        window.start.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                timer = new TaskTimer();
            }
        });

        window.stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                stopped = true;
                timer.end();
            }
        });

        window.pause.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                paused = true;
            }
        });
    }
}
</code>```

答:
So the main problem is in your ControlTimer class. As TaskTimer extends TaskTimerWindow it was creating new window each time start button was pressed. You should modify it like following:

```<code>public class ControlTimer {
    boolean stopped = false;
    boolean paused = false;
    TaskTimer timer;

    public ControlTimer() {
        timer = new TaskTimer();
        timer.start.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                timer.resume();
                timer.start();
            }
        });

        timer.stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                timer.stopped = true;
                timer.end();
            }
        });

        timer.pause.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                timer.end();
            }
        });
    }
}
</code>```

Also there're some minor changes in TaskTimer class (removing timer.start() from constructor and introducing separate start() method instead:

```<code>public TaskTimer() {

    ActionListener go = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            count();
        }
    };

    timer = new Timer(UNIT, go);
}

public void start() {
    timer.start();
}
</code>```

Title: Timer creates a new Window on Start

Body:
My timer is creating a new window with non-working buttons when I hit the start button. The change in display only happens in the new window but the start/stop functionality only works in the old window. I'm not sure what's going on here. Can someone help me figure out how to stop it from creating a new window when start is pressed?

I have three classes I'm working with. The first runs the timer.

package timer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.event.*;

public class TaskTimer extends TaskTimerWindow {

    int seconds = 0;
    int minutes = 0;
    int hours = 0;
    final int UNIT = 1000;
    boolean stopped = false;
    Timer timer;

    public TaskTimer() {

        ActionListener go = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                count();
            }
        };

        timer = new Timer(UNIT, go);
        timer.start();
    }

    public void resume() {
        if(stopped) {
            seconds = 0;
            minutes = 0;
            hours = 0;
        }
    }

    public void end() {
        timer.stop();
    }

    public void count() {
        if(seconds < 59) {
            seconds++;
        } else if(minutes < 59) {
            seconds = 0;
            minutes++;
        } else {
            seconds = 0;
            minutes = 0;
            hours++;
        }
        changeDisplay(String.format("%02d", hours) + ":"
             + String.format("%02d", minutes)  + ":"
             + String.format("%02d", seconds));
    }
}

The second creates and updates the display.

package timer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TaskTimerWindow extends JFrame {

    JLabel timeDisplay;
    JButton start, stop, pause;

    public TaskTimerWindow() {

        JPanel timerWindow = new JPanel();
        JPanel buttonSpace = new JPanel();

        timeDisplay = new JLabel("00:00:00");
        timeDisplay.setHorizontalAlignment((int) CENTER_ALIGNMENT);
        timeDisplay.setFont(new Font("Arial", Font.PLAIN, 48));

        timeDisplay.setBackground(Color.WHITE);

        timerWindow.add(timeDisplay);

        start = new JButton("Start");
        stop = new JButton("Stop");
        pause = new JButton("Pause");

        buttonSpace.add(start);
        buttonSpace.add(stop);
        buttonSpace.add(pause);

        getContentPane().add(timerWindow, BorderLayout.NORTH);
        getContentPane().add(buttonSpace);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setLocationRelativeTo(null);
        setTitle("Task Timer");
        pack();
    }

    public JLabel getText() {
        return timeDisplay;
    }

    public void changeDisplay(String time) {
        getText().setText(time);
    }

}

And the third is the controller.

package timer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ControlTimer {
    boolean stopped = false;
    boolean paused = false;
    TaskTimer timer;

    public ControlTimer() {
        TaskTimerWindow window = new TaskTimerWindow();
        window.start.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                timer = new TaskTimer();
            }
        });

        window.stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                stopped = true;
                timer.end();
            }
        });

        window.pause.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                paused = true;
            }
        });
    }
}

Body:
So the main problem is in your ControlTimer class. As TaskTimer extends TaskTimerWindow it was creating new window each time start button was pressed. You should modify it like following:

public class ControlTimer {
    boolean stopped = false;
    boolean paused = false;
    TaskTimer timer;

    public ControlTimer() {
        timer = new TaskTimer();
        timer.start.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                timer.resume();
                timer.start();
            }
        });

        timer.stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                timer.stopped = true;
                timer.end();
            }
        });

        timer.pause.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                timer.end();
            }
        });
    }
}

Also there're some minor changes in TaskTimer class (removing timer.start() from constructor and introducing separate start() method instead:

public TaskTimer() {

    ActionListener go = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            count();
        }
    };

    timer = new Timer(UNIT, go);
}

public void start() {
    timer.start();
}


问:
Laravel stylesheets and javascript don't load for non-base routes
Okay--I know this is a really elementary issue, but I can't figure it out. This is a question regarding Laravel.

Basically, I have my stylesheets embedded in my default layout view. I'm currently just using regular css to link them, such as:

```<code><link rel="stylesheet" href="css/app.css" />
</code>```

It works great when I am at a single level route such as /about, but stops working when I go deeper, such as /about/me.

If I look at Chrome's developer console I see some of the following errors (only for the deeper routes):

```<code>Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://example.dev/about/css/app.css".
</code>```

So clearly it is now looking for the css inside the "about" folder--which of course isn't a folder at all.

I just want it to look in the same place for the assets regardless of the route.

答:
Laravel 5.4 with mix helper:</p>

```<code><link href="{{ mix('/css/app.css') }}" rel="stylesheet">
<script src="{{ mix('/js/app.js') }}"> </script>
</code>```

Body:
Okay--I know this is a really elementary issue, but I can't figure it out. This is a question regarding Laravel.

Basically, I have my stylesheets embedded in my default layout view. I'm currently just using regular css to link them, such as:

<link rel="stylesheet" href="css/app.css" />

It works great when I am at a single level route such as /about, but stops working when I go deeper, such as /about/me.

If I look at Chrome's developer console I see some of the following errors (only for the deeper routes):

Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://example.dev/about/css/app.css".

So clearly it is now looking for the css inside the "about" folder--which of course isn't a folder at all.

I just want it to look in the same place for the assets regardless of the route.

Body:
Laravel 5.4 with mix helper:

<link href="{{ mix('/css/app.css') }}" rel="stylesheet">
<script src="{{ mix('/js/app.js') }}"> </script>


问:
Make VBA DateDif behave and round down like Excel DATEDIFF
```<code>DateDiff("m", "06/14/1982", "09,01,1982") = 3

A1 = 06/14/1982
A2 = 09/01/1982
=DATEDIF(A1, A2, "m") = 2
</code>```

If I need DateDiff to round down like DATEDIF does, how do I accomplish this?

答:
You can use the Evaluate function in VBA.  However, when working with dates in this manner, you need to ensure that the value being seen by the formula is the number corresponding to the date, and not a VBA Date data type.  If the date is stored in a worksheet cell, you would do something like:

```<code>Evaluate("DATEDIF(" & [a1].Value2 & "," & [a2].Value2 & ", ""m"")")
</code>```

If the dates are stored as dates in VBA variables, then:

```<code>Evaluate("DATEDIF(" & CDbl(DT1) & "," & CDbl(DT2) & ", ""m"")")
</code>```

Body:
DateDiff("m", "06/14/1982", "09,01,1982") = 3

A1 = 06/14/1982
A2 = 09/01/1982
=DATEDIF(A1, A2, "m") = 2

If I need DateDiff to round down like DATEDIF does, how do I accomplish this?

Body:
You can use the Evaluate function in VBA.  However, when working with dates in this manner, you need to ensure that the value being seen by the formula is the number corresponding to the date, and not a VBA Date data type.  If the date is stored in a worksheet cell, you would do something like:

Evaluate("DATEDIF(" & [a1].Value2 & "," & [a2].Value2 & ", ""m"")")

If the dates are stored as dates in VBA variables, then:

Evaluate("DATEDIF(" & CDbl(DT1) & "," & CDbl(DT2) & ", ""m"")")


问:
Streaming live audio from Wowza to HTML5 clients?
I have an existing app that streams live audio from a Flash client over RTMP to a Wowza zerver ... I am able to connect Flash clients to this and get real-time, low latency audio without problem.

I'd like to connect some HTML5 based clients in PC, Android and iOS and not use any Flash on the client side ... the RTMP URI is normally "rtmp://myserver/live/mystream"  I've tried connecting video and audio tags from HTML5 pages with no success.

Wowza sells on the basis of being able to stream to any client ... if anyone knows the magic URI to put into an HTML video/audio tag, or some other method to allow me to receive the stream without suing Flash in the browser, I'd be very interested to see them.

Please note: this is live audio from an RTMP source, not files. It is audio, not video.

答:
You will need to use HLS for playback. The URI is in the form

```<code>http://<wowzaIP>:1935/<appName>/<streamName>/playlist.m3u8
</code>```

Moreover, Wowza currently supports HTML5 playback with the video tag for Safari on OSX/iOS devices only. Other browsers/platforms may be possible, but results vary. Alternatively, you can look into using an HTML5 player such as the free Wowza Player, and it should work across platforms.

Body:
You will need to use HLS for playback. The URI is in the form

http://<wowzaIP>:1935/<appName>/<streamName>/playlist.m3u8

Moreover, Wowza currently supports HTML5 playback with the video tag for Safari on OSX/iOS devices only. Other browsers/platforms may be possible, but results vary. Alternatively, you can look into using an HTML5 player such as the free Wowza Player, and it should work across platforms.


问:
How to prevent Vue.js from automatically merging CSS classes?
I recently started working with Vue.js and I really enjoy it but I have come across something that I just can't figure out how to do. I have searched and read the documentation but found no solution.

When you add a CSS class to any of your components Vue.js will automatically add or merge the CSS classes with the root element in your child component.

This is a nice feature but I need to deactivate this feature for a specific component since I want the classes to be added to a child element of the root element.

I made this fiddle to illustrate http://jsfiddle.net/rasmuswoelk/9m2j0a9s/3

```<code><div id="demo">
  <child-component class="some-class"></child-component>
</div>
</code>```

(The "some-class" is being added automatically and adds a green background color)

How can I prevent Vue.js from automatically merging CSS classes?

答:
You can't abstract away the wrapper div that you have in your template, and trying to make the component work in such as way as though that div doesn't exist will only lead to confusion and incorrect styling.

Let's say that you managed to get your component to apply the outer class to a nested element in its template (which is what you want). Now when people use that component and apply a class to it, the style is applied to the input element and it is as though the whole component consists solely of the input element and there is no such wrapper div (this is the behavior you want).

The problem with this is that some styles will work (like background-color, or any appearance style), but other styles that affect the layout won't work (like position: absolute, because it will cause the input element to be positioned relative to the wrapper div which is not what was expected).

People who use that component should know about how the template is structured so they can style it correctly, because in reality there is a wrapper div there which they need to take into account.

I should mention you might be able to abstract away the wrapper div by using web components or the shadow DOM, but that's out of context of Vue.

Body:
I recently started working with Vue.js and I really enjoy it but I have come across something that I just can't figure out how to do. I have searched and read the documentation but found no solution.

When you add a CSS class to any of your components Vue.js will automatically add or merge the CSS classes with the root element in your child component.

This is a nice feature but I need to deactivate this feature for a specific component since I want the classes to be added to a child element of the root element.

I made this fiddle to illustrate http://jsfiddle.net/rasmuswoelk/9m2j0a9s/3

  <child-component class="some-class"></child-component>

(The "some-class" is being added automatically and adds a green background color)

How can I prevent Vue.js from automatically merging CSS classes?


问:
Using CSS or JS to hide text inside the a href tag
I have a list in this format:

```<code><ul>
    <li><a href="link">Part 1</a></li>
    <li><a href="link">Part 2</a></li>
    <li><a href="link">Part 3</a></li>
</ul>
</code>```

I am using css :before to display something instead of the text inside the a href tag and I want to hide the text. I just want to hide Part 1, Part 2, Part 3 text and leave a href tag there.

If I use display:none; then everything is hidden, how can I just hide the text inside the href tag?

答:
This should solve your issue with only the Part 1, Part 2 etc hidden.

```<code>ul li a {
  visibility: hidden;
}
ul li a:before {
  visibility: visible;
}
</code>```

The other declaration is necessary, or your :before text is hidden as well. This will keep your anchor intact, of course.

Body:
This should solve your issue with only the Part 1, Part 2 etc hidden.

ul li a {
  visibility: hidden;
}
ul li a:before {
  visibility: visible;
}

The other declaration is necessary, or your :before text is hidden as well. This will keep your anchor intact, of course.


问:
Declaring Height of an Article
 I am working on creating my Portfolio Website gw.mvctc.com/Class2018/smcintosh I recently converted it partly to bootstrap, and it looks ok, but as you can see, on the home page, there is a horizontal scroll to nothing, and the boxes are not the same height. I have figured out that the horiz. scroll is the same width as the vertical scroll bar, so I'm not sure if that is part of the issue, or not.

How can I fix the horizontal scroll issue and how do I make the boxes  the same height?

At the moment i have this style code on my article, the object that has the box:

```<code>article {
    padding: 10px;
    border: #ff4100 solid 7.5px;
    border-radius: 15px;
}
</code>```

and this is the HTML for the article itself:

```<code><div class="fluid-container">
    <div class="row">
        <section class="col-lg-4 col-md-6 col-sm-6">
            <article>
                <h2>Education Goals</h2>
                <ul>
                    <li>At the moment my largest education goal is to graduate
                        from high school</li>
                    <li>I hope to have enough scholarships to be able to go to a
                        good college to further my education and gain more knowledge</li>
                    <li>I hope to graduate from a good college with a bachelor's
                        degree in some form of computer science</li>
                </ul>
            </article>
        </section>
        //More sections follow, hence the 2 other boxes
        //...
    </div>
</div>
</code>```

答:
The div with the class row has margin-right property set to -15px. The navbar also has margins set. Specifically though, the div is overflowing the body. Add an id tag to the div named boxcontent and style as follows:

```<code>nav,#boxcontent{
margin-left:0; /*optional but adding this makes the nav full width!*/
margin-right:0;
}
</code>```

Edit

pen is here

Title: Declaring Height of an Article

Body:
 I am working on creating my Portfolio Website gw.mvctc.com/Class2018/smcintosh I recently converted it partly to bootstrap, and it looks ok, but as you can see, on the home page, there is a horizontal scroll to nothing, and the boxes are not the same height. I have figured out that the horiz. scroll is the same width as the vertical scroll bar, so I'm not sure if that is part of the issue, or not.

How can I fix the horizontal scroll issue and how do I make the boxes  the same height?

At the moment i have this style code on my article, the object that has the box:

article {
    padding: 10px;
    border: #ff4100 solid 7.5px;
    border-radius: 15px;
}

and this is the HTML for the article itself:

Education Goals

At the moment my largest education goal is to graduate
                        from high school

I hope to have enough scholarships to be able to go to a
                        good college to further my education and gain more knowledge

I hope to graduate from a good college with a bachelor's
                        degree in some form of computer science

        //More sections follow, hence the 2 other boxes
        //...

Body:
The div with the class row has margin-right property set to -15px. The navbar also has margins set. Specifically though, the div is overflowing the body. Add an id tag to the div named boxcontent and style as follows:

nav,#boxcontent{
margin-left:0; /*optional but adding this makes the nav full width!*/
margin-right:0;
}

Edit

pen is here


答:
You can make your text color the same as the background-color (white in this example). The advantage is, that the link space is still there, when you move the mouse over it, keeping it clickable.

li a {
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li>Part 1</li>
    <li>Part 2</li>
    <li>Part 3</li>
</ul></code>```

Body:
I have a list in this format:

Part 1

Part 2

Part 3

I am using css :before to display something instead of the text inside the a href tag and I want to hide the text. I just want to hide Part 1, Part 2, Part 3 text and leave a href tag there.

If I use display:none; then everything is hidden, how can I just hide the text inside the href tag?

Body:
You can make your text color the same as the background-color (white in this example). The advantage is, that the link space is still there, when you move the mouse over it, keeping it clickable.

li a {
  color: #fff;
}

<ul>
    <li><a href="link">Part 1</a></li>
    <li><a href="link">Part 2</a></li>
    <li><a href="link">Part 3</a></li>
</ul>


问:
Check if a subset of characters in a list of strings is contained in another list of strings
So I have two list of strings. Those strings are formed by a sorted combination of one or more different characters. The characters are not all in the alphabet but are given.

Let's say, all the possible characters are [A, B, C, D, E], then the two lists have a combination of those elements (from 1 up to 5 in this case).

Example:

```<code>list1 = [AB, AB, C]
list2 = [ABC, CD, ABCDE, E]
</code>```

The number of elements in each list is not defined, but can range from 1 to 30, with the general case being around 10.

Now, what I want is to tell if there is at least one combination of unique characters per string in list1 that also exists in list2, regardless order. In the example, [A, A, C] is contained in list2 with [A, C, A, E].

The naive way I found to do this is doing all the possible 1 character combinations from each list and see if exists at least one case where list1 is contained in list2. But this can grow exponentially as all possible combinations of a 10 element list of 5-characters strings can be huge (and that's only the general case).

I have thought of using regular expressions or something like that, but I am really not picturing a more efficient solution.

I am using Python for this. Just in case is relevant because of an existing solution or library.

Thank you for your help!

答:
This may be a prime candidate for set operations. Lets take your example (notice, we needed to add quotes to make them strings).

```<code>list1 = ["AB", "AB", "C"]
list2 = ["ABC", "CD", "ABCDE", "E"]
</code>```

If we want a set with unique elements from both list1 and list2

```<code>print(set(list1) | set(list2))
#OUTPUT: {'C', 'AB', 'ABCDE', 'CD', 'ABC', 'E'}
</code>```

If we want to check what elements are common in both list1 and list2(If we were to add "C" to list2 we would have an output of {'C'} otherwise, there are no common elements shared which results in an empty set())

```<code>print(set(list1) & set(list2))
#OUTPUT: set()
</code>```

If we want the elements that are in list1 but not in list2

```<code>print(set(list1) - set(list2))
#OUTPUT: {'C', 'AB'}
</code>```

If we want a set with elements that are either in list1 or list2

```<code>print(set(list1) ^ set(list2))
#OUTPUT: {'E', 'CD', 'AB', 'ABC', 'C', 'ABCDE'}
</code>```

For more information you can check out https://docs.python.org/2/library/sets.html

I hope this helped!

Body:
So I have two list of strings. Those strings are formed by a sorted combination of one or more different characters. The characters are not all in the alphabet but are given.

Let's say, all the possible characters are [A, B, C, D, E], then the two lists have a combination of those elements (from 1 up to 5 in this case).

Example:

list1 = [AB, AB, C]
list2 = [ABC, CD, ABCDE, E]

The number of elements in each list is not defined, but can range from 1 to 30, with the general case being around 10.

Now, what I want is to tell if there is at least one combination of unique characters per string in list1 that also exists in list2, regardless order. In the example, [A, A, C] is contained in list2 with [A, C, A, E].

The naive way I found to do this is doing all the possible 1 character combinations from each list and see if exists at least one case where list1 is contained in list2. But this can grow exponentially as all possible combinations of a 10 element list of 5-characters strings can be huge (and that's only the general case).

I have thought of using regular expressions or something like that, but I am really not picturing a more efficient solution.

I am using Python for this. Just in case is relevant because of an existing solution or library.

Thank you for your help!

Body:
This may be a prime candidate for set operations. Lets take your example (notice, we needed to add quotes to make them strings).

list1 = ["AB", "AB", "C"]
list2 = ["ABC", "CD", "ABCDE", "E"]

If we want a set with unique elements from both list1 and list2

print(set(list1) | set(list2))
#OUTPUT: {'C', 'AB', 'ABCDE', 'CD', 'ABC', 'E'}

If we want to check what elements are common in both list1 and list2(If we were to add "C" to list2 we would have an output of {'C'} otherwise, there are no common elements shared which results in an empty set())

print(set(list1) & set(list2))
#OUTPUT: set()

If we want the elements that are in list1 but not in list2

print(set(list1) - set(list2))
#OUTPUT: {'C', 'AB'}

If we want a set with elements that are either in list1 or list2

print(set(list1) ^ set(list2))
#OUTPUT: {'E', 'CD', 'AB', 'ABC', 'C', 'ABCDE'}

For more information you can check out https://docs.python.org/2/library/sets.html

I hope this helped!


问:
Updating Ruby Hash Values with Array Values
I've created the following hash keys with values parsed from PDF into array:

```<code>columns = ["Sen", "P-Hire#", "Emp#", "DOH", "Last", "First"]
h = Hash[columns.map.with_index.to_h]
=> {"Sen"=>0, "P-Hire#"=>1, "Emp#"=>2, "DOH"=>3, "Last"=>4, "First"=>5}
</code>```

Now I want to update the value of each key with 6 equivalent values from another parsed data array:

```<code>rows = list.text.scan(/^.+/)
row = rows[0].tr(',', '')
@data = row.split
=> ["2", "6", "239", "05/05/67", "Harp", "Erin"]
</code>```

I can iterate over @data in the view and it will list each of the 6 values. When I try to do the same in the controller it sets the same value to each key:

```<code>data.each do |e|
  h.update(h){|key,v1| (e) }
end
=>
{"Sen"=>"Harper", "P-Hire#"=>"Harper", "Emp#"=>"Harper", "DOH"=>"Harper", "Last"=>"Harper", "First"=>"Harper"
</code>```

So it's setting the value of each key to the last value of the looped array...

答:
There are several ways to solve this problem but a more direct and straight forward way would be:

```<code>columns = ["Sen", "P-Hire#", "Emp#", "DOH", "Last", "First"]
...
@data = row.split

h = Hash.new
columns.each_with_index do |column, index|
 h[column] = @data[index]
end
</code>```

Another way:

```<code>h.each do |key, index|
  h[key] = @data[index]
end
</code>```

Like I said, there are several ways of solving the issue and the best is always going to depend on what you're trying to achieve.

Body:
I've created the following hash keys with values parsed from PDF into array:

columns = ["Sen", "P-Hire#", "Emp#", "DOH", "Last", "First"]
h = Hash[columns.map.with_index.to_h]
=> {"Sen"=>0, "P-Hire#"=>1, "Emp#"=>2, "DOH"=>3, "Last"=>4, "First"=>5}

Now I want to update the value of each key with 6 equivalent values from another parsed data array:

rows = list.text.scan(/^.+/)
row = rows[0].tr(',', '')
@data = row.split
=> ["2", "6", "239", "05/05/67", "Harp", "Erin"]

I can iterate over @data in the view and it will list each of the 6 values. When I try to do the same in the controller it sets the same value to each key:

data.each do |e|
  h.update(h){|key,v1| (e) }
end
=>
{"Sen"=>"Harper", "P-Hire#"=>"Harper", "Emp#"=>"Harper", "DOH"=>"Harper", "Last"=>"Harper", "First"=>"Harper"

So it's setting the value of each key to the last value of the looped array...

Body:
There are several ways to solve this problem but a more direct and straight forward way would be:

columns = ["Sen", "P-Hire#", "Emp#", "DOH", "Last", "First"]
...
@data = row.split

h = Hash.new
columns.each_with_index do |column, index|
 h[column] = @data[index]
end

Another way:

h.each do |key, index|
  h[key] = @data[index]
end

Like I said, there are several ways of solving the issue and the best is always going to depend on what you're trying to achieve.