问:
Performant data-tables with JavaScript

Introduction

I am making a request to a backend and getting a list of objects in JSON. Then I change it into an HTML table (it is a Vuetify data-table) where every object is a row.

Each row contains an array of exactly 72 ones and zeros ([1, 1, 1, 1, 0, ...]). They indicate activity back in time (72 hours).

In each row I have a for loop (kind of. It is Vue.js v-for directive) that goes through that array and loads an image 1.svg or 0.svg accordingly, to make a chart.

With 40 rows only, the table becomes to lag a little. Now, the table is quite wide and so it goes off screen (overflow: scroll or whatever).

TL;DR

Is it possible in JavaScript to somehow fluently hide DOM elements (in this case table cells (and rows)) (hide means remove from DOM, so that the browser doesn't have to render all of them) when they are off the screen?

Is there a literature you could recommend? Any tutorials? What to look for?

I remember seeing a Google talk on a list of thousands of elements scrolling smoothly on mobile, but can't seem to find it.

Demo

https://codepen.io/DCzajkowski/pen/yPbPqy

答:
Example of Vue application with Polymer element canvas-datagrid with 5000 rows dataset.

new Vue({
  el: '#app',
  data: {
    data: []
  },
  async created () {
    var response = await fetch('https://jsonplaceholder.typicode.com/photos')
    this.data = await response.json()
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body, #app {
  margin: 0;
  padding: 0;
  height: 100%;
}</code>```

  <canvas-datagrid>
    {{ data }}
  </canvas-datagrid>

```

Title: Performant data-tables with JavaScript

Body:
Example of Vue application with Polymer element canvas-datagrid with 5000 rows dataset.

new Vue({
  el: '#app',
  data: {
    data: []
  },
  async created () {
    var response = await fetch('https://jsonplaceholder.typicode.com/photos')
    this.data = await response.json()
  }
})

html, body, #app {
  margin: 0;
  padding: 0;
  height: 100%;
}

<div id="app">
  <canvas-datagrid>
    {{ data }}
  </canvas-datagrid>
</div>

<script src="https://unpkg.com/vue@2.5.3/dist/vue.min.js"></script>
<script src="https://unpkg.com/canvas-datagrid@0.18.12/dist/canvas-datagrid.js"></script>


来源: stackexchange

问:
Get line number from preg_match_all()
I'm using PHP's preg_match_all() to search a string imported using file_get_contents(). The regex returns matches but I would like to know at which line number those matches are found. What's the best technique to achieve this?

I could read the file as an array and perform the regex for each line, but the problem is that my regex matches results across carriage returns (new lines).

答:
You can't do this with only regexs. At least not cleanly. What can you do it to use the PREG_OFFSET_CAPTURE flag of the preg_match_all and do a post parsing of the entire file.

I mean after you have the array of matches strings and starting offsets for each string just count how many \r\n or \n or \r are between the beginning of the file and the offset for each match. The line number of the match would be the number of distinct EOL terminators (\r\n | \n | \r) plus 1.

ContentLicense: CC BY-SA 2.5

Title: Get line number from preg_match_all()


问:
3-Tier BizTalk Architecture Possible?
According to this BizTalk documentation, the HTTP receive adapter must be in the application (middle) layer. This means BizTalk is limited to a 2-tier architecture, which for modern enterprises is a pretty big limitation.

Is the reverse proxy suggestion that Microsoft recommends (on the link above) the common solution to this problem? Has anyone used any other configuration to use the HTTP receive adapter in the web/perimeter layer and been able to negotiate messages through an application layer?

If the reverse proxy method was used, were existing proxy's in the enterprise used or were dedicated proxy's configured for the solution?

答:
I believe you are confusing application tiers with network architecture.

BizTalk is almost by definition the middle tier, implying at least a 3-tier solution. There would be the client that calls a BizTalk service, the BizTalk application itself, and some line of business application that contains most of the business logic (and then whatever database/repository that system uses to store its records). There could be more than one line of business application that BizTalk interacts with to process the client request.

The diagram and article you have referenced simply describe how you can use a reverse proxy to grant external clients access to BizTalk HTTP(S) endpoints that are hosted on your internal network.

ContentLicense: CC BY-SA 3.0

Title: 3-Tier BizTalk Architecture Possible?


问:
grpc proto file parser
I want to parse a .proto file that is part of a gRPC client/server definition.  I just want a starting point for doing this.  I have the gRPC code installed and can autogenerate python code from the proto files.  I am wondering if there are any obvious python classes in the gRPC code (or open source libs out there) that read in proto files and, in some limited way, parses them into some kind of structured objects?</p>

答: parsy (combinator library) has an example that parses .proto files, version 3. You can find it  in the repo. The result is a structured object, using simple custom defined classes such as Proto for the whole file, which has a statements attribute, which contains Import for each import line, Message for each message etc.

Title: grpc proto file parser

ContentLicense: CC BY-SA 4.0


问:
Permissioning in Hyperlededger Fabric Composer transactions
I have two Participants A and B, each have their own identity issued to them by the CA

There is a transaction that enables one Participant to transfer Coins to the other.

```<code>participant Person identified by id {
    o String id
    o String firstName
    o String lastName
    o Double coins
}
</code>```

The transaction cto file

```<code>transaction TransferCoins {
    o Double coinsTransferred
    --> Person receiver
    --> Person sender
}
</code>```

The permissions.acl file

```<code>rule PersonCanModifyOnlySelf {
    description: "Allow Persons to modify only their profile"
    participant(p): "org.varun.business.Person"
    operation: READ, UPDATE, DELETE
    resource(r): "org.varun.business.Person"
    condition: (r.getIdentifier() === p.getIdentifier())
    action: ALLOW
}

rule PersonCanReadAllProfile {
    description: "Allow Persons read access to other Persons"
    participant: "org.varun.business.Person"
    operation: READ
    resource: "org.varun.business.Person"
    action: ALLOW
}
</code>```

The transaction.js file

```<code>/**
 * Person to Person transaction
 * @param {org.varun.business.TransferCoins} transferCoins
 * @transaction
 */
function TransferCoins(transferCoins) {

    var coinsToTransfer = transferCoins.coinsTransferred;
    transferCoins.sender.coins = transferCoins.sender.coins - coinsToTransfer;
    transferCoins.receiver.coins = transferCoins.receiver.coins + coinsToTransfer;

    return getParticipantRegistry('org.varun.business.Person')
        .then(registry => {
            return registry.updateAll([transferCoins.sender, transferCoins.receiver]);
        })
}
</code>```

In short

Each Person can only update their own profile

Each Person has universal read access

When the TransferCoins function is called, coins are subtracted from A while coins are added to B. The participant registry is called and updated.

Now If A were to call this transaction, I am getting an error saying A cannot update B's coins (Obviously due to acl defined above). So how does this kind of transaction work? Could someone please help me out.

答:
good question!

So I would have two transactions defined:

InitiateTransfer {}
AcceptTransfer{}

in your model.

InitiateTransfer (transaction function) will be invoked by Participant A. Upon invoking, you can emit an event following update, such as a Node Red event - to email Participant B of an Incoming Transfer, with a link in the email etc to go and accept the transfer.

Participant B signs into the application and accepts the transfer (ultimately invoking AcceptTransfer() transaction function).

Participant A and Participant B are two separate transactions, and won't contravene your existing ACL conditions. Whether or not you want the CoinTransfer to update a balance on a Participant or an Asset, (eg account-style with a relationship to Participant, in the transaction - see ***NOTE below) is entirely up to you.

Transaction processor functions will wait for Promises to be resolved, before committing the transaction. If a promise is rejected, the transaction will fail.

Changes made by Composer transactions are atomic, either the transaction (as you've defined it) is successful and all changes are applied, or the transaction fails and no changes are applied per that transaction. Suggest to also see 'Error Handling' in the docs specifically relating to handling errors if a transaction does not get 'committed' by the Fabric or blockchain itself (so therefore, whether Participant B would have a transaction to work with) -> https://hyperledger.github.io/composer/reference/js_scripts.html

*****NOTE:***
You may (up to you) wish to consider what model is set up. You raise the concept of maintaining a balance (initiator and acceptor) after transfer - this might be modeled as an Asset (eg. coinAccount), with an ID field, coinBalance, and coinHolder (link to Person) minimally.   The transaction is initiated by the initiator and updates its account (reducing coinAccount balance) and similarly, a separate transaction updates the acceptor coinAccount balance.

Body:
I have two Participants A and B, each have their own identity issued to them by the CA

There is a transaction that enables one Participant to transfer Coins to the other.

participant Person identified by id {
    o String id
    o String firstName
    o String lastName
    o Double coins
}

The transaction cto file

transaction TransferCoins {
    o Double coinsTransferred
    --> Person receiver
    --> Person sender
}

The permissions.acl file

rule PersonCanModifyOnlySelf {
    description: "Allow Persons to modify only their profile"
    participant(p): "org.varun.business.Person"
    operation: READ, UPDATE, DELETE
    resource(r): "org.varun.business.Person"
    condition: (r.getIdentifier() === p.getIdentifier())
    action: ALLOW
}

rule PersonCanReadAllProfile {
    description: "Allow Persons read access to other Persons"
    participant: "org.varun.business.Person"
    operation: READ
    resource: "org.varun.business.Person"
    action: ALLOW
}

The transaction.js file

/**
 * Person to Person transaction
 * @param {org.varun.business.TransferCoins} transferCoins
 * @transaction
 */
function TransferCoins(transferCoins) {

    var coinsToTransfer = transferCoins.coinsTransferred;
    transferCoins.sender.coins = transferCoins.sender.coins - coinsToTransfer;
    transferCoins.receiver.coins = transferCoins.receiver.coins + coinsToTransfer;

    return getParticipantRegistry('org.varun.business.Person')
        .then(registry => {
            return registry.updateAll([transferCoins.sender, transferCoins.receiver]);
        })
}

In short

Each Person can only update their own profile

Each Person has universal read access

When the TransferCoins function is called, coins are subtracted from A while coins are added to B. The participant registry is called and updated.

Now If A were to call this transaction, I am getting an error saying A cannot update B's coins (Obviously due to acl defined above). So how does this kind of transaction work? Could someone please help me out.


问:
Is there a way to get my page URL to update when changing steps within a Single-Page Ember Application?
I have a client of mine who's using a single page application, built in Ember, and they are trying to use analytics to measure dropoff rates at each stage of the form.

I need to try to give them a trigger they can fire when a new stage is reached, in order to update the URL of the page, thereby allowing them to track it in analytics.

Is this even the best way to achieve this?

Hopefully this makes sense, sorry, total lack of Ember knowledge on my side.

Thanks

答:
The code below in a route can update query params of an ember route:

routes/my-route.js

```<code>import Ember from 'ember';

export default Ember.Route.extend({
  queryParams:
  {
    no: {replace: true}
  },

  model: function(dto){
    this.set('no', dto.no);
    return {
      no: this.get('no')
    };
  },

  actions: {
    buttonClicked(){
      this.incrementProperty('no');
      let newNo = this.get('no');
      this.controllerFor(this.get('routeName')).set('no', newNo);
      this.refresh();
    }
  }

});
</code>```

You can take a look at this twiddle for complete code.

Body:
The code below in a route can update query params of an ember route:

routes/my-route.js

import Ember from 'ember';

export default Ember.Route.extend({
  queryParams:
  {
    no: {replace: true}
  },

  model: function(dto){
    this.set('no', dto.no);
    return {
      no: this.get('no')
    };
  },

  actions: {
    buttonClicked(){
      this.incrementProperty('no');
      let newNo = this.get('no');
      this.controllerFor(this.get('routeName')).set('no', newNo);
      this.refresh();
    }
  }

});

You can take a look at this twiddle for complete code.


答:
Looks like this is a fairly simple lossy encoding of a short array. Since G711 is an audio codec, that makes sense. Just iterate over the input byte array, and put the values from the lookup table in the output short array.

```<code>private short[] alaw_exp_table = {/* same data as the C code */};

public short[] decodeG711a(byte[] input)
{
    short[] result = new short[input.Length];

    for (int i = 0; i < input.Length; i++)
    {
        result[i] = alaw_exp_table[input[i]];
    }

    return result;
}
</code>```

Title: decoding G711 converting from c++ to c#

Body:
i try to decoding G711 packet i find this code in c++ but i do not know how to convert this  code to c#

this the code

gint16 alaw_exp_table[256] = {
      -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
      -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
      -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
      -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
     -22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944,
     -30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136,
     -11008,-10496,-12032,-11520, -8960, -8448, -9984, -9472,
     -15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568,
       -344,  -328,  -376,  -360,  -280,  -264,  -312,  -296,
       -472,  -456,  -504,  -488,  -408,  -392,  -440,  -424,
        -88,   -72,  -120,  -104,   -24,    -8,   -56,   -40,
       -216,  -200,  -248,  -232,  -152,  -136,  -184,  -168,
      -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
      -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
       -688,  -656,  -752,  -720,  -560,  -528,  -624,  -592,
       -944,  -912, -1008,  -976,  -816,  -784,  -880,  -848,
       5504,  5248,  6016,  5760,  4480,  4224,  4992,  4736,
       7552,  7296,  8064,  7808,  6528,  6272,  7040,  6784,
       2752,  2624,  3008,  2880,  2240,  2112,  2496,  2368,
       3776,  3648,  4032,  3904,  3264,  3136,  3520,  3392,
      22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
      30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
      11008, 10496, 12032, 11520,  8960,  8448,  9984,  9472,
      15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
        344,   328,   376,   360,   280,   264,   312,   296,
        472,   456,   504,   488,   408,   392,   440,   424,
         88,    72,   120,   104,    24,     8,    56,    40,
        216,   200,   248,   232,   152,   136,   184,   168,
       1376,  1312,  1504,  1440,  1120,  1056,  1248,  1184,
       1888,  1824,  2016,  1952,  1632,  1568,  1760,  1696,
        688,   656,   752,   720,   560,   528,   624,   592,
        944,   912,  1008,   976,   816,   784,   880,   848};

#include <glib.h>
#include "G711adecode.h"
#include "G711atable.h"

int
decodeG711a(void *input, int inputSizeBytes, void *output, int *outputSizeBytes)
{
  guint8 *dataIn = (guint8 *)input;
  gint16 *dataOut = (gint16 *)output;
  int i;

  for (i=0; i<inputSizeBytes; i++)
  {
    dataOut[i] = alaw_exp_table[dataIn[i]];
  }
  *outputSizeBytes = inputSizeBytes * 2;
  return 0;
}

can any body help me ?

thanks in advance

Body:
Looks like this is a fairly simple lossy encoding of a short array. Since G711 is an audio codec, that makes sense. Just iterate over the input byte array, and put the values from the lookup table in the output short array.

private short[] alaw_exp_table = {/* same data as the C code */};

public short[] decodeG711a(byte[] input)
{
    short[] result = new short[input.Length];

    for (int i = 0; i < input.Length; i++)
    {
        result[i] = alaw_exp_table[input[i]];
    }

    return result;
}


问:
MySQL - Select row if appear more than x times in other table
Lets say I have two tables, Members and Orders with a 1:N relation:

```<code>Members         | Orders
UserID  Name    | OrderID   UserID  Name
111     Peter   | 777       111     Peter
222     Bart    | 888       333     Joe
333     Joe     | 999       111     Peter
444     Andrew  | 101       444     Andrew
                | 102       111     Peter
                | 103       333     Joe
</code>```

I am trying to get the Members ID from the Members table, in case that Member has more than 1 order in the Orders table.

So the result should be...

```<code>Members
UserID  Name
111     Peter
333     Joe
</code>```

...because Peter and Joe both have at least 2 orders in the Orders table.

I have tried to get a result with:

```<code>SELECT
    s.UserID,
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )
</code>```

But that gives me Peter back 3 times, and Joe 2 times; so I get duplicates instead of each UserID once. How can I get the result without duplicates?

答:
To remove duplicates, use DISTINCT.</p>

```<code>SELECT
DISTINCT
    s.UserID
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )
</code>```

Body:
Lets say I have two tables, Members and Orders with a 1:N relation:

Members         | Orders
UserID  Name    | OrderID   UserID  Name
111     Peter   | 777       111     Peter
222     Bart    | 888       333     Joe
333     Joe     | 999       111     Peter
444     Andrew  | 101       444     Andrew
                | 102       111     Peter
                | 103       333     Joe

I am trying to get the Members ID from the Members table, in case that Member has more than 1 order in the Orders table.

So the result should be...

Members
UserID  Name
111     Peter
333     Joe

...because Peter and Joe both have at least 2 orders in the Orders table.

I have tried to get a result with:

SELECT
    s.UserID,
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )

But that gives me Peter back 3 times, and Joe 2 times; so I get duplicates instead of each UserID once. How can I get the result without duplicates?

Body:
To remove duplicates, use DISTINCT.

SELECT
DISTINCT
    s.UserID
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )


答:
Try this:

```<code>WITH DataSource AS
(
    SELECT MERC_KEY
         ,ROW_NUMBER() OVER (PARTITION BY  MERC_KEY ORDER BY MERC_KEY_LOG DESC) AS [RowID]
         ,MERC_LPR
    FROM @CAMERC_LOG
    WHERE MERC_LPR IS NOT NULL
        AND MERC_LPR <> 0
)
UPDATE @CAMERC
SET MERC_LPR = B.[MERC_LPR]
FROM @CAMERC A
INNER JOIN DataSource B
    ON A.[MERC_KEY] = B.[MERC_KEY]
    AND B.[RowID] = 1

SELECT *
FROM @CAMERC
</code>```

The idea is to eliminated the invalid records from the @CAMER_LOG and then using ROW_NUMBER to order the rows by MERC_KEY_LOG. After that, we are performing UPDATE by only where RowID = 1.

Title: Update first table based on values from second table

Body:
I have two tables:

- @CAMERC
- @CAMERC_LOG

I have to update column @CAMERC.MERC_LPR with values from column @CAMERC_LOG.MERC_LPR.
Records must match on MERC_KEY, but only one record must be taken from @CAMERC_LOG - with highest MERC_KEY_LOG, and @CAMERC_LOG.MERC_LPR must not be null or 0.

My problem is updating one table based on results from second table. I don't know how to properly make such an update?

Table @CAMERC:

+----------+----------+
| MERC_KEY | MERC_LPR |
+----------+----------+
|        1 | 0.0000   |
|        2 | NULL     |
|        3 | 0.0000   |
|        4 | 0.0000   |
+----------+----------+

Table @CAMERC_LOG:

+----------+--------------+----------+
| MERC_KEY | MERC_KEY_LOG | MERC_LPR |
+----------+--------------+----------+
|        1 |            1 | 1.1000   |
|        1 |            2 | 2.3000   |
|        2 |            3 | 3.4000   |
|        2 |            4 | 4.4000   |
|        1 |            5 | 7.8000   |
|        1 |            6 | NULL     |
|        2 |            7 | 0.0000   |
|        2 |            8 | 12.4000  |
|        3 |            1 | 12.1000  |
|        3 |            2 | 42.3000  |
|        3 |            3 | 43.4000  |
|        3 |            4 | 884.4000 |
|        4 |            5 | 57.8000  |
|        4 |            6 | NULL     |
|        4 |            7 | 0.0000   |
|        4 |            8 | 412.4000 |
+----------+--------------+----------+

Code for table creation:

DECLARE @CAMERC TABLE
(
MERC_KEY INT,
MERC_LPR DECIMAL(10,4)
)

DECLARE @CAMERC_LOG TABLE
(
MERC_KEY INT,
MERC_KEY_LOG INT,
MERC_LPR DECIMAL(10,4)
)

INSERT INTO @CAMERC(MERC_LPR, MERC_KEY) VALUES(0, 1),(NULL,2),(0,3),(0,4)
INSERT INTO @CAMERC_LOG(MERC_LPR, MERC_KEY, MERC_KEY_LOG) VALUES(1.1, 1,1),(2.3,1,2),(3.4,2,3),(4.4,2,4),(7.8, 1,5),(NULL,1,6),(0,2,7),(12.4,2,8),
(12.1, 3,1),(42.3,3,2),(43.4,3,3),(884.4,3,4),(57.8, 4,5),(NULL,4,6),(0,4,7),(412.4,4,8)

Body:
Try this:

WITH DataSource AS
(
    SELECT MERC_KEY
         ,ROW_NUMBER() OVER (PARTITION BY  MERC_KEY ORDER BY MERC_KEY_LOG DESC) AS [RowID]
         ,MERC_LPR
    FROM @CAMERC_LOG
    WHERE MERC_LPR IS NOT NULL
        AND MERC_LPR <> 0
)
UPDATE @CAMERC
SET MERC_LPR = B.[MERC_LPR]
FROM @CAMERC A
INNER JOIN DataSource B
    ON A.[MERC_KEY] = B.[MERC_KEY]
    AND B.[RowID] = 1

SELECT *
FROM @CAMERC

The idea is to eliminated the invalid records from the @CAMER_LOG and then using ROW_NUMBER to order the rows by MERC_KEY_LOG. After that, we are performing UPDATE by only where RowID = 1.


问:
Unable to make some part of UILabel underline in Swift?
I have a UILabel I want to make some part of it as underline. I am using below code for that. But it underline the whole label not the some part of label. Please tell me how can I make some part of label as Underline.

```<code>let attributedString = NSMutableAttributedString(string: "UserAgreement".localized)
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: 10))

labelTc.attributedText = attributedString
</code>```

I don't want to do with the storyboard

答:
Try this

Swift 4

```<code>    let wholeStr = "Don't have an account? Register"
    //let rangeToUnderLine = (wholeStr as NSString).range(of: "Register")
    let rangeToUnderLine = NSRange(location: 0, length: 10))
    let underLineTxt = NSMutableAttributedString(string: wholeStr, attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 20),NSAttributedStringKey.foregroundColor: UIColor.white.withAlphaComponent(0.8)])
    underLineTxt.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: rangeToUnderLine)
    labelTc.attributedText = underLineTxt
</code>```

Swift 3.2

```<code>    let wholeStr = "Don't have an account? Register"
    //let rangeToUnderLine = (wholeStr as NSString).range(of: "Register")
    let rangeToUnderLine = NSRange(location: 0, length: 10))
    let underLineTxt = NSMutableAttributedString(string: wholeStr, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 20),NSForegroundColorAttributeName: UIColor.white])
    underLineTxt.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: rangeToUnderLine)
    labelTc.attributedText = underLineTxt
</code>```

Body:
I have a UILabel I want to make some part of it as underline. I am using below code for that. But it underline the whole label not the some part of label. Please tell me how can I make some part of label as Underline.

let attributedString = NSMutableAttributedString(string: "UserAgreement".localized)
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: 10))

