问:
Increment, display, and print a number of pages up to a Parameter maximum
I am trying to set up a Crystal Report to generate pallet labels which include a "Pallet N of M" line on each page.

The order in the database only has one entry, which contains all of the other information for the label(s).  My issue is that the number of pallets isn't known until print time, and each label needs the same order information as well as a pallet ID.  What I am looking for is for the user to enter a parameter for the total number of pallets, then have Crystal generate the correct number of unique labels.

For example, if the order has 4 pallets then Crystal should generate 4 copies of the label, the only difference on each copy being the last line which should read 'Pallet 1 of 4', 'Pallet 2 of 4', 'Pallet 3 of 4', and 'Pallet 4 of 4' respectively.

The only solution I can think of would be to create a number of sections equal to the maximum number of pallets, all containing my real data as a sub-report, then suppress any which are greater than the entered parameter.  I am trying to avoid this because we may have greater than 50 pallets on a given order, so that would be tedious to create and is just not a very clean solution.

-= EDIT =-

Big thanks to Aliqux for the solution.  In the end I needed to change the syntax to be Oracle compatible and also include the LINKVALUE field in the report, but the answer was 99% there especially considering I had not mentioned that my datasource was Oracle.  The Command syntax I ended up using (with my parameter called TotalPallets) was:

SELECT
-1 AS "LINKVALUE"
FROM table
WHERE rownum <= {?TotalPallets}

答:
You will need to Add a command to your tables.

1) Under database Expert in the Database you used select Add Command.

2) Click create to Create a Parameter.

3) Create the requested values, you can leave the Default Value blank if you want, and change the Value Type to Number. (I will be calling my parameter Counter)

4) Put the following in the SQL query where table is the main table you are using

```<code>SELECT TOP {?Counter}
-1  AS LINKVALUE
FROM table
</code>```

5) Click okay and enter a value if prompted

6) In links link a number field, that will never go into negative numbers as we are using -1 for a base, to the LINKVALUE in the Command Table.

7)Link Options are as followed

Join Type: Inner Join, Enforce Join: Not Enforced, Link Type: !=

8) In your report create a formula with a shared numbervalue the starts from one.

```<code>shared numbervar counters;
if counters = {?Counter} then counters := 0;
counters := counters + 1
</code>```

9) You can use that formula and the Counter Parameter for your labels

```<code>totext({@Counts},0,"")+" of "+totext({?Counter},0,"")
</code>```

Credit reference: https://blogs.sap.com/2014/01/24/duplicating-data-details-records-n-times-eg-repeating-labels-n-times/

Body:
You will need to Add a command to your tables.

1) Under database Expert in the Database you used select Add Command.

2) Click create to Create a Parameter.

3) Create the requested values, you can leave the Default Value blank if you want, and change the Value Type to Number. (I will be calling my parameter Counter)

4) Put the following in the SQL query where table is the main table you are using

SELECT TOP {?Counter}
-1  AS LINKVALUE
FROM table

5) Click okay and enter a value if prompted

6) In links link a number field, that will never go into negative numbers as we are using -1 for a base, to the LINKVALUE in the Command Table.

7)Link Options are as followed

Join Type: Inner Join, Enforce Join: Not Enforced, Link Type: !=

8) In your report create a formula with a shared numbervalue the starts from one.

shared numbervar counters;
if counters = {?Counter} then counters := 0;
counters := counters + 1

9) You can use that formula and the Counter Parameter for your labels

totext({@Counts},0,"")+" of "+totext({?Counter},0,"")

Credit reference: https://blogs.sap.com/2014/01/24/duplicating-data-details-records-n-times-eg-repeating-labels-n-times/


来源: stackexchange

问:
Error When Unwrapping Optional Element
I have an optional element, but am facing an error when displaying said element in a tableview. For reference, this element is an image, obtained from a JSON API feed. I understand that force unwrapping an element using ! is not a good idea, but it is what xcode suggests I do, giving me no other options. If I follow its suggestion, the app crashes, displaying "unexpectedly found nil while unwrapping an Optional value." Does anyone know how I can display an image from a URL. Here is the code I have thus far.

```<code>struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}
</code>```

