问:
Complication on Apple Watch not showing my information
I'm faced with a problem with complications on Apple Watch.

I'm trying to display images and some texts on a complication. I can select the complication on the Clock interface but it shows nothing that the app title and two lines full of "-" character.

The complication should show my information instead, but I don't see what is wrong in my code

Here is the code:

```<code>func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
    // This method will be called once per supported complication, and the results will be cached
    handler(nil)
    var template: CLKComplicationTemplateModularLargeColumns?
    switch complication.family {
    case .modularSmall:
        template = nil
    case .modularLarge:
        let modularLargeTemplate =
            CLKComplicationTemplateModularLargeColumns()
        modularLargeTemplate.row1ImageProvider =
            CLKImageProvider(onePieceImage: UIImage(named: "GreenUser")!)
        modularLargeTemplate.row2ImageProvider =
            CLKImageProvider(onePieceImage: UIImage(named: "GreenUser")!)
        modularLargeTemplate.row3ImageProvider =
            CLKImageProvider(onePieceImage: UIImage(named: "GreenUser")!)

        modularLargeTemplate.row1Column1TextProvider = CLKSimpleTextProvider(text: "User: ")
        modularLargeTemplate.row1Column2TextProvider = CLKSimpleTextProvider(text: "ok")

        modularLargeTemplate.row2Column1TextProvider = CLKSimpleTextProvider(text: "Car: ")
        modularLargeTemplate.row2Column2TextProvider = CLKSimpleTextProvider(text: "ok")

        modularLargeTemplate.row3Column1TextProvider = CLKSimpleTextProvider(text: "Environment: ")
        modularLargeTemplate.row3Column2TextProvider = CLKSimpleTextProvider(text: "ok")

        template = modularLargeTemplate
    case .utilitarianSmall:
        template = nil
    case .utilitarianLarge:
        template = nil
    case .circularSmall:
        template = nil
    default:
        template = nil
    }
    handler(template)

}
</code>```

If I place a breakpoint in the middle of the code, the debugger trigger it, so it executes this code. However nothing is displayed like I want.

Can you find what is wrong/missing?

答:
This is just the template, you need to take care of getCurrentTimelineEntry, the simplest would be just to return the same entry as template (see below).
And as other mentioned in comments, you need to delete handler(nil) in your code as well.

```<code>func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
        getLocalizableSampleTemplate(for: complication) {template in
            guard let template = template else {
                handler(nil)
                return
            }
            handler(CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template))
        }
    }
</code>```

Body:
I'm faced with a problem with complications on Apple Watch.

I'm trying to display images and some texts on a complication. I can select the complication on the Clock interface but it shows nothing that the app title and two lines full of "-" character.

The complication should show my information instead, but I don't see what is wrong in my code

Here is the code:

func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
    // This method will be called once per supported complication, and the results will be cached
    handler(nil)
    var template: CLKComplicationTemplateModularLargeColumns?
    switch complication.family {
    case .modularSmall:
        template = nil
    case .modularLarge:
        let modularLargeTemplate =
            CLKComplicationTemplateModularLargeColumns()
        modularLargeTemplate.row1ImageProvider =
            CLKImageProvider(onePieceImage: UIImage(named: "GreenUser")!)
        modularLargeTemplate.row2ImageProvider =
            CLKImageProvider(onePieceImage: UIImage(named: "GreenUser")!)
        modularLargeTemplate.row3ImageProvider =
            CLKImageProvider(onePieceImage: UIImage(named: "GreenUser")!)

        modularLargeTemplate.row1Column1TextProvider = CLKSimpleTextProvider(text: "User: ")
        modularLargeTemplate.row1Column2TextProvider = CLKSimpleTextProvider(text: "ok")

        modularLargeTemplate.row2Column1TextProvider = CLKSimpleTextProvider(text: "Car: ")
        modularLargeTemplate.row2Column2TextProvider = CLKSimpleTextProvider(text: "ok")

        modularLargeTemplate.row3Column1TextProvider = CLKSimpleTextProvider(text: "Environment: ")
        modularLargeTemplate.row3Column2TextProvider = CLKSimpleTextProvider(text: "ok")

        template = modularLargeTemplate
    case .utilitarianSmall:
        template = nil
    case .utilitarianLarge:
        template = nil
    case .circularSmall:
        template = nil
    default:
        template = nil
    }
    handler(template)

}

If I place a breakpoint in the middle of the code, the debugger trigger it, so it executes this code. However nothing is displayed like I want.

Can you find what is wrong/missing?

Body:
This is just the template, you need to take care of getCurrentTimelineEntry, the simplest would be just to return the same entry as template (see below).
And as other mentioned in comments, you need to delete handler(nil) in your code as well.

func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
        getLocalizableSampleTemplate(for: complication) {template in
            guard let template = template else {
                handler(nil)
                return
            }
            handler(CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template))
        }
    }


来源: stackexchange

问:
Error "unresolved reference" in Kotlin Android
I have code:

```<code>package com.example.admin.maytinh

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.example.admin.maytinh.R.id.button
import com.example.admin.maytinh.R.id.editText
import com.example.admin.maytinh.R.id.editText2
import com.example.admin.maytinh.R.id.editText3

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener(View.OnClickListener{xuly()})
    }

    public fun xuly(){
        val a:Int = editText.text.ToString().ToInt()
        val b:Int = editText2.text.ToString().ToInt()
        val c:Int = a + b
        editText3.text = c.ToString()
    }

}
</code>```

When i run it, i receive errors:

unresolved reference setOnClickListener

unresolved reference: text

unresolved reference: ToString

Anyone can explain for me why this is so and fix it
Thank you

答:
You got unresolved error because you have not imported view. Instead of view you have imported ids.

There import To import single view

```<code>import kotlinx.android.synthetic.main.<layout_name>.<view_name>;
</code>```

or

To import all widget properties for a specific layout

```<code>import kotlinx.android.synthetic.main.<layout>.*
</code>```

Also you need is to enable the Android Extensions Gradle plugin in your module's build.gradle file:

```<code>apply plugin: 'kotlin-android-extensions'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have code:

package com.example.admin.maytinh

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.example.admin.maytinh.R.id.button
import com.example.admin.maytinh.R.id.editText
import com.example.admin.maytinh.R.id.editText2
import com.example.admin.maytinh.R.id.editText3

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener(View.OnClickListener{xuly()})
    }

    public fun xuly(){
        val a:Int = editText.text.ToString().ToInt()
        val b:Int = editText2.text.ToString().ToInt()
        val c:Int = a + b
        editText3.text = c.ToString()
    }

}

When i run it, i receive errors:

unresolved reference setOnClickListener

unresolved reference: text

unresolved reference: ToString

Anyone can explain for me why this is so and fix it
Thank you

Body:
You got unresolved error because you have not imported view. Instead of view you have imported ids.

There import To import single view

import kotlinx.android.synthetic.main.<layout_name>.<view_name>;

or

To import all widget properties for a specific layout

import kotlinx.android.synthetic.main.<layout>.*

Also you need is to enable the Android Extensions Gradle plugin in your module's build.gradle file:

apply plugin: 'kotlin-android-extensions'


问:
Retrieve CPU usage and memory usage of a single process on Linux?
I want to get the CPU and memory usage of a single process on Linux - I know the PID.  Hopefully, I can get it every second and write it to a CSV using the 'watch' command.  What command can I use to get this info from the Linux command-line?</p>

答:
Above list out the top cpu and memory consuming process</p>

```<code>        ps axo %cpu,%mem,command | sort -nr | head
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Above list out the top cpu and memory consuming process

        ps axo %cpu,%mem,command | sort -nr | head


问:
How to use If with classes
I am making a calculator and the Operator keys have different color than the Number keys to distinguish them. I have this code that flashes a different color on mousedown and brings back their color on mouseup.
I want to shorten it with an If stamement but i am not sure how. (all the keys flash the same color regardless of class on mousedown)

Could you use something like If->its Operator class->then bring back this color?

```<code>$('.number').mousedown(function() {
    $(this).css('background-color', '#363636');
  });
$('.number').mouseup(function() {
    $(this).css('background-color', '#232323');
  });
$('.operator').mousedown(function() {
    $(this).css('background-color', '#363636');
  });
$('.operator').mouseup(function() {
    $(this).css('background-color', '#1a1a1a');
  });
</code>```

答:
Do it using CSS   </p>

```<code>    .example {
    background-color: #232323;
    }
    .example:active {
    background-color: #363636;
    }
</code>```

Title: How to use If with classes

Body:
I am making a calculator and the Operator keys have different color than the Number keys to distinguish them. I have this code that flashes a different color on mousedown and brings back their color on mouseup.
I want to shorten it with an If stamement but i am not sure how. (all the keys flash the same color regardless of class on mousedown)

Could you use something like If->its Operator class->then bring back this color?

$('.number').mousedown(function() {
    $(this).css('background-color', '#363636');
  });
$('.number').mouseup(function() {
    $(this).css('background-color', '#232323');
  });
$('.operator').mousedown(function() {
    $(this).css('background-color', '#363636');
  });
$('.operator').mouseup(function() {
    $(this).css('background-color', '#1a1a1a');
  });

Body:
Do it using CSS

    .example {
    background-color: #232323;
    }
    .example:active {
    background-color: #363636;
    }


问:
new JSP in a parent window closing a popup child JSP page
I am learning Apache Struts, JSP and building a simple web application. Now, I would like to see the feasibility of the below functionality.

Clicking a button on parent JSP page, a popup (also a JSP page) opens in a new window. I have a submit button in the popup JSP page.

When the user clicks on the submit button on the child popup JSP page, the child window closes and a new JSP page to be loaded on the parent window.

Is it possible to load a new JSP page in the parent window by closing the child JSP page. Or can I adopt reloading the page with different table in the same parent window.

Thanks,
Kaygee

答:
You can do this by executing the following piece of JS on click or submit of the button/form in the popup window.

```<code>window.opener.location = newURL;
</code>```

The window.opener refers to the parent window.

ContentLicense: CC BY-SA 2.5

Body:
You can do this by executing the following piece of JS on click or submit of the button/form in the popup window.

window.opener.location = newURL;

The window.opener refers to the parent window.


问:
How can I access a property of an html element?
I'm trying to get the "validacion" property of an HTML element.

```<code>console.log (element[0]);
</code>```

This returns me:

```<code><input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text" validacion="required">
</code>```

How can I access the "validacion" property?

答:
I think this is the answer you're looking for.

Since you're using Angular and you're implementing ng-model="asunto" why not make it like this in html.

```<code><input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text">

<button ng-click="get_model(asunto)"></button>
</code>```

In your JS:

```<code>$scope.asunto = "model";

$scope.get_model = function (string) {
  console.log(string)
}
</code>```

