问:
Using node.js and promise to fetch paginated data
Please keep in mind that I am new to node.js and I am used with android development.

My scenario is like this:

Run a query against the database that returns either null or a value

Call a web service with that database value, that offers info paginated, meaning that on a call I get a parameter to pass for the next call if there is more info to fetch.

After all the items are retrieved, store them in a database table

If everything is well, for each item received previously, I need to make another web call and store the retrieved info in another table

if fetching any of the data set fails, all data must be reverted from the database

So far, I've tried this:

```<code>getAllData: function(){
  self.getMainWebData(null)
     .then(function(result){
       //get secondary data for each result row and insert it into database
   }
}

getMainWebData: function(nextPage){
    return new Promise(function(resolve, reject) {

      module.getWebData(nextPage, function(errorReturned, response, values) {

    if (errorReturned) {
          reject(errorReturned);
        }

        nextPage = response.nextPageValue;
        resolve(values);
      })
    }).then(function(result) {

    //here I need to insert the returned values in database

      //there's a new page, so fetch the next set of data
      if (nextPage) {
          //call again getMainWebData?
          self.getMainWebData(nextPage)
      }

    })
</code>```

There are a few things missing, from what I've tested, getAllData.then fires only one for the first set of items and not for others, so clearly handling the returned data in not right.

LATER EDIT: I've edited the scenario. Given some more research my feeling is that I could use a chain or .then() to perform the operations in a sequence.

答:
Yes it is happening as you are resolving the promise on the first call itself. You should put resolve(value) inside an if statement which checks if more data is needed to be fetched. You will also need to restructure the logic as node is asynchronous. And the above code will not work unless you do change the logic.

Solution 1:

You can either append the paginated response to another variable outside the context of the calls you are making. And later use that value after you are done with the response.

```<code>getAllData: function(){
  self.getMainWebData(null)
  .then(function(result){
       // make your database transaction if result is not an error
   }
}

function getList(nextpage, result, callback){
  module.getWebData(nextPage, function(errorReturned, response, values) {
    if(errorReturned)
      callback(errorReturned);
    result.push(values);
    nextPage = response.nextPageValue;
    if(nextPage)
      getList(nextPage, result, callback);
    else
      callback(null, result);
  })
}
getMainWebData: function(nextPage){
  return new Promise(function(resolve, reject) {
    var result = [];
    getList(nextpage, result, function(err, results){
      if(err)
        reject(err);
      else{
        // Here all the items are retrieved, you can store them in a database table
        //  for each item received make your web call and store it into another variable or result set
        // suggestion is to make the database transaction only after you have retrieved all your data
        // other wise it will include database rollback which will depend on the database which you are using
        // after all this is done resolve the promise with the returning value
        resolve(results);
      }
    });
  })
}
</code>```

I have not tested it but something like this should work. If problem persists let me know in comments.

Solution 2:

You can remove promises and try the same thing with callback as they are easier to follow and will make sense to the programmers who are familiar with structural languages.

Body:
Please keep in mind that I am new to node.js and I am used with android development.

My scenario is like this:

Run a query against the database that returns either null or a value

Call a web service with that database value, that offers info paginated, meaning that on a call I get a parameter to pass for the next call if there is more info to fetch.

After all the items are retrieved, store them in a database table

If everything is well, for each item received previously, I need to make another web call and store the retrieved info in another table

if fetching any of the data set fails, all data must be reverted from the database

So far, I've tried this:

getAllData: function(){
  self.getMainWebData(null)
     .then(function(result){
       //get secondary data for each result row and insert it into database
   }
}

getMainWebData: function(nextPage){
    return new Promise(function(resolve, reject) {

      module.getWebData(nextPage, function(errorReturned, response, values) {

    if (errorReturned) {
          reject(errorReturned);
        }

        nextPage = response.nextPageValue;
        resolve(values);
      })
    }).then(function(result) {

    //here I need to insert the returned values in database

      //there's a new page, so fetch the next set of data
      if (nextPage) {
          //call again getMainWebData?
          self.getMainWebData(nextPage)
      }

    })

There are a few things missing, from what I've tested, getAllData.then fires only one for the first set of items and not for others, so clearly handling the returned data in not right.

LATER EDIT: I've edited the scenario. Given some more research my feeling is that I could use a chain or .then() to perform the operations in a sequence.

Body:
Yes it is happening as you are resolving the promise on the first call itself. You should put resolve(value) inside an if statement which checks if more data is needed to be fetched. You will also need to restructure the logic as node is asynchronous. And the above code will not work unless you do change the logic.

Solution 1:

You can either append the paginated response to another variable outside the context of the calls you are making. And later use that value after you are done with the response.

getAllData: function(){
  self.getMainWebData(null)
  .then(function(result){
       // make your database transaction if result is not an error
   }
}

function getList(nextpage, result, callback){
  module.getWebData(nextPage, function(errorReturned, response, values) {
    if(errorReturned)
      callback(errorReturned);
    result.push(values);
    nextPage = response.nextPageValue;
    if(nextPage)
      getList(nextPage, result, callback);
    else
      callback(null, result);
  })
}
getMainWebData: function(nextPage){
  return new Promise(function(resolve, reject) {
    var result = [];
    getList(nextpage, result, function(err, results){
      if(err)
        reject(err);
      else{
        // Here all the items are retrieved, you can store them in a database table
        //  for each item received make your web call and store it into another variable or result set
        // suggestion is to make the database transaction only after you have retrieved all your data
        // other wise it will include database rollback which will depend on the database which you are using
        // after all this is done resolve the promise with the returning value
        resolve(results);
      }
    });
  })
}

I have not tested it but something like this should work. If problem persists let me know in comments.

Solution 2:

You can remove promises and try the same thing with callback as they are easier to follow and will make sense to the programmers who are familiar with structural languages.


来源: stackexchange

问:
C# Retrieve Stored Procedures from MySQL
Good Afternoon,

We are currently working on a tool, which retrieves all the Stored Procedures in a given database, which then extracts each Table being used in each Stored Procedure.

Currently, I got all of the Stored Procedures in a List, don't know if there are any parsers available that I can pass the Stored Procedure and returns the Tables being used.

The plan is then to link each Stored Procedure with the Tables being used in a Graph Database.

Thanks

答:
I think there is no prewrited methods to get that. You have to request the database tables, then check in each stored procedure query if it contains the table name.

```<code> SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
</code>```

This query will return the tables in the database

ContentLicense: CC BY-SA 3.0

Body:
I think there is no prewrited methods to get that. You have to request the database tables, then check in each stored procedure query if it contains the table name.

 SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

This query will return the tables in the database


问:
how to return value from tryAdvance method in Java8's spliterator?
I am new to Java 8 and trying to understand the splitIterator feature of java8.

I have written below code, my requirement is whenever I call get(); the get method should return me one value from itr3; Is it possible to get the same? and how?

```<code>public class TestSplitIterator {

static List<Integer> list = new ArrayList<Integer>();

public static void main(String args[]) {

    for (int i = 0; i < 100; i++) {
        list.add(i);
    }
    // below method call should return only one value whenever i call it;
    get(list);
}

private static int get(List<Integer> list) {
    Collections.sort(list, Collections.reverseOrder());

    System.out.println(list);

    Spliterator<Integer> itr1 = list.spliterator();
    Spliterator<Integer> itr2 = itr1.trySplit();
    Spliterator<Integer> itr3 = itr2.trySplit();
    // i want to return value from itr3 whenever get(List list ic called)

  }

}
</code>```

答:
If I don't misunderstand you. you need a collector object that collect the elements in a spliterator. for example:

```<code>Integer[] collector = new Integer[1];

boolean exist = itr3.tryAdvance(value -> collector[0] = value);

System.out.println(collector[0]);
</code>```

OR collect all of the elements in a spliterator by using another List, for example:

```<code>List<Integer> collector = new ArrayList<>();

while (itr3.tryAdvance(collector::add)) ;

System.out.println(collector);
</code>```

Body:
I am new to Java 8 and trying to understand the splitIterator feature of java8.

I have written below code, my requirement is whenever I call get(); the get method should return me one value from itr3; Is it possible to get the same? and how?

public class TestSplitIterator {

static List<Integer> list = new ArrayList<Integer>();

public static void main(String args[]) {

    for (int i = 0; i < 100; i++) {
        list.add(i);
    }
    // below method call should return only one value whenever i call it;
    get(list);
}

private static int get(List<Integer> list) {
    Collections.sort(list, Collections.reverseOrder());

    System.out.println(list);

    Spliterator<Integer> itr1 = list.spliterator();
    Spliterator<Integer> itr2 = itr1.trySplit();
    Spliterator<Integer> itr3 = itr2.trySplit();
    // i want to return value from itr3 whenever get(List list ic called)

  }

}

Body:
If I don't misunderstand you. you need a collector object that collect the elements in a spliterator. for example:

Integer[] collector = new Integer[1];

boolean exist = itr3.tryAdvance(value -> collector[0] = value);

System.out.println(collector[0]);

OR collect all of the elements in a spliterator by using another List, for example:

List<Integer> collector = new ArrayList<>();

while (itr3.tryAdvance(collector::add)) ;

System.out.println(collector);


问:
CrossTable output to excel in R
When producing contingency tables I'm using the function CrossTable in R because it is the most informative and flexible that I have managed to find, and it gives you a lot of stuff right away without the need to calculate it seperately.
However, the ouput it generates is a text output that is aimed mainly for the console in R. This is a big problem for me because I'm relying on outputing these kind of tables to excel at the next step of the analysis.

Is there any way to output the CrossTable output to an Excel spreadsheet so that each number will be in its own cell? (i.e., not as text that goes entirely to a single cell) ("text to columns" does not help)

答:
```<code># obtaining data
library('gmodels')
data(infert, package = "datasets")
# asign the result to object
d <- CrossTable(infert$education, infert$induced, expected = TRUE)
# now you can use d object to build something you could save using
# `write.table` to csv or directly to xlsx by other methods

# use str(d) to study structure of returned object
str(d)
</code>```

Title: CrossTable output to excel in R


问:
How do I remove JSON form JSON array with repeated key-value
I have a JSON as follows:

```<code>[{"name": "John", "id": 1},
 {"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]
</code>```

I want to first identify if key "id" has same value. If yes, I want to remove previous JSON with the same "id" so that I get following JSON with unique "id" values in the JSON Array.

```<code>[{"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]
</code>```

How do I achieve this in javascript?

答:
You can use reduceRight to start loop from the end and add to new array if there wasn't element with same id.

var data = [{"name": "John", "id": 1}, {"name": "Don", "id": 2}, {"name": "Tom", "id": 3}, {"name": "NewJohn", "id": 1}, {"name": "Tim", "id": 4}]

var result = []
data.reduceRight(function(r, e) {
  if(!r[e.id]) {
    result.unshift(e);
    r[e.id] = 1;
  }
  return r;
}, {})

console.log(result)```

Body:
I have a JSON as follows:

[{"name": "John", "id": 1},
 {"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]

I want to first identify if key "id" has same value. If yes, I want to remove previous JSON with the same "id" so that I get following JSON with unique "id" values in the JSON Array.

[{"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]

How do I achieve this in javascript?


问:
Times / Rotas on SQL
Hello  I am trying to show a rota in sql but now stuck

I have tried a few things but seem way off the mark!

Essentially my data returned is

```<code>Name            | Role   | RotaDate              | StartTime             | EndTime
Joe Bloggs      |Cleaner |2017-01-09 00:00:00.000|1900-01-01 19:00:00.000|1900-01-02 07:15:00.000
Joe Bloggs      |Cleaner |2017-01-11 00:00:00.000|1900-01-01 19:00:00.000|1900-01-02 07:15:00.000
</code>```

So this is a shift on 9th Jan from 7pm - 7:15am.  There are other dates / times etc but this is just a snippet.

I would like it returned as the following (assuming he has shifts on the 11th as well for example

```<code>Name-------|Role-------| 09/01----------| 10/01 | 11/01

Joe Bloggs | Cleaner | 19:00-07:15 |           |19:00-0715
</code>```

Any help would be appreciated (both this and the layout!

My attempt was

```<code>select name, role, date,convert(datetime, r.timeFrom+' - '+convert(datetime,r.timeTo) as Shift
max (CASE when r.rotadate='2017-01-09' THEN timeFrom else 0 END) as '2017-01-09',
max (CASE when r.rotadate='2017-01-10' THEN timeFrom else 0 END) as '2017-01-10'
from rota
</code>```

where rota date between '2017-01-09' and '2017-01-13'

答:
Firstly i created sample data and converted the data in to required format

```<code>IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp
;With cte(Name,[Role],RotaDate, StartTime ,EndTime )
AS
(
SELECT 'Joe Bloggs','Cleaner' ,'2017-01-09 00:00:00.000','1900-01-01 19:00:00.000','1900-01-02 07:15:00.000' Union all
SELECT 'Joe Bloggs','Cleaner' ,'2017-01-11 00:00:00.000','1900-01-01 19:00:00.000','1900-01-02 07:15:00.000'
)
SELECT NAME
    ,[Role]
    ,LEFT(RotaDate, 10) AS RotaDate
    ,StartTime
    ,SUBSTRING(EndTime, CHARINDEX(' ', EndTime, 1) + 1, LEN(EndTime)) AS EndTime
    ,STUFF((
            SELECT DISTINCT '- ' + CAST(SUBSTRING(StartTime, CHARINDEX(' ', StartTime, 1) + 1, 5) AS VARCHAR(19))
                                 + '-' + CAST(SUBSTRING(EndTime, CHARINDEX(' ', EndTime, 1) + 1, 5) AS VARCHAR(19))
            FROM cte
            FOR XML PATH('')
            ), 1, 1, '') AS StartTimeENDTime
INTO #temp
FROM cte
</code>```

Then using pivot we get desired result

```<code>SELECT NAME
    ,[Role]
    ,ISNULL([2017-01-09],'') AS [09/01]
    ,ISNULL([2017-01-10],'') AS [10/01]
    ,ISNULL([2017-01-11],'') AS [11/01]
FROM (
    SELECT *
    FROM #temp
    ) AS Src
PIVOT(MIN(StartTimeENDTime) FOR RotaDate IN (
            [2017-01-09]
            ,[2017-01-10]
            ,[2017-01-11]
            )) AS PVT
</code>```

Result

```<code>             NAME       Role        09/01         10/01     11/01
            -----------------------------------------------------------
            Joe Bloggs  Cleaner    19:00-07:15              19:00-07:15
</code>```

Title: Times / Rotas on SQL

Body:
Hello  I am trying to show a rota in sql but now stuck

I have tried a few things but seem way off the mark!

Essentially my data returned is

Name            | Role   | RotaDate              | StartTime             | EndTime
Joe Bloggs      |Cleaner |2017-01-09 00:00:00.000|1900-01-01 19:00:00.000|1900-01-02 07:15:00.000
Joe Bloggs      |Cleaner |2017-01-11 00:00:00.000|1900-01-01 19:00:00.000|1900-01-02 07:15:00.000

So this is a shift on 9th Jan from 7pm - 7:15am.  There are other dates / times etc but this is just a snippet.

I would like it returned as the following (assuming he has shifts on the 11th as well for example

Name-------|Role-------| 09/01----------| 10/01 | 11/01

Joe Bloggs | Cleaner | 19:00-07:15 |           |19:00-0715

Any help would be appreciated (both this and the layout!

My attempt was

select name, role, date,convert(datetime, r.timeFrom+' - '+convert(datetime,r.timeTo) as Shift
max (CASE when r.rotadate='2017-01-09' THEN timeFrom else 0 END) as '2017-01-09',
max (CASE when r.rotadate='2017-01-10' THEN timeFrom else 0 END) as '2017-01-10'
from rota

where rota date between '2017-01-09' and '2017-01-13'

Body:
Firstly i created sample data and converted the data in to required format

IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp
;With cte(Name,[Role],RotaDate, StartTime ,EndTime )
AS
(
SELECT 'Joe Bloggs','Cleaner' ,'2017-01-09 00:00:00.000','1900-01-01 19:00:00.000','1900-01-02 07:15:00.000' Union all
SELECT 'Joe Bloggs','Cleaner' ,'2017-01-11 00:00:00.000','1900-01-01 19:00:00.000','1900-01-02 07:15:00.000'
)
SELECT NAME
    ,[Role]
    ,LEFT(RotaDate, 10) AS RotaDate
    ,StartTime
    ,SUBSTRING(EndTime, CHARINDEX(' ', EndTime, 1) + 1, LEN(EndTime)) AS EndTime
    ,STUFF((
            SELECT DISTINCT '- ' + CAST(SUBSTRING(StartTime, CHARINDEX(' ', StartTime, 1) + 1, 5) AS VARCHAR(19))
                                 + '-' + CAST(SUBSTRING(EndTime, CHARINDEX(' ', EndTime, 1) + 1, 5) AS VARCHAR(19))
            FROM cte
            FOR XML PATH('')
            ), 1, 1, '') AS StartTimeENDTime
INTO #temp
FROM cte

Then using pivot we get desired result

SELECT NAME
    ,[Role]
    ,ISNULL([2017-01-09],'') AS [09/01]
    ,ISNULL([2017-01-10],'') AS [10/01]
    ,ISNULL([2017-01-11],'') AS [11/01]
FROM (
    SELECT *
    FROM #temp
    ) AS Src
PIVOT(MIN(StartTimeENDTime) FOR RotaDate IN (
            [2017-01-09]
            ,[2017-01-10]
            ,[2017-01-11]
            )) AS PVT

Result

             NAME       Role        09/01         10/01     11/01
            -----------------------------------------------------------
            Joe Bloggs  Cleaner    19:00-07:15              19:00-07:15


问:
I got an error [Type "View Controller" does not conform to protocol "ORKTaskViewControllerDelegate"]
I am just starting to use swift3 in Xcode in order to utilize ResearchKit provided by Apple.inc.
Although I have worked through tutorials from Researchkit Tutorial with Swift: Getting started in Ray Wenderlich, I have a trouble in the extension of ViewController. The following is my code.</p>

```<code>import ResearchKit
import UIKit

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

  @IBAction func consentTapped(sender : AnyObject) {
    let taskViewController = ORKTaskViewController(task: ConsentTask, taskRun: nil)
    taskViewController.delegate = self
    present(taskViewController, animated: true, completion: nil)
  }
}

extension ViewController: ORKTaskViewControllerDelegate {

  func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason
         reason: ORKTaskViewControllerFinishReason, error: NSError?) {
    //Handle results with taskViewController.result
    taskViewController.dismiss(animated:true, completion: nil)
  }
}
</code>```

答:
You've missed to add delegate. Add ORKTaskViewControllerDelegate to ViewController

```<code>class ViewController: UIViewController,ORKTaskViewControllerDelegate {
   override func viewDidLoad() {
    super.viewDidLoad(
   }
}
</code>```

Body:
I am just starting to use swift3 in Xcode in order to utilize ResearchKit provided by Apple.inc.
Although I have worked through tutorials from Researchkit Tutorial with Swift: Getting started in Ray Wenderlich, I have a trouble in the extension of ViewController. The following is my code.

import ResearchKit
import UIKit

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

  @IBAction func consentTapped(sender : AnyObject) {
    let taskViewController = ORKTaskViewController(task: ConsentTask, taskRun: nil)
    taskViewController.delegate = self
    present(taskViewController, animated: true, completion: nil)
  }
}

extension ViewController: ORKTaskViewControllerDelegate {

  func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason
         reason: ORKTaskViewControllerFinishReason, error: NSError?) {
    //Handle results with taskViewController.result
    taskViewController.dismiss(animated:true, completion: nil)
  }
}

Body:
You've missed to add delegate. Add ORKTaskViewControllerDelegate to ViewController

class ViewController: UIViewController,ORKTaskViewControllerDelegate {
   override func viewDidLoad() {
    super.viewDidLoad(
   }
}


问:
What are practical guidelines for evaluating a language's "Turing Completeness"?
I've read "what-is-turing-complete" and the wikipedia page, but I'm less interested in a formal proof than in the practical implications of requirements for being Turing Complete.

What I'm actually trying to decide is if the toy language I've just designed could be used as a general-purpose language.  I know I can prove it is if I can write a Turing machine with it.  But I don't want to go through that exercise until I'm fairly certain of success.

Is there a minimum set of features without which Turing Completeness is impossible?
Is there a set of features which virtually guarantees completeness?

(My guess is that conditional branching and a readable/writeable memory store will get me most of the way there)

EDIT:

I think I've gone off on a tangent by saying "Turing Complete".   I'm trying to guess with reasonable confidence that a newly invented language with a certain feature set (or alternately, a VM with a certain instruction set) would be able to compute anything worth computing.  I know that proving you can build a Turing machine with it is one way, but not the only way.

What I was hoping for was a set of guidelines like: "if a language can do X,Y,and Z, it can probably do anything".

答: I'm not sure if there's a "minimum set of features", but to prove that a language is Turing complete, you only have to prove that it can emulate another Turing complete system (not necessarily a Turing machine), as long as the other system is known to be Turing complete. http://en.wikipedia.org/wiki/Turing_complete#Examples has a whole list of Turing complete systems. Some of them are simpler than Turing machines.</p>

OwnerDisplayName: AShelly

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: AShelly

OwnerDisplayName: Nathan Stoddard

ContentLicense: CC BY-SA 2.5


问:
Oracle tns listener error
I've just installed Oracle 10g When I try to connect to oracle db i get an error:

could not start OracleOraHome92TNSListener

when i got to services and try to start it, it says that the file doesnt exist. the service file is C:\oracle\ora92\BIN\TNSLSNR (TNSLSNR is a file not a directory)

C:\oracle\ora92\BIN\TNSLSNR  doesn't exist on my machine at all. do you know how to get it?

Could not start the Oracle Ora92 Listener service on Local Computer.Error 2: The system cannot find the file specified

答:
Here's a couple of issues I see.  You say you installed 10g but the error is a 9.2 error.  It could be that your computer already had an Oracle 9i on it that was mis-configured or uninstalled and that is leading to the error.

You need to check your disk and find the ORACLE_HOME (directory) where Oracle 10g was installed.  Once you find that you can adjust the PATH and ORACLE_HOME and TNS_ADMIN environment variables to point to the right place.  This should allow you to start the database and the listener.

If you need to install the Oracle Client for 10g then this information below will be helpful as well.

The Oracle client can be installed separately. Just go to this address, download the client and unzip it into a subdirectory and then run the Oracle Universal Installer by running setup.exe from the directory.

Oracle Downloads Page

Title: Oracle tns listener error


问:
How to Using if Else statement in Array
im trying create if else statement, but not working,

this is  my code

```<code>$selected = (array) $_POST[gejala];
if($selected == "1"):
    print_msg('Belum ada gejala terpilih. <a href="?m=konsultasi">Kembali</a>');
else:
    print_msg('agsjhdgashjgdajhsgd');
</code>```

when im select 1 data but not displaying print_msg...

print_r when im select 2 data

```<code>Array
(
    [m] => hasil
    [gejala] => Array
        (
            [0] => G014
            [1] => G015
        )

)
</code>```

答:
As I have seen you form code you are posting multiple input fields values, so you need to run foreach loop get the every input fields value.

Please use the below code hope this will help:

```<code>$gejala = $_POST['gejala'];

foreach($gejala as $value) {

   $gejala = $value;
   if($gejala == "1"){
        print_msg('Belum ada gejala terpilih. <a href="?m=konsultasi">Kembali</a>');
   }else{
       print_msg('agsjhdgashjgdajhsgd');
   }
}
</code>```

Title: How to Using if Else statement in Array

Body:
im trying create if else statement, but not working,

this is  my code

$selected = (array) $_POST[gejala];
if($selected == "1"):
    print_msg('Belum ada gejala terpilih. Kembali');
else:
    print_msg('agsjhdgashjgdajhsgd');

when im select 1 data but not displaying print_msg...

print_r when im select 2 data

Array
(
    [m] => hasil
    [gejala] => Array
        (
            [0] => G014
            [1] => G015
        )

)

Body:
As I have seen you form code you are posting multiple input fields values, so you need to run foreach loop get the every input fields value.

Please use the below code hope this will help:

$gejala = $_POST['gejala'];

foreach($gejala as $value) {

   $gejala = $value;
   if($gejala == "1"){
        print_msg('Belum ada gejala terpilih. <a href="?m=konsultasi">Kembali</a>');
   }else{
       print_msg('agsjhdgashjgdajhsgd');
   }
}


问:
(String)Iterator based conversion to int
There are the atox, strtox and stox families that I know of, but I can't seem to find any iterator based string to int conversions in the Standard Library or Boost.

The reason I need them is because I am having a parser whose match result is a range referencing the input string. I might very well have an input string like

```<code>...8973893488349798923475...
     ^begin   ^end
</code>```

so I need 738934883 as an integer.

Of couse, I could first take begin and end to construct an std::string to use with any of above families, but I would very much like to avoid that overhead.

So my question: Is there anything in the Standard Library or Boost accepting iterators as input, or do I have to write my own.

答: With modern STL implementations std::string(begin,end) is not that bad - SSO eliminates any allocations for strings, smaller than ~15 chars (22 for 64bit).

Body:
There are the atox, strtox and stox families that I know of, but I can't seem to find any iterator based string to int conversions in the Standard Library or Boost.

The reason I need them is because I am having a parser whose match result is a range referencing the input string. I might very well have an input string like

...8973893488349798923475...
     ^begin   ^end

so I need 738934883 as an integer.

Of couse, I could first take begin and end to construct an std::string to use with any of above families, but I would very much like to avoid that overhead.

So my question: Is there anything in the Standard Library or Boost accepting iterators as input, or do I have to write my own.


问:
Socket IO Rooms: Get list of clients in specific room
I'm trying to display a list of clients in a specific room. I just want to show their username, and not their socket id.

This where I'm at:

```<code>socket.set('nickname', "Earl");
socket.join('chatroom1');
console.log('User joined chat room 1);

var roster = io.sockets.clients('chatroom1');
for ( i in roster )
{
   console.log('Username: ' + roster[i]);
}
</code>```

Haven't had any luck getting it to list Socket IDs or anything. Would like it to return the nicknames however.

答:
All the answers above and the one here socket.io get rooms which socket is currently in or here Socket.IO - how do I get a list of connected sockets/clients? were either incorrect or incomplete if you use 2.0.

In 2.0, io.sockets.manager and io.sockets.clients don't exist anymore.

Without using namespace, the following 3 parameters can all get sockets in a specific room.

socket.adapter.rooms;

io.sockets.adapter.rooms;

io.sockets.adapter.sids; // the socket.id array

With namespace (I used "cs" here), io.sockets.adapter.rooms will give a quite confusing result and the result socket.adapter.rooms gives is correct:

```<code>/* socket.adapter.rooms give: */

{
  "/cs#v561bgPlss6ELZIZAAAB": {
    "sockets": {
      "/cs#v561bgPlss6ELZIZAAAB": true
    },
    "length": 1
  },
  "a room xxx": {"sockets": {
    "/cs#v561bgPlss6ELZIZAAAB": true
  },
  "length": 1
  }
}

/* io.sockets.adapter.rooms give: a sid without namespace*/

{
  "v561bgPlss6ELZIZAAAB": {
    "sockets": {
      "v561bgPlss6ELZIZAAAB": true
    }, "length": 1
  }
}
</code>```

Note: the default room is this: "Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id."

I only tried memory adapter so far, have not tried redis-adapter.

Body:
I'm trying to display a list of clients in a specific room. I just want to show their username, and not their socket id.

This where I'm at:

socket.set('nickname', "Earl");
socket.join('chatroom1');
console.log('User joined chat room 1);

var roster = io.sockets.clients('chatroom1');
for ( i in roster )
{
   console.log('Username: ' + roster[i]);
}

Haven't had any luck getting it to list Socket IDs or anything. Would like it to return the nicknames however.

Body:
All the answers above and the one here socket.io get rooms which socket is currently in or here Socket.IO - how do I get a list of connected sockets/clients? were either incorrect or incomplete if you use 2.0.

In 2.0, io.sockets.manager and io.sockets.clients don't exist anymore.

Without using namespace, the following 3 parameters can all get sockets in a specific room.

socket.adapter.rooms;

io.sockets.adapter.rooms;

io.sockets.adapter.sids; // the socket.id array

With namespace (I used "cs" here), io.sockets.adapter.rooms will give a quite confusing result and the result socket.adapter.rooms gives is correct:

/* socket.adapter.rooms give: */

{
  "/cs#v561bgPlss6ELZIZAAAB": {
    "sockets": {
      "/cs#v561bgPlss6ELZIZAAAB": true
    },
    "length": 1
  },
  "a room xxx": {"sockets": {
    "/cs#v561bgPlss6ELZIZAAAB": true
  },
  "length": 1
  }
}

/* io.sockets.adapter.rooms give: a sid without namespace*/

{
  "v561bgPlss6ELZIZAAAB": {
    "sockets": {
      "v561bgPlss6ELZIZAAAB": true
    }, "length": 1
  }
}

Note: the default room is this: "Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id."

I only tried memory adapter so far, have not tried redis-adapter.


问:
Using functions in observables vs creating many actions/epics

I'm just starting to use redux-observable and I'm having trouble deciding between multiple ways to do the same thing. Here is a contrived example of two ways to execute some logic in response to actions:

Method A (epics):

function epic1(action$){
    return action$.ofType(FOO)
        .map(action => something(action.payload))
        .map(result => ({type: BAR}));
}

function epic2(action$){
    return action$.ofType(BAR)
        .map(action => something(action.payload));
        // potentially returning actions for a third epic, etc.
}
```

<p>Method B (functions):</p>

<pre class="lang-js prettyprint-override"><code>function helperFunction(result){
    // something that returns an action eventually
}

function singleEpic(action$){
    action$.ofType(FOO)
        .map(action => something(action.payload))
        .map(helperFunction);
}
</code>```

You can imagine each pattern scaling out and the functions being realistically complex. Is there a lot of overhead to doing Method A? Are the actions going to go through the entire redux loop before arriving at epic2 and is this something that has been noticeable in anyone's experience?

I definitely want to make as many things epics as possible so far because they've ended up being really small and simple, but I'm not sure about the costs.

答:
I can offer my experience from a project using redux-saga. I think the performance characteristics and design trade-offs are quite similar.

It is likely that there will be some performance hit in case A. However, unless there is something really wrong, it should not be a big consideration for your average SPA. YMMV if you're developing games or something else performance intensive. From this point of view creating fewer sagas seems like a micro optimisation.

We were leaning very much towards something similar to what you describe as method B. We would typically create factories for families of similar sagas, pretty much like in the following example:

```<code>const factory = ({ actionType, mapper, actionCreator }) => (action$) =>
  action$.ofType(actionType)
    .map(action => mapper(action.payload))
    .map(actionCreator);

const epic = factory({
  actionType: 'FOO',
  mapper: payload => payload + 1,
  actionCreator: newPayload => ({ type: 'BAR', payload: newPayload })
});
</code>```

It probably does not make all that much sense in this contrived example, because the cognitive overhead of the abstraction is higher than what you're getting from it, but you get the idea. We employed a very similar strategy for reducers, too.

However, when possible, I would warn against creating waterfalls of actions like you describe with epic1, epic2, etc. I believe that if you have too many of those implicit interdependencies in your code, it will eventually be more difficult to debug. Though probably nowhere near as hard as chains of two-way bindings in some frameworks of the past (Ember, for example).

So in general, my recommendation would be to create as many little sagas as you like, creating little helpers to help you construct them. But prefer longer more explicit epics for more complex asynchronous flows (as opposed to having too many collaborating epics).

Body:
I'm just starting to use redux-observable and I'm having trouble deciding between multiple ways to do the same thing. Here is a contrived example of two ways to execute some logic in response to actions:

Method A (epics):

function epic1(action$){
    return action$.ofType(FOO)
        .map(action => something(action.payload))
        .map(result => ({type: BAR}));
}

function epic2(action$){
    return action$.ofType(BAR)
        .map(action => something(action.payload));
        // potentially returning actions for a third epic, etc.
}

Method B (functions):

function helperFunction(result){
    // something that returns an action eventually
}

function singleEpic(action$){
    action$.ofType(FOO)
        .map(action => something(action.payload))
        .map(helperFunction);
}

You can imagine each pattern scaling out and the functions being realistically complex. Is there a lot of overhead to doing Method A? Are the actions going to go through the entire redux loop before arriving at epic2 and is this something that has been noticeable in anyone's experience?

I definitely want to make as many things epics as possible so far because they've ended up being really small and simple, but I'm not sure about the costs.

Body:
I can offer my experience from a project using redux-saga. I think the performance characteristics and design trade-offs are quite similar.

It is likely that there will be some performance hit in case A. However, unless there is something really wrong, it should not be a big consideration for your average SPA. YMMV if you're developing games or something else performance intensive. From this point of view creating fewer sagas seems like a micro optimisation.

We were leaning very much towards something similar to what you describe as method B. We would typically create factories for families of similar sagas, pretty much like in the following example:

const factory = ({ actionType, mapper, actionCreator }) => (action$) =>
  action$.ofType(actionType)
    .map(action => mapper(action.payload))
    .map(actionCreator);

const epic = factory({
  actionType: 'FOO',
  mapper: payload => payload + 1,
  actionCreator: newPayload => ({ type: 'BAR', payload: newPayload })
});

It probably does not make all that much sense in this contrived example, because the cognitive overhead of the abstraction is higher than what you're getting from it, but you get the idea. We employed a very similar strategy for reducers, too.

However, when possible, I would warn against creating waterfalls of actions like you describe with epic1, epic2, etc. I believe that if you have too many of those implicit interdependencies in your code, it will eventually be more difficult to debug. Though probably nowhere near as hard as chains of two-way bindings in some frameworks of the past (Ember, for example).

So in general, my recommendation would be to create as many little sagas as you like, creating little helpers to help you construct them. But prefer longer more explicit epics for more complex asynchronous flows (as opposed to having too many collaborating epics).


问:
Get ID with onClick function and populate it on a different html
I'm have a HTML page that loading a table and a dhtmlxgantt chart. The javascript function below works but now i want to load the gantt chart from a different html and display it through iframe.

How can I get the content_id from the main_page.html table and populate it on scheduler.html gantt chart

Everyone helps is much appreciated

main_page.html

```<code><table id="project-content-datatable">
    <tbody>
        <tr>
            <td class="project_content_id">1</td>
            <td class="project_content_id">2</td>
            <td class="project_content_id">3</td>
        </tr>
    </tbody>
</table>

<div class="col-md-12" style="padding: 3px; margin: 0px;">
     <iframe src="/dashboard/projects/scheduler.html" height="330"; width="99%" style="border:2px  solid blue; border-radius: 5px;"></iframe>
</div>
</code>```

scheduler.html

```<code><div id="my_scheduler" style='width:1567px; height:325px;'></div>
</code>```

javascript

```<code>$('#project-content-datatable').on('click', 'tr', function () {
    var content_id =$(this).closest('tr').children('td.project_content_id').text();
    initializeGantt(content_id)
    });

    gantt.config.xml_date = "%Y-%m-%d";
    function initializeGantt(content_id) {
        scheduler = gantt.init("my_scheduler", new Date('2017, 01, 01'), new Date('2017, 12, 31'));
        $.get("/dashboard/ganttchart_list/"+content_id+"/?format=json", function(result) { gantt.parse(prepareData(result)); });
    }

    initializeGantt();
</code>```

答:
An easy way to do this is call dynamically create the url that you pass to the iframe:

```<code><div class="col-md-12" style="padding: 3px; margin: 0px;">
    <iframe id="iframe" height="330"; width="99%" style="border:2px  solid blue; border-radius: 5px;"></iframe>
</div>
</code>```

and in your script:

```<code>var url = "/dashboard/projects/scheduler.html?content_id=" + content_id;
document.getElementById('iframe').src = url;
</code>```

Now within the iframe you can fetch the content id from the window.hash. Extracting the id can, in this specific case, easily be done with a substring, but for a more complete approach you can use a function which extracts query parameters from a url as described here: How can I get query string values in JavaScript?

Body:
I'm have a HTML page that loading a table and a dhtmlxgantt chart. The javascript function below works but now i want to load the gantt chart from a different html and display it through iframe.

How can I get the content_id from the main_page.html table and populate it on scheduler.html gantt chart

Everyone helps is much appreciated

main_page.html

            1
            2
            3

scheduler.html

javascript

$('#project-content-datatable').on('click', 'tr', function () {
    var content_id =$(this).closest('tr').children('td.project_content_id').text();
    initializeGantt(content_id)
    });

    gantt.config.xml_date = "%Y-%m-%d";
    function initializeGantt(content_id) {
        scheduler = gantt.init("my_scheduler", new Date('2017, 01, 01'), new Date('2017, 12, 31'));
        $.get("/dashboard/ganttchart_list/"+content_id+"/?format=json", function(result) { gantt.parse(prepareData(result)); });
    }

    initializeGantt();

Body:
An easy way to do this is call dynamically create the url that you pass to the iframe:

<div class="col-md-12" style="padding: 3px; margin: 0px;">
    <iframe id="iframe" height="330"; width="99%" style="border:2px  solid blue; border-radius: 5px;"></iframe>
</div>

and in your script:

var url = "/dashboard/projects/scheduler.html?content_id=" + content_id;
document.getElementById('iframe').src = url;

Now within the iframe you can fetch the content id from the window.hash. Extracting the id can, in this specific case, easily be done with a substring, but for a more complete approach you can use a function which extracts query parameters from a url as described here: How can I get query string values in JavaScript?


问:
Which method will call when user press back with add Fragment method (not replace fragment)
I am looking for an answer but could not find for the following.

I have Fragment A loaded by default.

Now I add new Fragment (B) with getFragmentManager().beginTransaction().add() and the fragment B is visible

user press back, FragmentManager will pop the Fragment B, and the fragment A visible again

So my question is, which method in fragment A will be called when fragment B is detached, I am debugging all onResume, onAttach in fragment A, but looks like it is not called.

one point that if we using replace fragment instead of add fragment, it will run extract with the fragment lifecycle, but with "add" method, look like fragment A still visible on screen, so anyway to detect when fragment A not being overlay by Fragment B any more?

Any ideas?

答:
When user navigate one activity to  fragment then below life cycle called

FirstFragment: onAttach

FirstFragment: onCreate

FirstFragment: onCreateView

FirstFragment: onViewCreated

FirstFragment: onActivityCreated

FirstFragment: onStart

FirstFragment: onResume

when user navigate firstfragment to second fragment in case of
addtobackstack and add() then below life cycle called
SecondFragment: onAttach

SecondFragment: onCreate

SecondFragment: onCreateView

SecondFragment: onViewCreated

SecondFragment: onActivityCreated

SecondFragment: onStart

SecondFragment: onResume

when user pressed back in case of addtobackstack() and add() then below life cycle called
SecondFragment: onPause

SecondFragment: onStop

SecondFragment: onDestroyView

SecondFragment: onDestroy

SecondFragment: onDetach

when user navigate firstfragment to second fragment in case of addtobackstack and replace() then below life cycle called
SecondFragment: onAttach

SecondFragment: onAttachonAttach

SecondFragment: onCreate

FirstFragment: onPause

FirstFragment: onStop

FirstFragment: onDestroyView

SecondFragment: onCreateView

SecondFragment: onViewCreated

SecondFragment: onActivityCreated

SecondFragment: onStart

SecondFragment: onResume

when user pressed back in case of addtobackstack() and replace then below life cycle called
SecondFragment: onPause

SecondFragment: onStop

SecondFragment: onDestroyView

SecondFragment: onDestroy

SecondFragment: onDetach

FirstFragment: onCreateView

FirstFragment: onViewCreated

FirstFragment: onActivityCreated

FirstFragment: onStart

FirstFragment: onResume


问:
symfony translation resource path
I can't make my translator to load a resource yams file.
I have a file admin.ru.yml inside AppBundle/Resources/config/translations/
I have in my other bundle the following lines

```<code>    $translator = new Translator('ru_RU', new MessageSelector());
    $translator->addLoader('yaml', new FileLoader());
    $translator->addResource('yaml', 'admin.ru.yml', 'ru_RU', 'admin');
    $tt = $translator->trans('Category', array(), 'admin');
</code>```

It does not load the yml file.

I even have specified in my app/config.yml file of the whole application

```<code>   translator:
       paths:
        - '%kernel.root_dir%/../src/AppBundle/Resources/config/translations'
</code>```

but with no result. I tried many paths but can't find the right way. Any suggestions of what am I doing wrong?

答: you have to rename your file @AppBundle.ru.yml, the file path is not necessary</p>

Title: symfony translation resource path

Body:
I can't make my translator to load a resource yams file.
I have a file admin.ru.yml inside AppBundle/Resources/config/translations/
I have in my other bundle the following lines

    $translator = new Translator('ru_RU', new MessageSelector());
    $translator->addLoader('yaml', new FileLoader());
    $translator->addResource('yaml', 'admin.ru.yml', 'ru_RU', 'admin');
    $tt = $translator->trans('Category', array(), 'admin');

It does not load the yml file.

I even have specified in my app/config.yml file of the whole application

   translator:
       paths:
        - '%kernel.root_dir%/../src/AppBundle/Resources/config/translations'

but with no result. I tried many paths but can't find the right way. Any suggestions of what am I doing wrong?


问:
Java '+=' Compound operator working concept
I just wanted to know what is the difference between
a = a+b; and a += b;

consider,

```<code>int a = 10;
long b = 20;

a = a+b; // is not possible
</code>```

but

```<code>a += b; // is possible.
</code>```

Thank you!

```<code>package com.test;

public class ClassCast {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int a = 1;
        long b = 2;

        /*Not possible. Compile time error.
        a = a+b;
        */

        //Possible. Why?
        //a += b;

        System.out.println(a += b);

    }

}
</code>```

答:
So a += b is equivalent to a = (int) (a + b).

implicit conversion done by compiler

Body:
I just wanted to know what is the difference between
a = a+b; and a += b;

consider,

int a = 10;
long b = 20;

a = a+b; // is not possible

but

a += b; // is possible.

Thank you!

package com.test;

public class ClassCast {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int a = 1;
        long b = 2;

        /*Not possible. Compile time error.
        a = a+b;
        */

        //Possible. Why?
        //a += b;

        System.out.println(a += b);

    }

}


问:
Architectural and design question about uploading photos from iPhone app and S3
I want to allow users of an iPhone app to upload photos and use Amazon S3.  There are 2 ways I see going about this:

Upload from iPhone to my server, which proxies it then to Amazon S3.

Upload from iPhone direct to S3

For option 1, the security is straightforward. I don't ever have to tell the iPhone my S3 secret. Downside is that everything is proxied through our server for uploads which sort of defeats the purpose of going to S3.

For option 2, in theory it's better but the issue is how do you enable the iPhone (or any mobile app on a different platform) to write into my S3 bucket without giving it my secret?  Additionally, I'm not sure if this is a good design or not because the flow would be: iphone uploads to S3, gets the URL, then tells the server what the URL is so it can add it to our database to reference in the future. However, since the communication is separated into 2 legs (iphone->S3 vs iPhone->My-Server) it leaves it fragile as a non-atomic operation.

I've found some older info that references using Browser-based Uploads using POST but unsure if that is still the recommended approach. I'm hoping for a better solution where we can just use the REST APIs rather than relying on POST.  I've also see the AWS iOS Beta SDK, but their docs didn't help much and I found an Amazon article that was equally unhelpful as it cautions you on what not to do, but doesn't tell you an alternative approach:

The mobile AWS SDKs sign the API
  requests sent to Amazon Web Services
  (AWS) in order to validate the
  identity of the AWS account making the
  request. Otherwise, a malicious
  developer could easily make requests
  to another developer's infrastructure.
  The requests are signed using an AWS
  Access Key ID and a Secret Access Key
  that AWS provides. The Secret Access
  Key is similar to a password, and it
  is extremely important to keep secret.

Tip: You can view all your AWS
  security credentials, including Access
  Key ID and Secret Access Key, on the
  AWS web site at
  http://aws.amazon.com/security-credentials.

Embedding credentials in source code
  is problematic for software, including
  mobile applications, because malicious
  users can de-compile the software or
  view the source code to retrieve the
  Secret Access Key.

Does anyone have any advice on the best architectural design and flow for this?

Update: The more I dig into this, it seems that a bunch of pople recommend using the HTTP POST method with the json policy file as described here: http://docs.amazonwebservices.com/AmazonS3/2006-03-01/dev/index.html?UsingHTTPPOST.html.

With this, the flow would be something like (1) iPhone makes request to my server, asking for policy file (2) server generates json policy file and gives back to client (3) iPhone does HTTP POST of photo + json policy to S3.  I hate that I'm using HTTP POST in an apparently kludgy way but it appears to be better because it removes the need for my server to store the photo at all.

答:
Upload to your server and then post to S3. From an architecture standpoint you will want to do this from your server. There are many things that could go wrong during the data transfer you can handle better on the server and if you want to store any data about the image you are sending to S3 you are probably going to have a server side call anyway.

Plus, your Secret Access Key is stored in a more secure environment.  Your own.

If you are worried about scalability and you are going to be doing a considerable number of S3 transfers I would consider hosting your server on and EC2 instance. Transferring data between the two is free (given you store you data in following data centers).

There is no Data Transfer charge for data transferred between Amazon EC2 and Amazon S3 within the same Region or for data transferred between the Amazon EC2 Northern Virginia Region and the Amazon S3 US Standard Region." Amazon Simple Storage Service (Amazon S3)

There are many post here on SO Amazon - EC2 cost? (example) about the pros and cons of using EC2.


问:
read hbase table salted with phoenix in hive with hbase serde
I have created an hbase table with Phoenix SQL create table query and also specified salt_buckets. Salting adds prefix to the the rowkey as expected.

I have created an external hive table to map to this hbase table with hbase serde  The problem is when I query this table by filtering on rowkey:

where key = "value"

it doesn't work because I think salt pre-fix is also getting fetched for the key. This limits the ability to filter the data on key. The option:

"where rowkey like "%value"

works but it takes a long time as likely does the entire table scan.

My question is how can I query this table efficiently on row key values in hive (strip off salt pre-fix)?

答:
Yes you're correct while mentioning

it doesn't work because I think salt pre-fix is also getting fetched for the key. '

One way to mitigate is to use hashing instead of random prefix.
And prefix the rowkey with the calculated hash
Using this technique you can calculate hash for the rowkey you want to scan for.:

mod(hash(rowkey),n) where n is the number of regions will remove the hotspotting issue

Using random prefix brings in the problem you mentioned in your question.

The option:
  "where rowkey like "%value"
  works but it takes a long time as likely does the entire table scan.

This is exactly what random prefix salting does. HBase is forced to scan the whole table to get the required value, so it would be better if you could prefix your rowkey with its calculated Hash.
But this hashing technique wont prove good in Range scans.

Now you may ask, why cant I simply replace my rowKey with its Hash and store the rowkey as separate column.
It may/may not work, but I would recommend implementing it this way because HBase is already very sensitive when it comes to Column Families.
But then again I am not clear on this solution.

You also might want to read this for more detailed explanation.


问:
How to add Slugify to ElasticSearch?
There is a Russian word for "pizza" = "пицца" and they are very similar since:

```<code>"p" equals to "п"
"i" equals to "и"
"z" equals to "ц"
"z" equals to "ц"
"a" equals to "а"
</code>```

So when I'm searching for "пицца" I must get all results with "pizza" as result.

How can I achieve that?

答:
The problem solved and the way it solved is not what i expected but still, it just works, here is the solution:</p>

```<code>"settings": {
    "analysis": {
        "filter": {
            "ru_synonym": {
                "type": "synonym",
                "synonyms": [
                    "pizza, пицца"
                ]
            }
        },
        "analyzer": {
            "ru_analyzer": {
                "type": "custom",
                "tokenizer": "whitespace",
                "filter": [
                    "lowercase",
                    "ru_synonym"
                ]
            }
        }
    }
}
</code>```

Title: How to add Slugify to ElasticSearch?

Body:
There is a Russian word for "pizza" = "пицца" and they are very similar since:

"p" equals to "п"
"i" equals to "и"
"z" equals to "ц"
"z" equals to "ц"
"a" equals to "а"

So when I'm searching for "пицца" I must get all results with "pizza" as result.

How can I achieve that?

Body:
The problem solved and the way it solved is not what i expected but still, it just works, here is the solution:

"settings": {
    "analysis": {
        "filter": {
            "ru_synonym": {
                "type": "synonym",
                "synonyms": [
                    "pizza, пицца"
                ]
            }
        },
        "analyzer": {
            "ru_analyzer": {
                "type": "custom",
                "tokenizer": "whitespace",
                "filter": [
                    "lowercase",
                    "ru_synonym"
                ]
            }
        }
    }
}


问:
json_encode can not escape single quotation marks?
```<code>$emailFields =  array(
    array(
        'name' => 'comments',
        'type' => 'html',
        'content' => "ahfsd\jfh/sf's askghaskg sadf"
    ),
);
echo json_encode($emailFields);
</code>```

The print is

```<code>[{
    "name": "comments",
    "type": "html",
    "content": "ahfsd\\jfh/sf's askghaskg sadf"
}]
</code>```

Why the json_encode can not escape the '?

答:
As JSON Docs say, strings in JSON are surrounded by double quotes. There is no need to escape single quote in JSON.

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

Also

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string.

You should escape double quotes in your string values.

Body:
$emailFields =  array(
    array(
        'name' => 'comments',
        'type' => 'html',
        'content' => "ahfsd\jfh/sf's askghaskg sadf"
    ),
);
echo json_encode($emailFields);

The print is

[{
    "name": "comments",
    "type": "html",
    "content": "ahfsd\\jfh/sf's askghaskg sadf"
}]

Why the json_encode can not escape the '?


问:
Authentication and Authorization in asp.net core WEB API
I am new in asp.net core and want to implement authentication and authorization in WEB API 2 project. I am little bit confuse to use basic authentication, bearer token, JWT token or  any other. please suggest more preferable
Thanks

答:
Basic auth is as the name suggests, very basic and not very secure, it uses base64 encoding of the username and password so you must use HTTPS if you use it, but best is not to use it at all.

A bearer token is a type of token which effectively gives access to a resource to the "bearer" of the token. Both basic and bearer are used in an HTTP Authorization header.

You can have different formats of bearer tokens, one of which is JWT - JWT is the industry standard so I recommend you use it, and therefore you'll be using bearer tokens.

This article is a good starting point to look into all this in the context of asp.net core. See also this video series and this article goes into more detail about JWT validation.

Edit

To answer your questions in the comments:

OAuth is a standard for users to delegate permissions to apps or websites to access their resources, for example when you allow some web app to post on your behalf to your Facebook feed. Various tokens are used in this process and they're very often JWT. OAuth2 adds authentication via OpenID Connect.

OWIN on the other hand is a standard for web servers which decouples IIS and ASP.NET with the aim of allowing ASP.NET to run on other web servers which implement OWIN and other frameworks generally to run on OWIN compatible servers if those frameworks are OWIN compatible.

Auth0 is an identity platform which can do OAuth and allows you to use JWTs, generally it handles your identity and SSO. IdentityServer is another identity platform with some similar features.

I'd still recommend starting with the articles I linked at the top, don't worry too much about OWIN, and read more about OAuth to determine if you really need it. If you do, I'd recommend IdentityServer.


问:
Add separate click events for multiple buttons in custom control
All:

The more I search for solutions to this question the more confused I become. After spending 12-16 hours watching YouTube, reading StackOverflow and general goggling, I thought I'd plead for additional help.

I would like to create a custom control so I can write various apps to remote to my video switcher.

I've created my control with dependency properties and that part is working well.

This answer on SO seemed to get me close, but I still can't get my app to run.
  How to wire up a click event for a custom usercontrol button? Should I use CustomControl?

What I simply want to do is click btnIn1 in the control and have it return a "1", btnIn2 returns a "2" and so on.

I've also read about delegates, ICommand, TemplateParts and MVVM patterns which all seem like incredibly complex ways to click a button within a group. Maybe there's just not a simple way to do it.

Here's what I have so far. I simplified everything to a 2x2 matrix switcher (rather than the 4x4 I'm working on)

Thanks for all your help.
Norm

Generic.xaml

```<code><ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:VideoSwitcher"
xmlns:enk="clr-namespace:VideoSwitcher.Controls">

<Style TargetType="{x:Type enk:Matrix44}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type enk:Matrix44}">
                <Grid x:Name="grdBase" HorizontalAlignment="Stretch">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="25*"/>
                        <ColumnDefinition Width="25*"/>
                        <ColumnDefinition Width="25*"/>
                        <ColumnDefinition Width="25*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="40*"/>
                        <RowDefinition Height="100*"/>
                        <RowDefinition Height="40*"/>
                        <RowDefinition Height="100*"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <Label x:Name="lblInputHeader" Content="Input"
                           Grid.Column="0"
                           Grid.Row="0"
                           Grid.ColumnSpan="4"
                           Visibility="{TemplateBinding HeaderVisible}"
                           FontFamily="{TemplateBinding HeaderFont}"
                           FontSize="{TemplateBinding HeaderFontSize}"/>
                    <StackPanel Orientation="Horizontal"
                                Grid.Column="0"
                                Grid.Row="1"
                                Grid.ColumnSpan="4">
                        <Button x:Name="btnIn1"
                                Margin="{TemplateBinding ButtonMargin}"
                                Height="{TemplateBinding ButtonHeight}"
                                Width="{TemplateBinding ButtonWidth}"
                                Content="{TemplateBinding Input1Label}"
                                Click="btnIn1Click"/>
                        <Button x:Name="btnIn2"
                                Margin="{TemplateBinding ButtonMargin}"
                                Height="{TemplateBinding ButtonHeight}"
                                Width="{TemplateBinding ButtonWidth}"
                                Content="{TemplateBinding Input2Label}"
                                Click="btnIn2Click"/>
                    </StackPanel>
                    <Label x:Name="lblOutputHeader" Content="Output"
                           Grid.Column="0"
                           Grid.Row="2"
                           Grid.ColumnSpan="4"
                           Visibility="{TemplateBinding HeaderVisible}"
                           FontFamily="{TemplateBinding HeaderFont}"
                           FontSize="{TemplateBinding HeaderFontSize}"/>
                    <StackPanel Orientation="Horizontal"
                                Grid.Column="0"
                                Grid.Row="3"
                                Grid.ColumnSpan="4">
                        <Button x:Name="btnOut1"
                                Margin="{TemplateBinding ButtonMargin}"
                                Height="{TemplateBinding ButtonHeight}"
                                Width="{TemplateBinding ButtonWidth}"
                                Content="{TemplateBinding Output1Label}"
                                Click="btnOut1Click"/>
                        <Button x:Name="btnOut2"
                                Margin="{TemplateBinding ButtonMargin}"
                                Height="{TemplateBinding ButtonHeight}"
                                Width="{TemplateBinding ButtonWidth}"
                                Content="{TemplateBinding Output2Label}"
                                Click="btnOut2Click"/>
                    </StackPanel>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</ResourceDictionary>
</code>```

Custom Control (Matrix44.cs)

```<code>using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.ComponentModel;

namespace VideoSwitcher.Controls
{

public class Matrix44 : Control
{

    #region Events - Go here if I can ever find out how to use them

    #endregion

    //This does not work --------
    public event RoutedEventHandler Click;

    void btnIn1Click(object sender, RoutedEventArgs e)
    {
        if (this.Click != null)
        {
            this.Click(this, e);
        }
    }

    void btnIn2Click(object sender, RoutedEventArgs e)
    {
        if (this.Click != null)
        {
            this.Click(this, e);
        }
    }

    void btnOut1Click(object sender, RoutedEventArgs e)
    {
        if (this.Click != null)
        {
            this.Click(this, e);
        }
    }

    void btnOut2Click(object sender, RoutedEventArgs e)
    {
        if (this.Click != null)
        {
            this.Click(this, e);
        }
    }

    #region Properties - Exposed to the user in the Properties panel, XAML or code-behind

    #region Switcher Appearance Properies (Height, Width, Margin)

    [Category("Switcher Appearance Properties")]
    public double ButtonHeight
    {
        get { return (double)GetValue(ButtonHeightProperty); }
        set { SetValue(ButtonHeightProperty, value); }
    }

    public static readonly DependencyProperty ButtonHeightProperty =
        DependencyProperty.Register(nameof(ButtonHeight), typeof(double), typeof(Matrix44), new PropertyMetadata(50.0));

    [Category("Switcher Appearance Properties")]
    public double ButtonWidth
    {
        get { return (double)GetValue(ButtonWidthProperty); }
        set { SetValue(ButtonWidthProperty, value); }
    }

    public static readonly DependencyProperty ButtonWidthProperty =
        DependencyProperty.Register(nameof(ButtonWidth), typeof(double), typeof(Matrix44), new PropertyMetadata(50.0));

    [Category("Switcher Appearance Properties")]
    public Thickness ButtonMargin
    {
        get { return (Thickness)GetValue(ButtonMarginProperty); }
        set { SetValue(ButtonMarginProperty, value); }
    }

    public static readonly DependencyProperty ButtonMarginProperty =
        DependencyProperty.Register("ButtonMargin", typeof(Thickness), typeof(Matrix44));

    #endregion

    #region Labels

    [Category("Switcher Label Properties")]
    public string Input1Label
    {
        get { return (string)GetValue(Input1LabelProperty); }
        set { SetValue(Input1LabelProperty, value); }
    }

    public static readonly DependencyProperty Input1LabelProperty =
        DependencyProperty.Register(nameof(Input1Label), typeof(string), typeof(Matrix44), new PropertyMetadata("Input 1"));

    [Category("Switcher Label Properties")]
    public string Input2Label
    {
        get { return (string)GetValue(Input2LabelProperty); }
        set { SetValue(Input2LabelProperty, value); }
    }

    public static readonly DependencyProperty Input2LabelProperty =
        DependencyProperty.Register(nameof(Input2Label), typeof(string), typeof(Matrix44), new PropertyMetadata("Input 2"));

    [Category("Switcher Label Properties")]
    public string Output1Label
    {
        get { return (string)GetValue(Output1LabelProperty); }
        set { SetValue(Output1LabelProperty, value); }
    }

    public static readonly DependencyProperty Output1LabelProperty =
        DependencyProperty.Register(nameof(Output1Label), typeof(string), typeof(Matrix44), new PropertyMetadata("Output 1"));

    [Category("Switcher Label Properties")]
    public string Output2Label
    {
        get { return (string)GetValue(Output2LabelProperty); }
        set { SetValue(Output2LabelProperty, value); }
    }

    public static readonly DependencyProperty Output2LabelProperty =
        DependencyProperty.Register(nameof(Output2Label), typeof(string), typeof(Matrix44), new PropertyMetadata("Output 2"));

    #endregion

    #region Header Properties

    [Category("Switcher Header Properties")]
    public Visibility HeaderVisible
    {
        get { return (Visibility)GetValue(HeaderVisibleProperty); }
        set { SetValue(HeaderVisibleProperty, value); }
    }

    public static readonly DependencyProperty HeaderVisibleProperty =
        DependencyProperty.Register("HeaderVisible", typeof(Visibility), typeof(Matrix44));

    [Category("Switcher Header Properties")]
    public FontFamily HeaderFont
    {
        get { return (FontFamily)GetValue(HeaderFontProperty); }
        set { SetValue(HeaderFontProperty, value); }
    }

    public static readonly DependencyProperty HeaderFontProperty =
        DependencyProperty.Register("HeaderFont", typeof(FontFamily), typeof(Matrix44));

    [Category("Switcher Header Properties")]
    public double HeaderFontSize
    {
        get { return (double)GetValue(HeaderFontSizeProperty); }
        set { SetValue(HeaderFontSizeProperty, value); }
    }

    public static readonly DependencyProperty HeaderFontSizeProperty =
        DependencyProperty.Register("HeaderFontSize", typeof(double), typeof(Matrix44));

    #endregion

    #region Channel Properties
    [Category("Switcher Channel Properties")]

    //Channel Property - use to extend switcher tool capabilties; e.g. add new bank of ins/outs and remap input 1 to input 5 on 2nd bank

    public int Input1Channel
    {
        get { return (int)GetValue(Input1ChannelProperty); }
        set { SetValue(Input1ChannelProperty, value); }
    }

    public static readonly DependencyProperty Input1ChannelProperty =
        DependencyProperty.Register("Input1Channel", typeof(int), typeof(Matrix44), new PropertyMetadata(1));

    [Category("Switcher Channel Properties")]
    public bool Input1Enabled
    {
        get { return (bool)GetValue(Input1EnabledProperty); }
        set { SetValue(Input1EnabledProperty, value); }
    }

    public static readonly DependencyProperty Input1EnabledProperty =
        DependencyProperty.Register("Input1Enabled", typeof(bool), typeof(Matrix44), new PropertyMetadata(false));

    [Category("Switcher Channel Properties")]
    public int Input2Channel
    {
        get { return (int)GetValue(Input2ChannelProperty); }
        set { SetValue(Input2ChannelProperty, value); }
    }

    public static readonly DependencyProperty Input2ChannelProperty =
        DependencyProperty.Register("Input2Channel", typeof(int), typeof(Matrix44), new PropertyMetadata(2));

    [Category("Switcher Channel Properties")]
    public bool Input2Enabled
    {
        get { return (bool)GetValue(Input1EnabledProperty); }
        set { SetValue(Input1EnabledProperty, value); }
    }

    [Category("Switcher Channel Properties")]
    public int Output1Channel
    {
        get { return (int)GetValue(Output1ChannelProperty); }
        set { SetValue(Output1ChannelProperty, value); }
    }

    //Output channels

    public static readonly DependencyProperty Output1ChannelProperty =
        DependencyProperty.Register("Output1Channel", typeof(int), typeof(Matrix44), new PropertyMetadata(1));

    [Category("Switcher Channel Properties")]
    public int Output2Channel
    {
        get { return (int)GetValue(Output2ChannelProperty); }
        set { SetValue(Output2ChannelProperty, value); }
    }

    public static readonly DependencyProperty Output2ChannelProperty =
        DependencyProperty.Register("Output2Channel", typeof(int), typeof(Matrix44), new PropertyMetadata(2));

    #endregion

    #endregion

    public Matrix44()
    {
        DefaultStyleKey = typeof(Matrix44);
    }

}

}
</code>```

MainWindow.XAML

```<code><Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:VideoSwitcher"
    xmlns:Controls="clr-namespace:VideoSwitcher.Controls" x:Class="VideoSwitcher.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="300" Width="200">
<Grid Margin="0,1,0,0">
    <Controls:Matrix44 x:Name="swtMatrix"
                       HorizontalAlignment="Left"
                       Margin="10,10,0,0"
                       VerticalAlignment="Top"
                       ButtonHeight="65"
                       ButtonMargin="4"
                       ButtonWidth="65"/>
    <Button x:Name="btnTake"
            Content="Take"
            HorizontalAlignment="Left"
            Margin="10,213,0,0"
            VerticalAlignment="Top"
            Width="146"
            Height="45" Click="btnTake_Click"/>
</Grid>
</code>```

MainWindow.xaml.cs

```<code>    using System.Windows;

    namespace VideoSwitcher
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public int VideoInputChannel { get; set; }
    public int VideoOutputChannel { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        AddLabelsToMatrix();
    }

    public void AddLabelsToMatrix()
    {
        swtMatrix.Input1Label = "DVR1";
        swtMatrix.Input2Label = "DVR2";
        swtMatrix.Output1Label = "Videowall";
        swtMatrix.Output2Label = "US Right";
    }

    private void btnTake_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Input channel: " + VideoInputChannel + " routed to Output: " + VideoOutputChannel);
    }

    /* switcher button psuedo-code

        btnIn1_Click (object sender, RoutedEventArgs e)
        {
            //get input channel of matrix switcher
            VideoInputChannel = swtMatrix.btnIn1.Channel;
        }

        btnIn2_Click (object sender, RoutedEventArgs e)
        {
            //get input channel of matrix switcher
            VideoInputChannel = swtMatrix.btnIn2.Channel;
        }

         btnOut1_Click (object sender, RoutedEventArgs e)
        {
            //get output channel of matrix switcher
            VideoInputChannel = swtMatrix.btnIn1.Channel;
        }

        btnOut2_Click (object sender, RoutedEventArgs e)
        {
            //get output channel of matrix switcher
            VideoInputChannel = swtMatrix.btnIn2.Channel;
        }

    */

}
}
</code>```

答:
You could override the OnApplyTemplate() method to get a reference to each Button and then hook up the event handlers:

```<code>public class Matrix44 : Control
{
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        Button btnOut1 = this.Template.FindName("btnOut1", this) as Button;
        if (btnOut1 != null)
            btnOut1.Click += btnIn1Click;

        //...and so on for each Button

    }
}
</code>```

You could then either raise a specific event for each Button or define a custom EventArgs that can be used to identify which Button that was clicked in an event handler:

C# event with custom arguments

Body:
All:

The more I search for solutions to this question the more confused I become. After spending 12-16 hours watching YouTube, reading StackOverflow and general goggling, I thought I'd plead for additional help.

I would like to create a custom control so I can write various apps to remote to my video switcher.

I've created my control with dependency properties and that part is working well.

This answer on SO seemed to get me close, but I still can't get my app to run.
  How to wire up a click event for a custom usercontrol button? Should I use CustomControl?

What I simply want to do is click btnIn1 in the control and have it return a "1", btnIn2 returns a "2" and so on.

I've also read about delegates, ICommand, TemplateParts and MVVM patterns which all seem like incredibly complex ways to click a button within a group. Maybe there's just not a simple way to do it.

Here's what I have so far. I simplified everything to a 2x2 matrix switcher (rather than the 4x4 I'm working on)

Thanks for all your help.
Norm

Generic.xaml

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:VideoSwitcher"
xmlns:enk="clr-namespace:VideoSwitcher.Controls">

</ResourceDictionary>

Custom Control (Matrix44.cs)

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.ComponentModel;

namespace VideoSwitcher.Controls
{

public class Matrix44 : Control
{

    #region Events - Go here if I can ever find out how to use them

    #endregion

    //This does not work --------
    public event RoutedEventHandler Click;

    void btnIn1Click(object sender, RoutedEventArgs e)
    {
        if (this.Click != null)
        {
            this.Click(this, e);
        }
    }

    void btnIn2Click(object sender, RoutedEventArgs e)
    {
        if (this.Click != null)
        {
            this.Click(this, e);
        }
    }

    void btnOut1Click(object sender, RoutedEventArgs e)
    {
        if (this.Click != null)
        {
            this.Click(this, e);
        }
    }

    void btnOut2Click(object sender, RoutedEventArgs e)
    {
        if (this.Click != null)
        {
            this.Click(this, e);
        }
    }

    #region Properties - Exposed to the user in the Properties panel, XAML or code-behind

    #region Switcher Appearance Properies (Height, Width, Margin)

    [Category("Switcher Appearance Properties")]
    public double ButtonHeight
    {
        get { return (double)GetValue(ButtonHeightProperty); }
        set { SetValue(ButtonHeightProperty, value); }
    }

    public static readonly DependencyProperty ButtonHeightProperty =
        DependencyProperty.Register(nameof(ButtonHeight), typeof(double), typeof(Matrix44), new PropertyMetadata(50.0));

    [Category("Switcher Appearance Properties")]
    public double ButtonWidth
    {
        get { return (double)GetValue(ButtonWidthProperty); }
        set { SetValue(ButtonWidthProperty, value); }
    }

    public static readonly DependencyProperty ButtonWidthProperty =
        DependencyProperty.Register(nameof(ButtonWidth), typeof(double), typeof(Matrix44), new PropertyMetadata(50.0));

    [Category("Switcher Appearance Properties")]
    public Thickness ButtonMargin
    {
        get { return (Thickness)GetValue(ButtonMarginProperty); }
        set { SetValue(ButtonMarginProperty, value); }
    }

    public static readonly DependencyProperty ButtonMarginProperty =
        DependencyProperty.Register("ButtonMargin", typeof(Thickness), typeof(Matrix44));

    #endregion

    #region Labels

    [Category("Switcher Label Properties")]
    public string Input1Label
    {
        get { return (string)GetValue(Input1LabelProperty); }
        set { SetValue(Input1LabelProperty, value); }
    }

    public static readonly DependencyProperty Input1LabelProperty =
        DependencyProperty.Register(nameof(Input1Label), typeof(string), typeof(Matrix44), new PropertyMetadata("Input 1"));

    [Category("Switcher Label Properties")]
    public string Input2Label
    {
        get { return (string)GetValue(Input2LabelProperty); }
        set { SetValue(Input2LabelProperty, value); }
    }

    public static readonly DependencyProperty Input2LabelProperty =
        DependencyProperty.Register(nameof(Input2Label), typeof(string), typeof(Matrix44), new PropertyMetadata("Input 2"));

    [Category("Switcher Label Properties")]
    public string Output1Label
    {
        get { return (string)GetValue(Output1LabelProperty); }
        set { SetValue(Output1LabelProperty, value); }
    }

    public static readonly DependencyProperty Output1LabelProperty =
        DependencyProperty.Register(nameof(Output1Label), typeof(string), typeof(Matrix44), new PropertyMetadata("Output 1"));

    [Category("Switcher Label Properties")]
    public string Output2Label
    {
        get { return (string)GetValue(Output2LabelProperty); }
        set { SetValue(Output2LabelProperty, value); }
    }

    public static readonly DependencyProperty Output2LabelProperty =
        DependencyProperty.Register(nameof(Output2Label), typeof(string), typeof(Matrix44), new PropertyMetadata("Output 2"));

    #endregion

    #region Header Properties

    [Category("Switcher Header Properties")]
    public Visibility HeaderVisible
    {
        get { return (Visibility)GetValue(HeaderVisibleProperty); }
        set { SetValue(HeaderVisibleProperty, value); }
    }

    public static readonly DependencyProperty HeaderVisibleProperty =
        DependencyProperty.Register("HeaderVisible", typeof(Visibility), typeof(Matrix44));

    [Category("Switcher Header Properties")]
    public FontFamily HeaderFont
    {
        get { return (FontFamily)GetValue(HeaderFontProperty); }
        set { SetValue(HeaderFontProperty, value); }
    }

    public static readonly DependencyProperty HeaderFontProperty =
        DependencyProperty.Register("HeaderFont", typeof(FontFamily), typeof(Matrix44));

    [Category("Switcher Header Properties")]
    public double HeaderFontSize
    {
        get { return (double)GetValue(HeaderFontSizeProperty); }
        set { SetValue(HeaderFontSizeProperty, value); }
    }

    public static readonly DependencyProperty HeaderFontSizeProperty =
        DependencyProperty.Register("HeaderFontSize", typeof(double), typeof(Matrix44));

    #endregion

    #region Channel Properties
    [Category("Switcher Channel Properties")]

    //Channel Property - use to extend switcher tool capabilties; e.g. add new bank of ins/outs and remap input 1 to input 5 on 2nd bank

    public int Input1Channel
    {
        get { return (int)GetValue(Input1ChannelProperty); }
        set { SetValue(Input1ChannelProperty, value); }
    }

    public static readonly DependencyProperty Input1ChannelProperty =
        DependencyProperty.Register("Input1Channel", typeof(int), typeof(Matrix44), new PropertyMetadata(1));

    [Category("Switcher Channel Properties")]
    public bool Input1Enabled
    {
        get { return (bool)GetValue(Input1EnabledProperty); }
        set { SetValue(Input1EnabledProperty, value); }
    }

    public static readonly DependencyProperty Input1EnabledProperty =
        DependencyProperty.Register("Input1Enabled", typeof(bool), typeof(Matrix44), new PropertyMetadata(false));

    [Category("Switcher Channel Properties")]
    public int Input2Channel
    {
        get { return (int)GetValue(Input2ChannelProperty); }
        set { SetValue(Input2ChannelProperty, value); }
    }

    public static readonly DependencyProperty Input2ChannelProperty =
        DependencyProperty.Register("Input2Channel", typeof(int), typeof(Matrix44), new PropertyMetadata(2));

    [Category("Switcher Channel Properties")]
    public bool Input2Enabled
    {
        get { return (bool)GetValue(Input1EnabledProperty); }
        set { SetValue(Input1EnabledProperty, value); }
    }

    [Category("Switcher Channel Properties")]
    public int Output1Channel
    {
        get { return (int)GetValue(Output1ChannelProperty); }
        set { SetValue(Output1ChannelProperty, value); }
    }

    //Output channels

    public static readonly DependencyProperty Output1ChannelProperty =
        DependencyProperty.Register("Output1Channel", typeof(int), typeof(Matrix44), new PropertyMetadata(1));

    [Category("Switcher Channel Properties")]
    public int Output2Channel
    {
        get { return (int)GetValue(Output2ChannelProperty); }
        set { SetValue(Output2ChannelProperty, value); }
    }

    public static readonly DependencyProperty Output2ChannelProperty =
        DependencyProperty.Register("Output2Channel", typeof(int), typeof(Matrix44), new PropertyMetadata(2));

    #endregion

    #endregion

    public Matrix44()
    {
        DefaultStyleKey = typeof(Matrix44);
    }

}

}

MainWindow.XAML

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:VideoSwitcher"
    xmlns:Controls="clr-namespace:VideoSwitcher.Controls" x:Class="VideoSwitcher.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="300" Width="200">
<Grid Margin="0,1,0,0">
    <Controls:Matrix44 x:Name="swtMatrix"
                       HorizontalAlignment="Left"
                       Margin="10,10,0,0"
                       VerticalAlignment="Top"
                       ButtonHeight="65"
                       ButtonMargin="4"
                       ButtonWidth="65"/>
    <Button x:Name="btnTake"
            Content="Take"
            HorizontalAlignment="Left"
            Margin="10,213,0,0"
            VerticalAlignment="Top"
            Width="146"
            Height="45" Click="btnTake_Click"/>
</Grid>

MainWindow.xaml.cs

    using System.Windows;

    namespace VideoSwitcher
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
    public int VideoInputChannel { get; set; }
    public int VideoOutputChannel { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        AddLabelsToMatrix();
    }

    public void AddLabelsToMatrix()
    {
        swtMatrix.Input1Label = "DVR1";
        swtMatrix.Input2Label = "DVR2";
        swtMatrix.Output1Label = "Videowall";
        swtMatrix.Output2Label = "US Right";
    }

    private void btnTake_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Input channel: " + VideoInputChannel + " routed to Output: " + VideoOutputChannel);
    }

    /* switcher button psuedo-code

        btnIn1_Click (object sender, RoutedEventArgs e)
        {
            //get input channel of matrix switcher
            VideoInputChannel = swtMatrix.btnIn1.Channel;
        }

        btnIn2_Click (object sender, RoutedEventArgs e)
        {
            //get input channel of matrix switcher
            VideoInputChannel = swtMatrix.btnIn2.Channel;
        }

         btnOut1_Click (object sender, RoutedEventArgs e)
        {
            //get output channel of matrix switcher
            VideoInputChannel = swtMatrix.btnIn1.Channel;
        }

        btnOut2_Click (object sender, RoutedEventArgs e)
        {
            //get output channel of matrix switcher
            VideoInputChannel = swtMatrix.btnIn2.Channel;
        }

    */

}
}

Body:
You could override the OnApplyTemplate() method to get a reference to each Button and then hook up the event handlers:

public class Matrix44 : Control
{
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        Button btnOut1 = this.Template.FindName("btnOut1", this) as Button;
        if (btnOut1 != null)
            btnOut1.Click += btnIn1Click;

        //...and so on for each Button

    }
}

You could then either raise a specific event for each Button or define a custom EventArgs that can be used to identify which Button that was clicked in an event handler:

C# event with custom arguments


问:
How to align html elements on the same row
If you see the attachment below, three share buttons are not equally margined from the top. Tweet button didn't maintain the consistency, it is little bit up than the other two. How do I make all of them equally distanced from the top?

The code I am working on:

```<code>                            <h2 class="title">Share this blog</h2>

                            <div class="fb-share-button" data-href="http://alfa-blog.com/"
                                 data-layout="button_count" data-size="large" data-mobile-iframe="true">
                                <a class="fb-xfbml-parse-ignore" target="_blank"
                                   href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Falfa-blog.com%2Findex.html&src=sdkpreparse">Share</a>
                            </div>

                            <a href="https://twitter.com/share"
                               data-size="large"
                               class="twitter-share-button" data-show-count="false">Tweet</a>

                            <div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>