labelTc.attributedText = attributedString

I don't want to do with the storyboard

Body:
Try this

Swift 4

    let wholeStr = "Don't have an account? Register"
    //let rangeToUnderLine = (wholeStr as NSString).range(of: "Register")
    let rangeToUnderLine = NSRange(location: 0, length: 10))
    let underLineTxt = NSMutableAttributedString(string: wholeStr, attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 20),NSAttributedStringKey.foregroundColor: UIColor.white.withAlphaComponent(0.8)])
    underLineTxt.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: rangeToUnderLine)
    labelTc.attributedText = underLineTxt

Swift 3.2

    let wholeStr = "Don't have an account? Register"
    //let rangeToUnderLine = (wholeStr as NSString).range(of: "Register")
    let rangeToUnderLine = NSRange(location: 0, length: 10))
    let underLineTxt = NSMutableAttributedString(string: wholeStr, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 20),NSForegroundColorAttributeName: UIColor.white])
    underLineTxt.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: rangeToUnderLine)
    labelTc.attributedText = underLineTxt


问:
How can 2 or more pie-charts with the property of "pullOutOnlyOne" work with one another- Amcharts
There are two pie-charts. I want the functionality so that only one slice of the pie-charts pulls out whichever last clicked. "pullOutOnlyOne" is working only for single pie-chart. I need it to be worked like this, If i click on a slice of One pie-chart then second one, then slice of first pie-chart should pulled in.