The Problem is with the "avatar" element, in the cellForRowAt func.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "rankCell") as? RankTableViewCell else { return UITableViewCell() }
    cell.nameLabel.text = rank[indexPath.row].personaname

    if let imageURL = URL(string: rank[indexPath.row].avatar) {
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL)
            if let data = data {
            guard let avatar = UIImage(data: data) else { return }
                DispatchQueue.main.async {
                    cell.avatarImage.image = avatar
                }
            }
        }
    }

    return cell
}
</code>```

答:
The code crashes if avatar is nil. You need to create the URL in two steps

```<code>if let avatar = rank[indexPath.row].avatar,
   let imageURL = URL(string: avatar) { ...
</code>```

Alternatively decode avatar directly to URL, JSONDecoder can that

```<code>let avatar: URL?
</code>```

Then you can shorten the code

```<code>if let imageURL = rank[indexPath.row].avatar {
</code>```

And you are strongly discouraged from using synchronous Data(contentsOf: API as mentioned by Dávid. Use asynchronous URLSession

ContentLicense: CC BY-SA 3.0

Title: Error When Unwrapping Optional Element

Body:
I have an optional element, but am facing an error when displaying said element in a tableview. For reference, this element is an image, obtained from a JSON API feed. I understand that force unwrapping an element using ! is not a good idea, but it is what xcode suggests I do, giving me no other options. If I follow its suggestion, the app crashes, displaying "unexpectedly found nil while unwrapping an Optional value." Does anyone know how I can display an image from a URL. Here is the code I have thus far.

struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}

The Problem is with the "avatar" element, in the cellForRowAt func.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "rankCell") as? RankTableViewCell else { return UITableViewCell() }
    cell.nameLabel.text = rank[indexPath.row].personaname

    if let imageURL = URL(string: rank[indexPath.row].avatar) {
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL)
            if let data = data {
            guard let avatar = UIImage(data: data) else { return }
                DispatchQueue.main.async {
                    cell.avatarImage.image = avatar
                }
            }
        }
    }

    return cell
}

Body:
The code crashes if avatar is nil. You need to create the URL in two steps

if let avatar = rank[indexPath.row].avatar,
   let imageURL = URL(string: avatar) { ...

Alternatively decode avatar directly to URL, JSONDecoder can that

let avatar: URL?

Then you can shorten the code

if let imageURL = rank[indexPath.row].avatar {

And you are strongly discouraged from using synchronous Data(contentsOf: API as mentioned by Dávid. Use asynchronous URLSession


问:
importing nested JSON to Google Spreadsheets

Hi!
I'm trying to import data from a nested JSON into Google spreadsheets. I use code that has worked perfectly with another nested JSON but now I'm getting the JSON from a different API and it looks slightly different and it throws a "The coordinates or dimensions of the range are invalid. (line 18, file "Code")"-error, referring to the line;

```<code>dataRange = sheet.getRange(2, 1, rows.length, 5);
</code>```

I use the following code;

```<code>function getHistoricalRatesETH() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheets = ss.getSheets();
    var sheet = ss.getSheetByName("getData");
    ss.setSpreadsheetLocale('en-us');
    var url="https://min-api.cryptocompare.com/data/histoday?fsym=ETH&tsym=USD&limit=1460";
    var response = UrlFetchApp.fetch(url); // get feed
    var dataAll = JSON.parse(response.getContentText()); //
    var dataSet = dataAll;
    var rows = [],data;
    for (i = 0; i < dataSet.length; i++) {
        data = dataSet[i];
        rows.push([data.time,data.close,data.high,data.low,data.open]);
    }
    dataRange = sheet.getRange(2, 1, rows.length, 5); //Last digit denotes columns
    dataRange.setValues(rows);
    ss.setSpreadsheetLocale('en-us');
}
</code>```

I tried to change

```<code>var rows = [],data;
</code>```

to

```<code>var rows = [],Data;
</code>```

Also tried using the ids

```<code>rows.push([data.Data.time,data.Data.close,data.Data.high,data.Data.low,data.Data.open]);
</code>```

But the result is the same.

I've tripple-checked so the sheet name isn't misspelt and
searched like crazy on how to address a nested json but to no avail.

答:
There is the data you want at response.Data. So how about the following modification for your script?

From :

```<code>var dataSet = dataAll;
</code>```

To :

```<code>var dataSet = dataAll.Data;
</code>```

Body:
Hi!
I'm trying to import data from a nested JSON into Google spreadsheets. I use code that has worked perfectly with another nested JSON but now I'm getting the JSON from a different API and it looks slightly different and it throws a "The coordinates or dimensions of the range are invalid. (line 18, file "Code")"-error, referring to the line;

dataRange = sheet.getRange(2, 1, rows.length, 5);

I use the following code;

function getHistoricalRatesETH() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheets = ss.getSheets();
    var sheet = ss.getSheetByName("getData");
    ss.setSpreadsheetLocale('en-us');
    var url="https://min-api.cryptocompare.com/data/histoday?fsym=ETH&tsym=USD&limit=1460";
    var response = UrlFetchApp.fetch(url); // get feed
    var dataAll = JSON.parse(response.getContentText()); //
    var dataSet = dataAll;
    var rows = [],data;
    for (i = 0; i < dataSet.length; i++) {
        data = dataSet[i];
        rows.push([data.time,data.close,data.high,data.low,data.open]);
    }
    dataRange = sheet.getRange(2, 1, rows.length, 5); //Last digit denotes columns
    dataRange.setValues(rows);
    ss.setSpreadsheetLocale('en-us');
}

I tried to change

var rows = [],data;

to

var rows = [],Data;

Also tried using the ids

rows.push([data.Data.time,data.Data.close,data.Data.high,data.Data.low,data.Data.open]);

But the result is the same.

I've tripple-checked so the sheet name isn't misspelt and
searched like crazy on how to address a nested json but to no avail.

Body:
There is the data you want at response.Data. So how about the following modification for your script?

From :

var dataSet = dataAll;

To :

var dataSet = dataAll.Data;


问:
Google Spreadsheet conditional formatting based on another cell Date
I have a Google spreedsheet with multiple columns and I am trying to apply the following two tasks but can't seem to figure out how to do so.

I have two columns C and D, where C present a date picker and D present a drop down list with two values [Complete - In Progress]. I am trying to figure out a way where any cell in column D will display (In Progress) if the corresponding cell date is less than or equal todays date

If column C date is 2 days ahead, change the whole row color to blue

Can the above be done using Google d=Any thoughts how I can complete any of the above two tasks? Thanks in advance for your time and efforts

答:
I'm not sure on what your particular setup is, but I think using the IF statement may be what you're looking for.

For example:

C4 = Dec 10, 2017

D4 = Completed
D5 = In-Progress

E5 = IF(C4<[Specified Date], D5, D4)

Let's say [Specified Date] = Dec 8, 2017, then E5 would display In-Progress.
if the [Specified Date] = Dec 10, 2017 or higher E5 would display Completed.

For task 2:
You just need to add 2 Conditional Formatting for when cells are labelled as In-Progress and Completed.

I may have misunderstood your question as well.


问:
What is the configuration of the microsoft.com IIS servers?
A couple of months ago, I had found a page on a Microsoft Team blog, where the techs were explaining what configuration they used on their own IIS web servers running the microsoft.com website behind the scene.

This article was dated several years ago. Infortunately, I have forgotten to bookmark it ! .. and cannot find it again.

Even if some of the information in this article was dated in some aspects, a large portion of it was very relevant to help me configure my own IIS web servers.

Shame on me for not having bookmarked it !

Would I have the chance that one of you can lead me to this blog entry again ? Maybe on archive.org ?

Many thanks ;)

答:
I finally got this article again !
It was not on a microsoft blog, but on Technet. My fault, sorry.

In this article, the Microsoft Engineering Operations (MSCOM Ops) team share with us which configuration settings they use to tune application pools running the microsoft own servers.

I really thank their team for sharing with us the Microsoft.com Operations settings, that abviously must be adapted for each or our cases.

Here it is ! :-)

https://technet.microsoft.com/en-us/library/cc745955.aspx

Hoping having saved the day of many other users in addition to mine ;)


问:
Loading modules JS
I'm having a synchronization and loading issues with some JS modules when the program starts. This error only shows up once at the beginning and then everything works, so it is an obvious sync problem.

The code:

```<code>//pyramid of doom
function initGame(){
  initWorld(function(){
    initPlayer(function(){
      initBots(function(){
        console.log("Game Loaded!");
        update();
      })
    })
  });
}
function initWorld(callback){
  world.init(worldParams);
  callback&&callback();
}
function initPlayer(callback){
  player.init(scene,playerParams,world.getPhysicModel());
  callback&&callback();
}
function initBots(callback){
  bots.init(scene,botsParams,world.getPhysicModel());
  callback&&callback();
}
function update() {
  world.update(1/60);
  player.update();
  bots.update();
}
initGame();
</code>```

The following is the error I'm getting.

```<code>Bots.js:112 Uncaught TypeError: Cannot read property 'mixer' of undefined
    at Bots.update (Bots.js:112)
    at update (Final.html:160)
</code>```

What am I doing wrong? How can I synchronize the execution of the init functions?

(What I think that is going on is that the execution of initBots doesn't reach it end before the udpdate function starts to run.)

You can find the Bots.js module in my repository at ( 1  )

答:
You need to be passing the callbacks into the init functions. Guessing from a brief look at your bots code, they are not expecting to receive callbacks so you might be in for a rebuild.

You can't tell from the outside of an async function if it is done yet!

Equivalent to what you are doing:

let result = undefined

function takeTime () {
  setTimeout(function() {
    result = 'hello!'
  }, 100)
}

function callback () {
  console.log(result)
}

function run (callback) {
  takeTime()
  callback && callback()
}

run(callback) // undefined! takeTime has not finished yet```
</div>
</div>
</p>

<p>What you need to be doing:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let result = undefined

function takeTime (callback) {
  setTimeout(function() {
    result = 'hello!'
    callback()
  }, 100)
}

function callback () {
  console.log(result)
}

function run (callback) {
  callback && takeTime(callback)
}

run(callback) // 'hello!', the callback was only called once the takeTime function completed</code>```

Title: Loading modules JS

Body:
I'm having a synchronization and loading issues with some JS modules when the program starts. This error only shows up once at the beginning and then everything works, so it is an obvious sync problem.

The code:

//pyramid of doom
function initGame(){
  initWorld(function(){
    initPlayer(function(){
      initBots(function(){
        console.log("Game Loaded!");
        update();
      })
    })
  });
}
function initWorld(callback){
  world.init(worldParams);
  callback&&callback();
}
function initPlayer(callback){
  player.init(scene,playerParams,world.getPhysicModel());
  callback&&callback();
}
function initBots(callback){
  bots.init(scene,botsParams,world.getPhysicModel());
  callback&&callback();
}
function update() {
  world.update(1/60);
  player.update();
  bots.update();
}
initGame();

The following is the error I'm getting.

Bots.js:112 Uncaught TypeError: Cannot read property 'mixer' of undefined
    at Bots.update (Bots.js:112)
    at update (Final.html:160)

What am I doing wrong? How can I synchronize the execution of the init functions?

(What I think that is going on is that the execution of initBots doesn't reach it end before the udpdate function starts to run.)

You can find the Bots.js module in my repository at ( 1  )

Body:
You need to be passing the callbacks into the init functions. Guessing from a brief look at your bots code, they are not expecting to receive callbacks so you might be in for a rebuild.

You can't tell from the outside of an async function if it is done yet!

Equivalent to what you are doing:

let result = undefined

function takeTime () {
  setTimeout(function() {
    result = 'hello!'
  }, 100)
}

function callback () {
  console.log(result)
}

function run (callback) {
  takeTime()
  callback && callback()
}

run(callback) // undefined! takeTime has not finished yet

What you need to be doing:

let result = undefined

function takeTime (callback) {
  setTimeout(function() {
    result = 'hello!'
    callback()
  }, 100)
}

function callback () {
  console.log(result)
}

function run (callback) {
  callback && takeTime(callback)
}

run(callback) // 'hello!', the callback was only called once the takeTime function completed


问:
How can i change the icon color of searchview in actionbar?
This is my menu.xml

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

<item
    android:id="@+id/action_search"
    android:icon="@drawable/search_icon"
    android:title="@string/action_search"
    app:actionViewClass="android.widget.SearchView"
    app:showAsAction="always" />

<item
    android:id="@+id/action_favorite"
    android:icon="@drawable/favorite_icon"
    android:title="@string/action_favorite"
    app:showAsAction="always" />

<item
    android:id="@+id/themes"
    android:title="@string/overflow_menu_item"
    app:showAsAction="never">

<menu>
        <item
            android:id="@+id/background1"
            android:title="Red-PinkGradient"
            />
        <item
            android:id="@+id/background2"
            android:title="Red-Gradient"
            />
        <item
            android:id="@+id/background3"
            android:title="Green-Gradient"
            />
        <item
            android:id="@+id/background4"
            android:title="Black-GreyGradient"
            />
</menu>

</item>

<item
    android:title="@string/overflow_menu_item2"
    android:id="@+id/settings"
    />
</code>```

And this is my styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionOverflowButtonStyle">@style/overFlow</item>
    <item name="searchViewStyle">@style/CustomSearchViewStyle</item>

</style>
<style name="overFlow" parent="@style/Widget.AppCompat.Light.ActionButton.Overflow">
    <item name="android:src">@drawable/ic_overflow_icon</item>
</style>
<style name="CustomSearchViewStyle" parent="Widget.AppCompat.SearchView">
    <item name="queryBackground">@color/white</item>
    <item name="searchIcon">@drawable/search_icon</item>
</style>
</code>```

How can i change the icon color of my searchview?
I tried to set the icon in my item to the drawable which is a white search icon, but i stays black.
https://imgur.com/a/LCRzt (this is what i have now, but the search icon needs to be white)
https://imgur.com/a/Q65lS (what is want as result)

I want the color to be white, for the other icons it works, but not for my searchview.

A second problem is when i click the search icon, my overflow disappears which is what i want, but my favorite icon stays there, how can i make it disappear?
And how can i make the close button also white, the small x icon to close the searchView.
https://imgur.com/a/3EBa4  (what i have now)
https://imgur.com/a/CbvqR  (what i want)
How can i solve this?

Thanks in advance,
-Vince

答:
You need to use android.support.v7.widget.SearchView</p>

```<code><style name="SearchViewStyle" parent="Widget.AppCompat.SearchView">
    <!-- Gets rid of the search icon -->
    <item name="searchIcon">@drawable/ic_search</item>
    <!-- Gets rid of the "underline" in the text -->
    <item name="queryBackground">@color/white</item>
    <!-- Gets rid of the search icon when the SearchView is expanded -->
    <item name="searchHintIcon">@null</item>
    <!-- The hint text that appears when the user has not typed anything -->
    <item name="queryHint">@string/search_hint</item>
</style>
</code>```

Body:
This is my menu.xml

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

<item
    android:id="@+id/action_search"
    android:icon="@drawable/search_icon"
    android:title="@string/action_search"
    app:actionViewClass="android.widget.SearchView"
    app:showAsAction="always" />

<item
    android:id="@+id/action_favorite"
    android:icon="@drawable/favorite_icon"
    android:title="@string/action_favorite"
    app:showAsAction="always" />

<item
    android:id="@+id/themes"
    android:title="@string/overflow_menu_item"
    app:showAsAction="never">

<menu>
        <item
            android:id="@+id/background1"
            android:title="Red-PinkGradient"
            />
        <item
            android:id="@+id/background2"
            android:title="Red-Gradient"
            />
        <item
            android:id="@+id/background3"
            android:title="Green-Gradient"
            />
        <item
            android:id="@+id/background4"
            android:title="Black-GreyGradient"
            />
</menu>

</item>

<item
    android:title="@string/overflow_menu_item2"
    android:id="@+id/settings"
    />

And this is my styles.xml

How can i change the icon color of my searchview?
I tried to set the icon in my item to the drawable which is a white search icon, but i stays black.
https://imgur.com/a/LCRzt (this is what i have now, but the search icon needs to be white)
https://imgur.com/a/Q65lS (what is want as result)

I want the color to be white, for the other icons it works, but not for my searchview.

A second problem is when i click the search icon, my overflow disappears which is what i want, but my favorite icon stays there, how can i make it disappear?
And how can i make the close button also white, the small x icon to close the searchView.
https://imgur.com/a/3EBa4  (what i have now)
https://imgur.com/a/CbvqR  (what i want)
How can i solve this?

Thanks in advance,
-Vince

Body:
You need to use android.support.v7.widget.SearchView

<style name="SearchViewStyle" parent="Widget.AppCompat.SearchView">
    <!-- Gets rid of the search icon -->
    <item name="searchIcon">@drawable/ic_search</item>
    <!-- Gets rid of the "underline" in the text -->
    <item name="queryBackground">@color/white</item>
    <!-- Gets rid of the search icon when the SearchView is expanded -->
    <item name="searchHintIcon">@null</item>
    <!-- The hint text that appears when the user has not typed anything -->
    <item name="queryHint">@string/search_hint</item>
</style>


问:
Openshift 3: App will not deploy unless pod manually scaled to 0 then back to 1
The only way I can get a new build deployed on my Openshift 3 Starter app is if I manually scale the existing running pod down to 0, deploy my latest build, then scale the pod back to 1.

If I don't manually scale down the pod to 0 the deployment process results in a insufficient memory error or time out.  When the system deploys automatically after a new build the log says it scales the pod down to 0, deploys, then scales up to 1 and that is when the error occurs.

My app is on US west 2.

Is this just an Openshift 3 bug or am I building and deploying incorrectly?

答:
This likely means you are at the limit of your memory resources. It occurs because the default deployment strategy is a rolling deployment, which means there needs to be enough memory available to start a new instance, before the old instance is stopped.

What you need to do is switch the deployment config to use a 'Recreate' deployment strategy instead of 'Rolling'. With this strategy the existing instance will be shut down before a new one is started and so you can work within the memory quota.

You can change to 'Recreate' by editing the deployment config in the web console, or running the command:

```<code>oc patch dc/yourappname --patch '{"spec":{"strategy":{"type":"Recreate"}}}'
</code>```

Body:
This likely means you are at the limit of your memory resources. It occurs because the default deployment strategy is a rolling deployment, which means there needs to be enough memory available to start a new instance, before the old instance is stopped.

What you need to do is switch the deployment config to use a 'Recreate' deployment strategy instead of 'Rolling'. With this strategy the existing instance will be shut down before a new one is started and so you can work within the memory quota.

You can change to 'Recreate' by editing the deployment config in the web console, or running the command:

oc patch dc/yourappname --patch '{"spec":{"strategy":{"type":"Recreate"}}}'


问:
Adding state to HXT parsing
I'm trying to write an arrow that will generate numbered elements from an XML parse with HXT.  It seems like it should be done with a state arrow, like the State monad, but all the examples I can find in the HXT package and the methods to access the state (XmlState) use the IOStateArrow and I would much rather keep it pure to simplify the testing process, with the StateArrow.  Do such variants exist?  If not, how would I add state to an HXT parse without having to resort to running the Arrow in IO?</p>

答:
You can use ArrowState instance of SLA for that.
An example: let assume we need to concatenate all the second-level text elements.

```<code>Prelude Text.XML.HXT.Core> fst $ runSLA (xread >>> getChildren >>> getChildren >>> isText >>> getText >>> changeState (++)) "" "<xml><item>a</item><item>b</item></xml>"
"ab"
</code>```

Note, that you can't use IO inside the SLA since in doesn't have ArrowIO instance.

Hope, it is what you need.

ContentLicense: CC BY-SA 2.5

Title: Adding state to HXT parsing

Body:
You can use ArrowState instance of SLA for that.
An example: let assume we need to concatenate all the second-level text elements.

Prelude Text.XML.HXT.Core> fst $ runSLA (xread >>> getChildren >>> getChildren >>> isText >>> getText >>> changeState (++)) "" "<xml><item>a</item><item>b</item></xml>"
"ab"

Note, that you can't use IO inside the SLA since in doesn't have ArrowIO instance.

Hope, it is what you need.


问:
How to validate dropdown using angularjs?
I have one text box and dropdown bar .if user enter anything in textbox we need ask user to select anyone from dropdown list (which means user is required).if user removed entered value from text box then user no need to select dropdown (which means text box might be empty and so no need to slect dropdown list) help me out to move forward .
i have added my code below

angular
  .module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
    .controller('DemoCtrl', function ($scope) {
        $scope.users = ['','abs','xcv'];

    })

  .config(function($mdThemingProvider) {

    $mdThemingProvider.theme('docs-dark', 'default')
      .primaryPalette('green')
      .dark();

  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
    <link rel='stylesheet prefetch' href='https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.5/angular-material.css'>
    <link rel='stylesheet prefetch' href='https://material.angularjs.org/1.1.5/docs.css'>
    <div ng-controller="DemoCtrl" layout="column" ng-cloak="" class="md-inline-form inputdemoBasicUsage" ng-app="MyApp">

        <md-card class="asd">
  <div >
       <form name="form">
        <div layout-gt-sm="row">
          <md-input-container class="md-block" layout-xs>
            <label>User</label>
            <md-select ng-model="" >
              <md-option ng-repeat="user in users" value="{{user}}">{{user}}</md-option>
            </md-select>
          </md-input-container>
          <md-input-container class="md-block" flex-xs>
            <label>Name</label>
            <input ng-model="name" >
          </md-input-container>

        </div>

       </form>

  </div>

  </md-card>

    </div>
     <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js'></script>
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js'></script>
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.min.js'></script>
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js'></script>
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js'></script>
    <script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-114/svg-assets-cache.js'></script>
    <script src='https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.5/angular-material.js'></script></code>```

答:
You can add ng-if to select

```<code><md-select ng-model="" ng-if="textBoxModel == ''">
         <md-option ng-repeat="user in users" value="{{user}}">{{user}}</md-option>
</md-select>
</code>```

remember "textBoxModel" is the model assigned to the text input

Body:
I have one text box and dropdown bar .if user enter anything in textbox we need ask user to select anyone from dropdown list (which means user is required).if user removed entered value from text box then user no need to select dropdown (which means text box might be empty and so no need to slect dropdown list) help me out to move forward .
i have added my code below

angular
  .module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
    .controller('DemoCtrl', function ($scope) {
        $scope.users = ['','abs','xcv'];

    })

  .config(function($mdThemingProvider) {

    $mdThemingProvider.theme('docs-dark', 'default')
      .primaryPalette('green')
      .dark();

  });

 <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
    <link rel='stylesheet prefetch' href='https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.5/angular-material.css'>
    <link rel='stylesheet prefetch' href='https://material.angularjs.org/1.1.5/docs.css'>

        <md-card class="asd">

       <form name="form">

          <md-input-container class="md-block" layout-xs>
            User
            <md-select ng-model="" >
              <md-option ng-repeat="user in users" value="{{user}}">{{user}}</md-option>
            </md-select>
          </md-input-container>
          <md-input-container class="md-block" flex-xs>
            Name
            <input ng-model="name" >
          </md-input-container>

       </form>

  </md-card>

Body:
You can add ng-if to select

<md-select ng-model="" ng-if="textBoxModel == ''">
         <md-option ng-repeat="user in users" value="{{user}}">{{user}}</md-option>
</md-select>

remember "textBoxModel" is the model assigned to the text input


问:
SQL Server: "Script table as..." in SSMS shows wrong column widths
This is weird - so weird I haven't even been able to search for it effectively.

We're migrating schema and code changes to a database belonging to a new customer.  We've trying to script some tables out of Object Explorer by right-clicking the table and selecting "Script table as...".

The script that we get is several generations out of date, and doesn't match what we get if we use sp_help.

There are two columns that are really causing a problem.  If I use sp_help, the columns are defined as 70 and 30 characters long.  This is the current length.

```<code>MEMBER_LAST_NAME   nvarchar no  70  yes (n/a)  (n/a)  Latin1_General_BIN
MEMBER_FIRST_NAME  nvarchar no  30  yes (n/a)  (n/a)  Latin1_General_BIN
</code>```

But if I script the table, the lengths are cut in half:

```<code>[MEMBER_LAST_NAME] [nvarchar](35) NULL,
[MEMBER_FIRST_NAME] [nvarchar](15) NULL,
</code>```

Now, it's likely that the columns were originally defined as 35 and 15, and then altered later.  But if we script out the table, why doesn't it show the current column widths?

Unfortunately, we're using a third-party migration utility that appears to rely on "script as", so we're assigning the wrong widths.  Any ideas welcome.

答: try this option right click database and select task, then select generate the script. follow the steps as per wizard and generate the script for the object which you need.</p>

Body:
This is weird - so weird I haven't even been able to search for it effectively.

We're migrating schema and code changes to a database belonging to a new customer.  We've trying to script some tables out of Object Explorer by right-clicking the table and selecting "Script table as...".

The script that we get is several generations out of date, and doesn't match what we get if we use sp_help.

There are two columns that are really causing a problem.  If I use sp_help, the columns are defined as 70 and 30 characters long.  This is the current length.

MEMBER_LAST_NAME   nvarchar no  70  yes (n/a)  (n/a)  Latin1_General_BIN
MEMBER_FIRST_NAME  nvarchar no  30  yes (n/a)  (n/a)  Latin1_General_BIN

But if I script the table, the lengths are cut in half:

[MEMBER_LAST_NAME] [nvarchar](35) NULL,
[MEMBER_FIRST_NAME] [nvarchar](15) NULL,

Now, it's likely that the columns were originally defined as 35 and 15, and then altered later.  But if we script out the table, why doesn't it show the current column widths?

Unfortunately, we're using a third-party migration utility that appears to rely on "script as", so we're assigning the wrong widths.  Any ideas welcome.


问:
How are Google Protocol repeated values structured? What are their limitations and advantages?
I'm trying to create an array that is going to transfer data from C++ application to a Java app. Because of the two languages, how do you format the a Google Protocol message?

Also, what are their limitations and advantages?

So far, I have the following:

```<code>message Config {
    repeated string types = 1;
}
</code>```

I think I'm missing somethings!

答:
If you mean on the wire - then firstly: it is the serializer's job to worry about that, but in this case it is implemented simply as (per repeated element):

```<code>0x0a = "field 1, length prefixed" (strings are always length prefixed)
{number of bytes as UTF8, varint-encoded}
{that many bytes of UTF8}
</code>```

So if you have 3 items repeated you'll have 3 lots of 0x0a, varint, payload slammed one after the other. In the case of some primitive types - integers etc, there is a "packed" encoding that removes the need for a header per element, by prepending the byte-length of the entire array first, then just the array contents as raw non-tokenized data.

If you mean from the caller's perspective, then: it is down to the implementation, but essentially you should expect some familiar API - common to that framework. This might mean that repeated data is exposed as an array / vector, or it might mean a "collection" class with an Add etc API. It will depend entirely on what is sensible for the target framework and the implementing author's whimsy.

Body:
I'm trying to create an array that is going to transfer data from C++ application to a Java app. Because of the two languages, how do you format the a Google Protocol message?

Also, what are their limitations and advantages?

So far, I have the following:

message Config {
    repeated string types = 1;
}

I think I'm missing somethings!

Body:
If you mean on the wire - then firstly: it is the serializer's job to worry about that, but in this case it is implemented simply as (per repeated element):

0x0a = "field 1, length prefixed" (strings are always length prefixed)
{number of bytes as UTF8, varint-encoded}
{that many bytes of UTF8}

So if you have 3 items repeated you'll have 3 lots of 0x0a, varint, payload slammed one after the other. In the case of some primitive types - integers etc, there is a "packed" encoding that removes the need for a header per element, by prepending the byte-length of the entire array first, then just the array contents as raw non-tokenized data.

If you mean from the caller's perspective, then: it is down to the implementation, but essentially you should expect some familiar API - common to that framework. This might mean that repeated data is exposed as an array / vector, or it might mean a "collection" class with an Add etc API. It will depend entirely on what is sensible for the target framework and the implementing author's whimsy.


问:
Why ssh-agent doesn't forward my SSH certificate?

This thread is a response to the titled question : Why ssh-agent doesn't forward my SSH certificate ?
  Actually I couldn't find any information during my search. I had to read the C code of ssh-add
  to resolve my issue..

Problem

I got a valid SSH Certificate :

```<code>$ ssh-keygen -L -f ~/.ssh/id_rsa-cert.pub
/home/user/.ssh/id_rsa-cert.pub:
    Type: ssh-rsa-cert-v01@openssh.com user certificate
    Public key: RSA-CERT SHA256:YgFzKPkUdZHLLi8bEKUs5/hLumNoMNG+oDJ+KD6mS3s
    Signing CA: RSA SHA256:w+Cjpu/QQUunuojs9Af82ENdBUreCDXo+APao9X4dHw
    Key ID: "user_key"
    Serial: 0
    Valid: from 2017-12-06T10:53:00 to 2017-12-07T10:54:57
    Principals:
            user
            admin
    Critical Options: (none)
    Extensions:
            permit-X11-forwarding
            permit-agent-forwarding
            permit-port-forwarding
            permit-pty
            permit-user-rc
</code>```

This is my ssh-agent list of keys :

```<code>$ ssh-add -l
4096 SHA256:YgFzKPkUdAGBPi8bEKUs5/hLumNoAds+oDJ+KD6mS3s user_key (RSA)
</code>```

When I SSH on a remote server, it works. I have no ~/.ssh/authorized_keys and my key is probably well forwarded because I got the same previous result.

Now I would like to SSH to another server from the first one (with ForwardAgent yes):

```<code>$ ssh srv1
srv1:~$ ssh srv2 -vvv
...
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: user_key
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
...
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
srv1:~$
</code>```

What did I do wrong ?

答:
In fact, ssh-agent didn't took well my SSH Certificate. We can see that it is an RSA and not a RSA-CERT.
How import a certificate in ssh-agent ?

You must have 2 couple keys (location and naming is important) :

Original RSA couple :

Private Key : ~/.ssh/example_key

Public Key : ~/.ssh/example_key .pub

RSA Certificate :

Private Key/Certificate : ~/.ssh/example_key -cert

Public Certificate : ~/.ssh/example_key -cert.pub

Then import the original couple :

```<code>$ ssh-add ~/.ssh/example_key
Enter passphrase for /home/user/.ssh/example_key:
Identity added: /home/user/.ssh/example_key (/home/user/.ssh/example_key)
Certificate added: /home/user/.ssh/example_key-cert.pub (user)
</code>```

Automatically, the certificate is added.

Then, the SSH agent forwards it without a problem. Meanwhile, it is impossible to delete from the agent the original RSA Key couple without removing the SSH certificate.

```<code>$ ssh-add -l
4096 SHA256:YgFzKPkUdAGBPi8bEKUs5/hLumNoAds+oDJ+KD6mS3s user_key (RSA)
4096 SHA256:YgFzKPkUdAGBPi8bEKUs5/hLumNoAds+oDJ+KD6mS3s user_key (RSA-CERT)
$ ssh srv1
srv1:~$ ssh srv2
srv2:~$
</code>```

Recap : Why was wrong and why ?

Bad naming of my keys. My RSA couple was something like ~/.ssh/id_rsa_github and my SSH certificate was ~/.ssh/id_rsa-cert.

Agent import badly my certificate and consider it as a Identity and not a Certificate.

During the first SSH connection, the agent provides the certificate as a Identity but it could negotiate with the remote openssh server (I don't really know why). During the second SSH connection, it couldn't...

Be also careful to this :

Add permit-agent-forwarding in certificate extensions

Put ForwardAgent yes in your SSH client configuration

Finally, to sign certificates I use CASSH.

Body:
This thread is a response to the titled question : Why ssh-agent doesn't forward my SSH certificate ?
  Actually I couldn't find any information during my search. I had to read the C code of ssh-add
  to resolve my issue..

Problem

I got a valid SSH Certificate :

$ ssh-keygen -L -f ~/.ssh/id_rsa-cert.pub
/home/user/.ssh/id_rsa-cert.pub:
    Type: ssh-rsa-cert-v01@openssh.com user certificate
    Public key: RSA-CERT SHA256:YgFzKPkUdZHLLi8bEKUs5/hLumNoMNG+oDJ+KD6mS3s
    Signing CA: RSA SHA256:w+Cjpu/QQUunuojs9Af82ENdBUreCDXo+APao9X4dHw
    Key ID: "user_key"
    Serial: 0
    Valid: from 2017-12-06T10:53:00 to 2017-12-07T10:54:57
    Principals:
            user
            admin
    Critical Options: (none)
    Extensions:
            permit-X11-forwarding
            permit-agent-forwarding
            permit-port-forwarding
            permit-pty
            permit-user-rc

This is my ssh-agent list of keys :

$ ssh-add -l
4096 SHA256:YgFzKPkUdAGBPi8bEKUs5/hLumNoAds+oDJ+KD6mS3s user_key (RSA)

When I SSH on a remote server, it works. I have no ~/.ssh/authorized_keys and my key is probably well forwarded because I got the same previous result.

Now I would like to SSH to another server from the first one (with ForwardAgent yes):

$ ssh srv1
srv1:~$ ssh srv2 -vvv
...
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: user_key
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
...
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
srv1:~$

What did I do wrong ?

Body:
In fact, ssh-agent didn't took well my SSH Certificate. We can see that it is an RSA and not a RSA-CERT.
How import a certificate in ssh-agent ?

You must have 2 couple keys (location and naming is important) :

Original RSA couple :

Private Key : ~/.ssh/example_key

Public Key : ~/.ssh/example_key .pub

RSA Certificate :

Private Key/Certificate : ~/.ssh/example_key -cert

Public Certificate : ~/.ssh/example_key -cert.pub

Then import the original couple :

$ ssh-add ~/.ssh/example_key
Enter passphrase for /home/user/.ssh/example_key:
Identity added: /home/user/.ssh/example_key (/home/user/.ssh/example_key)
Certificate added: /home/user/.ssh/example_key-cert.pub (user)

Automatically, the certificate is added.

Then, the SSH agent forwards it without a problem. Meanwhile, it is impossible to delete from the agent the original RSA Key couple without removing the SSH certificate.

$ ssh-add -l
4096 SHA256:YgFzKPkUdAGBPi8bEKUs5/hLumNoAds+oDJ+KD6mS3s user_key (RSA)
4096 SHA256:YgFzKPkUdAGBPi8bEKUs5/hLumNoAds+oDJ+KD6mS3s user_key (RSA-CERT)
$ ssh srv1
srv1:~$ ssh srv2
srv2:~$

Recap : Why was wrong and why ?

Bad naming of my keys. My RSA couple was something like ~/.ssh/id_rsa_github and my SSH certificate was ~/.ssh/id_rsa-cert.

Agent import badly my certificate and consider it as a Identity and not a Certificate.

During the first SSH connection, the agent provides the certificate as a Identity but it could negotiate with the remote openssh server (I don't really know why). During the second SSH connection, it couldn't...

Be also careful to this :

Add permit-agent-forwarding in certificate extensions

Put ForwardAgent yes in your SSH client configuration

Finally, to sign certificates I use CASSH.


问:
Google Maps Distance Matrix Service API returning wrong items
I am trying to sort items in React.js based on their distance from a user inputted location. The following code sets up the API call.

```<code>autofill = (event) => {
    var dest = autocomplete.getPlace().geometry.location;
    var service = new google.maps.DistanceMatrixService();
    var origins = [];

    this.props.items.forEach(function(element) {
        origins.push(element.latLong);
    });

    service.getDistanceMatrix({
        origins: origins,
        destinations: [dest],
        travelMode: 'WALKING'}, this.callback);
}
</code>```

Earlier in the application, the items stored in this.props.items can be filtered. Imagine there are three items, [1,2,3]. I filter out 1, meaning that this.props.items is now equal to [2,3]. I have verified this by printing origin to the console after the forEach loop.

Inside callback(), the request callback function, I print out the response and the originAddresses list returned by the API holds addresses corresponding to [1,3]! How is this possible, since I only passed the API 2 and 3?

答: Ok... Turns out I had certain coordinates the wrong way round so this is not actually an issue. Oops.</p>

Body:
I am trying to sort items in React.js based on their distance from a user inputted location. The following code sets up the API call.

autofill = (event) => {
    var dest = autocomplete.getPlace().geometry.location;
    var service = new google.maps.DistanceMatrixService();
    var origins = [];

    this.props.items.forEach(function(element) {
        origins.push(element.latLong);
    });

    service.getDistanceMatrix({
        origins: origins,
        destinations: [dest],
        travelMode: 'WALKING'}, this.callback);
}

Earlier in the application, the items stored in this.props.items can be filtered. Imagine there are three items, [1,2,3]. I filter out 1, meaning that this.props.items is now equal to [2,3]. I have verified this by printing origin to the console after the forEach loop.

Inside callback(), the request callback function, I print out the response and the originAddresses list returned by the API holds addresses corresponding to [1,3]! How is this possible, since I only passed the API 2 and 3?


问:
how to sort string characters alphabetically in pig latin
If I have a table as below:name:chararray

example :

```<code>acab
bca
das
desac
</code>```

How can I order the column 'name' alphabetically in Pig?

like this :

```<code>aacb
abc
ads
acdes
</code>```

答:
Write your own UDF.Pass the name to UDF.In the UDF convert the string to a chararray and sort it.Return the sorted string.

PIG

```<code>REGISTER ORDER_UDF.jar;
A = LOAD 'data.txt' USING PigStorage(',') AS (name: chararray);
B = FOREACH A GENERATE ORDER_UDF.ORDER(name);
DUMP B;
</code>```

UDF

```<code>import java.io.IOException;
import java.util.Arrays;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;

   public class ORDER extends EvalFunc<String>
   {
     public String exec(Tuple input) throws IOException {
        if (input == null || input.size() == 0)
            return null;
        try{
            char tempArray[] = ((String)input).toCharArray();
            Arrays.sort(tempArray);
            return new String(tempArray);
        }catch(Exception e){
            throw new IOException("Caught exception processing input row ", e);
        }
    }
  }
</code>```

Body:
If I have a table as below:name:chararray

example :

acab
bca
das
desac

How can I order the column 'name' alphabetically in Pig?

like this :

aacb
abc
ads
acdes

Body:
Write your own UDF.Pass the name to UDF.In the UDF convert the string to a chararray and sort it.Return the sorted string.

PIG

REGISTER ORDER_UDF.jar;
A = LOAD 'data.txt' USING PigStorage(',') AS (name: chararray);
B = FOREACH A GENERATE ORDER_UDF.ORDER(name);
DUMP B;

UDF

import java.io.IOException;
import java.util.Arrays;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;

   public class ORDER extends EvalFunc<String>
   {
     public String exec(Tuple input) throws IOException {
        if (input == null || input.size() == 0)
            return null;
        try{
            char tempArray[] = ((String)input).toCharArray();
            Arrays.sort(tempArray);
            return new String(tempArray);
        }catch(Exception e){
            throw new IOException("Caught exception processing input row ", e);
        }
    }
  }


问:
why json response has square brackets
For some reason I have to use JSON like this:

php code

```<code>$json = json_decode([{
"key":1812,
        "ticks":0,
        "events":"7F7E7F7E7F7E7F7E7F7E7F7E7F7E",
        "s1a":"011A00002066C0D9",
        "s1c":"011C0149040901496650002830000000000000023344000043410000000300000004C5BD",
        "s46":"014600283000CA8D","s10":"011000287182943B",
        "s9a":"019A0000000018000000000000000000DC69",
        "version" : "18.05"
}]);

// and use $json in loop to populate the table...
</code>```

that pair of square brackets does not let me do anything with it in php. My editor show an parse error. I solved this problem in js like this:

```<code>var data = json[0];
var i;
for(i=0; i<json.length; i++){
    var html = '';
    html += '<td>' + json[i]["key"] + '</td>'
    + '<td>' + json[i]["ticks"] + '</td>'
    + '<td>' + json[i]["events"] + '</td>'
    + '<td>' + json[i]["s1a"] + '</td>'
    + '<td>' + json[i]["s1c"] + '</td>'
    + '<td>' + json[i]["s46"] + '</td>'
    + '<td>' + json[i]["s9a"] + '</td>'
    + '<td>' + json[i]["version"] + '</td>';
}
    $(html).appendTo('#bundle');
//var jsonEncoded = JSON.parse(data);
console.log(json.length);*/
</code>```

But it seems bad to use it like this. How can I solve this in php?

答:
Also worth mentioning that if you are using an ORM, and you are working with collections (which is a common use case with Laravel, for example, and with many other PHP frameworks), there are two ways you can return something that you are looking for in a query.

First: you query an array of elements, and in this case, only one is found. Then, if you pass that as your response, it will contain the array brackets - a valid JSON type.

But if you specifically query for a single element (like with ::first() in the case of Eloquent), if you return that, it will automatically only return the object, without any enclosing brackets.

Edit: seeing your edit, yeah, mega6382 has the answer.

Title: why json response has square brackets

Body:
For some reason I have to use JSON like this:

php code

$json = json_decode([{
"key":1812,
        "ticks":0,
        "events":"7F7E7F7E7F7E7F7E7F7E7F7E7F7E",
        "s1a":"011A00002066C0D9",
        "s1c":"011C0149040901496650002830000000000000023344000043410000000300000004C5BD",
        "s46":"014600283000CA8D","s10":"011000287182943B",
        "s9a":"019A0000000018000000000000000000DC69",
        "version" : "18.05"
}]);

// and use $json in loop to populate the table...

that pair of square brackets does not let me do anything with it in php. My editor show an parse error. I solved this problem in js like this:

var data = json[0];
var i;
for(i=0; i<json.length; i++){
    var html = '';
    html += '' + json[i]["key"] + '	'
    + '' + json[i]["ticks"] + '	'
    + '' + json[i]["events"] + '	'
    + '' + json[i]["s1a"] + '	'
    + '' + json[i]["s1c"] + '	'
    + '' + json[i]["s46"] + '	'
    + '' + json[i]["s9a"] + '	'
    + '' + json[i]["version"] + '	';
}
    $(html).appendTo('#bundle');
//var jsonEncoded = JSON.parse(data);
console.log(json.length);*/

But it seems bad to use it like this. How can I solve this in php?


问:
Common initialisation from mutually exclusive constructors
Suppose I have a simple base class with mutually exclusive constructors for different scenarios.

```<code>abstract class ExampleA
{
    protected ExampleA(int intParam)
    {

    }

    protected ExampleA(string stringParam)
    {

    }
}
</code>```

My sub-classes for the most part need only implement a single constructor that extends a single base constructor. All is well. However, I have a special case where a sub class must be initialised outside of my standard workflow.

```<code>class ExampleB : ExampleA
{
    private readonly int myMagicInt;

    public ExampleB(ExampleC instanceC)
        : base(instanceC.someString)
    {
        // Derive readonly values here.
    }

    public ExampleB(ExampleD instanceD)
        : base(instanceD.someInt)
    {
        // Derive readonly values here.
    }
}
</code>```

This is my first encounter with a scenario where I cannot appropriately chain my constructors; doing so in this circumstance would introduce more overhead than initialising my readonly values in more than one place.

Short of re-architecture, is there an approach that can be used handle these scenarios cleanly, or is it something that is simply not expressible in C# without additional layers of complexity or overhead?

Although I have considered the following solutions, none of these are more appealing to me than a re-architecture:

Nullable parameters on the base, so a common constructor could be called.

Using another method to initialise the ReadOnly values with 'out' parameters.

Changing Readonly members to private settable members.

答:
Well, can't you do this? (do note that I am inferring quite a lot from your code and could be misinterpreting your actual scenario):</p>

```<code>class ExampleB : ExampleA
{
    private readonly int myMagicInt;

    public ExampleB(ExampleC instanceC)
        : this(GetEquivalentIntFromString(instanceC.someString))
    {
    }

    public ExampleB(ExampleD instanceD)
        : base(instanceD.someInt)
    {
        // Derive readonly values here.
    }

    private static int GetEquivalentIntFromString(string s)
    { //whatever }
}
</code>```

Body:
Suppose I have a simple base class with mutually exclusive constructors for different scenarios.

abstract class ExampleA
{
    protected ExampleA(int intParam)
    {

    }

    protected ExampleA(string stringParam)
    {

    }
}

My sub-classes for the most part need only implement a single constructor that extends a single base constructor. All is well. However, I have a special case where a sub class must be initialised outside of my standard workflow.

class ExampleB : ExampleA
{
    private readonly int myMagicInt;

    public ExampleB(ExampleC instanceC)
        : base(instanceC.someString)
    {
        // Derive readonly values here.
    }

    public ExampleB(ExampleD instanceD)
        : base(instanceD.someInt)
    {
        // Derive readonly values here.
    }
}

This is my first encounter with a scenario where I cannot appropriately chain my constructors; doing so in this circumstance would introduce more overhead than initialising my readonly values in more than one place.

Short of re-architecture, is there an approach that can be used handle these scenarios cleanly, or is it something that is simply not expressible in C# without additional layers of complexity or overhead?

Although I have considered the following solutions, none of these are more appealing to me than a re-architecture:

Nullable parameters on the base, so a common constructor could be called.

Using another method to initialise the ReadOnly values with 'out' parameters.

Changing Readonly members to private settable members.

Body:
Well, can't you do this? (do note that I am inferring quite a lot from your code and could be misinterpreting your actual scenario):

class ExampleB : ExampleA
{
    private readonly int myMagicInt;

    public ExampleB(ExampleC instanceC)
        : this(GetEquivalentIntFromString(instanceC.someString))
    {
    }

    public ExampleB(ExampleD instanceD)
        : base(instanceD.someInt)
    {
        // Derive readonly values here.
    }

    private static int GetEquivalentIntFromString(string s)
    { //whatever }
}


问:
Encrypting efficiently on mobile devices
What is the most efficient industry-strength encryption method/library for mobile devices?  Ideally, I would like it to be endorsed by the US government for transmitting sensitive data.

I have a number of mass-produced mobile devices, and I want to start encrypting
their satellite and GSM communication.  The firmware is in C.  My concern is that the battery won't last once I start encrypting.

Many thanks.

答:
Way to platform specific...

Many ARM architectures have native, instruction level support for cryptography.
However, you should understand that you may be able to encrypt the message, but most of the message passing infrastructure is in-the-clear. Second, the standard recommendation for cryptography is NOT to implement it yourself-your implementation WILL be the part that fails first.

In the interest of academic study, I will ask you to consider All the AES You Need on Cortex-M3 and M4 by Peter Schwabe and Ko Stoffelen

As for power concerns, the display and cellular modem are by far the largest factors.


问:
Which are the FLV supported audio types?
I'm having issues with playing back some quick time files using actionscript 3.0 (NetStream class).

I have no control on how the quick time files are produced, but it seems so far that the files with uncompressed audio do not play audio at all in Flash Player.

I'm trying to compile a list of audio formats using video(mov/flv/etc.) in Flash Player, but I'm confused by the resources.

I've look through the FLV Format Specs(pdf link) on devnet and the media types listed there are:

MP3 A media type of .mp3 (0x2E6D7033)
  indicates that the track contains MP3
  audio data. The  dot character, hex
  0x2E, is included to make a complete
  four-character code.

AAC A media type
  of mp4a (0x6D703461) indicates that
  the track is encoded with AAC audio.
  Flash Player supports the following
  AAC profiles, denoted by their object
  types:
  - 1 = main profile
  - 2 = low complexity, a.k.a. LC

  - 5 = high efficiency/scale band replication, a.k.a. HE/SBR  When the
  audio codec is AAC, an esds box occurs
  inside the stsd box of a sample table.
  This box contains initialization data
  that an AAC decoder requires to decode
  the stream.  See ISO/IEC 14496-3 for
  more information about the structure
  of this box.

On the wikipedia entry, there is a mention on uncompressed audio:

FLV files also support uncompressed
  audio or ADPCM format audio.

but there is no reference for that statement.

Is there a page that lists all the supported audio formats for playing back video in Flash Player ?

答:
Be careful not to confuse the F4V and FLV container formats.

The official specification you mentioned describes both of these formats.

Your quote specifically refers to the F4V format which only supports MP3 and AAC in the flash player.

The list of audio codecs supported by the FLV container is shown on page 70 in the same file:

```<code>SoundFormat
(See notes following
table, for special
encodings)
UB [4] Format of SoundData. The following values are defined:
0 = Linear PCM, platform endian
1 = ADPCM
2 = MP3
3 = Linear PCM, little endian
4 = Nellymoser 16 kHz mono
5 = Nellymoser 8 kHz mono
6 = Nellymoser
7 = G.711 A-law logarithmic PCM
8 = G.711 mu-law logarithmic PCM
9 = reserved
10 = AAC
11 = Speex
14 = MP3 8 kHz
15 = Device-specific sound
Formats 7, 8, 14, and 15 are reserved.
AAC is supported in Flash Player 9,0,115,0 and higher.
Speex is supported in Flash Player 10 and higher.
</code>```

Body:
Be careful not to confuse the F4V and FLV container formats.

The official specification you mentioned describes both of these formats.

Your quote specifically refers to the F4V format which only supports MP3 and AAC in the flash player.

The list of audio codecs supported by the FLV container is shown on page 70 in the same file:

SoundFormat
(See notes following
table, for special
encodings)
UB [4] Format of SoundData. The following values are defined:
0 = Linear PCM, platform endian
1 = ADPCM
2 = MP3
3 = Linear PCM, little endian
4 = Nellymoser 16 kHz mono
5 = Nellymoser 8 kHz mono
6 = Nellymoser
7 = G.711 A-law logarithmic PCM
8 = G.711 mu-law logarithmic PCM
9 = reserved
10 = AAC
11 = Speex
14 = MP3 8 kHz
15 = Device-specific sound
Formats 7, 8, 14, and 15 are reserved.
AAC is supported in Flash Player 9,0,115,0 and higher.
Speex is supported in Flash Player 10 and higher.

ContentLicense: CC BY-SA 4.0


问:
WPF Submenus of the ContextMenu suddenly disappear
I'm trying to dynamically show menus and submenus related to a TreeViewItem, but I found a weird behaviour: the first time I right-click on the node, the menu and submenus appear correctly, then if I press escape and then I repeat the right-click on the node, the submenus dissapear. And after that, sometimes the submenus randomly appear or disappear.

I reduced the error to the following code (It's the minimum code to reproduce the error). Does anyone know how I can correct the code? I've been looking for days but I cannot find any solution.

Thank you.

Image showing what happens..

.Net framework 4.6.1 and 4.7

MainWindow.xaml

```<code><Window x:Class="WpfTester.TestWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfTester"
    mc:Ignorable="d"
    Title="Window" Height="300" Width="300">
<Grid>
    <TreeView HorizontalContentAlignment="Stretch">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:MyMenu}" ItemsSource="{Binding Commands}">
                <TextBlock Text="{Binding Name}" Background="Blue" />
            </HierarchicalDataTemplate>
        </TreeView.Resources>
        <TreeViewItem Header="Level 1" IsExpanded="True" ContextMenuOpening="OnContextMenuOpening">
            <TreeViewItem.ContextMenu>
                <ContextMenu>
                    <ContextMenu.ItemContainerStyle>

                        <Style TargetType="{x:Type MenuItem}">
                            <Setter Property="Command" Value="{Binding}" />
                        </Style>

                    </ContextMenu.ItemContainerStyle>
                </ContextMenu>
            </TreeViewItem.ContextMenu>
        </TreeViewItem>
    </TreeView>
</Grid>
</code>```

MainWindow.xaml.cs

```<code>public partial class TestWindow : Window
{
    public TestWindow()
    {
        InitializeComponent();
    }

    private void OnContextMenuOpening(object sender, ContextMenuEventArgs args)
    {
        ((TreeViewItem)sender).ContextMenu.ItemsSource = GetCommands();
    }

    private static IEnumerable<MyMenu> GetCommands()
    {
        return new MyMenu[]
        {
            new MyMenu("Pep", new[]
            {
                new MyMenu("x"),
                new MyMenu("y"),
                new MyMenu("z"),
            }),
            new MyMenu("fuz")
        };
    }
}

public class MyMenu : ICommand
{
    public MyMenu(string name)
    {
        this.Name = name;
    }

    public MyMenu(string name, IEnumerable<MyMenu> items)
    {
        this.Name = name;
        items.ToList().ForEach(x => this.commands.Add(x));
    }

    public string Name { get; }

    public ObservableCollection<MyMenu> Commands
    {
        get { return this.commands; }
    }

    private readonly ObservableCollection<MyMenu> commands = new ObservableCollection<MyMenu>();

    public virtual bool CanExecute(object parameter)
    {
        return true;
    }

    public virtual void Execute(object parameter)
    {
    }

    public event EventHandler CanExecuteChanged;
}
</code>```

Note: thanks to Rowbear I found the best solution.

MainWindow.xaml

```<code><Window x:Class="WpfTester.TestWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfTester"
    mc:Ignorable="d"
    Title="Window" Height="300" Width="300">
<Grid>
    <TreeView HorizontalContentAlignment="Stretch">
        <TreeView.Resources>
            <local:IsInstanceOfTypeConverter x:Key="IsInstanceOfTypeConverter" />
        </TreeView.Resources>
        <TreeViewItem Header="Level 1" IsExpanded="True" ContextMenuOpening="OnContextMenuOpening">
            <TreeViewItem.ContextMenu>
                <ContextMenu>
                    <ContextMenu.ItemContainerStyle>

                        <!-- Style for MenuItem -->
                        <Style TargetType="{x:Type MenuItem}">
                            <Setter Property="Header" Value="{Binding Name}" />
                            <Setter Property="ToolTip" Value="{Binding Name}" />
                            <Setter Property="Command" Value="{Binding}" />

                            <Style.Triggers>

                                <!-- Style for MyMenu -->
                                <DataTrigger Binding="{Binding Converter={StaticResource IsInstanceOfTypeConverter},
                                                               ConverterParameter={x:Type local:MyMenu}}"
                                             Value="True">
                                    <Setter Property="ItemsSource" Value="{Binding Commands}"/>
                                    <Setter Property="Background" Value="Blue" />
                                </DataTrigger>

                                <!-- More types of menus and commands with different binding.. -->
                                <DataTrigger Binding="{Binding Converter={StaticResource IsInstanceOfTypeConverter},
                                                               ConverterParameter={x:Type local:MyMenu2}}"
                                             Value="True">
                                    <Setter Property="ItemsSource" Value="{Binding Actions}"/>
                                    <Setter Property="Background" Value="Green" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>

                    </ContextMenu.ItemContainerStyle>
                </ContextMenu>
            </TreeViewItem.ContextMenu>
        </TreeViewItem>
    </TreeView>
</Grid>
</code>```

IsInstanceOfTypeConverter.cs

```<code>/// <summary>
/// This class tests if <code>value</code> is instance of the type indicated in <code>parameter</code>.
/// </summary>
public sealed class IsInstanceOfTypeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Type type = parameter as Type;
        return (type != null) && type.IsInstanceOfType(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("IsInstanceOfTypeConverter can only be used for one way conversion.");
    }
}
</code>```

答:
You're doing something odd where you're relying on a ContextMenu's ItemsSource for the top level list of menu items, but then relying on a hierarchicaldatatemplate to build a tree. Maybe it'll work in some cases - I haven't tried that strategy. However, changing your demo code's xaml to the below should get you to what you want:

```<code><Grid>
    <TreeView HorizontalContentAlignment="Stretch">
        <TreeViewItem Header="Level 1" IsExpanded="True" ContextMenuOpening="OnContextMenuOpening">
            <TreeViewItem.ContextMenu>
                <ContextMenu>
                    <ContextMenu.ItemContainerStyle>
                        <Style TargetType="{x:Type MenuItem}">
                            <Setter Property="Header" Value="{Binding Name}"></Setter>
                            <Setter Property="Command" Value="{Binding}" />
                            <Setter Property="Background" Value="Blue"></Setter>
                            <Setter Property="ItemsSource" Value="{Binding Commands}"></Setter>
                        </Style>
                    </ContextMenu.ItemContainerStyle>
                </ContextMenu>
            </TreeViewItem.ContextMenu>
        </TreeViewItem>
    </TreeView>
</Grid>
</code>```

Here I'm relying on MenuItem's ItemsSource to create my child menu items.

Body:
I'm trying to dynamically show menus and submenus related to a TreeViewItem, but I found a weird behaviour: the first time I right-click on the node, the menu and submenus appear correctly, then if I press escape and then I repeat the right-click on the node, the submenus dissapear. And after that, sometimes the submenus randomly appear or disappear.

I reduced the error to the following code (It's the minimum code to reproduce the error). Does anyone know how I can correct the code? I've been looking for days but I cannot find any solution.

Thank you.

Image showing what happens..

.Net framework 4.6.1 and 4.7

MainWindow.xaml

<Window x:Class="WpfTester.TestWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfTester"
    mc:Ignorable="d"
    Title="Window" Height="300" Width="300">
<Grid>
    <TreeView HorizontalContentAlignment="Stretch">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:MyMenu}" ItemsSource="{Binding Commands}">
                <TextBlock Text="{Binding Name}" Background="Blue" />
            </HierarchicalDataTemplate>
        </TreeView.Resources>
        <TreeViewItem Header="Level 1" IsExpanded="True" ContextMenuOpening="OnContextMenuOpening">
            <TreeViewItem.ContextMenu>
                <ContextMenu>
                    <ContextMenu.ItemContainerStyle>

                    </ContextMenu.ItemContainerStyle>
                </ContextMenu>
            </TreeViewItem.ContextMenu>
        </TreeViewItem>
    </TreeView>
</Grid>

MainWindow.xaml.cs

public partial class TestWindow : Window
{
    public TestWindow()
    {
        InitializeComponent();
    }

    private void OnContextMenuOpening(object sender, ContextMenuEventArgs args)
    {
        ((TreeViewItem)sender).ContextMenu.ItemsSource = GetCommands();
    }

    private static IEnumerable<MyMenu> GetCommands()
    {
        return new MyMenu[]
        {
            new MyMenu("Pep", new[]
            {
                new MyMenu("x"),
                new MyMenu("y"),
                new MyMenu("z"),
            }),
            new MyMenu("fuz")
        };
    }
}

public class MyMenu : ICommand
{
    public MyMenu(string name)
    {
        this.Name = name;
    }

    public MyMenu(string name, IEnumerable<MyMenu> items)
    {
        this.Name = name;
        items.ToList().ForEach(x => this.commands.Add(x));
    }

    public string Name { get; }

    public ObservableCollection<MyMenu> Commands
    {
        get { return this.commands; }
    }

    private readonly ObservableCollection<MyMenu> commands = new ObservableCollection<MyMenu>();

    public virtual bool CanExecute(object parameter)
    {
        return true;
    }

    public virtual void Execute(object parameter)
    {
    }

    public event EventHandler CanExecuteChanged;
}

Note: thanks to Rowbear I found the best solution.

MainWindow.xaml

<Window x:Class="WpfTester.TestWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfTester"
    mc:Ignorable="d"
    Title="Window" Height="300" Width="300">
<Grid>
    <TreeView HorizontalContentAlignment="Stretch">
        <TreeView.Resources>
            <local:IsInstanceOfTypeConverter x:Key="IsInstanceOfTypeConverter" />
        </TreeView.Resources>
        <TreeViewItem Header="Level 1" IsExpanded="True" ContextMenuOpening="OnContextMenuOpening">
            <TreeViewItem.ContextMenu>
                <ContextMenu>
                    <ContextMenu.ItemContainerStyle>

                        </Style>

                    </ContextMenu.ItemContainerStyle>
                </ContextMenu>
            </TreeViewItem.ContextMenu>
        </TreeViewItem>
    </TreeView>
</Grid>

IsInstanceOfTypeConverter.cs

///
/// This class tests if value is instance of the type indicated in parameter.
///
public sealed class IsInstanceOfTypeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Type type = parameter as Type;
        return (type != null) && type.IsInstanceOfType(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("IsInstanceOfTypeConverter can only be used for one way conversion.");
    }
}

Body:
You're doing something odd where you're relying on a ContextMenu's ItemsSource for the top level list of menu items, but then relying on a hierarchicaldatatemplate to build a tree. Maybe it'll work in some cases - I haven't tried that strategy. However, changing your demo code's xaml to the below should get you to what you want:

<Grid>
    <TreeView HorizontalContentAlignment="Stretch">
        <TreeViewItem Header="Level 1" IsExpanded="True" ContextMenuOpening="OnContextMenuOpening">
            <TreeViewItem.ContextMenu>
                <ContextMenu>
                    <ContextMenu.ItemContainerStyle>
                        <Style TargetType="{x:Type MenuItem}">
                            <Setter Property="Header" Value="{Binding Name}"></Setter>
                            <Setter Property="Command" Value="{Binding}" />
                            <Setter Property="Background" Value="Blue"></Setter>
                            <Setter Property="ItemsSource" Value="{Binding Commands}"></Setter>
                        </Style>
                    </ContextMenu.ItemContainerStyle>
                </ContextMenu>
            </TreeViewItem.ContextMenu>
        </TreeViewItem>
    </TreeView>
</Grid>

Here I'm relying on MenuItem's ItemsSource to create my child menu items.


问:
What are MEAN and STD in Tensorflow Tflearn?
When I launch TFLearn examples, I get this

Preprocessing... Calculating mean over all dataset (this may take long)...
Mean: 0.916834
Preprocessing... Calculating std over all dataset (this may take long)...
STD: 0.227089

I don't understand what they are. I googled it , I looked on SO, I read http://tflearn.org/data_preprocessing/ I found that:

mean: Provides a custom mean

std: Provides a custom standard derivation

So what is "custom mean" for?
What is "custom derivation" for?

答:
What is Mean and STD (Standard Deviation)

They don't have a special meaning in Tensorflow but are statistical tools to understand a set of numbers.

Mean: is just the average of a set of numbers.

STD: is how far (on average) the numbers are from the mean.

Eg. consider set of just 2 numbers 3 and 6 (very simplified but the concept is the same for any amount of numbers).

Mean (or average) = (3 + 6)/2 = 4.5 (sum of all numbers divided by the count).

STD: = 1.5 ( 3 is 1.5 away from 4.5 and 6 is also 1.5 away from 4.5 so on average the numbers are 1.5 away from the mean ie STD)


问:
How create a new image other html when "css checked button" is pressed?
Hello i wonder this question. I create checked button in css on index.html. When i checked in index.html i want create image in other.html. (other.html is empty before you pressed) If you "checked button" checked in index.html how create new image in other.html?

sample simple code

```<code><html>
<head>
<style>
input[type="checkbox"] {}
</style>
</head>
<body>
<input type="checkbox"  >
</body>
</html>
</code>```

答:
There is a simple way to implement this without using LocalStorage, and just a little bit of JavaScript instead. This function checks if the checkbox is checked, and outputs the value in the URL, as if it were a "get" form. The link (other.html) in the "location.href" would be the equivalent of the form tag's action attribute, and would be your second page.

function go() {
  var value = document.getElementById("checkbox").checked;
  location.href = "other.html?checked=" + value;
}```
</div>
</div>

<br />
<br />
This function can be activated one of two ways. You can create a button with an onclick reffering to the function:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onClick="go()">Continue</button></code>```

Or, just use the "onChange" attribute, with the value equaling the function go(). This will make the function activate as soon as you click the checkbox.

<input type="checkbox" onchange="go()" />```
</div>
</div>
</p>

<p><br />
So, your first page (index.html) should look similar to this:
<br />
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function go() {
  var value = document.getElementById("checkbox").checked;
  location.href = "test2.html?checked=" + value;
}</code>```

input[type="checkbox"] {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="checkbox" onchange="go()" /><br />
<button onClick="go()">Continue</button></code>```

For your second page, we will implement a function to detect if the user checked the button. The "yourImage.jpg" would be the url of your image that you wish for the user to see if they have clicked the checkbox.

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var check = getParameterByName('checked');

if (check == "true") {
  document.getElementById("image").src = "yourImage.jpg";
}```
</div>
</div>
</p>

<p><br />
The HTML is simple, just one image tag. The id must be "image" otherwise the JavaScript above won't be able to detect it. The src is blank, but can be changed to the default image for those who didn't check the checkbox.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="image" src=""></code>```

Finally, the second page should look like this:

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var check = getParameterByName('checked');

if (check == "true") {
  document.getElementById("image").src = "yourImage.jpg";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="image" src=""></code>```

Edit: To add a picture into the same page (index.html), just use the code below:

function showImage() {
  var check = document.getElementById("checkbox").checked;

  if (check == true) {
    document.getElementById("image").src = "yourImage.jpg";
  }

  if (check == false) {
    document.getElementById("image").src = "";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="checkbox" onchange="showImage()" />
<br />
<img id="image" src=""></code>```

Body:
Hello i wonder this question. I create checked button in css on index.html. When i checked in index.html i want create image in other.html. (other.html is empty before you pressed) If you "checked button" checked in index.html how create new image in other.html?

sample simple code

<input type="checkbox"  >

Body:
There is a simple way to implement this without using LocalStorage, and just a little bit of JavaScript instead. This function checks if the checkbox is checked, and outputs the value in the URL, as if it were a "get" form. The link (other.html) in the "location.href" would be the equivalent of the form tag's action attribute, and would be your second page.

function go() {
  var value = document.getElementById("checkbox").checked;
  location.href = "other.html?checked=" + value;
}

This function can be activated one of two ways. You can create a button with an onclick reffering to the function:

<button onClick="go()">Continue</button>

Or, just use the "onChange" attribute, with the value equaling the function go(). This will make the function activate as soon as you click the checkbox.

<input type="checkbox" onchange="go()" />

So, your first page (index.html) should look similar to this:

function go() {
  var value = document.getElementById("checkbox").checked;
  location.href = "test2.html?checked=" + value;
}

input[type="checkbox"] {}

<input type="checkbox" id="checkbox" onchange="go()" /><br />
<button onClick="go()">Continue</button>

For your second page, we will implement a function to detect if the user checked the button. The "yourImage.jpg" would be the url of your image that you wish for the user to see if they have clicked the checkbox.

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var check = getParameterByName('checked');

if (check == "true") {
  document.getElementById("image").src = "yourImage.jpg";
}

The HTML is simple, just one image tag. The id must be "image" otherwise the JavaScript above won't be able to detect it. The src is blank, but can be changed to the default image for those who didn't check the checkbox.

<img id="image" src="">

Finally, the second page should look like this:

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var check = getParameterByName('checked');

if (check == "true") {
  document.getElementById("image").src = "yourImage.jpg";
}

<img id="image" src="">

Edit: To add a picture into the same page (index.html), just use the code below:

function showImage() {
  var check = document.getElementById("checkbox").checked;

  if (check == true) {
    document.getElementById("image").src = "yourImage.jpg";
  }

  if (check == false) {
    document.getElementById("image").src = "";
  }
}

<input type="checkbox" id="checkbox" onchange="showImage()" />
<br />
<img id="image" src="">


问:
Make an API call inside of another API call?
I basically need to combine data from two different API calls. Here is what I have right now:

```<code>    var url= "https://website.com/api.json";
    $.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': 'xxxxxx'},
        success: function(data){

            var api = data.results[0].api;

            for (var i=0;i<api.length;++i)
            var api2url = api[i].api2url;

            {
                $('tbody').append('<tr><td>'+api[i].thing+'</td></tr>');
            }
        }
    });
</code>```

The above works.

The problem is that I also need data from https://website.com/api2.json (which will come from data from the api1 call). I need my final code to look like:

$('tbody').append('
+api[i].thing+'
');

答:
You can make the second ajax call on the success of the first.  Then perform your DOM updates as needed.  But the idea is to run the second ajax call once the first has completed and was successful.</p>

```<code>function callApi2(aip1) {
    $.ajax({
        //params for the call
        url: api1.api2url,
        success: function(data) {
            var api2 = data.results[0].api; // or whatever the property is
            $('tbody').append('<tr><td><a href="'+api2[i].thing+'">'+api1.thing+'</a></td></tr>');

        },
    });
}

var url= "https://website.com/api.json";
$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    headers: {'X-API-Key': 'xxxxxx'},
    success: function(data){
        var api1 = data.results[0].api;
        for (var i=0; i<api1.length;++i){
            callApi2(api1[i]);
        }
    }
});
</code>```

Body:
I basically need to combine data from two different API calls. Here is what I have right now:

    var url= "https://website.com/api.json";
    $.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': 'xxxxxx'},
        success: function(data){

            var api = data.results[0].api;

            for (var i=0;i<api.length;++i)
            var api2url = api[i].api2url;

            {
                $('tbody').append('
'+api[i].thing+'
');
            }
        }
    });

The above works.

The problem is that I also need data from https://website.com/api2.json (which will come from data from the api1 call). I need my final code to look like:

$('tbody').append('
+api[i].thing+'
');

Body:
You can make the second ajax call on the success of the first.  Then perform your DOM updates as needed.  But the idea is to run the second ajax call once the first has completed and was successful.

function callApi2(aip1) {
    $.ajax({
        //params for the call
        url: api1.api2url,
        success: function(data) {
            var api2 = data.results[0].api; // or whatever the property is
            $('tbody').append('<tr><td><a href="'+api2[i].thing+'">'+api1.thing+'</a></td></tr>');

        },
    });
}

var url= "https://website.com/api.json";
$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    headers: {'X-API-Key': 'xxxxxx'},
    success: function(data){
        var api1 = data.results[0].api;
        for (var i=0; i<api1.length;++i){
            callApi2(api1[i]);
        }
    }
});


问:
Run python scripts from within Django app

I'm helping to build a Django app that will interface with a voip phone system, and they've created some scripts to execute when an action is performed (add, update,delete) in order to have parity with the phone system side. They've asked me to pass the parameters to the script like this
/var/www/html/om/om_add.sh deviceid filename title
They've also mentioned to pass the title as a url, using urllib.quote_plus(title)
Lastly, it should occur after each action is executed in the app.
Now, I've heard that executing shell scripts from a Django app is not advised, but wondering if this is a different case? Also, how I can go about doing this, the only way I know how to pass those params is to pass them through a view. Any help is greatly appreciated!

```<code>def post_create(request):
    device = request.session['device']

    if device == 'dummy':
        return render(request,'access_denied.html')

    did = {'device_id': device }
    form= PostForm(request.POST or None, request.FILES or None,initial=did)

    if form.is_valid():
        instance = form.save(commit=False)
        check = Sounds.objects.all().filter(device_id= device).filter(target=instance.target).exclude(target='generic').first()

        if check:
            instance.pk = check.pk
            instance.device_id= device
            instance.save()
            return HttpResponseRedirect('/')
        else:
            instance.device_id = device
            instance.save()

            dev = instance.device_id
            name = instance.sound.name
            title = urllib.quote_plus(instance.title)

            os.execv('/var/www/html/ogm/ogm_add.sh', [dev,name,title])

            return HttpResponseRedirect('/')

    context= {
        'form': form,
    }
    return render(request, 'post_form.html',context,)
</code>```

答:
executing a shell script has nothing
to do with django framework it's core python future .

```<code>import os
os.execv('path' , ['arg'])
</code>```

the arg can be a list or a tuple you can pass it from database or url etc.

the folowing simple is match batter for this purpose

```<code>from subprocess import call
sub = call(['ls' , '-l'])
print(sub)
</code>```

the sub contain the output

Body:
I'm helping to build a Django app that will interface with a voip phone system, and they've created some scripts to execute when an action is performed (add, update,delete) in order to have parity with the phone system side. They've asked me to pass the parameters to the script like this
/var/www/html/om/om_add.sh deviceid filename title
They've also mentioned to pass the title as a url, using urllib.quote_plus(title)
Lastly, it should occur after each action is executed in the app.
Now, I've heard that executing shell scripts from a Django app is not advised, but wondering if this is a different case? Also, how I can go about doing this, the only way I know how to pass those params is to pass them through a view. Any help is greatly appreciated!

def post_create(request):
    device = request.session['device']

    if device == 'dummy':
        return render(request,'access_denied.html')

    did = {'device_id': device }
    form= PostForm(request.POST or None, request.FILES or None,initial=did)

    if form.is_valid():
        instance = form.save(commit=False)
        check = Sounds.objects.all().filter(device_id= device).filter(target=instance.target).exclude(target='generic').first()

        if check:
            instance.pk = check.pk
            instance.device_id= device
            instance.save()
            return HttpResponseRedirect('/')
        else:
            instance.device_id = device
            instance.save()

            dev = instance.device_id
            name = instance.sound.name
            title = urllib.quote_plus(instance.title)

            os.execv('/var/www/html/ogm/ogm_add.sh', [dev,name,title])

            return HttpResponseRedirect('/')

    context= {
        'form': form,
    }
    return render(request, 'post_form.html',context,)

Body:
executing a shell script has nothing
to do with django framework it's core python future .

import os
os.execv('path' , ['arg'])

the arg can be a list or a tuple you can pass it from database or url etc.

the folowing simple is match batter for this purpose

from subprocess import call
sub = call(['ls' , '-l'])
print(sub)

the sub contain the output