</code>```

答:
It may work for you..

.social-holder {width: 100%;}
.social-holder * {display: inline-block; vertical-align: top; padding: 0px; margin: 0px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 class="title">Share this blog</h2>
<div class="social-holder">
<div class="fb-share-button" data-href="http://alfa-blog.com/"
data-layout="button_count" data-size="large" data-mobile-iframe="true">
Share
</div>

Tweet

<div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>

</div></code>```

Body:
If you see the attachment below, three share buttons are not equally margined from the top. Tweet button didn't maintain the consistency, it is little bit up than the other two. How do I make all of them equally distanced from the top?

The code I am working on:

Share this blog

                                Share

                            Tweet

Body:
It may work for you..

.social-holder {width: 100%;}
.social-holder * {display: inline-block; vertical-align: top; padding: 0px; margin: 0px;}

<h2 class="title">Share this blog</h2>
<div class="social-holder">
<div class="fb-share-button" data-href="http://alfa-blog.com/"
data-layout="button_count" data-size="large" data-mobile-iframe="true">
<a class="fb-xfbml-parse-ignore" target="_blank"
href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Falfa-blog.com%2Findex.html&amp;src=sdkpreparse">Share</a>
</div>

<a href="https://twitter.com/share"
data-size="large"
class="twitter-share-button" data-show-count="false">Tweet</a>