JSFIDDLE

I tried this one but unable to capture which pie-chart and which slice...:(

var lastClickedSlice;
...
...
{
     "event": "clickSlice",
     "method": function (e) {
           if (lastClickedSlice === "") {
                 lastClickedSlice = e.dataItem.dataContext;
           } else {
                 console.log(JSON.stringify(lastClickedSlice));
                 lastClickedSlice.clickSlice(lastClickedSlice.index);
                 lastClickedSlice = e.dataItem.dataContext;
           }
   }
}

How to implement this thing with 2 or more than 2 pie-charts?

答:
Add click listners on each slice of the chart, for example on chart-1 slice click event below :

"listeners": [{
    "event": "clickSlice",
    "method": function(e) {

      chart2.pullOutRadius = "0%";
      chart2.validateData();
      chart2.pullOutRadius = "20%";
      chart2.validateData();
    }
    }]

Working Demo here : https://jsfiddle.net/6oo9jvLj/5/


问:
Eclipse for C/C++: Jvm terminated error
I installed over Ubuntu GNU/Linux 16.04.2 VM the latest eclipse IDE for C/C++ via the eclipse oxygen provided via http://www.eclipse.org/.

After a complete Installation when I try to run the eclipse Application I get the following error:

```<code>JVM terminated. Exit code=1
/usr/lib/jvm/java-9-openjdk-amd64/bin/java
-Dosgi.requiredJavaVersion=1.8
-Dosgi.instance.area.default=@user.home/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx1024m
--add-modules=ALL-SYSTEM
-Declipse.p2.max.threads=10
-Doomph.update.url=http://download.eclipse.org/oomph/updates/milestone/latest
-Doomph.redirection.index.redirection=index:/->http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/
-jar /home/user/eclipse/cpp-oxygen/eclipse//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
-os linux
-ws gtk
-arch x86_64
-showsplash
-launcher /home/user/eclipse/cpp-oxygen/eclipse/eclipse
-name Eclipse
--launcher.library /home/user/.p2/pool/plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.550.v20170928-1359/eclipse_1629.so
-startup /home/user/eclipse/cpp-oxygen/eclipse//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.appendVmargs
-exitdata 3d800b
-product org.eclipse.epp.package.cpp.product
-vm /usr/lib/jvm/java-9-openjdk-amd64/bin/java
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Dosgi.instance.area.default=@user.home/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx1024m
--add-modules=ALL-SYSTEM
-Declipse.p2.max.threads=10
-Doomph.update.url=http://download.eclipse.org/oomph/updates/milestone/latest
-Doomph.redirection.index.redirection=index:/->http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/
-jar /home/user/eclipse/cpp-oxygen/eclipse//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
</code>```

Do you have any idea why?

答:
I had this same problem and have just managed to fix it.

The error message is saying that it is looking for Java version 1.8, but it can only find version 1.9.

First make sure you have java 1.8 installed.
If you open a terminal and enter the command RustyX suggested:

```<code>sudo update-alternatives --config java
</code>```

you will be shown a lists of java versions on your machine and asked to select a version to be your default. Pick 1.8 and try opening eclipse again, it should work now.

Title: Eclipse for C/C++: Jvm terminated error

Body:
I installed over Ubuntu GNU/Linux 16.04.2 VM the latest eclipse IDE for C/C++ via the eclipse oxygen provided via http://www.eclipse.org/.

After a complete Installation when I try to run the eclipse Application I get the following error:

JVM terminated. Exit code=1
/usr/lib/jvm/java-9-openjdk-amd64/bin/java
-Dosgi.requiredJavaVersion=1.8
-Dosgi.instance.area.default=@user.home/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx1024m
--add-modules=ALL-SYSTEM
-Declipse.p2.max.threads=10
-Doomph.update.url=http://download.eclipse.org/oomph/updates/milestone/latest
-Doomph.redirection.index.redirection=index:/->http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/
-jar /home/user/eclipse/cpp-oxygen/eclipse//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
-os linux
-ws gtk
-arch x86_64
-showsplash
-launcher /home/user/eclipse/cpp-oxygen/eclipse/eclipse
-name Eclipse
--launcher.library /home/user/.p2/pool/plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.550.v20170928-1359/eclipse_1629.so
-startup /home/user/eclipse/cpp-oxygen/eclipse//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.appendVmargs
-exitdata 3d800b
-product org.eclipse.epp.package.cpp.product
-vm /usr/lib/jvm/java-9-openjdk-amd64/bin/java
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Dosgi.instance.area.default=@user.home/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx1024m
--add-modules=ALL-SYSTEM
-Declipse.p2.max.threads=10
-Doomph.update.url=http://download.eclipse.org/oomph/updates/milestone/latest
-Doomph.redirection.index.redirection=index:/->http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/
-jar /home/user/eclipse/cpp-oxygen/eclipse//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar

Do you have any idea why?

Body:
I had this same problem and have just managed to fix it.

The error message is saying that it is looking for Java version 1.8, but it can only find version 1.9.

First make sure you have java 1.8 installed.
If you open a terminal and enter the command RustyX suggested:

sudo update-alternatives --config java

you will be shown a lists of java versions on your machine and asked to select a version to be your default. Pick 1.8 and try opening eclipse again, it should work now.


问:
How to get image saved into session variable PHP
FILE 1:

```<code>$_SESSION['imguserF'] =  $_FILES['imguser'];
</code>```

FILE 2:

```<code><p>Photo: </p><input id=\"imgrace\" type=\"file\" name=\"imguser\" />
</code>```

When I create a session variable, file 2 opens. I want that when file2 be open, the image saved into session variable be selected into the input.

How can I get that value and insert it into the input?

答:
I will try to break it down as much as i can:

First we have your form:

Php can not read elements like javascript or css can so you need to include what you want inside form. In form you must define the method you are going to use (post,get) and the action which is your php file. I provide you a sample form to help you understand

```<code><form method="post" action="test2.php">
    <p>Photo: </p><input id="imgrace" type="file" name="imguser"/>
    <input type="submit" id="imguser" name="imguser2"/>
</form>
</code>```

After that we move to php section:

In php file i need to receive what i am sending. The method that i set in html must be the one that receives in php and of course the same file name. I present you a sample of php file:

```<code>$data=$_POST['imguser'];
echo "<img src='/$data' />";
</code>```

What this 2 files are doing is simple. I upload an image from the html page, i capture it and display it in php page. My variable $data has all the info i need (the image name) to display the image and except of display i can simple store it into a DB. Also you need to submit your form. Php is not real-time like ajax calls or javascript functions so needs to "refresh".

Body:
FILE 1:

$_SESSION['imguserF'] =  $_FILES['imguser'];

FILE 2:

Photo:
<input id=\"imgrace\" type=\"file\" name=\"imguser\" />

When I create a session variable, file 2 opens. I want that when file2 be open, the image saved into session variable be selected into the input.

How can I get that value and insert it into the input?

Body:
I will try to break it down as much as i can:

First we have your form:

Php can not read elements like javascript or css can so you need to include what you want inside form. In form you must define the method you are going to use (post,get) and the action which is your php file. I provide you a sample form to help you understand

<form method="post" action="test2.php">
    <p>Photo: </p><input id="imgrace" type="file" name="imguser"/>
    <input type="submit" id="imguser" name="imguser2"/>
</form>

After that we move to php section:

In php file i need to receive what i am sending. The method that i set in html must be the one that receives in php and of course the same file name. I present you a sample of php file:

$data=$_POST['imguser'];
echo "<img src='/$data' />";

What this 2 files are doing is simple. I upload an image from the html page, i capture it and display it in php page. My variable $data has all the info i need (the image name) to display the image and except of display i can simple store it into a DB. Also you need to submit your form. Php is not real-time like ajax calls or javascript functions so needs to "refresh".


问:
How to get child object from PSObject using dot notation string
providing I have the following JSON

{
    "firstName":  "Frank",
    "lastName":  "Smith",
    "age":  "25",
    "address":  {
                    "streetAddress":  "21 3rd st",
                    "city":  "New York",
                    "state":  "NY",
                    "postalCode":  "10021"
                },
    "phoneNumber":  [
                        {
                            "type":  "home",
                            "number":  "212 555-1234"
                        },
                        {
                            "type":  "fax",
                            "number":  "646 555-4567"
                        }
                    ]
}
```

<p>I need to be able to update a value using dotted notation.</p>

<pre class="lang-posh prettyprint-override"><code>$path = "C:\somePath\test.json"
$node = "address.streetAddress"         # should also work with "phoneNumber[0].number"
$value = "21 Jump St."

$config = Get-Content -Path $path -Raw | ConvertFrom-Json
$config.$node = $value
Write-Host $config.$node

#Set-Content $path $($config | ConvertTo-Json)
</code>```

The problem I'm getting is that the property cannot be found.

Exception setting "address.streetAddress": "The property 'address.streetAddress' cannot be found on this object. Verify that the property exists and can be set."

What do I need to do to be able to pass in dotted notation, and update the appropriate value?

答:
Shortest way around it is:

```<code>$config.$($node) = $value
</code>```

Level of nesting does not matter, You can do this:

```<code>$config.$($node).$($subnode).$($subSubNode) = $value
</code>```

You can also refer to properties in objects like this:

```<code>$config.$($node.nodename)=$value
</code>```

Body:
providing I have the following JSON

{
    "firstName":  "Frank",
    "lastName":  "Smith",
    "age":  "25",
    "address":  {
                    "streetAddress":  "21 3rd st",
                    "city":  "New York",
                    "state":  "NY",
                    "postalCode":  "10021"
                },
    "phoneNumber":  [
                        {
                            "type":  "home",
                            "number":  "212 555-1234"
                        },
                        {
                            "type":  "fax",
                            "number":  "646 555-4567"
                        }
                    ]
}

I need to be able to update a value using dotted notation.

$path = "C:\somePath\test.json"
$node = "address.streetAddress"         # should also work with "phoneNumber[0].number"
$value = "21 Jump St."

$config = Get-Content -Path $path -Raw | ConvertFrom-Json
$config.$node = $value
Write-Host $config.$node

#Set-Content $path $($config | ConvertTo-Json)

The problem I'm getting is that the property cannot be found.

Exception setting "address.streetAddress": "The property 'address.streetAddress' cannot be found on this object. Verify that the property exists and can be set."

What do I need to do to be able to pass in dotted notation, and update the appropriate value?

Body:
Shortest way around it is:

$config.$($node) = $value

Level of nesting does not matter, You can do this:

$config.$($node).$($subnode).$($subSubNode) = $value

You can also refer to properties in objects like this:

$config.$($node.nodename)=$value


问:
ncl: /lib/x86_64-linux-gnu/libssl.so.10: version `libssl.so.10' not found (required by ncl)
This is in reference to running the WRF model in my system. I am trying to run the file plotgrids.ncl to ensure that the domain is in the right location before running geogrid.exe . Running the following command in my terminal(ubuntu)
ncl util/plotgrids.ncl
gives me the following error:

ncl: /lib/x86_64-linux-gnu/libssl.so.10: version 'libssl.so.10' not found (required by ncl)
ncl: /lib/x86_64-linux-gnu/libcrypto.so.10: version 'libcrypto.so.10' not found (required by ncl)

答:
for Ubuntu 16 please check help given by NCL forum at
mailman.ucar.edu/pipermail/ncl-install/2017-November/thread.html
as resumed here:

http://conda.pydata.org/miniconda.html
used Python 3.6 Linux 64-bit (bash installer)

```<code>cd /home/user/Downloads/
chmod +x Miniconda2-latest-Linux-x86_64.sh
./Miniconda2-latest-Linux-x86_64.sh
conda -V
</code>```

conda 4.3.30

http://ncl.ucar.edu/Download/conda.shtml

```<code>conda create -n ncl_stable -c conda-forge ncl=6.4.0 gsl
root@hostname:~# source activate ncl_stable
(ncl_stable) root@hostname:~# ncl -V
</code>```

6.4.0

```<code>ng4ex xy05n -clean -W png
</code>```

it works!

outside conda (ncl_stable)

```<code>ng4ex
</code>```

The program 'ng4ex' is currently not installed. You can install it by:

```<code>sudo su
vi /etc/apt/sources.list
</code>```

add at the end

```<code>deb http://http.us.debian.org/debian/ testing non-free contrib main
</code>```

exit editor

```<code>apt-get update
apt install libncarg-bin
</code>```

Body:
for Ubuntu 16 please check help given by NCL forum at
mailman.ucar.edu/pipermail/ncl-install/2017-November/thread.html
as resumed here:

http://conda.pydata.org/miniconda.html
used Python 3.6 Linux 64-bit (bash installer)

cd /home/user/Downloads/
chmod +x Miniconda2-latest-Linux-x86_64.sh
./Miniconda2-latest-Linux-x86_64.sh
conda -V

conda 4.3.30

http://ncl.ucar.edu/Download/conda.shtml

conda create -n ncl_stable -c conda-forge ncl=6.4.0 gsl
root@hostname:~# source activate ncl_stable
(ncl_stable) root@hostname:~# ncl -V

6.4.0

ng4ex xy05n -clean -W png

it works!

outside conda (ncl_stable)

ng4ex

The program 'ng4ex' is currently not installed. You can install it by:

sudo su
vi /etc/apt/sources.list

add at the end

deb http://http.us.debian.org/debian/ testing non-free contrib main

exit editor

apt-get update
apt install libncarg-bin


问:
How to set a swiper slider to start from right, rather than left?
I want to have 2 Swiper sliders staying side by side, one starting from left, the other one from right, How to set one of them to start from right going to left?

<- [a...] [a3] [a2] [a1] || [b1] [b2] [b3] [b...] ->

For example each swiper has 12 slides.

I tried RTL and many other approaches but none of them works for me. RTL puts an empty space at the beginning.

Thanks for any kind help.

答: Maybe you are probably looking for the initialSlide parameter. Setting it to your last slide index and it will give you what you want (if I understood it well!)


问:
InstallAnywhere issue: This application has unexpectely quit
I have downloaded IBM Client SDK 4.10 FC5DE for Windows x64. When I proceed to install it, InstallAnyWhere popups saying "Preparing installation files...". When it reaches to 100% below error is shown and installation terminates:

```<code>This application has unexpectely quit:
Invocation of this Java application has caused an InvocationTargetException. This application will now exit (LAX).
</code>```

And If I click on details button its show stack trace:

```<code>ZeroGu6: Windows DLL failed to load
    at ZeroGa4.b(DashoA10*..)
    at ZeroGa4.b(DashoA10*..)
    at com.zerog.ia.installer.LifeCycleManager.b(DashoA10*..)
    at com.zerog.ia.installer.LifeCycleManager.a(DashoA10*..)
    at com.zerog.ia.installer.Main.main(DashoA10*..)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:94)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:619)
    at com.zerog.lax.LAX.launch(DashoA10*..)
    at com.zerog.lax.LAX.main(DashoA10*..)