I think this might work becuase you're already using ng-model why not use ng-model instead.

Body:
I'm trying to get the "validacion" property of an HTML element.

console.log (element[0]);

This returns me:

<input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text" validacion="required">

How can I access the "validacion" property?

Body:
I think this is the answer you're looking for.

Since you're using Angular and you're implementing ng-model="asunto" why not make it like this in html.

<input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text">

<button ng-click="get_model(asunto)"></button>

In your JS:

$scope.asunto = "model";

$scope.get_model = function (string) {
  console.log(string)
}

I think this might work becuase you're already using ng-model why not use ng-model instead.


问:
How to Full Control (Read/Write) of custom resource resw file (Universal Windows)
How can I read/write Keys/Values on a custom Resource File (resw) (storing string and conditional resources) ?

I added  Resource File(resw) for storing settings of app. And Then ?

```<code> private void button1_Click(object sender, RoutedEventArgs e)
    {
        ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse();
        ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");//resources.resw accessing in root is ok.
        var resourceValue = resourceMap.GetValue("PicPath", resourceContext);

        resourceMap.SetValue("DBPath", resourceContext,"PicPath2");//no write avaible ? ERROR LINE
    }
</code>```

答: ResourceMap class does not have SetValue method. The *.resw files may contain only strings and file paths.At run time, the Windows.ApplicationModel.Resources.ResourceLoader class and the types in the Windows.ApplicationModel.Resources.Core namespace provide access to app resources, but does not provide write APIs.

Body:
How can I read/write Keys/Values on a custom Resource File (resw) (storing string and conditional resources) ?

I added  Resource File(resw) for storing settings of app. And Then ?

 private void button1_Click(object sender, RoutedEventArgs e)
    {
        ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse();
        ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");//resources.resw accessing in root is ok.
        var resourceValue = resourceMap.GetValue("PicPath", resourceContext);

        resourceMap.SetValue("DBPath", resourceContext,"PicPath2");//no write avaible ? ERROR LINE
    }


问:
C++ code without having to declare temporary at the outer scope
Is there any way to write following code without using the temporary "result"?</p>

```<code>result = func();
if(result == -1)
        return func2();
else
    return result;
</code>```

答:
No.

But I'd simplify to

```<code>result = func();
if(result == -1)
        return func2();
return result;
</code>```

You could use a ternary but I don't think it makes things clearer.

```<code>result = func();
return (result == -1) ? func2() : result;
</code>```

Body:
Is there any way to write following code without using the temporary "result"?

result = func();
if(result == -1)
        return func2();
else
    return result;

Body:
No.

But I'd simplify to

result = func();
if(result == -1)
        return func2();
return result;

You could use a ternary but I don't think it makes things clearer.

result = func();
return (result == -1) ? func2() : result;


问:
ambiguity in package references version
In a project, there are several references to Ninject library which have their version, and the unit test fails, this is the error :

Message: System.IO.FileLoadException : Could not load file or assembly 'Ninject, Version=4.0.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) ---- System.IO.FileLoadException : Could not load file or assembly 'Ninject, Version=3.2.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

1- csproj file

```<code><Reference Include="Ninject, Version=3.2.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7, processorArchitecture=MSIL">
  <HintPath>..\packages\Ninject.3.2.2.0\lib\net45-full\Ninject.dll</HintPath>
</Reference>
</code>```

2- packages.config

```<code><package id="Ninject" version="3.2.2.0" targetFramework="net462" />
</code>```

3- app.config

```<code><dependentAssembly>
    <assemblyIdentity name="Ninject" publicKeyToken="c7192dc5380945e7" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
</code>```

4- references folder -> expand -> right click on Ninject -> properties

```<code>Version: 3.2.0.0
</code>```

5- Manage NuGet packages -> installed ->

looks like somewhere in my project referenced to version 4.0.0.0 and 3.2.0.0
I want only reference to version 3.2.2.0.

how to do that?

what're the differences between these references?

答:
In my case, it was trying to find Ninject 3.3.3.0 (and I had installed v3.3.4)

I checked project file (.csproj), web.config and packages.config, and they were all fine.

I uninstalled all Ninject NuGet packages from all my projects.

Then went to "Manage NuGet packages for Solution" and reinstalled all Ninject packages for all projects from there.

I know it seems silly ... but it fixed it for me!

Title: ambiguity in package references version

Body:
In a project, there are several references to Ninject library which have their version, and the unit test fails, this is the error :

Message: System.IO.FileLoadException : Could not load file or assembly 'Ninject, Version=4.0.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) ---- System.IO.FileLoadException : Could not load file or assembly 'Ninject, Version=3.2.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

1- csproj file

<Reference Include="Ninject, Version=3.2.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7, processorArchitecture=MSIL">
  <HintPath>..\packages\Ninject.3.2.2.0\lib\net45-full\Ninject.dll</HintPath>
</Reference>

2- packages.config

<package id="Ninject" version="3.2.2.0" targetFramework="net462" />

3- app.config

<dependentAssembly>
    <assemblyIdentity name="Ninject" publicKeyToken="c7192dc5380945e7" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>

4- references folder -> expand -> right click on Ninject -> properties

Version: 3.2.0.0

5- Manage NuGet packages -> installed ->

looks like somewhere in my project referenced to version 4.0.0.0 and 3.2.0.0
I want only reference to version 3.2.2.0.

how to do that?

what're the differences between these references?


问:
Remove alpha channel in an image
I have an app icon for iOS but Apple doesn't allow alpha to be in the image. How to remove this alpha channel? I only have the png image with me I don't have the source file as my friend did the image for me.</p>

答:
Just got the the following error when trying to upload my app to the iTunes app store:

iTunes Store Operations Failed

ERROR ITMS-90717: "Invalid App Store Icon. The App Store icon in the asset catalog in 'MyApp.app' can't be transparent nor contain an alpha channel."

I confirmed that my app store icons did include the alpha channel by locating the asset in Finder and looking up its info (⌘+i). Underneath More info, it showed:

Alpha channel: Yes

Found the solution above to use Preview to remove the alpha channel by exporting it with the Alpha checkbox unchecked, but figured a way to batch export them since I had 18 assets I needed to strip the alpha channel from.

The way I got batch exporting to work was to select all my app icon assets in finder > right click > open (or open with preview)

All of the assets will now appear in the same window. Select all (⌘+a), and then select File > Export Selected Images… > Expand Options > uncheck the Alpha checkbox > Choose (your destination folder)

Done! All your images are now exported with the alpha channel stripped off.

Title: Remove alpha channel in an image


问:
Multi-dimensional arrays and how to find largest number
I am trying to find and return the largest number in each array using a for loop but every time I try to print something I get an error. I have tried using the following JS array methods: Math.max, Math.max.apply but I cannot get them to work.

My code is below. Any help will be appreciated and if you could please point out what I am doing wrong, that would be really great. Thanks in advance!

Question: numbers is an array of integers.  Find and return the largest integer.

My code:

```<code>function largestNumber(numbers) { // this function was given by the quiz writer, my code starts below "code here"
  // code here

  numbers = [1, 2, 3, 4, 5];
  for(let i = 0; i < numbers.length; i++){
    let largest = 0;
    if(numbers[i] > largest){
      largest = largest.numbers[i];
    }
  }
  return largest;
}

console.log(largestNumber);
</code>```

答:
You can use Math.max.apply as below sample to find max value in array

function largestNumber(numbers) {
    return Math.max.apply(null, numbers);
}
console.log(largestNumber([1, 2, 3, 4, 5]));```

Body:
I am trying to find and return the largest number in each array using a for loop but every time I try to print something I get an error. I have tried using the following JS array methods: Math.max, Math.max.apply but I cannot get them to work.

My code is below. Any help will be appreciated and if you could please point out what I am doing wrong, that would be really great. Thanks in advance!

Question: numbers is an array of integers.  Find and return the largest integer.

My code:

function largestNumber(numbers) { // this function was given by the quiz writer, my code starts below "code here"
  // code here

  numbers = [1, 2, 3, 4, 5];
  for(let i = 0; i < numbers.length; i++){
    let largest = 0;
    if(numbers[i] > largest){
      largest = largest.numbers[i];
    }
  }
  return largest;
}

console.log(largestNumber);


问:
Regex: Disable Symbols
Is there any way to disable all symbols, punctuations, block elements, geometric shapes and dingbats such like these:

✁ ✂ ✃ ✄ ✆ ✇ ✈ ✉ ✌ ✍ ✎ ✏ ✐ ✑ ✒ ✓ ✔ ✕  ⟻ ⟼ ⟽ ⟾ ⟿  ⟻ ⟼ ⟽ ⟾ ⟿ ▚ ▛ ▜ ▝ ▞ ▟

without writing down all of them in the Regular Expression Pattern, while enable all other normal language characters such like chinese, arabic etc.. such like these:

文化中国 الجزيرة نت

?

I'm building a javascript validation function and my real problem is that I can't use:

```<code>[a-zA-Z0-9]
</code>```

Because this ignores a lots of languages too not just the symbols.

答: Take a look at the Unicode Planes. You probably want to exclude everything but planes 0 and 2. After that, it gets ugly as you'll have to exclude a lot of plane 0 on a case-by-case basis.</p>

Title: Regex: Disable Symbols

Body:
Is there any way to disable all symbols, punctuations, block elements, geometric shapes and dingbats such like these:

✁ ✂ ✃ ✄ ✆ ✇ ✈ ✉ ✌ ✍ ✎ ✏ ✐ ✑ ✒ ✓ ✔ ✕  ⟻ ⟼ ⟽ ⟾ ⟿  ⟻ ⟼ ⟽ ⟾ ⟿ ▚ ▛ ▜ ▝ ▞ ▟

without writing down all of them in the Regular Expression Pattern, while enable all other normal language characters such like chinese, arabic etc.. such like these:

文化中国 الجزيرة نت

?

I'm building a javascript validation function and my real problem is that I can't use:

[a-zA-Z0-9]

Because this ignores a lots of languages too not just the symbols.


答:
Use jQuery.hasClass

```<code>$('.number, .operators').mousedown(function() {
    var  $this = $(this);
      If ($this.hasClass("number")) $this.css('background-color', '#363636');
    else $this.css('background-color', '#363636')
 });
</code>```

Title: How to use If with classes

Body:
Use jQuery.hasClass

$('.number, .operators').mousedown(function() {
    var  $this = $(this);
      If ($this.hasClass("number")) $this.css('background-color', '#363636');
    else $this.css('background-color', '#363636')
 });


答:
So combine it down to a common selector and a check of the type

$('button').on("mousedown mouseup", function(e) {
  var color = e.type === "mousedown" ? '#998877' : '#001122'
  $(this).css('background-color', color);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>a</button>
<button>b</button></code>```