<div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>

</div>


问:
deploy rails app on heroku
Hey
I'm afraid I should ask a rookie question :

After push my app to heroku. I got error of no database

This is the command I use

heroku rake db:migrate

My app can run locally with no problem, but I notice the database file only in development.
and my test evironment only use rails server and localhost:3000

anyone tell me how to make the database in production mode in heroku.

Thanks

here's the heroku log file:

here's the logs

Started GET "/drummers/1" for
  221.9.247.14 at Sat Dec 18 06:17:40 -0800 2010  Processing by DrummersController#show as HTML
  Parameters: {"id"=>"1"}  Completed in
  167ms

ActiveRecord::RecordNotFound (Couldn't
  find Drummer with ID=1):
  app/controllers/drummers_controller.rb:11:in
  `show'

I think it may due to the datebase,config file, become I use sqlite3 in local test, and all the migration file is development prefix,

答:
It's not telling you that you have no Database.

It's telling you that it can't find a specific record

```<code>(Couldn't find Drummer with ID=1):
</code>```

It's likely that you have code that's doing Drummer.find(1) and that doesn't exist on your production environment.

Recommend you either:

create a seeds file (heroku rake db:seed) rails cast

push your entire database to heroku (heroku db:push) [make sure you understand this will wipe out your production database]

Title: deploy rails app on heroku

Body:
It's not telling you that you have no Database.

It's telling you that it can't find a specific record

(Couldn't find Drummer with ID=1):

It's likely that you have code that's doing Drummer.find(1) and that doesn't exist on your production environment.

Recommend you either:

create a seeds file (heroku rake db:seed) rails cast

push your entire database to heroku (heroku db:push) [make sure you understand this will wipe out your production database]


问:
How to create MasterEndpoint programmatically
I need to create an MasterEndpoint from a given (as Endpoint instance in Java) FileEndpoint.

Normally i create an class extending the desired endpoint and call all needed setter (e.g. to set context) from with in constructor or in an init method.
Sometimes i create a method that uses getContext().getEndpoint("name", ClazzOfEndpoint.class) within the route builder.

But how to do this with MasterEndpoint (preferable without using string literals/constants)?
The problem with extending MasterEndpoint is the unusual constructor it uses. The problem with using getEndpoint is: how to connect the returned master endpoint to the FileEndpoint?

答:
I found a way that suits my needs:

First create the master endpoint together with it's child:

```<code>masterEndpoint = context.getEndpoint("master:fileLock:file:" + rootFolder, MasterEndpoint.class);
</code>```

To programmatically configure the child endpoint (in my case FileEndpoint) obtain it from master and configure it:

```<code>fileEndpoint = (FileEndpoint) masterEndpoint.getEndpoint();
fileEndpoint.setAutoCreate(false);
fileEndpoint.setAntInclude(ANT_INCLUDE);
fileEndpoint.setMove(doneFolder);
fileEndpoint.setMoveFailed(errorFolder);
</code>```

It would be extreme cumbersome (and error prone) to configure it with strings.

Body:
I found a way that suits my needs:

First create the master endpoint together with it's child:

masterEndpoint = context.getEndpoint("master:fileLock:file:" + rootFolder, MasterEndpoint.class);

To programmatically configure the child endpoint (in my case FileEndpoint) obtain it from master and configure it:

fileEndpoint = (FileEndpoint) masterEndpoint.getEndpoint();
fileEndpoint.setAutoCreate(false);
fileEndpoint.setAntInclude(ANT_INCLUDE);
fileEndpoint.setMove(doneFolder);
fileEndpoint.setMoveFailed(errorFolder);

It would be extreme cumbersome (and error prone) to configure it with strings.


问:
Date format issue when i web-scraping into excel?
I am web-scraping datas from a website with python 2.7, and after i export them to excel.
But i get a format issue in excel :
In the website there is : "9/18" and i get "18.sept" in excel.

How can i hold these values in "9/18" format?

Here my code:

filename=r'output.csv'

resultcsv=open(filename,"wb")
output=csv.writer(resultcsv, delimiter=';',quotechar = '"', quoting=csv.QUOTE_NONNUMERIC, encoding='latin-1')

f = open('0910000511.txt', 'r')
x = f.read()

soup = BeautifulSoup(x, 'lxml')

datatable=[]
for ctable in soup.find_all('table',  "ctable" )[:-1]:
    for record in ctable.find_all('tr'):
        temp_data = []
        for data in record.find_all('td'):
            temp_data.append(data.text.encode('latin-1'))
        datatable.append(temp_data)

tab6col = soup.find('table', { "class" : "tab6col" })
datatable2=[]
for record in tab6col.find_all('tr'):
    temp_data2 = []
    for data in record.find_all('td'):
        temp_data2.append(data.text.encode('latin-1'))
    datatable.append(temp_data2)

output.writerows(datatable)

resultcsv.close()```

答:
Question:

  I just asked it, is it possible for holding these values in this format, and not to do manually.

There is NO hold because a String has no Format assigned.

Consider your Dataflow:

```<code>scrap `Date string`
-> csv.write `Date string`
-> Excel imports from CSV `Date string`
</code>```

Excel Magic detect Date string and convert it to Type DATE.

Excel Displays all Cells of Type DATE with the Default
Date Format, resulting in DAY.SHORTMONTHNAME.

You have 2 Options:

Change the Date Format in Excel

You can do this manually or using a VBA Script.

Write your scraped Data using a xslx package and assing your
Date Format("9/18") to the Date Cells.

Note: This SO Answer doesn't show how to do NumberFormat.

SO Answer Solution using openpyxl.

SO Answer cell.number_format

openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files

Body:
Question:

  I just asked it, is it possible for holding these values in this format, and not to do manually.

There is NO hold because a String has no Format assigned.

Consider your Dataflow:

scrap `Date string`
-> csv.write `Date string`
-> Excel imports from CSV `Date string`

Excel Magic detect Date string and convert it to Type DATE.

Excel Displays all Cells of Type DATE with the Default
Date Format, resulting in DAY.SHORTMONTHNAME.

You have 2 Options:

Change the Date Format in Excel

You can do this manually or using a VBA Script.

Write your scraped Data using a xslx package and assing your
Date Format("9/18") to the Date Cells.

Note: This SO Answer doesn't show how to do NumberFormat.

SO Answer Solution using openpyxl.

SO Answer cell.number_format

openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files