</code>```

My OS is Windows 8.1 Pro and I have the last Java x86 and Java x86_64 installed on my system. Java x86_64 is the only activated in Java configuration panel. If I activated both, it does not work either. Leaving activating Java x86 it does not work either.

Below the Java packages installed on my system:

Java 8 Update 151

Java 8 Update 151 (64-bit)

Java(TM) SE Development Kit 6 Update 24

So any ideas on what is happening?

SOLVED:
I have solved it.

In order to work you need to set Compatibility Mode to Windows 7 for setup ( executable file).

Right click on setup file, go to compatibility tab, and then set "Compatibility Mode" to "Windows 7". Also in configuration, you can check "Launch this program as Administrator".

Link where I found a similar problem: see this.

答:
Change compatibility to windows 7

Check this (not the same product, but looks like the same error)

The installation can be finished successfully while setting the two
  files below to Windows 7 compatibility mode.

File 1: launchpad64.exe launchpad.exe, depending on which bit version you plan to install

File2: depending on the used launchpad version, 64 or 32 bit, go into
      a. win86_64 (If you are running launchpad64.exe) or
      b. win86_32 (If you are running launchpad.exe) folder.

If you Install as Administrator, change the compatibility of install.exe to
  Windows 7.

If you Install as Current User, change the compatibility of
  userinst.exe to Windows 7.

Launch the launchpad64.exe or launchpad.exe
  as Administrator

Body:
I have downloaded IBM Client SDK 4.10 FC5DE for Windows x64. When I proceed to install it, InstallAnyWhere popups saying "Preparing installation files...". When it reaches to 100% below error is shown and installation terminates:

This application has unexpectely quit:
Invocation of this Java application has caused an InvocationTargetException. This application will now exit (LAX).

And If I click on details button its show stack trace:

ZeroGu6: Windows DLL failed to load
    at ZeroGa4.b(DashoA10*..)
    at ZeroGa4.b(DashoA10*..)
    at com.zerog.ia.installer.LifeCycleManager.b(DashoA10*..)
    at com.zerog.ia.installer.LifeCycleManager.a(DashoA10*..)
    at com.zerog.ia.installer.Main.main(DashoA10*..)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:94)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:619)
    at com.zerog.lax.LAX.launch(DashoA10*..)
    at com.zerog.lax.LAX.main(DashoA10*..)

My OS is Windows 8.1 Pro and I have the last Java x86 and Java x86_64 installed on my system. Java x86_64 is the only activated in Java configuration panel. If I activated both, it does not work either. Leaving activating Java x86 it does not work either.

Below the Java packages installed on my system:

Java 8 Update 151

Java 8 Update 151 (64-bit)

Java(TM) SE Development Kit 6 Update 24

So any ideas on what is happening?

SOLVED:
I have solved it.

In order to work you need to set Compatibility Mode to Windows 7 for setup ( executable file).

Right click on setup file, go to compatibility tab, and then set "Compatibility Mode" to "Windows 7". Also in configuration, you can check "Launch this program as Administrator".

Link where I found a similar problem: see this.


问:
Accessing nested associative array using array_keys (PHP)
I'm trying to access a nested associative array:

```<code>$data = array('1'=>'value1','2'=>'value2','3'=>array('one','two'))
</code>```

The value of the key '3' is an array.

Since I need to cycle my values, I extracted the keys of given array:

```<code>$keys = array_keys($data);
</code>```

and used to get the associated value with:

```<code>foreach(range(1, 10) as $val):
 echo "key: ".$keys[$val];
 echo "value: ".$data[$keys[$val]];