Title: How to use If with classes

Body:
So combine it down to a common selector and a check of the type

$('button').on("mousedown mouseup", function(e) {
  var color = e.type === "mousedown" ? '#998877' : '#001122'
  $(this).css('background-color', color);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>a</button>
<button>b</button>


问:
Postgresql multi Insert with array variable
I'm looking to do a multiple dynamic insert with a variable array/list. The number of inserts will always vary.

I'd like to replace

```<code>insert into my table (col 1, col 2)
select *
from unnest(array[1, 2], array[3, 4]);
</code>```

with

```<code>insert into my table (col 1, col 2)
select *
from unnest(:list-of-inserts);
</code>```

答:
I'd wrap it in a function...  this will then translate nicely into any programming language that has a data adapter for PostgreSQL, which is pretty much all of them.  As an added bonus, it will work great in psql also.

```<code>CREATE OR REPLACE FUNCTION ez_insert(list1 integer[], list2 integer[])
  RETURNS integer AS
$BODY$
DECLARE
  rowcount integer;
BEGIN

  insert into my_table (col_1, col_2)
  values
  (unnest (list1), unnest (list2));

  GET DIAGNOSTICS rowcount = ROW_COUNT;
  return rowcount;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
</code>```

Invoking:

```<code>select ez_insert (array[1, 2, 3], array[7, 8, 9])
</code>```

Caveat -- if your arrays are different sizes, expect weirdness.

Here is a quick example of an implementation in C#:

```<code>NpgsqlCommand cmd = new NpgsqlCommand("select ez_insert(:ARRAY1, :ARRAY2)", conn);
cmd.Parameters.Add(new NpgsqlParameter("ARRAY1",
    NpgsqlDbType.Array | NpgsqlDbType.Integer));
cmd.Parameters.Add(new NpgsqlParameter("ARRAY2",
    NpgsqlDbType.Array | NpgsqlDbType.Integer));
cmd.Parameters[0].Value = ar1;
cmd.Parameters[1].Value = ar2;

int inserts = (int)cmd.ExecuteScalar();
</code>```

Body:
I'm looking to do a multiple dynamic insert with a variable array/list. The number of inserts will always vary.

I'd like to replace

insert into my table (col 1, col 2)
select *
from unnest(array[1, 2], array[3, 4]);

with

insert into my table (col 1, col 2)
select *
from unnest(:list-of-inserts);

Body:
I'd wrap it in a function...  this will then translate nicely into any programming language that has a data adapter for PostgreSQL, which is pretty much all of them.  As an added bonus, it will work great in psql also.

CREATE OR REPLACE FUNCTION ez_insert(list1 integer[], list2 integer[])
  RETURNS integer AS
$BODY$
DECLARE
  rowcount integer;
BEGIN

  insert into my_table (col_1, col_2)
  values
  (unnest (list1), unnest (list2));

  GET DIAGNOSTICS rowcount = ROW_COUNT;
  return rowcount;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

Invoking:

select ez_insert (array[1, 2, 3], array[7, 8, 9])

Caveat -- if your arrays are different sizes, expect weirdness.

Here is a quick example of an implementation in C#:

NpgsqlCommand cmd = new NpgsqlCommand("select ez_insert(:ARRAY1, :ARRAY2)", conn);
cmd.Parameters.Add(new NpgsqlParameter("ARRAY1",
    NpgsqlDbType.Array | NpgsqlDbType.Integer));
cmd.Parameters.Add(new NpgsqlParameter("ARRAY2",
    NpgsqlDbType.Array | NpgsqlDbType.Integer));
cmd.Parameters[0].Value = ar1;
cmd.Parameters[1].Value = ar2;

int inserts = (int)cmd.ExecuteScalar();


问:
How to compare tensorflow tensors with Python objects?
I'm trying to convert string label tensors loaded from tfrec files into numbers for one-hot encoding. The idea is to use a numpy array as a lookup table, and once there's a hit, the index is returned and stored in a tensor.

However, the problem is that tensors cannot be directly compared with python objects. I tried to implement using tf.map_fn to enumerate my batch of labels and tf.cond to make the comparison - which didn't work:

```<code>def elem_op(t):
    global all_labels
    for idx, lbl in enumerate(all_labels):
        lbl_tensor = tf.constant(lbl.encode())  # tensorflow stores string as bytes, so convert the Python string object to bytes tensor
        ret = tf.cond(tf.equal(lbl_tensor, t), lambda : idx, lambda : -1)
        if ret != -1:  # now this doesn't work because tf.cond returns a tensor
            return ret
    return -1

# labels is a tensor storing a batch of label strings
train_labels = tf.map_fn(fn=elem_op, elems=labels, dtype=tf.int32)
</code>```

The problem is that tf.cond also returns a tensor and cannot be used in a "if" clause. And I wonder what's the way of resolving this?

Thanks!

答:
You have to evaluate the tensor in a session in order to obtain it's actual value.

Change you if condition to:

```<code>if sess.run(ret) != -1:
</code>```

where sess is your tf.Session instance. For example:

```<code>sess = tf.Session()
</code>```

Similarly, you may run:

```<code>sess.run(train_labels)
</code>```

Body:
I'm trying to convert string label tensors loaded from tfrec files into numbers for one-hot encoding. The idea is to use a numpy array as a lookup table, and once there's a hit, the index is returned and stored in a tensor.

However, the problem is that tensors cannot be directly compared with python objects. I tried to implement using tf.map_fn to enumerate my batch of labels and tf.cond to make the comparison - which didn't work:

def elem_op(t):
    global all_labels
    for idx, lbl in enumerate(all_labels):
        lbl_tensor = tf.constant(lbl.encode())  # tensorflow stores string as bytes, so convert the Python string object to bytes tensor
        ret = tf.cond(tf.equal(lbl_tensor, t), lambda : idx, lambda : -1)
        if ret != -1:  # now this doesn't work because tf.cond returns a tensor
            return ret
    return -1

# labels is a tensor storing a batch of label strings
train_labels = tf.map_fn(fn=elem_op, elems=labels, dtype=tf.int32)

The problem is that tf.cond also returns a tensor and cannot be used in a "if" clause. And I wonder what's the way of resolving this?

Thanks!

Body:
You have to evaluate the tensor in a session in order to obtain it's actual value.

Change you if condition to:

if sess.run(ret) != -1:

where sess is your tf.Session instance. For example:

sess = tf.Session()

Similarly, you may run:

sess.run(train_labels)


问:
How to open native video player to play local contents in Xamarin forms
I have some video file embedded with the project, that to be opened in the native video player using Xamarin forms.

Note: Having in-app video player is limited here.

Any idea for this?

答:
Sorry for late, you could refer to FormsNativeVideoPlayer.
When you load your video file from Raw  folder, you just need to modify the VideoPlayer_CustomRenderer code like this  :

```<code>protected override void OnElementChanged (ElementChangedEventArgs<Xamarin.Forms.View> e)
{
    base.OnElementChanged (e);

    ...

    string uriPath = "android.resource://" + Forms.Context.PackageName + "/" + Resource.Raw.audio;
    var uri = Android.Net.Uri.Parse((uriPath));

    //Set the videoView with our uri, this could also be a local video on device
    videoView.SetVideoURI (uri);

    ...
 }
</code>```

Body:
Sorry for late, you could refer to FormsNativeVideoPlayer.
When you load your video file from Raw  folder, you just need to modify the VideoPlayer_CustomRenderer code like this  :

protected override void OnElementChanged (ElementChangedEventArgs<Xamarin.Forms.View> e)
{
    base.OnElementChanged (e);

    ...

    string uriPath = "android.resource://" + Forms.Context.PackageName + "/" + Resource.Raw.audio;
    var uri = Android.Net.Uri.Parse((uriPath));

    //Set the videoView with our uri, this could also be a local video on device
    videoView.SetVideoURI (uri);

    ...
 }


问:
Sort and Group an Immutable.js List
Given the following data structure:

```<code>var MyData = [
  {"id": 1, "status": "live", dateCreated: "12:00:00 01/02/2016"},
  {"id": 2, "status": "draft", dateCreated: "13:00:00 03/12/2015"},
  {"id": 3, "status": "ready", dateCreated: "16:00:00 04/09/2016"},
  {"id": 4, "status": "ready", dateCreated: "10:00:00 01/10/2016"},
  {"id": 5, "status": "live", dateCreated: "09:00:00 05/07/2015"},
  {"id": 6, "status": "draft", dateCreated: "08:00:00 11/03/2016"},
  {"id": 7, "status": "ready", dateCreated: "20:00:00 12/02/2016"}
]
</code>```

I'm trying to sort and group it into these conditions:

Grouped by status

Ordered by status such that the order is "live", "draft", "ready"

Items within each status should be ordered by dateCreated, most recent first.

What I have so far:

```<code>// this object will help us define our custom order as it's not alphabetical
const itemOrder = {
  'live': 1,
  'ready': 2,
  'draft': 3
};

const sortByStatus = (statusA, statusB) => {
  if ( itemOrder[statusA] > itemOrder[statusB] ) return 1;
  if ( itemOrder[statusA] < itemOrder[statusB] ) return -1;
  return 0;
};

return List(MyData)
  .groupBy(item => item.status)
  .sort( sortByStatus )
</code>```

Ignore for a moment the fact that I've not got to the point where I can sort by date yet :)

The problem with the above seems to be that sortByStatus is being passed the IndexedIterable that is the overall group but not it's key so I can't sort it by that key. I think I probably need to use sortBy but the Immutable.js docs are incomprehensible and have no examples on which to work out how to achieve this.

So, the question: how can I take the result of the groupBy action and sort it into a custom order and additionally how can I ensure that all the items in each group are sorted by date?

答:
I think you were almost there. The important thing to notice is that .groupBy is returning a collection of lists, so when you call sort on that, you need a comparator that compares two different lists rather than two items. You can do this easily by just comparing the status of the first item in each list. After that, you want to sort each list individually by date, so you use .map to apply a change to each list in your list, then .sortBy on that list to sort by a specific key. Assuming you are using the built in Date type, just sorting by that field should do what you want.

```<code>var MyData = [
  {"id": 1, "status": "live", dateCreated: "12:00:00 01/02/2016"},
  {"id": 2, "status": "draft", dateCreated: "13:00:00 03/12/2015"},
  {"id": 3, "status": "ready", dateCreated: "16:00:00 04/09/2016"},
  {"id": 4, "status": "ready", dateCreated: "10:00:00 01/10/2016"},
  {"id": 5, "status": "live", dateCreated: "09:00:00 05/07/2015"},
  {"id": 6, "status": "draft", dateCreated: "08:00:00 11/03/2016"},
  {"id": 7, "status": "ready", dateCreated: "20:00:00 12/02/2016"}
]

Immutable.fromJs(MyData)
  // [{id: 1, ...}, ...]
  .groupBy(item => item.status) // group items into lists by status
  // [ 'live': [ { id: 1, ... }, { id:5, ... } ],
  //   'draft': [ { id: 2, ... }, { id: 6, ...} ],
  //   'ready': [ { id: 3, ... }, { id: 4, ... }, { id: 7, ... } ] ]
  .sort((listA, listB) => // order these groups by status
    itemOrder[listA.first().status] - itemOrder[listB.first().status])
  // [ 'live': [ { id: 1, ...}, ... ],
  //   'ready': [ { id: 3, ...}, ... ],
  //   'draft': [ { id: 2, ...}, ... ] ]
  .map(list => list.sortBy(item => item.dateCreated)); // sort the elements in each group by date
  // [ 'live': [ { id: 5, ... }, { id: 1, ... } ],
  //   'ready': [ { id: 4, ... }, { id: 3, ... }, { id: 7, ... } ],
  //   'draft': [ { id: 2, , ...}, { id: 6, ... } ] ]
</code>```

Title: Sort and Group an Immutable.js List

Body:
Given the following data structure:

var MyData = [
  {"id": 1, "status": "live", dateCreated: "12:00:00 01/02/2016"},
  {"id": 2, "status": "draft", dateCreated: "13:00:00 03/12/2015"},
  {"id": 3, "status": "ready", dateCreated: "16:00:00 04/09/2016"},
  {"id": 4, "status": "ready", dateCreated: "10:00:00 01/10/2016"},
  {"id": 5, "status": "live", dateCreated: "09:00:00 05/07/2015"},
  {"id": 6, "status": "draft", dateCreated: "08:00:00 11/03/2016"},
  {"id": 7, "status": "ready", dateCreated: "20:00:00 12/02/2016"}
]

I'm trying to sort and group it into these conditions:

Grouped by status

Ordered by status such that the order is "live", "draft", "ready"

Items within each status should be ordered by dateCreated, most recent first.

What I have so far:

// this object will help us define our custom order as it's not alphabetical
const itemOrder = {
  'live': 1,
  'ready': 2,
  'draft': 3
};

const sortByStatus = (statusA, statusB) => {
  if ( itemOrder[statusA] > itemOrder[statusB] ) return 1;
  if ( itemOrder[statusA] < itemOrder[statusB] ) return -1;
  return 0;
};

return List(MyData)
  .groupBy(item => item.status)
  .sort( sortByStatus )

Ignore for a moment the fact that I've not got to the point where I can sort by date yet :)

The problem with the above seems to be that sortByStatus is being passed the IndexedIterable that is the overall group but not it's key so I can't sort it by that key. I think I probably need to use sortBy but the Immutable.js docs are incomprehensible and have no examples on which to work out how to achieve this.

So, the question: how can I take the result of the groupBy action and sort it into a custom order and additionally how can I ensure that all the items in each group are sorted by date?

Body:
I think you were almost there. The important thing to notice is that .groupBy is returning a collection of lists, so when you call sort on that, you need a comparator that compares two different lists rather than two items. You can do this easily by just comparing the status of the first item in each list. After that, you want to sort each list individually by date, so you use .map to apply a change to each list in your list, then .sortBy on that list to sort by a specific key. Assuming you are using the built in Date type, just sorting by that field should do what you want.

var MyData = [
  {"id": 1, "status": "live", dateCreated: "12:00:00 01/02/2016"},
  {"id": 2, "status": "draft", dateCreated: "13:00:00 03/12/2015"},
  {"id": 3, "status": "ready", dateCreated: "16:00:00 04/09/2016"},
  {"id": 4, "status": "ready", dateCreated: "10:00:00 01/10/2016"},
  {"id": 5, "status": "live", dateCreated: "09:00:00 05/07/2015"},
  {"id": 6, "status": "draft", dateCreated: "08:00:00 11/03/2016"},
  {"id": 7, "status": "ready", dateCreated: "20:00:00 12/02/2016"}
]

Immutable.fromJs(MyData)
  // [{id: 1, ...}, ...]
  .groupBy(item => item.status) // group items into lists by status
  // [ 'live': [ { id: 1, ... }, { id:5, ... } ],
  //   'draft': [ { id: 2, ... }, { id: 6, ...} ],
  //   'ready': [ { id: 3, ... }, { id: 4, ... }, { id: 7, ... } ] ]
  .sort((listA, listB) => // order these groups by status
    itemOrder[listA.first().status] - itemOrder[listB.first().status])
  // [ 'live': [ { id: 1, ...}, ... ],
  //   'ready': [ { id: 3, ...}, ... ],
  //   'draft': [ { id: 2, ...}, ... ] ]
  .map(list => list.sortBy(item => item.dateCreated)); // sort the elements in each group by date
  // [ 'live': [ { id: 5, ... }, { id: 1, ... } ],
  //   'ready': [ { id: 4, ... }, { id: 3, ... }, { id: 7, ... } ],
  //   'draft': [ { id: 2, , ...}, { id: 6, ... } ] ]


问:
Running Ant with JDK 1.6 on Mac OS X
I am having a problem running Ant with JDK 1.6 on Mac OS X. Even though Java application versions is set to Java SE 6 in OS X's Java Preference, executing java -version in Terminal also shows java version "1.6.0_07", Ant still seems to use JDK 1.5 to be using JDK 1.5 as it does not see JDK 1.6 classes when compiling my code.

I understand that Ant relies on JAVA_HOME environment variable to specify which JDK to use. However, I do not quite understand how this variable can be set on Mac OS X.

Hence, my question is how to make Ant runs with JDK 1.6 on Mac OS X. If the correct way is still to set JAVA_HOME environment variable, how to set the variable on OS X.

答:
I try everything, and only one thing works for me : unlink CurrentJDK, and link to 1.6 :

```<code>cd /System/Library/Frameworks/JavaVM.framework/Versions
sudo unlink CurrentJDK
sudo ln -sF "1.6" CurrentJDK
</code>```

Finally I get :

```<code>java -version
java version "1.6.0_22"
</code>```

I hope this help.

OwnerDisplayName: ejel

Title: Running Ant with JDK 1.6 on Mac OS X

LastEditorDisplayName: ejel

Body:
I try everything, and only one thing works for me : unlink CurrentJDK, and link to 1.6 :

cd /System/Library/Frameworks/JavaVM.framework/Versions
sudo unlink CurrentJDK
sudo ln -sF "1.6" CurrentJDK

Finally I get :

java -version
java version "1.6.0_22"

I hope this help.


问:
MIPS lw latency in pipelining
I'm given stages of a clock cycle in a processor.

```<code> IF     ID     EX     MEM    WB
250ps  350ps  150ps  300ps  200ps
</code>```

Now I'm being asked what is the total latency of a LW instruction in a pipelined instruction.

Here's what I know:

The clock cycle time in a pipelined version is 350ps because that's the longest instruction.

The clock cycle time in a non-pipelined version is 1250ps because that's the duration of all the instructions added together.

But how does the "latency of a LW instruction" relate to those times?

答:
Ok I'm pretty sure I figured out the answer which is you take the longest duration of the stages which in this case is 350ps and you multiply it by the amount of stages, in this case 5.

So

350 * 5 = 1750ps

Title: MIPS lw latency in pipelining

Body:
I'm given stages of a clock cycle in a processor.

 IF     ID     EX     MEM    WB
250ps  350ps  150ps  300ps  200ps

Now I'm being asked what is the total latency of a LW instruction in a pipelined instruction.

Here's what I know:

The clock cycle time in a pipelined version is 350ps because that's the longest instruction.

The clock cycle time in a non-pipelined version is 1250ps because that's the duration of all the instructions added together.

But how does the "latency of a LW instruction" relate to those times?


问:
Pagination keeps showing the same portion of SQL data
I have a really large data set from SQL that i need to paginate.

I have an issue with my pagination code. The code does show the page number in the URL and it does give me pagination hyperlinks at the bottom of the table. However, any page I click on, it outputs the same exact portion of the sql datatable.

Also, I'm doing this in wordpress.

```<code>// define how many results you want per page
$results_per_page = 10;

// find out the number of results stored in database
$sql='SELECT * FROM ETF';
$result = mysqli_query($con, $sql);
$number_of_results = mysqli_num_rows($result);

// determine number of total pages available
$number_of_pages = ceil($number_of_results/$results_per_page);

// determine which page number visitor is currently on
if (!isset($_GET['page'])) {
  $page = 1;
} else {
  $page = $_GET['page'];
}

// determine the sql LIMIT starting number for the results on the displaying page
$this_page_first_result = ($page-1)*$results_per_page;

// retrieve selected results from database and display them on page
$sql='SELECT * FROM ETF LIMIT ' . $this_page_first_result . "," .$results_per_page;

$result = mysqli_query($con, $sql);

while($row = mysqli_fetch_array($result)) {
  echo $row['ETF'] . ' ' . $row['ETF NAME']. '<br>';
}

// display the links to the pages
for ($page=1;$page<=$number_of_pages;$page++) {
  echo '<a href="index.php/stocks/sec-forms/?page=' . $page . '">' . $page. '</a>';
}
</code>```

答:
Try:

```<code>$sql='SELECT * FROM ETF LIMIT ' . $results_per_page . ' OFFSET ' . $this_page_first_result;
</code>```

Also as mentioned you should sort by a certain column  with 'ORDER BY' for consistent results.

Body:
I have a really large data set from SQL that i need to paginate.

I have an issue with my pagination code. The code does show the page number in the URL and it does give me pagination hyperlinks at the bottom of the table. However, any page I click on, it outputs the same exact portion of the sql datatable.

Also, I'm doing this in wordpress.

// define how many results you want per page
$results_per_page = 10;

// find out the number of results stored in database
$sql='SELECT * FROM ETF';
$result = mysqli_query($con, $sql);
$number_of_results = mysqli_num_rows($result);

// determine number of total pages available
$number_of_pages = ceil($number_of_results/$results_per_page);

// determine which page number visitor is currently on
if (!isset($_GET['page'])) {
  $page = 1;
} else {
  $page = $_GET['page'];
}

// determine the sql LIMIT starting number for the results on the displaying page
$this_page_first_result = ($page-1)*$results_per_page;

// retrieve selected results from database and display them on page
$sql='SELECT * FROM ETF LIMIT ' . $this_page_first_result . "," .$results_per_page;

$result = mysqli_query($con, $sql);

while($row = mysqli_fetch_array($result)) {
  echo $row['ETF'] . ' ' . $row['ETF NAME']. '
';
}

// display the links to the pages
for ($page=1;$page<=$number_of_pages;$page++) {
  echo '' . $page. '';
}

Body:
Try:

$sql='SELECT * FROM ETF LIMIT ' . $results_per_page . ' OFFSET ' . $this_page_first_result;

Also as mentioned you should sort by a certain column  with 'ORDER BY' for consistent results.


问:
Appending characters to each line in a txt file with python
I wrote the following python code snippet to append a lower p character to each line of a txt file:

```<code>f = open('helloworld.txt','r')
for line in f:
    line+='p'
print(f.read())
f.close()
</code>```

However, when I execute this python program, it returns nothing but an empty blank:

```<code>zhiwei@zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py
</code>```

Can anyone tell me what's wrong with my codes?

答:
well, type help(f) in shell, you can get "Character and line based layer over a BufferedIOBase object, buffer."
it's meaning：if you reading first buffer,you can get content, but again. it's empty。
so like this:</p>

```<code>with open(oldfile, 'r') as f1, open(newfile, 'w') as f2:
       newline = ''
       for line in f1:
         newline+=line.strip()+"p\n"
         f2.write(newline)
</code>```

Body:
I wrote the following python code snippet to append a lower p character to each line of a txt file:

f = open('helloworld.txt','r')
for line in f:
    line+='p'
print(f.read())
f.close()

However, when I execute this python program, it returns nothing but an empty blank:

zhiwei@zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py

Can anyone tell me what's wrong with my codes?

Body:
well, type help(f) in shell, you can get "Character and line based layer over a BufferedIOBase object, buffer."
it's meaning：if you reading first buffer,you can get content, but again. it's empty。
so like this:

with open(oldfile, 'r') as f1, open(newfile, 'w') as f2:
       newline = ''
       for line in f1:
         newline+=line.strip()+"p\n"
         f2.write(newline)


问:
VPN connection between 2 google instances across google project
We have a technical requirement, wherein we need to have two instances across different google project (but under same google account) to communicate with each other.

To illustrate, we have two google project X and Y under the same google account. We need all our VM instance on project X (of google account) to have a reliable communication(maybe over HTTP) with a known VM instance of project Y(of the same google account).

Because we programmatically scale up and scale down our VM instances of project X we cannot approach the solution of whitelisting IPs of VM instances of X on Project Y firewall. (under google networking rule)

We have been reading around VPN in google,(sure and easier solution to this could be a Proxy but because of our business constraints, we cannot explore that as possible options).

Google documentation says about VPN setup of two kind static and dynamic route.

But, because of our limited experience(never set the VPN before) on this we are not sure what is the ideal VPN setup(or there exist any other solution which we haven't encountered yet) for us.

Can some one please help with some pointer on the correct setup for above problem.

答:
You can use VPN to connect your two projects. Both static or dyanmic will work. Dynamic requires you to set up Cloud Routers in both projects and some additional configuration and allows your network to automatically react if the VPN is down. However I don't think this is helpful for you as you don't have a fallback, so static VPN is probably the better choice for you.

You may also want to look at VPC Network Peering and Shared VPC. These allow instacnes in different projects to communicate without needing a VPN at all.


问:
Bootstrap show.bs.modal not firing
I am trying to pass the id of the element to the modal dialog. However, the event is not getting fired. I have looked at bootstrap jquery show.bs.modal event won't fire but it did not help. Here is what I do.

I build a set of links as follows.

```<code>// invitations is an array of id's retrieved from the back-end
for (var i = 0; i < invitations.length; i++) {
   var labelTxt = '<label><a href="#" data-toggle="modal" id=' + invitations[i] + ' data-target="#modalInvitation">' +  invitations[i] + '</a></label>';
   $('<div>').text($(labelTxt).appendTo('#myDiv'));
}
</code>```

My modal dialog is as follows

```<code><div id="modalInvitation" class="modal fade" role="dialog">
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-header">
            <h4 class="modal-title">Invite</h4>
         </div>
         <div class="modal-body">
            <button id="inviteBtn" type="button" class="btn btn-primary" data-dismiss="modal">Invite</button>
         </div>
         <div class="modal-footer">
            <button type="button" class="btn" data-dismiss="modal">Cancel</button>
         </div>
      </div>
   </div>
</div>
</code>```

Finally I call event, show.bs.modal as follows.

```<code><script type="text/javascript">
$(function() {
    $(document).on('show.bs.modal',
        '#modalInvitation',
        function() {
            var inviteId = e.relatedTarget.id;
            alert(inviteId);
        });
});
</code>```

However, the event show.bs.modal is not firing. Also referred to this Send parameter to Bootstrap modal window?

答:
Well, there was nothing wrong with the code. While stripping the code to the bare minimum I noticed that I had 2 versions of jQuery running, like so

```<code><script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</code>```

Removing the latter solves the problem. The problem still exists if I run just the latter. Not sure why though.

Title: Bootstrap show.bs.modal not firing

Body:
I am trying to pass the id of the element to the modal dialog. However, the event is not getting fired. I have looked at bootstrap jquery show.bs.modal event won't fire but it did not help. Here is what I do.

I build a set of links as follows.

// invitations is an array of id's retrieved from the back-end
for (var i = 0; i < invitations.length; i++) {
   var labelTxt = '' +  invitations[i] + '';
   $('
').text($(labelTxt).appendTo('#myDiv'));
}

My modal dialog is as follows

Invite

            <button id="inviteBtn" type="button" class="btn btn-primary" data-dismiss="modal">Invite</button>

            <button type="button" class="btn" data-dismiss="modal">Cancel</button>

Finally I call event, show.bs.modal as follows.

Body:
Well, there was nothing wrong with the code. While stripping the code to the bare minimum I noticed that I had 2 versions of jQuery running, like so

<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Removing the latter solves the problem. The problem still exists if I run just the latter. Not sure why though.


问:
A/B Test a Page Step in a Single Page without a new URL
I am trying to figure out how to run an A/B Test for a change on a Page Step for a Single Page. The idea is we have a payment flow with several page steps each containing a form. We'd like to swap out forms and test how our users react. We are trying to avoid changing the URL.

I looked into tools such as Google Analytics, but that requires a different URL to run the A/B test. The hesitation about creating a new URL is because our users are known to bookmark them, and we don't want to keep a backlog of redirects from invalid URLs, also we'd like to avoid constantly deploying new URLs for our tests.

I cannot seem to find any tool to do this, so I've tried to think of a few solutions but I'm not having a lot of luck.

My best idea is to build both a and b forms into the page, and when a user accesses the flow, the session randomly(based on a preset%) stores a value that dictates whether the user is in test a or b. Then when they step into that form, the server will serve the proper form to them. If they abandon their session, we'd track that, and if they complete the action, we'd track that.

I feel like there should be a better solution, but I just cannot come up with one.

My results online were either blogs showing how to approach it from a high level, and all of them used different URLs, I have found almost no developer resources.

Thanks.

We're using ExtJS 4.2.2, and .NET as our server.

答: Whenever you need the server to be involved, you need server-side instrumentation. No free tools offer that, but you could consider Optimizely "full-stack" (has support for C#) or Variant (does not yet).</p>


问:
SQL: Groupby and arrange different row values under one column to one horizontal row in second column
Please see the logic I want to implement (easier to show in tables than describe in text):

Using python, I was able to achieve my desired table using the code below:

```<code>df_3 = df_2.groupby(['a', 'b', 'c'])['reqmnt'].apply(' '.join).reset_index()
</code>```

How do I do this in SQL?

答:
The following will work for you:</p>

```<code>DECLARE @T table
(
    a varchar(10)
    , b varchar(10)
    , c varchar(10)
    , reqmnt varchar(255)
)

INSERT INTO @T (a, b, c, reqmnt)
VALUES
('AC1', 'BA2', 'test', 'C1')
, ('AC1', 'BA2', 'test', 'PAN')
, ('AC1', 'BA2', 'test', 'Woot')

SELECT DISTINCT
    a
    , b
    , c
    ,
        RTRIM(
            (
                SELECT reqmnt + ' '
                FROM @T t2
                WHERE
                    t2.a = t1.a
                    AND t2.b = t1.b
                    AND t2.c = t1.c
                ORDER BY reqmnt -- this line is optional
                FOR XML PATH ('')
            )
        ) reqmnt
FROM @T t1
</code>```

Body:
Please see the logic I want to implement (easier to show in tables than describe in text):

Using python, I was able to achieve my desired table using the code below:

df_3 = df_2.groupby(['a', 'b', 'c'])['reqmnt'].apply(' '.join).reset_index()

How do I do this in SQL?

Body:
The following will work for you:

DECLARE @T table
(
    a varchar(10)
    , b varchar(10)
    , c varchar(10)
    , reqmnt varchar(255)
)

INSERT INTO @T (a, b, c, reqmnt)
VALUES
('AC1', 'BA2', 'test', 'C1')
, ('AC1', 'BA2', 'test', 'PAN')
, ('AC1', 'BA2', 'test', 'Woot')

SELECT DISTINCT
    a
    , b
    , c
    ,
        RTRIM(
            (
                SELECT reqmnt + ' '
                FROM @T t2
                WHERE
                    t2.a = t1.a
                    AND t2.b = t1.b
                    AND t2.c = t1.c
                ORDER BY reqmnt -- this line is optional
                FOR XML PATH ('')
            )
        ) reqmnt
FROM @T t1


答:
It seems that your for loop has already read the file to the end, so f.read() return empty string.

If you just need to print the lines in the file, you could move the print into for loop just like print(line). And it is better to move the f.read() before for loop:

```<code>f = open("filename", "r")
lines = f.readlines()
for line in lines:
    line += "p"
    print(line)
f.close()
</code>```

If you need to modify the file, you need to create another file obj and open it in mode of "w", and use f.write(line) to write the modified lines into the new file.

Besides, it is more better to use with clause in python instead of open(), it is more pythonic.

```<code>with open("filename", "r") as f:
    lines = f.readlines()
    for line in lines:
        line += "p"
        print(line)
</code>```

When using with clause, you have no need to close file, this is more simple.

Title: Appending characters to each line in a txt file with python

Body:
It seems that your for loop has already read the file to the end, so f.read() return empty string.

If you just need to print the lines in the file, you could move the print into for loop just like print(line). And it is better to move the f.read() before for loop:

f = open("filename", "r")
lines = f.readlines()
for line in lines:
    line += "p"
    print(line)
f.close()

If you need to modify the file, you need to create another file obj and open it in mode of "w", and use f.write(line) to write the modified lines into the new file.

Besides, it is more better to use with clause in python instead of open(), it is more pythonic.

with open("filename", "r") as f:
    lines = f.readlines()
    for line in lines:
        line += "p"
        print(line)

When using with clause, you have no need to close file, this is more simple.


问:
What is the best Scheme or LISP implementation for OS X?
I am looking for a version of Scheme or even LISP that I can use to recover some lost Lisp development skills.  Some web capabilities would be nice but not essential.

I've looked at Plt and MIT scheme and, while both look pretty good, the Plt seems to be more feature rich.  I've also looked at Lisp implementations but all of the seem quite expensive.

I favor free/inexpensive implementations as this is truly likely to just be occasional hobby programming. What recommendations would you have?

答:
I have found that Chicken works well for Scheme and is available through homebrew.

```<code>brew install chicken
</code>```

Most of the code from SICP works with minor modifications.

OwnerDisplayName: Mark Brittingham

LastEditorDisplayName: Mark Brittingham

Body:
I have found that Chicken works well for Scheme and is available through homebrew.

brew install chicken

Most of the code from SICP works with minor modifications.


问:
What is the difference between AWSCLI and AWSEBCLI?
What is the difference between "AWS Command Line Interface" and "AWS Elastic Beanstalk Command Line Interface"?

Do I need both to deploy a Django project through AWS Elastic Beanstalk?

Thank you!

答:
You should start with the EBCLI and then involve the AWSCLI where the EBCLI falls short.

The AWSCLI (aws) allows you to run commands from a bunch of different services, whereas, the EBCLI (eb) is specific to Elastic Beanstalk. The EBCLI makes a lot of tedious tasks easier because it is less hands on than the AWS CLI. I have observed, for most of my tasks, the EBCLI is sufficient; I use the AWS CLI and the AWS SDKs otherwise.

Consider deploying your Django app.

You could start off by performing eb init, which would take you through an interactive set of menus, from which you would choose your region, and solution stack (Python).

Next, you would perform eb create, which creates an application version and subsequently an Elastic Beanstalk environment for you.

The above two EBCLI steps translate to half a dozen or more AWSCLI steps. Furthermore, a lot of the processes that the EBCLI hides from you involve multiple AWS services, which can make the task of replicating the EBCLI through the AWS CLI all the more tedious and error-prone.


问:
How to "POST" the JSON data form Salesforce to the external URL of php and fetch into Php
```<code>public with sharing class Util{

    @future (callout=true)
    public static void callWebservice(SET<Id> cont){

        List<Contact> contacts = [SELECT Id, LastName, FirstName FROM Contact WHERE Id = :cont];

        String jsonOrders = JSON.serialize(contacts);

        // debugging call, which you can check in debug logs
        System.debug('jsonOrders: ' + jsonOrders);
        // create an HTTPrequest object

        HttpRequest req = new HttpRequest();

        // set up the HTTP request with a method, endpoint, header, and body
        req.setMethod('POST');
        req.setEndpoint('//xyz.com/mastercopytest/salesforce/salesforce_cron.php');
        req.setHeader('Content-Type', 'application/json');

        req.setBody(jsonOrders);
        // create a new HTTP object
        Http http = new Http();

        System.debug('Request Data '+ req);

        // create a new HTTP response for receiving the remote response
        HTTPResponse res = http.send(req);

        // debugging call, which you can check in debug logs
         System.debug('Fulfillment service returned '+ res.getBody());

         System.debug('getStatusCode '+ res.getStatusCode());

        // If status code != 200, write debugging information, done
        if (res.getStatusCode() != 200) {
            System.debug('Error from ' + req.getEndpoint() + ' : ' + res.getStatusCode() + ' ' + res.getStatus());
        }

    }
}
</code>```

Now I want to fetch the posted JSON data in php.I am unable to fetch the data from php. Is there anything i am missing here?How to read post JSON data in php. It is showing empty array on php.Please Help me.

答:
Following code works for me in Apex Class</p>

```<code>     HttpRequest req = new HttpRequest();

     JSONGenerator gen = System.JSON.createGenerator(true);

     gen.writeStartObject();
     gen.writeStringField('client_id', 'ABCDE');
     gen.writeStringField('client_secret', 'EDFCHH');

     gen.writeEndObject();

     String jsonS = gen.getAsString();

     req.setEndpoint('https://yourservice.com/api');
     req.setMethod('POST');
     req.setHeader('Content-Type', 'application/json');
     req.setBody(jsonS );

     Http http = new Http();
     HTTPResponse res = http.send(req);
     String jsonstr = res.getBody();
</code>```

Body:
public with sharing class Util{

    @future (callout=true)
    public static void callWebservice(SET<Id> cont){

        List<Contact> contacts = [SELECT Id, LastName, FirstName FROM Contact WHERE Id = :cont];

        String jsonOrders = JSON.serialize(contacts);

        // debugging call, which you can check in debug logs
        System.debug('jsonOrders: ' + jsonOrders);
        // create an HTTPrequest object

        HttpRequest req = new HttpRequest();

        // set up the HTTP request with a method, endpoint, header, and body
        req.setMethod('POST');
        req.setEndpoint('//xyz.com/mastercopytest/salesforce/salesforce_cron.php');
        req.setHeader('Content-Type', 'application/json');

        req.setBody(jsonOrders);
        // create a new HTTP object
        Http http = new Http();

        System.debug('Request Data '+ req);

        // create a new HTTP response for receiving the remote response
        HTTPResponse res = http.send(req);

        // debugging call, which you can check in debug logs
         System.debug('Fulfillment service returned '+ res.getBody());

         System.debug('getStatusCode '+ res.getStatusCode());

        // If status code != 200, write debugging information, done
        if (res.getStatusCode() != 200) {
            System.debug('Error from ' + req.getEndpoint() + ' : ' + res.getStatusCode() + ' ' + res.getStatus());
        }

    }
}

Now I want to fetch the posted JSON data in php.I am unable to fetch the data from php. Is there anything i am missing here?How to read post JSON data in php. It is showing empty array on php.Please Help me.

Body:
Following code works for me in Apex Class

     HttpRequest req = new HttpRequest();

     JSONGenerator gen = System.JSON.createGenerator(true);

     gen.writeStartObject();
     gen.writeStringField('client_id', 'ABCDE');
     gen.writeStringField('client_secret', 'EDFCHH');

     gen.writeEndObject();

     String jsonS = gen.getAsString();

     req.setEndpoint('https://yourservice.com/api');
     req.setMethod('POST');
     req.setHeader('Content-Type', 'application/json');
     req.setBody(jsonS );

     Http http = new Http();
     HTTPResponse res = http.send(req);
     String jsonstr = res.getBody();


问:
Setting Up Apollo Server with subscriptions-transport-ws?
It seems like I have my server set up according to the Apollo docs at http://dev.apollodata.com/tools/apollo-server/setup.html. In my server/main.js file:

```<code>//SET UP APOLLO INCLUDING APOLLO PUBSUB
const executableSchema = makeExecutableSchema({
    typeDefs: Schema,
    resolvers: Resolvers,
    connectors: Connectors,
    logger: console,
});

const GRAPHQL_PORT = 8080;
const graphQLServer = express();

// `context` must be an object and can't be undefined when using connectors
graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({
    schema: executableSchema,
    context: {}, //at least(!) an empty object
}));

graphQLServer.use('/graphiql', graphiqlExpress({
    endpointURL: '/graphql',
}));

graphQLServer.listen(GRAPHQL_PORT, () => console.log(
    `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`
));
//SET UP APOLLO INCLUDING APOLLO PUBSUB
</code>```

It prints out "GraphQL Server is now running on http://localhost:8080/graphql" to the terminal log indicating that the server was successfully initialized.

But at the top of my main_layout component, when I run this code:

```<code>import { Client } from 'subscriptions-transport-ws';
const wsClient = new Client('ws://localhost:8080');
</code>```

...I get this console message:

WebSocket connection to 'ws://localhost:8080/' failed: Connection closed before receiving a handshake response

What am I missing?

答:
Seems like you aren't actually making the websocket server. use SubscriptionServer. Keep in mind that it is absolutely NOT true that you have to have a dedicated websocket port (I thought this once too) as davidyaha says. I have both my normal queries and subs on the same port.</p>

```<code>import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { execute, subscribe } from 'graphql';
import { schema } from './my-schema';

// All your graphQLServer.use() etc setup goes here, MINUS the graphQLServer.listen(),
// you'll do that with websocketServer:

// Create WebSocket listener server
const websocketServer = createServer(graphQLServer);

// Bind it to port and start listening
websocketServer.listen(3000, () => console.log(
  `Server is now running on http://localhost:3000`
));

const subscriptionServer = SubscriptionServer.create(
  {
    schema,
    execute,
    subscribe,
  },
  {
    server: websocketServer,
    path: '/subscriptions',
  },
);
</code>```

Body:
It seems like I have my server set up according to the Apollo docs at http://dev.apollodata.com/tools/apollo-server/setup.html. In my server/main.js file:

//SET UP APOLLO INCLUDING APOLLO PUBSUB
const executableSchema = makeExecutableSchema({
    typeDefs: Schema,
    resolvers: Resolvers,
    connectors: Connectors,
    logger: console,
});

const GRAPHQL_PORT = 8080;
const graphQLServer = express();

// `context` must be an object and can't be undefined when using connectors
graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({
    schema: executableSchema,
    context: {}, //at least(!) an empty object
}));

graphQLServer.use('/graphiql', graphiqlExpress({
    endpointURL: '/graphql',
}));

graphQLServer.listen(GRAPHQL_PORT, () => console.log(
    `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`
));
//SET UP APOLLO INCLUDING APOLLO PUBSUB

It prints out "GraphQL Server is now running on http://localhost:8080/graphql" to the terminal log indicating that the server was successfully initialized.

But at the top of my main_layout component, when I run this code:

import { Client } from 'subscriptions-transport-ws';
const wsClient = new Client('ws://localhost:8080');

...I get this console message:

WebSocket connection to 'ws://localhost:8080/' failed: Connection closed before receiving a handshake response

What am I missing?

Body:
Seems like you aren't actually making the websocket server. use SubscriptionServer. Keep in mind that it is absolutely NOT true that you have to have a dedicated websocket port (I thought this once too) as davidyaha says. I have both my normal queries and subs on the same port.

import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { execute, subscribe } from 'graphql';
import { schema } from './my-schema';

// All your graphQLServer.use() etc setup goes here, MINUS the graphQLServer.listen(),
// you'll do that with websocketServer:

// Create WebSocket listener server
const websocketServer = createServer(graphQLServer);

// Bind it to port and start listening
websocketServer.listen(3000, () => console.log(
  `Server is now running on http://localhost:3000`
));

const subscriptionServer = SubscriptionServer.create(
  {
    schema,
    execute,
    subscribe,
  },
  {
    server: websocketServer,
    path: '/subscriptions',
  },
);


问:
Spring Redis issue: GetAllCacheNames from redis cache is not working with RedisCacheManager
Hi below is my redis cache configuration, and I am trying to get all the cachename stored on redis server using:

redisCacheManager.getCacheNames()

but it doesnot gives me the cacheName present in my redis server.

I prefix cacheName using Cachable annotation: @Cacheable("cacheName")

I have 2 questions here?

1) Why I am not able to get the cacheNames which i stored in redis server.
2)How can i dynamically create the prefix cacheName since i don't want to write seperate method for all of them?