endforeach;
</code>```

Now I would like to access the values related to '3'.
Using $data[$keys[$val]] won't work cause I get back an array, not a value.

My question is: how can I access, for example to the value 'one' using a syntax close to $data[$keys[$val]] ?

答:
You should add a condition to check if the value is a string or an array.
If it's a string - simply echo it, otherwise - access the first value in that array (key = 0, will print 'one') or use another foreach loop to access all of those array's values.</p>

```<code>foreach(range(1, 10) as $val):
 echo "key: ".$keys[$val];
 echo "value: ";
 if(is_array($data[$keys[$val]])){ //Is it an array?

  //echo 'one'
  echo $data[$keys[$val]][0];

  //or all the values with a loop
  foreach($data[$keys[$val]] as $val2){
   echo $val2;
   echo ",";
  }

 } else { //it's not an array, we can simply echo it.
  echo $data[$keys[$val]];
 }
endforeach;
</code>```

Body:
I'm trying to access a nested associative array:

$data = array('1'=>'value1','2'=>'value2','3'=>array('one','two'))

The value of the key '3' is an array.

Since I need to cycle my values, I extracted the keys of given array:

$keys = array_keys($data);

and used to get the associated value with:

foreach(range(1, 10) as $val):
 echo "key: ".$keys[$val];
 echo "value: ".$data[$keys[$val]];
endforeach;

Now I would like to access the values related to '3'.
Using $data[$keys[$val]] won't work cause I get back an array, not a value.

My question is: how can I access, for example to the value 'one' using a syntax close to $data[$keys[$val]] ?

Body:
You should add a condition to check if the value is a string or an array.
If it's a string - simply echo it, otherwise - access the first value in that array (key = 0, will print 'one') or use another foreach loop to access all of those array's values.

foreach(range(1, 10) as $val):
 echo "key: ".$keys[$val];
 echo "value: ";
 if(is_array($data[$keys[$val]])){ //Is it an array?

  //echo 'one'
  echo $data[$keys[$val]][0];

  //or all the values with a loop
  foreach($data[$keys[$val]] as $val2){
   echo $val2;
   echo ",";
  }

 } else { //it's not an array, we can simply echo it.
  echo $data[$keys[$val]];
 }
endforeach;


问:
.Net 4.5.x - custom TimeSpan formatting with optional sections?
I have a data processing system which returns a number of variables as Timespan. The user can configure how they wish to see this output by supplying a format string, which I then apply to the timespan.

e.g. User sets format to d\,\ h:mm:ss, output is 0, 0:00:00 (for zero).

I'd like to make it possible for the system to automatically skip days or hours if they're zero.

i.e. User sets format [d\, ][h:]mm:\ss and gets 00:00 to 59:59 for less than an hour, then 1:00:00 to 23:59:59 for less than a day, then 1, 00:00:00 to x, nn:nn:nn for anything greater, where x= number of days.

The built-in timespan doesn't offer the "optional" sections in square brackets.

Is there an easy way to achieve this I'm not seeing, or do I need to write my own version of the TimeSpan formatter?

答:
Not exactly elegant, but I did something like this:

```<code>    Dim fmt As String
    fmt = If(thisTimespan >= TimeSpan.FromDays(1), "d\d\-\ h\:mm\:ss\.fff", "h\:mm\:ss\.fff")
</code>```

You could easily expand this to eliminate unneeded hours as well.

Body:
Not exactly elegant, but I did something like this:

    Dim fmt As String
    fmt = If(thisTimespan >= TimeSpan.FromDays(1), "d\d\-\ h\:mm\:ss\.fff", "h\:mm\:ss\.fff")

You could easily expand this to eliminate unneeded hours as well.


问:
xPages REST Service Results into Combobox or Typeahead Text Field
I've read all the documentation I can find and watched all the videos I can find and don't understand how to do this.  I have set up an xPages REST Service and it works well.  Now I want to place the results of the service into either a combobox or typeahead text field.  Ideally I would like to know how to do it for both types of fields.

I have an application which has a view containing a list of countries, another view containing a list of states, and another containing a list of cities.  I would like the first field to only display the countries field from the list of data it returns in the XPages REST Service.  Then, depending upon which country was selected, I would like the states for that country to be listed in another field for selection, etc.

I can see code for calling the REST Service results from a button, or from a dojo grid, but I cannot find how to call it to populate either of the types of fields identified above.

Where would I call the Service for the field? I had thought it would go in the Data area, but perhaps I've just not found the right syntax to use.

November 6, 2017:

I have been following your suggestion, but am still lost as can be.  Here's what I currently have in my code:

```<code>x$( "#{id:ApplCountry}" ).select2({
                        placeholder: "select a country",
                        minimumInputLength: 2,
                        allowClear : true,
                        multiple: false,
                        ajax: {
                            dataType: 'text/plain',
                            url: "./Application.xsp/gridData",
                            quietMillis: 250,
                        data: function (params) {
                            return {
                                search:'[name=]*'+params.term+'*',
                                page: params.page
                            };
                        },
                        processResults: function (data, page) {
                            var data = $.map(data, function (obj) {
                            obj.id = obj.id || obj["@entityid"];
                            obj.text = obj.text || obj.name;
                            return obj;
                        });
                        },

            return {results: data};
        }
      }
});
</code>```

I'm using the dataType of 'text/plain' because that was what I understood I should use when gathering data from a domino application. I have tried changing this to json but it makes no difference.

I'm using processResults because I understand this is what should be used in version 4 of select2.

I don't understand the whole use of the hidden field, so I've stayed away from that.

No matter what I do, although my REST service works if I put it directly in the url, I cannot get any data to display in the field.  All I want to display in the field is the country code of the document, which is in the field named "name" (not my choice, it's how it came before I imported the data from MySQL.

I have read documentation and watched videos, but still don't really understand how everything fits together.  That was my problem with the REST service.  If you use it in Dojo, you just put the name of the service in a field on the Dojo element and it's done, so I don't understand why all the additional coding for another type of domino element.  Shouldn't it work the same way?

I should point out that at some points it does display the default message, so it does find the field.  Just doesn't display the country selections.

答:
I think the issue may be that you are not returning SelectItems to your select2, and that is what it is expecting. When I do something like you are trying, I actually use a bean to generate the selection choices. You may want to try that or I'm putting in the working part of my bean below.

The Utils.getItemValueAsString is a method I use to return either the string value of a field, or if it is not on the document/empty/null an empty string. I took out an if that doesn't relate to this, so there my be a mismatch, but I hope not.

You might be able to jump directly to populating the arrayList,  but as I recall I needed to leverage the LinkedHashMap for something.

You should be able to do the same using SSJS, but since that renders to Java before executing, I find this more efficient.

For label/value pairs:

```<code>LinkedHashMap lhmap = new LinkedHashMap();

Document doc = null;
            Document tmpDoc = null;
            allObjects.addElement(doc);
            if (dc.getCount() > 0) {
                doc = dc.getFirstDocument();
                while (doc != null) {

                        lhmap.put(Utils.getItemValueAsString(doc, LabelField, true), Utils.getItemValueAsString(doc, ValueField, true));
                    }

                    tmpDoc = dc.getNextDocument(doc);
                    doc.recycle();
                    doc = tmpDoc;
                }

            }

List<SelectItem> options = new ArrayList<SelectItem>();
        Set set = lhmap.entrySet();
        Iterator hsItr = set.iterator();
        while (hsItr.hasNext()) {
            Map.Entry me = (Map.Entry) hsItr.next();
            // System.out.println("after: " + hStr);
            SelectItem option = new SelectItem();

            option.setLabel(me.getKey() + "");
            option.setValue(me.getValue() + "");
            options.add(option);
        }
        System.out.println("About to return from generating");
        return options;
    }
</code>```

Body:
I've read all the documentation I can find and watched all the videos I can find and don't understand how to do this.  I have set up an xPages REST Service and it works well.  Now I want to place the results of the service into either a combobox or typeahead text field.  Ideally I would like to know how to do it for both types of fields.

I have an application which has a view containing a list of countries, another view containing a list of states, and another containing a list of cities.  I would like the first field to only display the countries field from the list of data it returns in the XPages REST Service.  Then, depending upon which country was selected, I would like the states for that country to be listed in another field for selection, etc.

I can see code for calling the REST Service results from a button, or from a dojo grid, but I cannot find how to call it to populate either of the types of fields identified above.

Where would I call the Service for the field? I had thought it would go in the Data area, but perhaps I've just not found the right syntax to use.

November 6, 2017:

I have been following your suggestion, but am still lost as can be.  Here's what I currently have in my code:

x$( "#{id:ApplCountry}" ).select2({
                        placeholder: "select a country",
                        minimumInputLength: 2,
                        allowClear : true,
                        multiple: false,
                        ajax: {
                            dataType: 'text/plain',
                            url: "./Application.xsp/gridData",
                            quietMillis: 250,
                        data: function (params) {
                            return {
                                search:'[name=]*'+params.term+'*',
                                page: params.page
                            };
                        },
                        processResults: function (data, page) {
                            var data = $.map(data, function (obj) {
                            obj.id = obj.id || obj["@entityid"];
                            obj.text = obj.text || obj.name;
                            return obj;
                        });
                        },

            return {results: data};
        }
      }
});

I'm using the dataType of 'text/plain' because that was what I understood I should use when gathering data from a domino application. I have tried changing this to json but it makes no difference.

I'm using processResults because I understand this is what should be used in version 4 of select2.

I don't understand the whole use of the hidden field, so I've stayed away from that.

No matter what I do, although my REST service works if I put it directly in the url, I cannot get any data to display in the field.  All I want to display in the field is the country code of the document, which is in the field named "name" (not my choice, it's how it came before I imported the data from MySQL.

I have read documentation and watched videos, but still don't really understand how everything fits together.  That was my problem with the REST service.  If you use it in Dojo, you just put the name of the service in a field on the Dojo element and it's done, so I don't understand why all the additional coding for another type of domino element.  Shouldn't it work the same way?

I should point out that at some points it does display the default message, so it does find the field.  Just doesn't display the country selections.

Body:
I think the issue may be that you are not returning SelectItems to your select2, and that is what it is expecting. When I do something like you are trying, I actually use a bean to generate the selection choices. You may want to try that or I'm putting in the working part of my bean below.

The Utils.getItemValueAsString is a method I use to return either the string value of a field, or if it is not on the document/empty/null an empty string. I took out an if that doesn't relate to this, so there my be a mismatch, but I hope not.

You might be able to jump directly to populating the arrayList,  but as I recall I needed to leverage the LinkedHashMap for something.

You should be able to do the same using SSJS, but since that renders to Java before executing, I find this more efficient.

For label/value pairs:

LinkedHashMap lhmap = new LinkedHashMap();

Document doc = null;
            Document tmpDoc = null;
            allObjects.addElement(doc);
            if (dc.getCount() > 0) {
                doc = dc.getFirstDocument();
                while (doc != null) {

                        lhmap.put(Utils.getItemValueAsString(doc, LabelField, true), Utils.getItemValueAsString(doc, ValueField, true));
                    }

                    tmpDoc = dc.getNextDocument(doc);
                    doc.recycle();
                    doc = tmpDoc;
                }

            }

List<SelectItem> options = new ArrayList<SelectItem>();
        Set set = lhmap.entrySet();
        Iterator hsItr = set.iterator();
        while (hsItr.hasNext()) {
            Map.Entry me = (Map.Entry) hsItr.next();
            // System.out.println("after: " + hStr);
            SelectItem option = new SelectItem();

            option.setLabel(me.getKey() + "");
            option.setValue(me.getValue() + "");
            options.add(option);
        }
        System.out.println("About to return from generating");
        return options;
    }


问:
Bootstrap footer is not at the bottom of any page
I've seen a few of these on Stack Overflow, but the questions that have been asked don't lead to an answer which solves my issue. Please take the time to look over my code before marking it down or flagging it as a duplicate.

I'm working through a book called "Beginning django CMS". I'm finding that a few parts are out of date, and that might be the issue here. It's tough for me to say because I'm new to web design.

The footer isn't in a
, and I've gone over the padding to see if that helps. Those are the kinds of issues that come up as answers to questions that have previously been posted on Stack Overflow.

I'm being left with a footer which begins ends an inch from the bottom of the screen. Does anyone know what might be causing this?

I've checked this in Chrome and Edge so far, both come up with the indent.

Here's the HTML:

```<code>{% load cms_tags staticfiles sekizai_tags menu_tags %}
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv"X-UA-Compatible" Content = "IE=Edge">
    <meta name = "viewport" content="width=device-width", initial-scale=1>

    <link rel="icon" href="favicon.ico">

    <title>{% block title %}MyBlog Title{% endblock title %}</title>

    <link href="https://cdnjs.cloudfare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel = "stylesheet">

    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">

    <!-- MyBlog custom styles -->
    <link href="{% static "myblog.css" %}" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
        <script src=https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    {% render_block "css" %}
</head>
<body>
    {% cms_toolbar %}
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a href=""><img src="{% static "" %}"/></a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    {% show_menu 0 1 0 100 "menu.html" %}
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="blog-header">
            <h1 class="blog-title">(Now a banner)</h1>
            <p class="lead blog-description">The political system is broken; it could do with a Patch</p>
        </div>
        {% block content %}{% endblock content %}
    </div>

    <footer class="footer">
     <div class="container">
      <p class="text-muted">{% block footer %}My Blog©2015{%endblock footer%}</p>
     </div>
    </footer>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bu -->
    <script src="{% static "ie10-viewport-bug-workaround.js" %}"></script>

    {% render_block "js" %}
</body>
</code>```

And the CSS:

```<code>html {
    position : relative;
    min-height: 100%;
}

body {
    /* Margin bottom by footer height */
    margin-bottom: 60px;
    font-family : Georgia, "Times New Roman", Times, serif;
    color #555;
}
h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 {
    margin-top: 0;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serfi;
    font-weight: normal;
    color: #333;
}
.footer {
    position: absolute;
    margin-left : 0px
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #f5f5f5;
}
.blog-header {
    padding-top: 20px;
    padding-bottom: 20px;
}

.blog-title {
    margin-top: 30px;
    margin-bottom: 0;
    font-size: 28px;
    font-weight: normal;
}
.blog-description{
    font-size: 20px;
    color: #999;
}
.sidebar-module{
    padding: 15px;
    margin: 0 -15px 15px;
}
.sidebar-module-inset {
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
}
.sidebar-module-inset p:last-child,
.sidebar-module-inset ul:last-child,
.sidebar-module-inset ol:last-child{
    margin-bottom: 0;
}
.pager {
    margin-bottom: 60px;
    text-align: left
}
.pager > li > a {
    width: 140px;
    padding: 10px 20px;
    text-align: center;
    border-radius: 30px;
}
.blog-post{
    margin-bottom: 60px;
}
.blog-post-title{
    margin-bottom: 5px;
    font-size: 40px;
}
.blog-post-meta {
    margin-bottom: 20px;
    color : #999;
}
body > container {
    padding: 0px 0px 0;
}
.container .text-muted {
    margin: 20px 0;
}
.footer > .container {
    padding-right: 15px;
    padding-left: 0;
}
.row {
    margin-right: 0px!important;
}
</code>```

答:
The issue is in the line

```<code> <h1 class="blog-title">Patch's Soapbox</h1>
</code>```

You can tell what the problem is because all the text beyond this point is in red.

The single quote in Patch's is telling HTML that everything after this point is a string. You need to us a replacement by using:

```<code><h1 class="blog-title">Patch's Soapbox</h1>
</code>```

Body:
I've seen a few of these on Stack Overflow, but the questions that have been asked don't lead to an answer which solves my issue. Please take the time to look over my code before marking it down or flagging it as a duplicate.

I'm working through a book called "Beginning django CMS". I'm finding that a few parts are out of date, and that might be the issue here. It's tough for me to say because I'm new to web design.

The footer isn't in a
, and I've gone over the padding to see if that helps. Those are the kinds of issues that come up as answers to questions that have previously been posted on Stack Overflow.

I'm being left with a footer which begins ends an inch from the bottom of the screen. Does anyone know what might be causing this?

I've checked this in Chrome and Edge so far, both come up with the indent.

Here's the HTML:

{% load cms_tags staticfiles sekizai_tags menu_tags %}
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv"X-UA-Compatible" Content = "IE=Edge">
    <meta name = "viewport" content="width=device-width", initial-scale=1>

    <link rel="icon" href="favicon.ico">

    <title>{% block title %}MyBlog Title{% endblock title %}</title>

    <link href="https://cdnjs.cloudfare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel = "stylesheet">

    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">

    <link href="{% static "myblog.css" %}" rel="stylesheet">

    {% render_block "css" %}

    {% cms_toolbar %}

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>

                    {% show_menu 0 1 0 100 "menu.html" %}

(Now a banner)

The political system is broken; it could do with a Patch

        {% block content %}{% endblock content %}

{% block footer %}My Blog©2015{%endblock footer%}

    {% render_block "js" %}

And the CSS:

html {
    position : relative;
    min-height: 100%;
}

body {
    /* Margin bottom by footer height */
    margin-bottom: 60px;
    font-family : Georgia, "Times New Roman", Times, serif;
    color #555;
}
h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 {
    margin-top: 0;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serfi;
    font-weight: normal;
    color: #333;
}
.footer {
    position: absolute;
    margin-left : 0px
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #f5f5f5;
}
.blog-header {
    padding-top: 20px;
    padding-bottom: 20px;
}

.blog-title {
    margin-top: 30px;
    margin-bottom: 0;
    font-size: 28px;
    font-weight: normal;
}
.blog-description{
    font-size: 20px;
    color: #999;
}
.sidebar-module{
    padding: 15px;
    margin: 0 -15px 15px;
}
.sidebar-module-inset {
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
}
.sidebar-module-inset p:last-child,
.sidebar-module-inset ul:last-child,
.sidebar-module-inset ol:last-child{
    margin-bottom: 0;
}
.pager {
    margin-bottom: 60px;
    text-align: left
}
.pager > li > a {
    width: 140px;
    padding: 10px 20px;
    text-align: center;
    border-radius: 30px;
}
.blog-post{
    margin-bottom: 60px;
}
.blog-post-title{
    margin-bottom: 5px;
    font-size: 40px;
}
.blog-post-meta {
    margin-bottom: 20px;
    color : #999;
}
body > container {
    padding: 0px 0px 0;
}
.container .text-muted {
    margin: 20px 0;
}
.footer > .container {
    padding-right: 15px;
    padding-left: 0;
}
.row {
    margin-right: 0px!important;
}

Body:
The issue is in the line

 <h1 class="blog-title">Patch's Soapbox</h1>

You can tell what the problem is because all the text beyond this point is in red.

The single quote in Patch's is telling HTML that everything after this point is a string. You need to us a replacement by using:

<h1 class="blog-title">Patch&#39;s Soapbox</h1>


问:
Crud em reactjs
I am studying react js and am creating a simple library design for book control. I'm good at the beginning of my studies and would like to implement a CRUD of books.

I perfectly created the layout and the routes. When I navigate to the book route, I will create a code to list the books. Only from this view / component, I want to create a code that I still do not know how to create the book registration and update view. But I want to call these new screens from the book listing screen. DO NOT WANT TO PLACE EVERYTHING ON A SINGLE VIEW! THAT I CAN DO.

Here's the code I'm doing for you to understand better.

https://github.com/wagnergrilo85/library-react/blob/master/src/screens/book/Book.js

答:
Your file structure can look like this :

Book.js (here you can handle data, from this component you can manage all smaller component )

import React from 'react';
import BookList from './bookList';

class Book extends React.Component {

        constructor(){
            super()
            this.state = {
                books: [],
                book: {},
            }
        }

        componentDidMount(){
            // Here you will call API to get full list of book
            // this.setState(books: responseApi)
        }

        showBook(id){
            // Find the single book
            // this.setState(book: responseApi)
        }

        updateBook(id, data){
            // Find the single book
            // Get new data
            // Update API
        }

        deleteBook(id){
            // Find the single book
            // Delete book in API
        }

        render(){

            return(

                    <BookList books={this.state.books} />

            )
        }
}```