```<code>@Bean
JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory factory = new JedisConnectionFactory();
    factory.setHostName(redisHost);
    factory.setPort(redisPort);
    factory.setUsePool(true);
    return factory;
}

@Bean
RedisTemplate<Object, Object> redisTemplate() {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    redisTemplate.setDefaultSerializer(new StringRedisSerializer());
   // redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
    return redisTemplate;
}

@Bean
CacheManager cacheManager() {
    // configuration to set the time to expire in seconds, messageCache is name of method
    Map<String,Long> cacheMap = new HashMap<String, Long>();
    //cacheMap is the name of the map where we put all the method names for which we want time to expire.
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
    redisCacheManager.setUsePrefix(true);
    //redisCacheManager.setExpires(cacheMap);
    return redisCacheManager;
}
</code>```

答:
For CacheNames, try</p>

```<code>@Autowired CacheManager cacheManager
cacheManager.getCacheNames().forEach(cacheM-> {System.out.println(cacheM);});
</code>```

Body:
Hi below is my redis cache configuration, and I am trying to get all the cachename stored on redis server using:

redisCacheManager.getCacheNames()

but it doesnot gives me the cacheName present in my redis server.

I prefix cacheName using Cachable annotation: @Cacheable("cacheName")

I have 2 questions here?