BookList.js (show list)

BookShow.js (show single book info)

BookUpdate.js

BookCreate.js

BookForm.js

You can start from there and find the rest by yourself

Title: Crud em reactjs

Body:
Your file structure can look like this :

Book.js (here you can handle data, from this component you can manage all smaller component )

import React from 'react';
import BookList from './bookList';

class Book extends React.Component {

        constructor(){
            super()
            this.state = {
                books: [],
                book: {},
            }
        }

        componentDidMount(){
            // Here you will call API to get full list of book
            // this.setState(books: responseApi)
        }

        showBook(id){
            // Find the single book
            // this.setState(book: responseApi)
        }

        updateBook(id, data){
            // Find the single book
            // Get new data
            // Update API
        }

        deleteBook(id){
            // Find the single book
            // Delete book in API
        }

        render(){

            return(
                <div>
                    <BookList books={this.state.books} />
                </div>
            )
        }
}

BookList.js (show list)

BookShow.js (show single book info)

BookUpdate.js

BookCreate.js

BookForm.js

You can start from there and find the rest by yourself


问:
MS Access Autonumber Field Set Start Index
Is there a way to set the start index of autonumber field in ms access?

It's start on 1 and i want it start at 1000

答: Use INSERT SQL query to add one record with ID=999 and delete it. Next autonumber ID will be 1000


问:
Fill HTML element with text based on input with JavaScript
The code right now works only to fill another input field. But I need it to fill a regular paragraph and not another input field. How can I do it?

$(".first").on('keydown',function(){
  $(".second").val($(this).val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="first" placeholder="type here">
<input type="text" class="second" placeholder="here it is the reuslt"></code>```

答:
Use the text function to insert the text into the element.

id's and classes can be used to specify either a specific element (id) or a group of elements (class). In the example below I added a class to change the colour of each
 tag using css to red. In our JS we select on individual id's.

//selecting on the insertTextHere id to specify the
 tag to insert text into
$("#first").on('keyup', function() {
  $("#insertTextHere").text($(this).val());
});

//you can even set it up to revert back to the original text on click
$("#resetButton").on("click", function() {
  var resetText = "Type into input to overwrite this text";
  //insert original string as text
  $("#insertTextHere").text(resetText);
  //empty the input value
  $("#first").val("");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.text {
  color: red;
}</code>```

<input type="text" id="first" placeholder="type here">
<button id="resetButton" type="button">reset text</button>

Type into input to overwrite this text

This text will not be overwritten

```

Body:
The code right now works only to fill another input field. But I need it to fill a regular paragraph and not another input field. How can I do it?

$(".first").on('keydown',function(){
  $(".second").val($(this).val());
});

<input type="text" class="first" placeholder="type here">
<input type="text" class="second" placeholder="here it is the reuslt">

Body:
Use the text function to insert the text into the element.

id's and classes can be used to specify either a specific element (id) or a group of elements (class). In the example below I added a class to change the colour of each <p> tag using css to red. In our JS we select on individual id's.

//selecting on the insertTextHere id to specify the <p> tag to insert text into
$("#first").on('keyup', function() {
  $("#insertTextHere").text($(this).val());
});

//you can even set it up to revert back to the original text on click
$("#resetButton").on("click", function() {
  var resetText = "Type into input to overwrite this text";
  //insert original string as text
  $("#insertTextHere").text(resetText);
  //empty the input value
  $("#first").val("");
});

.text {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="first" placeholder="type here">
<button id="resetButton" type="button">reset text</button>
<div>
  <p id="insertTextHere" class="text">Type into input to overwrite this text</p>
  <p class="text">This text will not be overwritten</p>
</div>


问:
Controls do not resize when maximised but do when resized by dragging - wpf
Question is as per
WPF: when I maximize my window, controls do not resize which is unanswered.

I have a WPF form with some controls which are tied to at least two edges of the form. I have added code to sizechanged event which resizes controls as a ratio of form size. The code works well and when the form is resized by dragging the controls resize correctly.

When form is maximized the controls do not resize, save for vertically on the controls attached to both top and bottom of the window.

I have added similar code to the statechanged event however this does nothing. I have tried a straight TextBox1.Width = 300; but this does not change the size once maximised.

Ideally what I want is for say
TextBox1.Width = Window.width/3; TextBox1.Margin = My_Margin; Where My_Margin sets the left margin to 1/3 Window.Width. So that the textbox occupies the central third of the window.

EDIT: I understand that the GRID method was the way to go from the start of the project. Is there a workaround I can do at this stage in c# instead of having to rework the form?

EDIT: Have accepted the best answer, though it does not answer the actual question, as it looks like the only option I have.
I know that there is a way to resize controls once the form is maximized, I don't have time to find it and no good suggestions came forth.

答:
Use a grid, define columns (with their width) and rows, and place the textbox using Grid.Row and Grid.Column properties. Also in a WPF Grid, * for Width and Height means proportional sizing.
So for instance if you have 2 columns defined like these ones

```<code><Grid.ColumnDefinitions>
     <ColumnDefinition Width="1*"></ColumnDefinition>
     <ColumnDefinition Width="9*"></ColumnDefinition>
</Grid.ColumnDefinitions>
</code>```

you are saying to wpf that the first column will occupy the 10% of the total available width, while the second 90%.

Body:
Use a grid, define columns (with their width) and rows, and place the textbox using Grid.Row and Grid.Column properties. Also in a WPF Grid, * for Width and Height means proportional sizing.
So for instance if you have 2 columns defined like these ones

<Grid.ColumnDefinitions>
     <ColumnDefinition Width="1*"></ColumnDefinition>
     <ColumnDefinition Width="9*"></ColumnDefinition>
</Grid.ColumnDefinitions>

you are saying to wpf that the first column will occupy the 10% of the total available width, while the second 90%.


问:
Find the number of multiples for a number in range
I have a question regarding the CountDiv problem in Codility.

The problem given is: Write a function:

```<code>class Solution { public int solution(int A, int B, int K); }
</code>```

that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:

```<code>{ i : A ≤ i ≤ B, i mod K = 0 }
</code>```

My code:

```<code>class Solution {
    public int solution(int A, int B, int K) {
         int start=0;
         if (B<A || K==0 || K>B )
            return 0;
         else if (K<A)
            start = K * ( A/K +1);
         else if (K<=B)
            start = K;

         return (B-start+1)/K+ 1;
    }
}
</code>```

I don't get why I'm wrong, specially with this test case:

```<code>extreme_ifempty
A = 10, B = 10, K in {5,7,20}
WRONG ANSWER
got 1 expected 0
</code>```

if K =5 then with i=10 A<=i<=B and i%k =0 so why should I have 0? Problem statement.

答:
```<code>int solution(int A, int B, int K)
{
    // write your code in C++14 (g++ 6.2.0)
    int counter = 0;

    if (A == B)
        A % K == 0 ? counter++ : 0;
    else
    {
        counter = (B - A) / K;

        if (A % K == 0) counter++;
        else if (B % K == 0) counter++;
        else if ((counter*K + K) > A && (counter*K + K) < B) counter++;
    }

    return counter;
}
</code>```

Body:
I have a question regarding the CountDiv problem in Codility.

The problem given is: Write a function:

class Solution { public int solution(int A, int B, int K); }

that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:

{ i : A ≤ i ≤ B, i mod K = 0 }

My code:

class Solution {
    public int solution(int A, int B, int K) {
         int start=0;
         if (BB )
            return 0;
         else if (K<A)
            start = K * ( A/K +1);
         else if (K<=B)
            start = K;

         return (B-start+1)/K+ 1;
    }
}

I don't get why I'm wrong, specially with this test case:

extreme_ifempty
A = 10, B = 10, K in {5,7,20}
WRONG ANSWER
got 1 expected 0

if K =5 then with i=10 A<=i<=B and i%k =0 so why should I have 0? Problem statement.


问:
Change position p:dialog when I resize the page
i'm a problem with a p:dialog.

Here the code:

```<code>        <p:dialog id="loginDialog" header="Login" width="400" widgetVar="dlg" visible="true"
            rendered="#{loginBean.f_loginRendered}" closable="false" showEffect="clip" draggable="false" resizable="false"
            style="box-shadow: 7px 10px 5px #303030; position:absolute;">
            <h:panelGrid id="panelGrid" columns="2" cellpadding="5" style="margin: 0 auto;">
                <h:outputLabel for="username" value="Username: *" />
                <p:inputText id="username" value="#{loginBean.f_username}" required="true" label="Username"/>
                <h:outputLabel for="password" value="Password: *" />
                <p:password id="password" value="#{loginBean.f_password}" required="true" label="Password"/>

<center>            <p:commandButton id="loginButton" value="Login" update="globalGrowl" actionListener="#{loginBean.checkDown}" /> </center>
        </h:panelGrid >

        </p:dialog>
</code>```

It's a simple login form. The problem is that when I resize the webpage, the dialog is fixed and it does not move by following the page, unlike the pictures.

How I can do it?

答: I would recommend to place it with css instead of jquery. The jquery resize event in this case, can lead to performance lags.</p>

Body:
i'm a problem with a p:dialog.

Here the code:

            <h:panelGrid id="panelGrid" columns="2" cellpadding="5" style="margin: 0 auto;">
                <h:outputLabel for="username" value="Username: *" />

                <h:outputLabel for="password" value="Password: *" />

        </h:panelGrid >

It's a simple login form. The problem is that when I resize the webpage, the dialog is fixed and it does not move by following the page, unlike the pictures.

How I can do it?


问:
Add header to http request
My first post here.
I'm using droidscript and I have to include an header that contains a specific user and a password in order to retrieve a token. I'm having trouble because I don't know where to include those headers.

That's the code I'm using:

```<code>function btn_OnTouch(){

    var url = "myurl";
    SendRequest(url);

}

//Send an http get request.

function SendRequest(url){

    var httpRequest = new XMLHttpRequest();

    httpRequest.onreadystatechange = function() {
        HandleReply(httpRequest);
    };

    httpRequest.open("GET", url, true);

    httpRequest.send(null);

    app.ShowProgress("Loading...");

}

//Handle the servers reply (a json object).

function HandleReply(httpRequest){

    if (httpRequest.readyState == 4){

        //If we got a valid response.

        if (httpRequest.status == 200){
            txt.SetText("Response: " + httpRequest.status + httpRequest.responseText);
        }

        //An error occurred
        else
            txt.SetText("Error: " + httpRequest.status + httpRequest.responseText);

    }

    app.HideProgress();

}
</code>```

The told me I should probably include the headers like this, but I don't know where to put them in my code.

```<code>httpRequest.setRequestHeader(“username”, “myuser”);

httpRequest.setRequestHeader(“password”, “mypass”);
</code>```

答:
You need to do it just after calling the open method like this:-</p>

```<code>httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("username", "myuser");
httpRequest.setRequestHeader("password", "mypass");
httpRequest.send(null);
</code>```

Title: Add header to http request

Body:
My first post here.
I'm using droidscript and I have to include an header that contains a specific user and a password in order to retrieve a token. I'm having trouble because I don't know where to include those headers.

That's the code I'm using:

function btn_OnTouch(){

    var url = "myurl";
    SendRequest(url);

}

//Send an http get request.

function SendRequest(url){

    var httpRequest = new XMLHttpRequest();

    httpRequest.onreadystatechange = function() {
        HandleReply(httpRequest);
    };

    httpRequest.open("GET", url, true);

    httpRequest.send(null);

    app.ShowProgress("Loading...");

}

//Handle the servers reply (a json object).

function HandleReply(httpRequest){

    if (httpRequest.readyState == 4){

        //If we got a valid response.

        if (httpRequest.status == 200){
            txt.SetText("Response: " + httpRequest.status + httpRequest.responseText);
        }

        //An error occurred
        else
            txt.SetText("Error: " + httpRequest.status + httpRequest.responseText);

    }

    app.HideProgress();

}

The told me I should probably include the headers like this, but I don't know where to put them in my code.

httpRequest.setRequestHeader(“username”, “myuser”);

httpRequest.setRequestHeader(“password”, “mypass”);

Body:
You need to do it just after calling the open method like this:-

httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("username", "myuser");
httpRequest.setRequestHeader("password", "mypass");
httpRequest.send(null);


问:
Excel and SSAS solution with Azure
We have a basic BI solution using SQL Server Analysis Services (SSAS) on top of a SQL Server Database updated by a standard 'line-of-business' systems.

Desktop Excel is used to connect to the Data Cubes and tandard Pivot table functionality used to create reports, run ad-hoc queries etc.

Question: Is there a way to move this partially or fully to Azure? What would be the best architecture?  e.g.

Can the application uses an azure-based SQL Server database as if it was a local database.

Can the data from this be ETL'ed using SSIS into SSAS all in the cloud

Can users access these cloud-based data cubes either via their desktop Excel or else via Excel 365 or some such (MS seem to have some product called Power BI which may be involved)

Is the cost of moving and processing fairly large amounts of data (500k+ records per day) prohibitive?

答: I had the same problem so I created a database in azure as "data warehouse" and upload the data in a daily basis. Then I use Analysis Services in azure with the data source "data warehouse" to create the models, now users can connect to the models directly to the cubes using excel or Power-bi from the azure portal. The solution is not that expensive, the most expensive is the Analysis services, and you can change the tiers as you need.</p>

Title: Excel and SSAS solution with Azure


问:
Angular2 validator which relies on multiple form fields
Is it possible to create a validator which can use multiple values to decide if my field is valid?

e.g. if the customer's preferred contact method is by email then the email field should be required.

Thanks.

Updated with example code...

    import {Component, View} from 'angular2/angular2';
    import {FormBuilder, Validators, formDirectives, ControlGroup} from 'angular2/forms';

    @Component({
        selector: 'customer-basic',
        viewInjector: [FormBuilder]
    })
    @View({
        templateUrl: 'app/components/customerBasic/customerBasic.html',
        directives: [formDirectives]
    })
    export class CustomerBasic {
        customerForm: ControlGroup;

        constructor(builder: FormBuilder) {
            this.customerForm = builder.group({
                firstname: [''],
                lastname: [''],
                validateZip: ['yes'],
                zipcode: ['', this.zipCodeValidator]
                // I only want to validate using the function below if the validateZip control is set to 'yes'
            });
        }

        zipCodeValidator(control) {
            if (!control.value.match(/\d\d\d\d\d(-\d\d\d\d)?/)) {
                return { invalidZipCode: true };
            }
        }

    }
```

答:
I tried most of these answers but none of them worked for me. I found a working example here
https://scotch.io/@ibrahimalsurkhi/match-password-validation-with-angular-2</p>


问:
Bootstrap animation doesn't work as expected
You can find bootstrap animations here. I want to remove the animation after it finished. On the website you can find a trigger which should help with that.
The problem is, that when I click the button, the classes get deleted immediately.</p>

```<code><button class="btn btn-primary" onclick="foo(this)">Press here</button>
<script>
function foo(element){
    $(element).addClass("animated shake");
    $(element).on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', $(element).removeClass("animated shake"));
    }
</script>
</code>```

答:
Just add a Timeout for the duration of your animation, to wait until the animaton is finished:</p>

```<code>function foo(element){
    $(element).addClass("animated shake");
    var duration = $(element).css("animation-duration");
    setTimeout(function() {
        $(element).removeClass("animated shake");
    }, duration);
}
</code>```

Body:
You can find bootstrap animations here. I want to remove the animation after it finished. On the website you can find a trigger which should help with that.
The problem is, that when I click the button, the classes get deleted immediately.

<button class="btn btn-primary" onclick="foo(this)">Press here</button>

Body:
Just add a Timeout for the duration of your animation, to wait until the animaton is finished:

function foo(element){
    $(element).addClass("animated shake");
    var duration = $(element).css("animation-duration");
    setTimeout(function() {
        $(element).removeClass("animated shake");
    }, duration);
}


问:
Get the absolute position of a div relative to the window
This question is quite similar to what I want I'm looking for, but my situation is different enough, I think, to merit a new question.

I have several divs positioned absolutely inside of a parent div (position: relative). I want to get the position of the children divs relative to the window. The jquery offset() method doesn't seem to work, because it gives me the offset from the parent div. Is there a way to get the absolute position of a div that has absolute position inside of a relative position div?

Sample html:

```<code><div id="parent" style="position:relative;">
  <div id="child1" style="position:absolute; top:10px; left 8px;">Child 1</div>
  <div id="child2" style="position:absolute; top:20px; left 8px;">Child 2</div>
</div>
</code>```

答:
Hi
Use the position () function of jQuery library.

Create a Div called Stage and another called Content.
On Stage Div write position absolute, top and left. In Div Content type position absolute, top and left too.

Ok?

Body:
This question is quite similar to what I want I'm looking for, but my situation is different enough, I think, to merit a new question.

I have several divs positioned absolutely inside of a parent div (position: relative). I want to get the position of the children divs relative to the window. The jquery offset() method doesn't seem to work, because it gives me the offset from the parent div. Is there a way to get the absolute position of a div that has absolute position inside of a relative position div?

Sample html:

Child 1

Child 2


问:
How to change image's href with Javascript by using title name?
Here in this slideshow there are around 50 images. I use a platform which is similar to wordpress and doesnt let me to change image href. The images have the same class name. Is it possible to use title name(which is unique for each image) and change some image's href?</p>

```<code><div id="slideshow" class="vlt-d-slider" style="position: relative; overflow: hidden; width: 928px; height: 522px;">
    <div class="slide" data-vltcaption="0" data-brand="none" data-topic="INST" data-url="_0.jpg" style="position: absolute; left: 0px; visibility: visible; z-index: 3; line-height: 520px; height: 522px;">
<a class="slide-lightbox" rel="vlt-slideshow" href="m_0.jpg" title="Pfusc number photo 1" target="_blank">
<img class="slide-img" src="_0.jpg" alt="Pfusc number photo 1">
</a>
</div>
      <div class="slide" data-vltcaption="1" data-brand="none" data-topic="INST" data-url="0.jpg" style="position: absolute; left: 0px; visibility: hidden; z-index: 1; line-height: 520px; display: block; height: 522px;">
<a class="slide-lightbox" rel="vlt-slideshow" href="f_0.jpg" title="Pfusc number photo 2" target="_blank">
<img class="slide-img" src="0.jpg" alt="Pfusc number photo 2">
</a>
</div>
      <div class="slide" ....
</div>
    </div>
</code>```

答:
Firstly, images don't have href, they have src.

Secondly, I think you mean alt when you say "title name"?

In that case, document.querySelector('[alt="the title"]').src = 'the new src';

If you want to find it by the title of the link, you would have to do document.querySelector('a[title="the title"] > img').src = 'the new src';

Body:
Here in this slideshow there are around 50 images. I use a platform which is similar to wordpress and doesnt let me to change image href. The images have the same class name. Is it possible to use title name(which is unique for each image) and change some image's href?

      <div class="slide" ....