1) Why I am not able to get the cacheNames which i stored in redis server.
2)How can i dynamically create the prefix cacheName since i don't want to write seperate method for all of them?

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory factory = new JedisConnectionFactory();
    factory.setHostName(redisHost);
    factory.setPort(redisPort);
    factory.setUsePool(true);
    return factory;
}

@Bean
RedisTemplate<Object, Object> redisTemplate() {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    redisTemplate.setDefaultSerializer(new StringRedisSerializer());
   // redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
    return redisTemplate;
}

@Bean
CacheManager cacheManager() {
    // configuration to set the time to expire in seconds, messageCache is name of method
    Map<String,Long> cacheMap = new HashMap<String, Long>();
    //cacheMap is the name of the map where we put all the method names for which we want time to expire.
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
    redisCacheManager.setUsePrefix(true);
    //redisCacheManager.setExpires(cacheMap);
    return redisCacheManager;
}

Body:
For CacheNames, try

@Autowired CacheManager cacheManager
cacheManager.getCacheNames().forEach(cacheM-> {System.out.println(cacheM);});


问:
Find html label associated with a given input
Let's say I have an html form.  Each input/select/textarea will have a corresponding  with the for attribute set to the id of it's companion. In this case, I know that each input will only have a single label.

Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?

答:
All the other answers are extremely outdated!!

All you have to do is:

```<code>input.labels
</code>```

HTML5 has been supported by all of the major browsers for many years already. There is absolutely no reason that you should have to make this from scratch on your own or polyfill it! Literally just use input.labels and it solves all of your problems.

OwnerDisplayName: Joel Coehoorn

Body:
All the other answers are extremely outdated!!

All you have to do is:

input.labels

HTML5 has been supported by all of the major browsers for many years already. There is absolutely no reason that you should have to make this from scratch on your own or polyfill it! Literally just use input.labels and it solves all of your problems.


问:
Consuming web services with jboss
Can someone point me a good step-by-step tutorial to consuming an already running web service in java?

PS: I tried creating the classes with wsconsume, but it cries with

[ERROR] rpc/encoded wsdls are not supported in JAXWS 2.0.  (my web service is rpc/encoded)

If I can consume web services entirely by hand (using no wizards), and understand how is it working, then I'll be happy.

Thanks!

Update: I have found out that rpc web services are not consumed using jbossws, but jboss-jaxrpc, which implements the JAX-RPC specification. I've found a guide for JAX-RPC here, but I'm still looking for other guides that could help.

答: How about the JBossWS website? The details on the client side wsconsume tool  are probally what you will look at first.</p>

OwnerDisplayName: Pablo

Title: Consuming web services with jboss

LastEditorDisplayName: Pablo


问:
creating xsl-fo with correct format
I need to create an xsl-fo document from an xml document which displays information of the the export ammount (profits) for each year and, within each year, for every region.

in order to produce a table which contains, for each year, the earnings for that year and how it compares to the previous year, in a three column table displaying such information.

this problem seems to have the whole class stumped and the teacher isn't currently available for consultation. Any help would be greatly appreciated. Thanks in advance.

答:
I have prepared the following XSLT, I hope this helps you.

```<code><xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xsl:template match="/">
    <html>
    <body>
    <table style="width:100%" border="1" >
        <tr bgcolor="#9acd32">
            <th>Year</th>
            <th>Total</th>
            <th>Delta</th>
        </tr>
    <xsl:for-each select="exports/year">
        <tr>
          <td><xsl:value-of select="./text()"/></td>
          <td><xsl:value-of select='format-number(./total, "#.0")'/></td>
          <xsl:choose>
          <xsl:when test="position()=1">
            <td><xsl:text>-</xsl:text></td>
          </xsl:when>
          <xsl:otherwise>
            <td><xsl:value-of select='format-number((xs:decimal(./total)- xs:decimal(preceding-sibling::*[ 1]/total)) div xs:decimal(preceding-sibling::*[ 1]/total),"#.00%")'/></td>
          </xsl:otherwise>
          </xsl:choose>
        </tr>
    </xsl:for-each>
    </table>
    </body>
    </html>

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

the main parts of it are:

for-each select="exports/year" that will loop on each year of your input data and generate one line in the output table

./text() to get the year

'format-number(./total, "#.0")' to get the one decimal precision of your total

then the last part, a choose when/otherwise to check if your element is the first of not using position()=1 if it is the case output "-" else do the following computation :

'format-number((xs:decimal(./total)- xs:decimal(preceding-sibling::*[ 1]/total)) div xs:decimal(preceding-sibling::*[ 1]/total),"#.00%")' where div is the divisor operator and preceding-sibling allows you to get the previous sibling node in your DOM tree, before formatting the result in percentage with 2 decimals

Title: creating xsl-fo with correct format

Body:
I have prepared the following XSLT, I hope this helps you.

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xsl:template match="/">
    <html>
    <body>
    <table style="width:100%" border="1" >
        <tr bgcolor="#9acd32">
            <th>Year</th>
            <th>Total</th>
            <th>Delta</th>
        </tr>
    <xsl:for-each select="exports/year">
        <tr>
          <td><xsl:value-of select="./text()"/></td>
          <td><xsl:value-of select='format-number(./total, "#.0")'/></td>
          <xsl:choose>
          <xsl:when test="position()=1">
            <td><xsl:text>-</xsl:text></td>
          </xsl:when>
          <xsl:otherwise>
            <td><xsl:value-of select='format-number((xs:decimal(./total)- xs:decimal(preceding-sibling::*[ 1]/total)) div xs:decimal(preceding-sibling::*[ 1]/total),"#.00%")'/></td>
          </xsl:otherwise>
          </xsl:choose>
        </tr>
    </xsl:for-each>
    </table>
    </body>
    </html>

  </xsl:template>
</xsl:stylesheet>

the main parts of it are:

for-each select="exports/year" that will loop on each year of your input data and generate one line in the output table

./text() to get the year

'format-number(./total, "#.0")' to get the one decimal precision of your total

then the last part, a choose when/otherwise to check if your element is the first of not using position()=1 if it is the case output "-" else do the following computation :

'format-number((xs:decimal(./total)- xs:decimal(preceding-sibling::*[ 1]/total)) div xs:decimal(preceding-sibling::*[ 1]/total),"#.00%")' where div is the divisor operator and preceding-sibling allows you to get the previous sibling node in your DOM tree, before formatting the result in percentage with 2 decimals


问:
How to create EBS volume using AWS SSM
I am new to AWS SSM. Could anyone help me to how create a EBS volume using AWS System service management (SSM).

Thanks.

答:
Amazon EC2 Systems Manager (SSM) is a nice product that is designed to help manage Windows and Linux operating systems.

You cannot create EBS volumes with SSM. You can use SSM to run tools that manage what is on an EBS volume.

Here is a good video on YouTube that will help you understand the capabilities of SSM.

Deep Dive with Amazon EC2 Systems Manager

Title: How to create EBS volume using AWS SSM


问:
Swift 4 - Editing label frame.size.height with negative number
So I have a label that I've made in Xcode's storyboard which I want to later edit in my code. I want it to simulate something like a vertical bar so I am editing its height by doing:

```<code>answerE.frame.size.height = -200
</code>```

The problem comes from the negative number, I want the label to "grow" up so the height has to be negative from its original position... I have the line in code in a simple action on button press, but each time the line is executed the label moves "up" and eventually after 3-4 clicks is out of the screen.
I just want to edit its height, what is the correct way and what am I doing wrong?

My exact line in code is:

```<code>label.frame.size.height = -CGFloat(Double(x)/Double(y) * (200))
</code>```

答:
If I'm right, you want the label to gain height, keeping the same bottom edge, but the top edge moving up.

In order to do this, you want to change the frame.origin.y as you change the frame.size.height at the same amount, as its placement (and so top edge) is determined by its origin. So maybe make it zero height, place it where you want it in storyboard, and then when you want it to 'grow' by x:

```<code>label.frame.size.height = label.frame.height + x
label.frame.origin.y = label.frame.origin.y - x
</code>```

Body:
So I have a label that I've made in Xcode's storyboard which I want to later edit in my code. I want it to simulate something like a vertical bar so I am editing its height by doing:

answerE.frame.size.height = -200

The problem comes from the negative number, I want the label to "grow" up so the height has to be negative from its original position... I have the line in code in a simple action on button press, but each time the line is executed the label moves "up" and eventually after 3-4 clicks is out of the screen.
I just want to edit its height, what is the correct way and what am I doing wrong?

My exact line in code is:

label.frame.size.height = -CGFloat(Double(x)/Double(y) * (200))

Body:
If I'm right, you want the label to gain height, keeping the same bottom edge, but the top edge moving up.

In order to do this, you want to change the frame.origin.y as you change the frame.size.height at the same amount, as its placement (and so top edge) is determined by its origin. So maybe make it zero height, place it where you want it in storyboard, and then when you want it to 'grow' by x:

label.frame.size.height = label.frame.height + x
label.frame.origin.y = label.frame.origin.y - x


问:
What's the xpath syntax to get tag names?
I'm using Nokogiri to parse a large XML file. Say I've got the following structure:

```<code><menagerie>
  <penguin>Pablo</penguin>
  <penguin>Mortimer</penguin>
  <bull>Ferdinand</bull>
  <aardvark>James Cornelius Madison Humphrey Zophar Handlebrush III</aardvark>
</menagerie>
</code>```

I can count the non-penguins like this:

```<code>xml.xpath('//menagerie//*[not(penguin)]').length // 2
</code>```

But how do I get a list of the tags, like this? (The exact format isn't important; I just want to visually scan the non-penguins.)

```<code>bull
aardvark
</code>```

Update

This gave me the list I wanted - thanks Oded and TMN and delnan!

```<code>xml.xpath('//menageries/*[not(penguin)]').each do |node|
  puts node.name()
end
</code>```

答:
You can use the name() or local-name() XPath function.

See the examples on zvon.

Body:
I'm using Nokogiri to parse a large XML file. Say I've got the following structure:

<menagerie>
  <penguin>Pablo</penguin>
  <penguin>Mortimer</penguin>
  <bull>Ferdinand</bull>
  <aardvark>James Cornelius Madison Humphrey Zophar Handlebrush III</aardvark>
</menagerie>

I can count the non-penguins like this:

xml.xpath('//menagerie//*[not(penguin)]').length // 2

But how do I get a list of the tags, like this? (The exact format isn't important; I just want to visually scan the non-penguins.)

bull
aardvark

Update

This gave me the list I wanted - thanks Oded and TMN and delnan!

xml.xpath('//menageries/*[not(penguin)]').each do |node|
  puts node.name()
end


问:
Dev Mode for Node, Webpack-Dev-Server, React - No Such File or Directory for Nested Routes
I am trying to get my application to work in development mode with Node and Webpack-Dev-Server. When I serve up '/' I get back exactly what I intend. However, when I do '/test' I get 'no such file or directory'. I have read a lot of documentation on Webpack's website and React Router Training, none seem to really answer this issue. I want to be able to use browserHistory instead of hashHistory (I am still using React-Router v3).

package.json:

```<code>{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "clean": "rimraf dist",
    "build": "NODE_ENV=production npm run clean && webpack -p",
    "dev": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.15.3",
    "babel-core": "^6.7.2",
    "babel-loader": "^6.2.4",
    "babel-plugin-transform-class-properties": "^6.22.0",
    "babel-preset-env": "^1.1.8",
    "babel-preset-react": "^6.5.0",
    "css-loader": "^0.26.1",
    "express": "^4.14.0",
    "html-webpack-plugin": "^2.26.0",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-redux": "^4.4.1",
    "react-router": "^3.2.0",
    "redux": "^3.3.1",
    "redux-promise": "^0.5.3",
    "rimraf": "^2.5.4",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^3.8.1"
  },
  "devDependencies": {
    "nodemon": "^1.11.0",
    "webpack-dev-middleware": "^1.9.0",
    "webpack-dev-server": "^2.2.0-rc.0",
    "webpack-hot-middleware": "^2.20.0"
  }
}
</code>```

webpack.config.js

```<code>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const VENDOR_LIBS = [
  'axios', 'react', 'redux', 'react-dom', 'react-redux',
  'react-router', 'redux-promise'
];

module.exports = {
  entry: {
    bundle: './client/src/index.js',
    vendor: VENDOR_LIBS
  },
  output: {
    chunkFilename: '[name].[chunkhash].js',
    path: path.join(__dirname, 'dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      },
      {
        test: /\.(jpe?g|png|gif|svg|)$/,
        use: [
          {
            loader: 'url-loader',
            options: {limit: 40000}
          },
          'image-webpack-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest']
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new HtmlWebpackPlugin({
      template: './client/src/index.html'
    })
  ],
  devtool: 'inline-source-map',
  devServer: {
    contentBase: '/dist',
    historyApiFallback: true
  },
};
</code>```

server.js:

```<code>const express = require('express');
const path = require('path');
const app = express();

if (process.env.NODE_ENV !== 'production') {
  app.use(express.static(path.join(__dirname, 'dist')));
  const webpack = require('webpack');
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const config = require('./webpack.config.js');
  const compiler = webpack(config);
  app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath
  }));
} else {
  app.use(express.static('dist'));
}

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(process.env.PORT || 3050, () => console.log('Listening'));
</code>```

routes.js:

```<code>import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';

import App from './components/app';
import Home from './components/home';

const componentRoutes = (
  <Route component={App} path='/'>
    <Route component={Home} path='/test' />
  </Route>
);

const Routes = () => {
  return <Router history={ browserHistory } routes={ componentRoutes } />
};

export default Routes;
</code>```

The App component renders a single div saying it loaded and same for the Home component. If you care to see the entire thing on Github, here is a link:

https://github.com/jlag34/nodeWebpackSupport

The main goal is to be able to load '/test' in dev mode without using hashHistory.

Wepback docs: https://webpack.js.org/guides/development/

答:
You are serving dist/index.html when no other route was matched, with:

```<code>app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
</code>```

But this looks for that file on your file system, which should work in your production build (when you build the bundle and then serve it). If you look at the error you get when going to /test you will see that this file doesn't exist.

```<code>Error: ENOENT: no such file or directory, stat '/path/to/nodeWebpackSupport/dist/index.html'
</code>```

This happens, because you're generating the index.html with html-webpack-plugin and webpack-dev-middleware keeps that in memory and doesn't write it to the file system. In development you cannot serve that file, but instead you need to serve the one from memory. You can access the files in webpack's memory with compiler.outputFileSystem.readFile.

In your development routes you need to add the following (originally taken from the comment of html-webpack-plugin #145):

```<code>app.use('*', (req, res, next) => {
  const filename = path.resolve(compiler.outputPath, 'index.html');
  compiler.outputFileSystem.readFile(filename, (err, result) => {
    if (err) {
      return next(err);
    }
    res.set('content-type','text/html');
    res.send(result);
    res.end();
  });
});
</code>```

Body:
I am trying to get my application to work in development mode with Node and Webpack-Dev-Server. When I serve up '/' I get back exactly what I intend. However, when I do '/test' I get 'no such file or directory'. I have read a lot of documentation on Webpack's website and React Router Training, none seem to really answer this issue. I want to be able to use browserHistory instead of hashHistory (I am still using React-Router v3).

package.json:

{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "clean": "rimraf dist",
    "build": "NODE_ENV=production npm run clean && webpack -p",
    "dev": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.15.3",
    "babel-core": "^6.7.2",
    "babel-loader": "^6.2.4",
    "babel-plugin-transform-class-properties": "^6.22.0",
    "babel-preset-env": "^1.1.8",
    "babel-preset-react": "^6.5.0",
    "css-loader": "^0.26.1",
    "express": "^4.14.0",
    "html-webpack-plugin": "^2.26.0",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-redux": "^4.4.1",
    "react-router": "^3.2.0",
    "redux": "^3.3.1",
    "redux-promise": "^0.5.3",
    "rimraf": "^2.5.4",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^3.8.1"
  },
  "devDependencies": {
    "nodemon": "^1.11.0",
    "webpack-dev-middleware": "^1.9.0",
    "webpack-dev-server": "^2.2.0-rc.0",
    "webpack-hot-middleware": "^2.20.0"
  }
}

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const VENDOR_LIBS = [
  'axios', 'react', 'redux', 'react-dom', 'react-redux',
  'react-router', 'redux-promise'
];

module.exports = {
  entry: {
    bundle: './client/src/index.js',
    vendor: VENDOR_LIBS
  },
  output: {
    chunkFilename: '[name].[chunkhash].js',
    path: path.join(__dirname, 'dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      },
      {
        test: /\.(jpe?g|png|gif|svg|)$/,
        use: [
          {
            loader: 'url-loader',
            options: {limit: 40000}
          },
          'image-webpack-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest']
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new HtmlWebpackPlugin({
      template: './client/src/index.html'
    })
  ],
  devtool: 'inline-source-map',
  devServer: {
    contentBase: '/dist',
    historyApiFallback: true
  },
};

server.js:

const express = require('express');
const path = require('path');
const app = express();

if (process.env.NODE_ENV !== 'production') {
  app.use(express.static(path.join(__dirname, 'dist')));
  const webpack = require('webpack');
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const config = require('./webpack.config.js');
  const compiler = webpack(config);
  app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath
  }));
} else {
  app.use(express.static('dist'));
}

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(process.env.PORT || 3050, () => console.log('Listening'));

routes.js:

import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';

import App from './components/app';
import Home from './components/home';

const componentRoutes = (
  <Route component={App} path='/'>
    <Route component={Home} path='/test' />
  </Route>
);

const Routes = () => {
  return <Router history={ browserHistory } routes={ componentRoutes } />
};

export default Routes;

The App component renders a single div saying it loaded and same for the Home component. If you care to see the entire thing on Github, here is a link:

https://github.com/jlag34/nodeWebpackSupport

The main goal is to be able to load '/test' in dev mode without using hashHistory.

Wepback docs: https://webpack.js.org/guides/development/

Body:
You are serving dist/index.html when no other route was matched, with:

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

But this looks for that file on your file system, which should work in your production build (when you build the bundle and then serve it). If you look at the error you get when going to /test you will see that this file doesn't exist.

Error: ENOENT: no such file or directory, stat '/path/to/nodeWebpackSupport/dist/index.html'

This happens, because you're generating the index.html with html-webpack-plugin and webpack-dev-middleware keeps that in memory and doesn't write it to the file system. In development you cannot serve that file, but instead you need to serve the one from memory. You can access the files in webpack's memory with compiler.outputFileSystem.readFile.

In your development routes you need to add the following (originally taken from the comment of html-webpack-plugin #145):

app.use('*', (req, res, next) => {
  const filename = path.resolve(compiler.outputPath, 'index.html');
  compiler.outputFileSystem.readFile(filename, (err, result) => {
    if (err) {
      return next(err);
    }
    res.set('content-type','text/html');
    res.send(result);
    res.end();
  });
});


问:
a puzzle about definition of the time complexity
Wikipedia defines time complexity as

In computer science, the time complexity of an algorithm quantifies
  the amount of time taken by an algorithm to run as a function of the
  length of the string representing the input.

What's mean of the strong part?

I know algorithm may be treated as a function but why its input must be "the length of the string representing"?

答:
The function in the bolder part means the time complexity of the algorithm, not the algorithm itself. An algorithm may be implemented in a programming language that has a function keyword, but that's something else.

Algorithm MergeSort has as input a list of 32m bits (assuming m 32-bit values). It's time complexity T(n) is a function of n = 32m, the input size, and in the worst case is bound from above by O(n log n). MergeSort could be implemented as a function in C or JavaScript.