问:
Output php processing instruction inside attribute value
In my XSLT (2.0 - the output method is html) I have this:

```<code><img>
    <xsl:attribute name="href">
        <xsl:text disable-output-escaping="yes"><?php echo get_url(); ?></xsl:text>
    </xsl:attribute>
</img>
</code>```

The output I want is as follows:

```<code><img href="<?php echo get_url(); ?>">
</code>```

The output I get is as follows:

```<code><img href="<?php echo get_url(); ?>">
</code>```

Tried a bunch of different things to get the ">" coming out in the output instead of > (CDATA marked sections etc.) but nothing seems to work. Strange that the less than sign works fine, but the greater than doesn't. I'm using Saxon-PE 9.5.1.7.

答:
Use a character map with some characters you don't need elsewhere, here is an example (https://www.w3.org/TR/xslt20/#character-maps) adapted from the XSLT 2.0 spec:

```<code><img href="«?php echo get_url(); ?»"/>
</code>```

and

```<code><xsl:output method="html" use-character-maps="m1"/>

<xsl:character-map name="m1">
    <xsl:output-character character="«" string="<"/>
    <xsl:output-character character="»" string=">"/>
</xsl:character-map>
</code>```

Online example is at http://xsltransform.net/93dEHFP.

As for disable-output-escaping, it does not work in attribute values as far as I know, that result that you get is not the result of disable-output-escaping but just the use of xsl:output method="html" (https://www.w3.org/TR/xslt-xquery-serialization/#HTML_ATTRIBS) mandating 'The HTML output method MUST NOT escape "<" characters occurring in attribute values.'.

Body:
In my XSLT (2.0 - the output method is html) I have this:

    <xsl:attribute name="href">
        <xsl:text disable-output-escaping="yes"><?php echo get_url(); ?></xsl:text>
    </xsl:attribute>

The output I want is as follows:

<img href="<?php echo get_url(); ?>">

The output I get is as follows:

<img href="<?php echo get_url(); ?>">

Tried a bunch of different things to get the ">" coming out in the output instead of > (CDATA marked sections etc.) but nothing seems to work. Strange that the less than sign works fine, but the greater than doesn't. I'm using Saxon-PE 9.5.1.7.

Body:
Use a character map with some characters you don't need elsewhere, here is an example (https://www.w3.org/TR/xslt20/#character-maps) adapted from the XSLT 2.0 spec:

<img href="«?php echo get_url(); ?»"/>

and

<xsl:output method="html" use-character-maps="m1"/>

<xsl:character-map name="m1">
    <xsl:output-character character="«" string="&lt;"/>
    <xsl:output-character character="»" string="&gt;"/>
</xsl:character-map>

Online example is at http://xsltransform.net/93dEHFP.

As for disable-output-escaping, it does not work in attribute values as far as I know, that result that you get is not the result of disable-output-escaping but just the use of xsl:output method="html" (https://www.w3.org/TR/xslt-xquery-serialization/#HTML_ATTRIBS) mandating 'The HTML output method MUST NOT escape "<" characters occurring in attribute values.'.


来源: stackexchange

问:
Excel VBA Looping a continuous copy/paste with delay
I already have code below which successfully copy and pastes one row on Sheet1 to the next open row on Sheet2.  The data on this row is imported from an external application and updates constantly, thereby creating a history writer.  I have attempted several methods to loop this action with a delay and have failed.

GOAL: Loop this code with .25 second delay with the option to exit the loop with a button click or key-press.  The delay is more important than the exit condition as I can just Esc if need be.

```<code>Private Sub START_Click()

    Application.ScreenUpdating = False
    Dim copySheet As Worksheet
    Dim pasteSheet As Worksheet

    Set copySheet = Worksheets("Sheet1")
    Set pasteSheet = Worksheets("Sheet2")

    copySheet.Range("A23:L23").Copy
    pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub
</code>```

答:
Use Application. Wait(Now + TimeValue("0:00:01")/4) that should do the trick.  TimeValue only drops to 1 second by design so dividing by 4 gets you to 0.25 seconds.  That's the easiest way to pause your code in 1 line.

BUT after timing the function it doesn't look to give you consistent time delays.  I like the Sleep presented in another answer by @David Zemens which is very consistent.  Here's some test code:

```<code>'These go ABOVE your function
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare Function GetTickCount Lib "kernel32" () As Long

Sub testwait()

StartTime = GetTickCount
Sleep 250
EndTime = GetTickCount
MsgBox ((EndTime - StartTime) & " milliseconds")

End Sub
</code>```

You then could call your function in a loop with that Sleep function.  Or just use the built in Application.Wait if you don't need super precise time delays.  As David pointed out to me, they are different - Sleep will freeze Excel while running http://analystcave.com/vba-sleep-vs-wait/ while Application.Wait will allow you to Esc out of the macro.

ContentLicense: CC BY-SA 3.0

Body:
I already have code below which successfully copy and pastes one row on Sheet1 to the next open row on Sheet2.  The data on this row is imported from an external application and updates constantly, thereby creating a history writer.  I have attempted several methods to loop this action with a delay and have failed.

GOAL: Loop this code with .25 second delay with the option to exit the loop with a button click or key-press.  The delay is more important than the exit condition as I can just Esc if need be.

Private Sub START_Click()

    Application.ScreenUpdating = False
    Dim copySheet As Worksheet
    Dim pasteSheet As Worksheet

    Set copySheet = Worksheets("Sheet1")
    Set pasteSheet = Worksheets("Sheet2")

    copySheet.Range("A23:L23").Copy
    pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub

Body:
Use Application. Wait(Now + TimeValue("0:00:01")/4) that should do the trick.  TimeValue only drops to 1 second by design so dividing by 4 gets you to 0.25 seconds.  That's the easiest way to pause your code in 1 line.

BUT after timing the function it doesn't look to give you consistent time delays.  I like the Sleep presented in another answer by @David Zemens which is very consistent.  Here's some test code:

'These go ABOVE your function
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare Function GetTickCount Lib "kernel32" () As Long

Sub testwait()

StartTime = GetTickCount
Sleep 250
EndTime = GetTickCount
MsgBox ((EndTime - StartTime) & " milliseconds")

End Sub

You then could call your function in a loop with that Sleep function.  Or just use the built in Application.Wait if you don't need super precise time delays.  As David pointed out to me, they are different - Sleep will freeze Excel while running http://analystcave.com/vba-sleep-vs-wait/ while Application.Wait will allow you to Esc out of the macro.


问:
Synchronizing Gmail mail
I have fetched all Gmail mail using JavaMail API Imap protocol and show them in table format but now the problem is how show delete them?
on click that mail has to be deleted, all connection using protocol is lost and I want to delete that mail.</p>

答:
Once you lose the connection to the server, you're effectively operating in "disconnected" mode.  The JavaMail FAQ has pointers to more information about how to handle disconnected mode with IMAP.  Doing this well is a lot of work.

A simpler approach is to do your best to ensure the connection isn't lost unnecessarily, e.g., by calling Folder.getMessageCount at least every 30 minutes.  If you still lose the connection (which will happen sometimes),
you toss all your cached data, reconnect, and refresh the user's view.

If you only care about being able to delete messages that the user can see, you might be able to take an intermediate approach.  You could save the UID of all messages (and the UIDVALIDITY of the Folder) and when the connection is lost you would reconnect and get the Message objects for all messages based on UID.  Then you would be able to delete the message, if it still exists on the server.

Title: Synchronizing Gmail mail


问:
C# Deserialize XML elements with attributes into List
Here's the XML:

```<code><xml id = "1234">
    <connect id="2"/>
    <connect id="1"/>
    <connect id="21"/>
    <connect id="3"/>
    <connect id="7"/>
</xml>
</code>```

Currently I am doing this:

```<code>public class xml
{
    //Constructor

    [XmlAttribute ("id")]
    public uint id;

    [XmlElement ("connect")]
    public List<Connection> Connections { get; set; }

    //Deserializer
}

public class Connection
{
    [XmlAttribute ("id")]
    public uint id { get; set; }
}
</code>```

The goal is to get rid of the Connection class entirely and Deserialize the xml straight into:

```<code>List<uint> connections;
</code>```

答:
<s>First, your XML is not valid, i guess it's just a typo - there no end tag for "connect".</s>

I recommend you to use linq XDocument.

Then it's easy:

```<code>XDocument xdoc = XDocument.Parse(xml);
List<uint> list = xdoc
                    .Descendants("connect")
                    .Select(node => uint.Parse(node.Attribute("id").Value))
                    .ToList();
</code>```

Body:
Here's the XML:

<xml id = "1234">
    <connect id="2"/>
    <connect id="1"/>
    <connect id="21"/>
    <connect id="3"/>
    <connect id="7"/>
</xml>

Currently I am doing this:

public class xml
{
    //Constructor

    [XmlAttribute ("id")]
    public uint id;

    [XmlElement ("connect")]
    public List<Connection> Connections { get; set; }

    //Deserializer
}

public class Connection
{
    [XmlAttribute ("id")]
    public uint id { get; set; }
}

The goal is to get rid of the Connection class entirely and Deserialize the xml straight into:

List<uint> connections;

Body:
<s>First, your XML is not valid, i guess it's just a typo - there no end tag for "connect".</s>

I recommend you to use linq XDocument.

Then it's easy:

XDocument xdoc = XDocument.Parse(xml);
List<uint> list = xdoc
                    .Descendants("connect")
                    .Select(node => uint.Parse(node.Attribute("id").Value))
                    .ToList();

ContentLicense: CC BY-SA 4.0


问:
Enterprise Service Bus and BPM
I am a Java professional. I have a requirement to implement Enterprise Service Bus(ESB). There are quite a few ESB providers are available in the market.I am confusing a bit among those.
Please suggest which one is the best to implement ESB and BPM. I am expecting to have an open source solution with rich documentation and easy to understand with number of examples and scenarios so that we can start from scratch and implement it without any hassle.</p>

答:
Yes the number of options can be confusing. It's highly depends on your use case and what you're trying to achieve. Without much context, I can only share with you the recent tutorial I wrote around Bonita (A Bpm platform) and Apache Camel (A lightweight ESB): http://community.bonitasoft.com/blog/enhance-your-bonita-applications-apache-camel

In this tutorial, I explain how to trigger new process instances on new incoming emails event.

Cheers

Title: Enterprise Service Bus and BPM


问:
How to access a webcam in Raspberry Pi Motion instead using the port
I am using a streaming of video, configured using this tutorial: https://pimylifeup.com/raspberry-pi-webcam-server

Can I configure the motion to access the webcam with a link like “ip:/cam1” where ip is like “146.106.91.100” instead using the port “:8081”?

Thanks!

答:
I've never used the software you are, but after a quick search, it appears as though you can modify the following directive in your motion.conf configuration file:

```<code>############################################################
# HTTP Based Control
############################################################

# TCP/IP port for the http server to listen on (default: 0 = disabled)
webcontrol_port 8081
</code>```

Change that port to 80. That will prevent you from having to specify a port in the URL.

Please note that a Unix system will not allow anyone other than the superuser (root) to start services on port numbers < 1024, so you'd need to run the application as root, or with sudo. This can open up gaping security issues though, so I would not recommend taking this approach unless you're extremely confident that this is on a private, and/or secured network.

Body:
I've never used the software you are, but after a quick search, it appears as though you can modify the following directive in your motion.conf configuration file:

############################################################
# HTTP Based Control
############################################################

# TCP/IP port for the http server to listen on (default: 0 = disabled)
webcontrol_port 8081

Change that port to 80. That will prevent you from having to specify a port in the URL.

Please note that a Unix system will not allow anyone other than the superuser (root) to start services on port numbers < 1024, so you'd need to run the application as root, or with sudo. This can open up gaping security issues though, so I would not recommend taking this approach unless you're extremely confident that this is on a private, and/or secured network.


问:
MYSQL: Incorrect collation is picked for query
I am facing some weird collation issue which I really don't understand. I have table containing polish accented letters like "Ł" in two or three columns. Due to occurrence of this letters, utf8_unicode_520_ci collation is most suitable for my purpose. I am facing this issue in my PHP page. Webserver is running Apache 2.4, PHP 7.1.0, MySQL 5.7.

After connecting to database, I am setting charset and collation this way:

```<code>$connection->set_charset("utf8");
$connection->query("SET NAMES utf8 COLLATE utf8_unicode_520_ci;");
</code>```

Afterwards I am double-checking actual charsets and collation using SHOW VARIABLES LIKE '%collat%'; and SHOW VARIABLES LIKE '%char%'; which in formatted form return following information:

```<code>collation_connection->utf8_unicode_520_ci
collation_database->utf8_unicode_520_ci
collation_server->binary
character_set_client->utf8
character_set_connection->utf8
character_set_database->utf8
character_set_filesystem->binary
character_set_results->utf8
character_set_server->binary
character_set_system->utf8
character_sets_dir->/usr/share/mysql/charsets/
</code>```

Until this point everything seems to be corrrect. But i am facing ordering issue when I am running query below:

```<code>SELECT birthPlace FROM persons ORDER BY birthPlace DESC LIMIT 5;
</code>```

which retrun following results:

```<code>Łapsze Wyżne
Łapsze Wyżne
Zvolenská Slatina
Župčany
Župčany
</code>```

Entry "Łapsze Wyżne" should not be listed as last as per utf8_unicode_520_ci collation it should be listed along with entries starting with normal "L" character. So it is evident that it is picking other collation then utf8_unicode_520_ci.I think is utf8_general_ci collation what is used (guessing from results order). Collation of table and column "birthPlace" is utf8_unicode_520_ci. I've expected collation precedence will be default column, table, database respectively.

phpMyAdmin and MySQL Workbench sort entries as expected. But my script is not sorting as expected.

So my question is what collation is really used if it is not explicitly set in query and how to solve it without modifying query if possible.

EDIT: Question itself is not about choosing proper collation as I already know and defined collation which is correct one for my purpose on all places I am able to control. Question is what collation is used if it is not explixitly defined in SELECT query. It is collation of connection, column, table, database, or server? Or it is default collation of used charset (in my case it is utf8_general_ci for uth8 charset? This is not clear to me from documentation. I want to order results by utf8_unicode_520_ci by default without defining it in every query I'll run in future. It is possible?

答:
Since this question seems to be more about Polish collation than about "best for PHP", I reopened it.

utf8_unicode_520_ci treats L=l=Ĺ=ĺ=Ļ=ļ=Ł=ł.  Virtually all other utf8 collations treat L=l=Ĺ=ĺ=Ļ=ļ < Ł=ł.  In particular, Ł is effectively a letter that comes after L and before M.

I suggest you consider utf8_polish_ci if Polish is the main content of the database.  Be aware that grave accents on C,N,O,S,Z may (or may not) be treated the way you want them in this collation.

See this for a rundown of the ordering of letters in the various utf8 collations for MySQL.

The 'blame' for the treatment of Ł goes to Unicode in its version 5.20.  Unicode 9.0 also works the same way.

The "best for PHP" (or any other general application) is utf8mb4_unicode_520_ci through MySQL 5.7.  In MySQL 8.0, utf8mb4_0900_ai_ci is probably considered 'best'.

(Note: CHARACTER SET utf8 is good enough for most languages. utf8mb4 is a superset, with Emoji and the rest of Chinese added.)

Body:
I am facing some weird collation issue which I really don't understand. I have table containing polish accented letters like "Ł" in two or three columns. Due to occurrence of this letters, utf8_unicode_520_ci collation is most suitable for my purpose. I am facing this issue in my PHP page. Webserver is running Apache 2.4, PHP 7.1.0, MySQL 5.7.

After connecting to database, I am setting charset and collation this way:

$connection->set_charset("utf8");
$connection->query("SET NAMES utf8 COLLATE utf8_unicode_520_ci;");

Afterwards I am double-checking actual charsets and collation using SHOW VARIABLES LIKE '%collat%'; and SHOW VARIABLES LIKE '%char%'; which in formatted form return following information:

collation_connection->utf8_unicode_520_ci
collation_database->utf8_unicode_520_ci
collation_server->binary
character_set_client->utf8
character_set_connection->utf8
character_set_database->utf8
character_set_filesystem->binary
character_set_results->utf8
character_set_server->binary
character_set_system->utf8
character_sets_dir->/usr/share/mysql/charsets/

Until this point everything seems to be corrrect. But i am facing ordering issue when I am running query below:

SELECT birthPlace FROM persons ORDER BY birthPlace DESC LIMIT 5;

which retrun following results:

Łapsze Wyżne
Łapsze Wyżne
Zvolenská Slatina
Župčany
Župčany

Entry "Łapsze Wyżne" should not be listed as last as per utf8_unicode_520_ci collation it should be listed along with entries starting with normal "L" character. So it is evident that it is picking other collation then utf8_unicode_520_ci.I think is utf8_general_ci collation what is used (guessing from results order). Collation of table and column "birthPlace" is utf8_unicode_520_ci. I've expected collation precedence will be default column, table, database respectively.

phpMyAdmin and MySQL Workbench sort entries as expected. But my script is not sorting as expected.

So my question is what collation is really used if it is not explicitly set in query and how to solve it without modifying query if possible.

EDIT: Question itself is not about choosing proper collation as I already know and defined collation which is correct one for my purpose on all places I am able to control. Question is what collation is used if it is not explixitly defined in SELECT query. It is collation of connection, column, table, database, or server? Or it is default collation of used charset (in my case it is utf8_general_ci for uth8 charset? This is not clear to me from documentation. I want to order results by utf8_unicode_520_ci by default without defining it in every query I'll run in future. It is possible?


问:
execute if statement if a value found in a multidimensional array
I have a piece of code which sole purpose is to find a desired value in a multidimensional array and if a match is found execute a if statement.

i have used array_search() method which returns the index of the match.So it means if match is found in the first index it returns that index which is 0.That is false by definition.

So when match is found in the first index ,my if statement doesn't get executed.How to solve this porblem?

```<code>$arr = array(

   0 =>array(
       'name' => 'mr.x',
       'id' => 1
   ),
   1 =>array(
       'name'=>'mr.y',
       'id'  =>2
   )

);

$match = array_search(2,array_column($arr,'id'));

echo $match;

if($match){

    echo 'a match found !';
}
</code>```

答:
You can use !== or ===.

```<code>if(($key = array_search( ... )) !== false){
   //do something
}
</code>```

Body:
I have a piece of code which sole purpose is to find a desired value in a multidimensional array and if a match is found execute a if statement.

i have used array_search() method which returns the index of the match.So it means if match is found in the first index it returns that index which is 0.That is false by definition.

So when match is found in the first index ,my if statement doesn't get executed.How to solve this porblem?

$arr = array(

   0 =>array(
       'name' => 'mr.x',
       'id' => 1
   ),
   1 =>array(
       'name'=>'mr.y',
       'id'  =>2
   )

);

$match = array_search(2,array_column($arr,'id'));

echo $match;

if($match){

    echo 'a match found !';
}

Body:
You can use !== or ===.

if(($key = array_search( ... )) !== false){
   //do something
}


问:
Can't pass Core Data object between Swift classes
I have an array of Core Data entities that I can successfully pass from Objective-C VC to a Swift VC. I've verified through the console that they are coming in.

Now I need to loop through the array of core data objects and pass them onto another swift vc. I have the array set up as a property (Customer is the CD entity):

var arrCustomers: Array = Customer

In my loop I am trying to pass them to the other Swift VC:

```<code>for thisCustomer in self.arrCustomers {

    let gridCell = storyboard.instantiateViewController(withIdentifier: "bulkAddCell") as! BulkAddCell
    resizeGridCell(vGridCell: gridCell.view, frameY: frameY, frameH:50.0)

    gridCell.thisCustomer = thisCustomer

    self.svData.addSubview(gridCell.view)
}
</code>```

In BulkAddCell I have thisCustomer as a property:

```<code>var thisCustomer: Customer!
</code>```

I know BulkAddCell is initializing correctly as I have some IBOutlets in it and I can see them in the console. But thisCustomer is always nil.

I'm making the switch from Obj-C to Swift so I am sure it is something basic I am missing.

答:
Change:

```<code>var arrCustomers: Array = Customer
</code>```

To:

```<code>var arrCustomers = [Customer]() //init to an empty array of customer objects

//sometime later
//append your arrCustomers with instances of Customer

// before leaving first view controller access the arrCustomers object
// contents as needed and assign to a corresponding property on the
// destination view controller. (usually in preparforSegue)
</code>```

Body:
I have an array of Core Data entities that I can successfully pass from Objective-C VC to a Swift VC. I've verified through the console that they are coming in.

Now I need to loop through the array of core data objects and pass them onto another swift vc. I have the array set up as a property (Customer is the CD entity):

var arrCustomers: Array = Customer

In my loop I am trying to pass them to the other Swift VC:

for thisCustomer in self.arrCustomers {

    let gridCell = storyboard.instantiateViewController(withIdentifier: "bulkAddCell") as! BulkAddCell
    resizeGridCell(vGridCell: gridCell.view, frameY: frameY, frameH:50.0)

    gridCell.thisCustomer = thisCustomer

    self.svData.addSubview(gridCell.view)
}

In BulkAddCell I have thisCustomer as a property:

var thisCustomer: Customer!

I know BulkAddCell is initializing correctly as I have some IBOutlets in it and I can see them in the console. But thisCustomer is always nil.

I'm making the switch from Obj-C to Swift so I am sure it is something basic I am missing.

Body:
Change:

var arrCustomers: Array = Customer

To:

var arrCustomers = [Customer]() //init to an empty array of customer objects

//sometime later
//append your arrCustomers with instances of Customer

// before leaving first view controller access the arrCustomers object
// contents as needed and assign to a corresponding property on the
// destination view controller. (usually in preparforSegue)


问:
What is an efficient way to store vector data in Postgres?
I have some vectors, from embedding faces, and I would like to store them in database. What I need is to be able to find similar vectors from database given a referenced embedded face.

I have tried using array type in Postgres, but there is no support for subtraction.

The short term question is: can we perform array subtraction efficiently at database level in Postgres?

The long term question is: is there a better database system for this type of data and computation?

Thanks

--Update--

The specific problem is, suppose I have some vector data in a table

```<code>{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
</code>```

I want to figure out which one of these 3 vectors is closest (in Euclidean distance) to vector {5, 5, 5}.

The operations required are first to subtract 2 vectors, then to find the length of the difference ||{5, 5, 5} - {4, 5, 6}||_2

In my scenario, a vector will have 128 dimensions.

答: It seems that you want to use PostGIS which is an easy extension of PostgresQL which allows a whole bunch of geometric data type extensions. (point, vector, arc, etc.)</p>

Body:
I have some vectors, from embedding faces, and I would like to store them in database. What I need is to be able to find similar vectors from database given a referenced embedded face.

I have tried using array type in Postgres, but there is no support for subtraction.

The short term question is: can we perform array subtraction efficiently at database level in Postgres?

The long term question is: is there a better database system for this type of data and computation?

Thanks

--Update--

The specific problem is, suppose I have some vector data in a table

{1, 2, 3},
{4, 5, 6},
{7, 8, 9}

I want to figure out which one of these 3 vectors is closest (in Euclidean distance) to vector {5, 5, 5}.

The operations required are first to subtract 2 vectors, then to find the length of the difference ||{5, 5, 5} - {4, 5, 6}||_2

In my scenario, a vector will have 128 dimensions.


问:
Does array assignment create a new reference
I am running into the following situation. I am initializing an array, and assigning it to an object's property.

```<code>var arr = [1,2,3,4,5];
var obj = { 'numbers': arr };
</code>```

I understand that I passed a reference to my array arr to my object obj. So I can do the following:

```<code>arr.push(6);
console.log(obj);
</code>```

will display the following, as expected:

```<code>{ numbers: [ 1, 2, 3, 4, 5, 6] }
</code>```

Now for the unexpected part. The value of arr changes, through an external event, and I want the value of obj.numbers to change at the same time. But it does not:

```<code>arr = [0,0,0,0,0];
console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [ 1, 2, 3, 4, 5, 6] }
</code>```

So the value of my arr variable changed, but not the numbers property in my obj variable.

So, my only explanation is, that as soon as you perform an assignment to an array, you break the old reference and create a new reference. Is that so?

And how would I assign my new values [0,0,0,0,0] to my arr variable and the obj.numbers (at the same time)?

答:
Yes, an assignment with = creates a new reference and gets rid of the old one. To get around this:

  var arr = [1, 2, 3, 4, 5];
  var obj = { 'numbers': arr };
  console.log(arr === obj.numbers); // -> true

  arr.length = 0;
  var newArr = [0, 0, 0, 0, 0];
  arr.push(...newArr);
  console.log(arr === obj.numbers); // -> true
  console.log(arr); // -> [0, 0, 0, 0, 0]```

Setting length equal to 0 clears the array. When you push items into an array, it doesn't create a new array, so you'll see both arr and obj change.

Body:
I am running into the following situation. I am initializing an array, and assigning it to an object's property.

var arr = [1,2,3,4,5];
var obj = { 'numbers': arr };

I understand that I passed a reference to my array arr to my object obj. So I can do the following:

arr.push(6);
console.log(obj);

will display the following, as expected:

{ numbers: [ 1, 2, 3, 4, 5, 6] }

Now for the unexpected part. The value of arr changes, through an external event, and I want the value of obj.numbers to change at the same time. But it does not:

arr = [0,0,0,0,0];
console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [ 1, 2, 3, 4, 5, 6] }

So the value of my arr variable changed, but not the numbers property in my obj variable.

So, my only explanation is, that as soon as you perform an assignment to an array, you break the old reference and create a new reference. Is that so?

And how would I assign my new values [0,0,0,0,0] to my arr variable and the obj.numbers (at the same time)?

Body:
Yes, an assignment with = creates a new reference and gets rid of the old one. To get around this:

  var arr = [1, 2, 3, 4, 5];
  var obj = { 'numbers': arr };
  console.log(arr === obj.numbers); // -> true

  arr.length = 0;
  var newArr = [0, 0, 0, 0, 0];
  arr.push(...newArr);
  console.log(arr === obj.numbers); // -> true
  console.log(arr); // -> [0, 0, 0, 0, 0]

Setting length equal to 0 clears the array. When you push items into an array, it doesn't create a new array, so you'll see both arr and obj change.


问:
error: local class incompatible: stream classdec serialversionUID= ...., local class serialversionUID=
I have a serializable java class and when I add either of the following methods. I get this error

" local class incompatible: stream classdec serialversionUID= ...., local class serialversionUID=..."

added methods:

```<code>public HashMap<Long, BookIndex> getBookIndexMap() {
    return bookIndexMap;
}

public String getDataFileName() {
    return dataFileName;
}
</code>```

what is causing this and how can I correct it?

答:
I solved it by doing the following:

Working in Eclipse Neon.

On Tomcat Server

Clean Tomcat Work Directory...

Clean... (to do something, just in case)

then

Project

'Clean...' select your project and click 'Ok'

Body:
I have a serializable java class and when I add either of the following methods. I get this error

" local class incompatible: stream classdec serialversionUID= ...., local class serialversionUID=..."

added methods:

public HashMap<Long, BookIndex> getBookIndexMap() {
    return bookIndexMap;
}

public String getDataFileName() {
    return dataFileName;
}

what is causing this and how can I correct it?


问:
Can Kotlin data class have more than one constructor?
I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

```<code>data class User(val name: String, val age: Int)
</code>```

Is it possible to declare a second constructor for that data class?

答:
A Kotlin data class must have a primary constructor that defines at least one member.  Other than that, you can add secondary constructors as explained in Classes and Inheritance - Secondary Constructors.

For your class, and example secondary constructor:

```<code>data class User(val name: String, val age: Int) {
    constructor(name: String): this(name, -1) { ... }
}
</code>```

Notice that the secondary constructor must delegate to the primary constructor in its definition.

Although many things common to secondary constructors can be solved by having default values for the parameters. In the case above, you could simplify to:

```<code>data class User(val name: String, val age: Int = -1)
</code>```

If calling these from Java, you should read the Java interop - Java calling Kotlin documentation on how to generate overloads, and maybe sometimes the NoArg Compiler Plugin for other special cases.

Body:
I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

data class User(val name: String, val age: Int)

Is it possible to declare a second constructor for that data class?

Body:
A Kotlin data class must have a primary constructor that defines at least one member.  Other than that, you can add secondary constructors as explained in Classes and Inheritance - Secondary Constructors.

For your class, and example secondary constructor:

data class User(val name: String, val age: Int) {
    constructor(name: String): this(name, -1) { ... }
}

Notice that the secondary constructor must delegate to the primary constructor in its definition.

Although many things common to secondary constructors can be solved by having default values for the parameters. In the case above, you could simplify to:

data class User(val name: String, val age: Int = -1)

If calling these from Java, you should read the Java interop - Java calling Kotlin documentation on how to generate overloads, and maybe sometimes the NoArg Compiler Plugin for other special cases.


问:
Eclipse p2 alternative for custom install handlers
Before p2, one could write a custom install handler with a feature that was executed to do any 'custom' task during installation.

I see that with p2 the custom install handler is no longer supported.
I keep hearing about 'custom touchpoints' being the replacement for that.

However I cant find any concrete example/documentation for it.

Can anyone tell me how to get the functionality of custom install handlers with the p2 update manager.

Edit: A description of what I want to do -

I need to edit the eclipse.ini file and set the -Xmx property to a value based on whether we are running inside a 64 bit or 32 bit env.

Edit 2: I tried creating a p2.inf file in my feature with the following line -

```<code>instructions.install = \
addJvmArg(jvmArg:-Xmx900m);

instructions.install.import= \
org.eclipse.equinox.p2.touchpoint.eclipse.addJvmArg,
</code>```

and it works, however it does not differentiate between 32 and 64 bit.

答:
p2.inf definitely is the right place to perform customized actions. It is a good place to add vm arguments into .ini. You could put a p2.inf under your feature/plug-in.

Updated on 20 Dec.:

I tried it on my own environment, it works well to set different vm args when installing the same feature on linux 32bit and 64bit. You could download the example code to play with it.

```<code>#create a requirement on the IU fragment we are creating
requires.2.namespace=org.eclipse.equinox.p2.iu
requires.2.name=configure.com.example.yourfeature.linux.x86
requires.2.range=[1.0.0,1.0.0]
requires.2.greedy=true
requires.2.filter=(&(osgi.os=linux)(osgi.arch=x86))

#create a IU frament named configure.com.example.yourfeature.linux.x86 for linux 32 bit
units.0.id=configure.com.example.yourfeature.linux.x86
units.0.version=1.0.0
units.0.filter=(&(osgi.os=linux)(osgi.arch=x86))
units.0.provides.1.namespace=org.eclipse.equinox.p2.iu
units.0.provides.1.name=configure.com.example.yourfeature.linux.x86
units.0.provides.1.version=1.0.0
units.0.instructions.configure=addJvmArg(jvmArg:-Xmx500m);
units.0.instructions.configure.import=org.eclipse.equinox.p2.touchpoint.eclipse.addJvmArg,

#create a requirement on the IU fragment we are creating
requires.3.namespace=org.eclipse.equinox.p2.iu
requires.3.name=configure.com.example.yourfeature.linux.x86_64
requires.3.range=[1.0.0,1.0.0]
requires.3.greedy=true
requires.3.filter=(&(osgi.os=linux)(osgi.arch=x86_64))

#create a IU frament named configure.com.example.yourfeature.linux.x86_64 for linux 64 bit
units.1.id=configure.com.example.yourfeature.linux.x86_64
units.1.version=1.0.0
units.1.filter=(&(osgi.os=linux)(osgi.arch=x86_64))
units.1.provides.1.namespace=org.eclipse.equinox.p2.iu
units.1.provides.1.name=configure.com.example.yourfeature.linux.x86_64
units.1.provides.1.version=1.0.0
units.1.instructions.configure=org.eclipse.equinox.p2.touchpoint.eclipse.addJvmArg(jvmArg:-Xmx900m);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Before p2, one could write a custom install handler with a feature that was executed to do any 'custom' task during installation.

I see that with p2 the custom install handler is no longer supported.
I keep hearing about 'custom touchpoints' being the replacement for that.

However I cant find any concrete example/documentation for it.

Can anyone tell me how to get the functionality of custom install handlers with the p2 update manager.

Edit: A description of what I want to do -

I need to edit the eclipse.ini file and set the -Xmx property to a value based on whether we are running inside a 64 bit or 32 bit env.

Edit 2: I tried creating a p2.inf file in my feature with the following line -

instructions.install = \
addJvmArg(jvmArg:-Xmx900m);

instructions.install.import= \
org.eclipse.equinox.p2.touchpoint.eclipse.addJvmArg,

and it works, however it does not differentiate between 32 and 64 bit.

Body:
p2.inf definitely is the right place to perform customized actions. It is a good place to add vm arguments into .ini. You could put a p2.inf under your feature/plug-in.

Updated on 20 Dec.:

I tried it on my own environment, it works well to set different vm args when installing the same feature on linux 32bit and 64bit. You could download the example code to play with it.

#create a requirement on the IU fragment we are creating
requires.2.namespace=org.eclipse.equinox.p2.iu
requires.2.name=configure.com.example.yourfeature.linux.x86
requires.2.range=[1.0.0,1.0.0]
requires.2.greedy=true
requires.2.filter=(&(osgi.os=linux)(osgi.arch=x86))

#create a IU frament named configure.com.example.yourfeature.linux.x86 for linux 32 bit
units.0.id=configure.com.example.yourfeature.linux.x86
units.0.version=1.0.0
units.0.filter=(&(osgi.os=linux)(osgi.arch=x86))
units.0.provides.1.namespace=org.eclipse.equinox.p2.iu
units.0.provides.1.name=configure.com.example.yourfeature.linux.x86
units.0.provides.1.version=1.0.0
units.0.instructions.configure=addJvmArg(jvmArg:-Xmx500m);
units.0.instructions.configure.import=org.eclipse.equinox.p2.touchpoint.eclipse.addJvmArg,

#create a requirement on the IU fragment we are creating
requires.3.namespace=org.eclipse.equinox.p2.iu
requires.3.name=configure.com.example.yourfeature.linux.x86_64
requires.3.range=[1.0.0,1.0.0]
requires.3.greedy=true
requires.3.filter=(&(osgi.os=linux)(osgi.arch=x86_64))

#create a IU frament named configure.com.example.yourfeature.linux.x86_64 for linux 64 bit
units.1.id=configure.com.example.yourfeature.linux.x86_64
units.1.version=1.0.0
units.1.filter=(&(osgi.os=linux)(osgi.arch=x86_64))
units.1.provides.1.namespace=org.eclipse.equinox.p2.iu
units.1.provides.1.name=configure.com.example.yourfeature.linux.x86_64
units.1.provides.1.version=1.0.0
units.1.instructions.configure=org.eclipse.equinox.p2.touchpoint.eclipse.addJvmArg(jvmArg:-Xmx900m);


问:
Send http request in Ionic with Angular http
I have an ionic app that I am trying to send my Stripe token to, for payment processing. When I send the request to the node server with curl it is receiving the request. However, when I try to send the request via Angular's http module, it isn't registering at all. All of this is currently being tested locally, so that might be part of the issue?

HTML

```<code><button (click)="testPost()" ion-button full>TEST POST</button>
</code>```

cart.ts

```<code>...
import {Http, Headers, RequestOptions} from '@angular/http';
import { Stripe } from '@ionic-native/stripe';

@Component({
 selector: 'page-cart',
 templateUrl: 'cart.html',
})
export class Cart {

  constructor(
    ...
    private http: Http,
    private stripe: Stripe
    ) {
      //
    });
  }

  testPost() {
    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json' );
    let options = new RequestOptions({ headers: headers });

    let postParams = {
      body: {
        token: 'axqrexample123tokenbasdflkjo3',
        amount: 225
      }
    }

    this.http.post("http://11.1.1.7:3100/charge", postParams, options)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });
  }

}
</code>```

NODE SERVER

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var stripe = require("stripe")("sk_test_abcTAdefgn1oDexamplex");

app.use(bodyParser.json());

app.post('/charge', function (req, res) {

  var token = req.body.token;
  var amount = req.body.amount;
  stripe.charges.create({
    amount: amount,
    currency: "usd",
    source: token, // obtained with Stripe.js
    description: "Charge for jones@example.com"
  }, function(err, charge) {
    // asynchronously called
  });
  res.send('Hello World!')
});

app.listen(3100, function () {
  console.log('Example app listening on port 3100!')
})
</code>```

答:
I think you need to map the request before subscribing to the request

```<code>this.http.post("http://11.1.1.7:3100/charge", postParams, options)
      .map(res => res.json())
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });
</code>```

also, import the rxjs

```<code>import 'rxjs/Rx';
</code>```

Body:
I have an ionic app that I am trying to send my Stripe token to, for payment processing. When I send the request to the node server with curl it is receiving the request. However, when I try to send the request via Angular's http module, it isn't registering at all. All of this is currently being tested locally, so that might be part of the issue?

HTML

<button (click)="testPost()" ion-button full>TEST POST</button>

cart.ts

...
import {Http, Headers, RequestOptions} from '@angular/http';
import { Stripe } from '@ionic-native/stripe';

@Component({
 selector: 'page-cart',
 templateUrl: 'cart.html',
})
export class Cart {

  constructor(
    ...
    private http: Http,
    private stripe: Stripe
    ) {
      //
    });
  }

  testPost() {
    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json' );
    let options = new RequestOptions({ headers: headers });

    let postParams = {
      body: {
        token: 'axqrexample123tokenbasdflkjo3',
        amount: 225
      }
    }

    this.http.post("http://11.1.1.7:3100/charge", postParams, options)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });
  }

}

NODE SERVER

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var stripe = require("stripe")("sk_test_abcTAdefgn1oDexamplex");

app.use(bodyParser.json());

app.post('/charge', function (req, res) {

  var token = req.body.token;
  var amount = req.body.amount;
  stripe.charges.create({
    amount: amount,
    currency: "usd",
    source: token, // obtained with Stripe.js
    description: "Charge for jones@example.com"
  }, function(err, charge) {
    // asynchronously called
  });
  res.send('Hello World!')
});

app.listen(3100, function () {
  console.log('Example app listening on port 3100!')
})

Body:
I think you need to map the request before subscribing to the request

this.http.post("http://11.1.1.7:3100/charge", postParams, options)
      .map(res => res.json())
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });

also, import the rxjs

import 'rxjs/Rx';


问:
C++/CLI Dictionary of Dictionaries
Is there a way to create a Dictionary of Dictionaries in C++ CLI? I was previously using a Dictionary of String,ArrayList pairs and found it useful to have my ArrayList converted to a Dictionary of String,CustomValueStruct pairs instead to make use of the key matching.

The code I had for the Dictionary of String,ArrayList pairs:

```<code>Dictionary<String^, ArrayList^> myDictionary = gcnew Dictionary<String^, ArrayList^>();
</code>```

How can I convert this to use a Dictionary of Dictionaries?

The code I tried using, which doesn't compile is:

```<code>Dictionary<String^, Dictionary<String^, CustomValueStruct>> myDictionary = gcnew Dictionary<String^, Dictionary<String^, CustomValueStruct>>();
</code>```

Where CustomValueStruct is just a custom struct in my code, which previously lived in the ArrayList.

The result of the attempted line is:

```<code>error C3225: generic type argument for 'TValue' cannot be 'System::Collections::Generic::Dictionary<TKey,TValue>', it must be a value type or a handle to a reference type
</code>```

答:
As the compiler said, you forgot a ^:

```<code>auto myDictionary = gcnew Dictionary<String^, Dictionary<String^, CustomValueStruct>^>();
</code>```

Note that you need create a Dictionary<String^, CustomValueStruct> when adding items to myDictionary:

```<code>myDictionary.Add("Key", gcnew Dictionary<String^, CustomValueStruct>());
</code>```

Finally, be sure you really want CustomValueStruct to be a value type; you're usually better off writing

```<code>ref class CustomRefClass { /* ... */ };
</code>```

which in turn requires a ^ for the nested Dictionary:

```<code> auto myDictionary = gcnew Dictionary<String^, Dictionary<String^, CustomRefClass^>^>();
</code>```

Title: C++/CLI Dictionary of Dictionaries

Body:
Is there a way to create a Dictionary of Dictionaries in C++ CLI? I was previously using a Dictionary of String,ArrayList pairs and found it useful to have my ArrayList converted to a Dictionary of String,CustomValueStruct pairs instead to make use of the key matching.

The code I had for the Dictionary of String,ArrayList pairs:

Dictionary<String^, ArrayList^> myDictionary = gcnew Dictionary<String^, ArrayList^>();

How can I convert this to use a Dictionary of Dictionaries?

The code I tried using, which doesn't compile is:

Dictionary<String^, Dictionary<String^, CustomValueStruct>> myDictionary = gcnew Dictionary<String^, Dictionary<String^, CustomValueStruct>>();

Where CustomValueStruct is just a custom struct in my code, which previously lived in the ArrayList.

The result of the attempted line is:

error C3225: generic type argument for 'TValue' cannot be 'System::Collections::Generic::Dictionary<TKey,TValue>', it must be a value type or a handle to a reference type

Body:
As the compiler said, you forgot a ^:

auto myDictionary = gcnew Dictionary<String^, Dictionary<String^, CustomValueStruct>^>();

Note that you need create a Dictionary<String^, CustomValueStruct> when adding items to myDictionary:

myDictionary.Add("Key", gcnew Dictionary<String^, CustomValueStruct>());

Finally, be sure you really want CustomValueStruct to be a value type; you're usually better off writing

ref class CustomRefClass { /* ... */ };

which in turn requires a ^ for the nested Dictionary:

 auto myDictionary = gcnew Dictionary<String^, Dictionary<String^, CustomRefClass^>^>();


问:
PHP Parsing HTML to multidimensional JSON Array
I am working on parsing HTML and get multidimensional output array as json.
I am parsing html like I want but I couldn't create JSON array.

The example output of foreach loop:

PS: every json object has different string value.

0:"blahblah"

1:"blahblah"

2:"blahblah"

3:"blahblah"

4:" " // only space

5:"blahblah"

6:"blahblah"

7:"blahblah"

8:"blahblah"

9:" " // only space

...

I want create json array like this:

```<code> $output = array();
    $html = str_get_html($ret);

    $lessons["lesson"] =array();
    foreach($html->find('table//tbody//tr') as $element) {

        $temp = strip_tags($element->innertext);

        array_push($lessons['lesson'], $temp); // the objects (I wrote as 'blahblah' every object but I getting different values always)

        if($temp == " ") // if there is only space push array the output and create new array
        {

            array_push($output , $lessons["lesson"]);
            unset($lessons);
            $lessons["lesson"] = array();
        }
    }
echo (json_encode($output ,JSON_UNESCAPED_UNICODE)); // $output show nothing
</code>```

Thanks in advice.

答:
If your issue is getting all the blah into the array then the below will get you there. I am not following the code too well but attempt to explain my thoughts in comments.</p>

```<code>$json = ["blahblah"
,"blahblah"
,"blahblah"
,"blahblah"
," "
,"blahblah"
,"blahblah"
,"blahblah"
,"blahblah"
," "];

$lessons["lesson"] = []; // I think this is the array you are using
$tmp = []; // Something tmp to hold things
foreach($json as $elm){ //Loop what I assume $html->find('table//tbody//tr') is returning
    if($elm != ' '){//Wait for a ' ' and add to tmp
        $tmp[] = $elm;
    } else {
         $lessons["lesson"][] = $tmp; // This array is done so keep it and restart
         $tmp = [];
    }
}
</code>```

Body:
I am working on parsing HTML and get multidimensional output array as json.
I am parsing html like I want but I couldn't create JSON array.

The example output of foreach loop:

PS: every json object has different string value.

0:"blahblah"

1:"blahblah"

2:"blahblah"

3:"blahblah"

4:" " // only space

5:"blahblah"

6:"blahblah"

7:"blahblah"

8:"blahblah"

9:" " // only space

...

I want create json array like this:

 $output = array();
    $html = str_get_html($ret);

    $lessons["lesson"] =array();
    foreach($html->find('table//tbody//tr') as $element) {

        $temp = strip_tags($element->innertext);

        array_push($lessons['lesson'], $temp); // the objects (I wrote as 'blahblah' every object but I getting different values always)

        if($temp == " ") // if there is only space push array the output and create new array
        {

            array_push($output , $lessons["lesson"]);
            unset($lessons);
            $lessons["lesson"] = array();
        }
    }
echo (json_encode($output ,JSON_UNESCAPED_UNICODE)); // $output show nothing

Thanks in advice.

Body:
If your issue is getting all the blah into the array then the below will get you there. I am not following the code too well but attempt to explain my thoughts in comments.

$json = ["blahblah"
,"blahblah"
,"blahblah"
,"blahblah"
," "
,"blahblah"
,"blahblah"
,"blahblah"
,"blahblah"
," "];

$lessons["lesson"] = []; // I think this is the array you are using
$tmp = []; // Something tmp to hold things
foreach($json as $elm){ //Loop what I assume $html->find('table//tbody//tr') is returning
    if($elm != '&nbsp;'){//Wait for a ' ' and add to tmp
        $tmp[] = $elm;
    } else {
         $lessons["lesson"][] = $tmp; // This array is done so keep it and restart
         $tmp = [];
    }
}


问:
data attribute not updated before page refresh with jQuery
In my project I have a table, each of its rows holding id and title as data attributes

```<code><tr data-id="1" data-title="title"><td id="td_title">some text</td></tr>
</code>```

I use jQuery to update the data-tile attribute

```<code>$newTitle = 'newTitle';
$row_to_update = $("tr").find("[data-id='1']");
$row_to_update.attr('data-title', newTitle );
</code>```

So after that, in  the html I can see the updated values, but if I try this:

```<code>$var = $row_to_update.data('title');
alert($var);
</code>```

It returns the old title, unless I load the page again.
I suppose I have to clear the cache, but I only found $.domCache, which is not applicable to jQuery and also saw and tried

```<code>function clearjQueryCache(){
    for (var x in jQuery.cache){
        delete jQuery.cache[x];
    }
}
</code>```

but obviously not correct, as everything stopped working

答: Rather than .data('title'), you can use .attr('data-title'). This may work.

Body:
In my project I have a table, each of its rows holding id and title as data attributes

some text

I use jQuery to update the data-tile attribute

$newTitle = 'newTitle';
$row_to_update = $("tr").find("[data-id='1']");
$row_to_update.attr('data-title', newTitle );

So after that, in  the html I can see the updated values, but if I try this:

$var = $row_to_update.data('title');
alert($var);

It returns the old title, unless I load the page again.
I suppose I have to clear the cache, but I only found $.domCache, which is not applicable to jQuery and also saw and tried

function clearjQueryCache(){
    for (var x in jQuery.cache){
        delete jQuery.cache[x];
    }
}

but obviously not correct, as everything stopped working


问:
Convert nested loop to recursion
I have used 3 nested loop. Now i want to convert these loops to recursive.
Also is there a general way to convert a loop into recursive?</p>

```<code>#include <stdio.h>

#define f(x, y, z) ((x + y) * (y + z))

int main()
{
    int test_case, p, q, r, i, j, k, a[100001], b[100001], c[100001], sum;
    scanf("%d", &test_case);
    while (test_case--) {
        scanf("%d%d%d", &p, &q, &r);
        sum = 0;
        for (i = 0; i < p; i++) {
            scanf("%d", &a[i]);
        }
        for (i = 0; i < q; i++) {
            scanf("%d", &b[i]);
        }
        for (i = 0; i < p; i++) {
            scanf("%d", &c[i]);
        }
        for (i = 0; i < q; i++) { // I have convert this to recursion.
            for (j = 0; j < p; j++) {
                for (k = 0; k < r; k++) {
                    if (b[i] >= a[j] && b[i] >= c[k]) {
                        sum += f(a[j], b[i], c[k]);
                    }
                }
            }
        }
        printf("%d\n", sum % 1000000007);
    }
    return 0;
}
</code>```

答:
Let us assume that the intention of this code is to only calculate the sum.

You can make a function as

```<code>int recurse_sum(int i, int j, int k) {
      int res = .... // Logic for calculating sum for these indices i, j, k.
      k++;
      if (k==r) {
          k = 0;
          j++;
      }
      if(j==p){
          j=0;
          i++;
      }
      if(i==q){
          return res;
      }
      return res + recurse_sum(i,j,k);
}
</code>```

Now you can just call with recurse_sum(0,0,0);
The rest of the parameters can either be made global or just passed along with i,j,k.

I hope this helps.

Edit:

As mentioned by @dlasalle this code can be made open to tail call recursion optimization by placing the call at the end of the function.

In that case you can have the following version.

```<code>int recurse_sum(int i, int j, int k, int sum) {
      int res = .... // Logic for calculating sum for these indices i, j, k.
      k++;
      if (k==r) {
          k = 0;
          j++;
      }
      if(j==p){
          j=0;
          i++;
      }
      if(i==q){
          return res + sum;
      }
      return recurse_sum(i,j,k,res+sum);
}
</code>```

Here the function ends with returning the value from the inner call and hence can be easily optimized.

Ofcourse in this case it will have to be called as recurse_sum(0,0,0,0);

Title: Convert nested loop to recursion

Body:
I have used 3 nested loop. Now i want to convert these loops to recursive.
Also is there a general way to convert a loop into recursive?

#include <stdio.h>

#define f(x, y, z) ((x + y) * (y + z))

int main()
{
    int test_case, p, q, r, i, j, k, a[100001], b[100001], c[100001], sum;
    scanf("%d", &test_case);
    while (test_case--) {
        scanf("%d%d%d", &p, &q, &r);
        sum = 0;
        for (i = 0; i < p; i++) {
            scanf("%d", &a[i]);
        }
        for (i = 0; i < q; i++) {
            scanf("%d", &b[i]);
        }
        for (i = 0; i < p; i++) {
            scanf("%d", &c[i]);
        }
        for (i = 0; i < q; i++) { // I have convert this to recursion.
            for (j = 0; j < p; j++) {
                for (k = 0; k < r; k++) {
                    if (b[i] >= a[j] && b[i] >= c[k]) {
                        sum += f(a[j], b[i], c[k]);
                    }
                }
            }
        }
        printf("%d\n", sum % 1000000007);
    }
    return 0;
}

Body:
Let us assume that the intention of this code is to only calculate the sum.

You can make a function as

int recurse_sum(int i, int j, int k) {
      int res = .... // Logic for calculating sum for these indices i, j, k.
      k++;
      if (k==r) {
          k = 0;
          j++;
      }
      if(j==p){
          j=0;
          i++;
      }
      if(i==q){
          return res;
      }
      return res + recurse_sum(i,j,k);
}

Now you can just call with recurse_sum(0,0,0);
The rest of the parameters can either be made global or just passed along with i,j,k.

I hope this helps.

Edit:

As mentioned by @dlasalle this code can be made open to tail call recursion optimization by placing the call at the end of the function.

In that case you can have the following version.

int recurse_sum(int i, int j, int k, int sum) {
      int res = .... // Logic for calculating sum for these indices i, j, k.
      k++;
      if (k==r) {
          k = 0;
          j++;
      }
      if(j==p){
          j=0;
          i++;
      }
      if(i==q){
          return res + sum;
      }
      return recurse_sum(i,j,k,res+sum);
}

Here the function ends with returning the value from the inner call and hence can be easily optimized.

Ofcourse in this case it will have to be called as recurse_sum(0,0,0,0);


问:
Finding the size of an array of strings in C++
So I have an array of strings. Here's an example:

```<code>std::string array[] = {"Example", "Example2", "Example3"};
</code>```

Is there any way I can find the number of elements in an array like the one above. I can't use this method:

```<code>int numberofelements = sizeof(array)/sizeof(array[0]);
</code>```

This is because the size of the elements vary. Is there another way?

答:
We can find the number of elements of an array by  simply using the size() function.

Example Code:

```<code>string exampleArray[] = { "Example", "Example2", "Example3" };
    int size_of_array = size(exampleArray);

cout << "Number of elements in array = " << size_of_array << endl;
</code>```

Output:

```<code>>>> Number of elements in array = 3
</code>```

Hope it helps you.

Body:
So I have an array of strings. Here's an example:

std::string array[] = {"Example", "Example2", "Example3"};

Is there any way I can find the number of elements in an array like the one above. I can't use this method:

int numberofelements = sizeof(array)/sizeof(array[0]);

This is because the size of the elements vary. Is there another way?

Body:
We can find the number of elements of an array by  simply using the size() function.

Example Code:

string exampleArray[] = { "Example", "Example2", "Example3" };
    int size_of_array = size(exampleArray);

cout << "Number of elements in array = " << size_of_array << endl;

Output:

>>> Number of elements in array = 3

Hope it helps you.


问:
Should I use the Main method in my C# program or the reader method to create my list?
I am working on a project that will read data from an excel sheet, put each row into a class called "Sale" and then manipulate the list in the future. Should I add the sales into the list in the class that I am using to read the excel document, titled "Reader", or should I create the list in the Main class and method. I currently have my main method creating an instance of the Reader. This reader then passes the rows, or "Sales" through a modifier which will sort them. Then a printer class takes the list as a parameter and prints it onto the same workbook on a different document.  </p>

<p>Will doing one or the other make any significant difference in my program? If so why and which is better in terms of efficiency and organization.  </p>

答:
I agree with @Deolus in reference to Sales being its own class.

Keep Sales and Reader separate because they have different purposes.  If the Reader class was created to solely read data from an excel sheet then that should be its only objective.  In the Sales class you can create additional methods to manipulate the list of sales in the future.

Will doing one or the other make any significant difference in my program?

In terms of speed when running the program this will not make a difference, but in terms of maintainability this is GOLD.

This is a perfect example of separation of concerns.  The better you keep your code organized and not mangled spaghetti code, the more efficient and effective you will be when it comes time to maintain this code in the future.  So, the significant difference will be when you have to maintain & sustain this in the future.

I hope this helps.

Body:
I am working on a project that will read data from an excel sheet, put each row into a class called "Sale" and then manipulate the list in the future. Should I add the sales into the list in the class that I am using to read the excel document, titled "Reader", or should I create the list in the Main class and method. I currently have my main method creating an instance of the Reader. This reader then passes the rows, or "Sales" through a modifier which will sort them. Then a printer class takes the list as a parameter and prints it onto the same workbook on a different document.

Will doing one or the other make any significant difference in my program? If so why and which is better in terms of efficiency and organization.


答:
That's a tricky question since you don't define your later action/classes you work with.
If you'll have another class to work on that data, it might be better to wipe the instance of your reader class from your memory.
Keeping the list in your main class however might be bad too, it is important to know if you pass by value or by reference here for example. Having your reader class pass values, having your main class save those values and pass them to your work class might be bad for cpu (as this takes more steps) and memory since you create copies - and maybe you don't need the data in your main class anymore after passing it.

What counts in on efficiency too is hard drive space (although nobody cares about that, in terms of small applications it isn't significant after all) - less code taking less of your hard drive often is more intense on memory and/or cpu.

Your question is generally to vague to explicitly say what's more efficient, but you also have to notice, that code optimization is to enhance existing code, not to build code itself in the first place.

Title: Should I use the Main method in my C# program or the reader method to create my list?


问:
How can I remove effect of gravity using LayoutParams method in Android? (Gravity.NO_GRAVITY doesn't work.)
I have expected that TextView was aligned to the right because of NO_GRAVITY, however it was aligned to the left. Shouldn't NO_GRAVITY leave the gravity setting as it is, instead of aligning it to the left. If I also remove this two lines belove, it still aligns the TextView to the left even if I specify android:layout_gravity="center" in xml code.

```<code>params.gravity = Gravity.RIGHT;
params.gravity = Gravity.NO_GRAVITY;
</code>```

How can I change other properties of the layout without effecting its gravity? What is exactly the difference between LEFT and NO_GRAVITY?

```<code>LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
params.gravity = Gravity.NO_GRAVITY;
textView.setLayoutParams(params);
</code>```

答:
Gravity.NO_GRAVITY might (its just a guess) mean "default" gravity, which in your locale is left, but in some countries it might be right (arabic e.g., due to writting direction). if you want centered aligning then you can set Gravity.CENTER, obviusly...

if you want to combine two Gravities, then you can use flag add

```<code>params.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
</code>```

besides that if you are setting LinearLayout.LayoutParams then textViews parent must be LinearLayout. in rare cases with dynamic layouts and multiple threads  change in params shoud be continued with requestLayout() method call for forcing "redraw" in proper position and thread

Body:
I have expected that TextView was aligned to the right because of NO_GRAVITY, however it was aligned to the left. Shouldn't NO_GRAVITY leave the gravity setting as it is, instead of aligning it to the left. If I also remove this two lines belove, it still aligns the TextView to the left even if I specify android:layout_gravity="center" in xml code.

params.gravity = Gravity.RIGHT;
params.gravity = Gravity.NO_GRAVITY;

How can I change other properties of the layout without effecting its gravity? What is exactly the difference between LEFT and NO_GRAVITY?

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
params.gravity = Gravity.NO_GRAVITY;
textView.setLayoutParams(params);

Body:
Gravity.NO_GRAVITY might (its just a guess) mean "default" gravity, which in your locale is left, but in some countries it might be right (arabic e.g., due to writting direction). if you want centered aligning then you can set Gravity.CENTER, obviusly...

if you want to combine two Gravities, then you can use flag add

params.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;

besides that if you are setting LinearLayout.LayoutParams then textViews parent must be LinearLayout. in rare cases with dynamic layouts and multiple threads  change in params shoud be continued with requestLayout() method call for forcing "redraw" in proper position and thread


问:
C# How to automatically navigate to {GUID} Directory?
I have a program which utilizes a 3rd party tool to create a log text file.

However the tool requires the restore point directory of windows XP. The directory that stores the Restore points is the "C:\System Volume Information_restore{GUID}".

The _restore{GUID} folder would contain all the restore points. However the {GUID} are totally random numbers and are different for each computers. The "C:\System Volume Information" directory would only usually contain 1 folder which is the "_random{GUID}" folder.

Therefore is there a way for the C# program to use any codes or methods to automatically fill in the command arguments for the tool?

May someone please advise on the codes? Thanks!

The codes:

```<code>        Process process = new Process();
        process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
        // How to automatically navigate to the {GUID} folder?
        process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\_restore{GUID} -p runmru";
        process.StartInfo.CreateNoWindow = false;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardError = true;
        process.Start();
</code>```

The 3rd party tool (2008 H. Carvey) Arguments:

```<code>C:\>ripxp -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist
</code>```

答:
This code shows how to get the most recently created _restore directory:</p>

```<code>    static void Main(string[] args)
    {
        DirectoryInfo di = new DirectoryInfo(@"c:\System Volume Information");
        DirectoryInfo directoryInfo = null;
        foreach (var enumerateDirectories in di.GetDirectories("_restore*"))
        {
            if (directoryInfo == null || enumerateDirectories.CreationTime > directoryInfo.CreationTime)
            {
                directoryInfo = enumerateDirectories;
            }
        }
        if (directoryInfo != null)
        {
            Console.WriteLine(directoryInfo.FullName);
        }
        Console.ReadLine();
    }
</code>```

Body:
I have a program which utilizes a 3rd party tool to create a log text file.

However the tool requires the restore point directory of windows XP. The directory that stores the Restore points is the "C:\System Volume Information_restore{GUID}".

The _restore{GUID} folder would contain all the restore points. However the {GUID} are totally random numbers and are different for each computers. The "C:\System Volume Information" directory would only usually contain 1 folder which is the "_random{GUID}" folder.

Therefore is there a way for the C# program to use any codes or methods to automatically fill in the command arguments for the tool?

May someone please advise on the codes? Thanks!

The codes:

        Process process = new Process();
        process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
        // How to automatically navigate to the {GUID} folder?
        process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\_restore{GUID} -p runmru";
        process.StartInfo.CreateNoWindow = false;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardError = true;
        process.Start();

The 3rd party tool (2008 H. Carvey) Arguments:

C:\>ripxp -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist

Body:
This code shows how to get the most recently created _restore directory:

    static void Main(string[] args)
    {
        DirectoryInfo di = new DirectoryInfo(@"c:\System Volume Information");
        DirectoryInfo directoryInfo = null;
        foreach (var enumerateDirectories in di.GetDirectories("_restore*"))
        {
            if (directoryInfo == null || enumerateDirectories.CreationTime > directoryInfo.CreationTime)
            {
                directoryInfo = enumerateDirectories;
            }
        }
        if (directoryInfo != null)
        {
            Console.WriteLine(directoryInfo.FullName);
        }
        Console.ReadLine();
    }


问:
Is there a way to get the task manager id of the flink taskmanagers
I want to get the integral id / hash id of task manager and report metrics using that.</p>

答:
Finally I got the solution by getting YARN application container ID for each task manager was running into.

The container id's suits my purpose, thanks for all your insights though.


问:
How to pass data from sub-view to main-view in Angular 2?
I have two buttons on the main view: Login and Logout. Initially only Login button is shown:

...

```<code><button type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button>
<button type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button>

<router-outlet></router-outlet>
</code>```

Login button will display a sub-view, once user is authenticated there, I want to pass the result back to main view, if user is authenticated, I want to hide the 'Login' button and show the 'Logout' button.

How can I pass the data from a sub-view back to main view via 'router-outlet'?

答:
You will want to use a service to share information between components. Once the user is authenticated you would want to set a property in this service that indicates the user is authenticated.

Once you have done that you can reference this service to determine if you should show hide something using *ngIf.

Here is a question answered that is similar to yours.

Body:
I have two buttons on the main view: Login and Logout. Initially only Login button is shown:

...

<button type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button>
<button type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button>

<router-outlet></router-outlet>

Login button will display a sub-view, once user is authenticated there, I want to pass the result back to main view, if user is authenticated, I want to hide the 'Login' button and show the 'Logout' button.

How can I pass the data from a sub-view back to main view via 'router-outlet'?


问:
Joomla current path
I have Joomla Component administrator/components/com_mycomp

And I have import.php file in this folder.

How I can access import.php from com_mycomp.php.

```<code>require_once('./import.php');
</code>```

Gives error file not found. Because current path is /administrator , instead of administrator/components/com_mycomp.

答:
Best way is to use Joomla constants, use

JPATH_ADMINISTRATOR - The path to the administrator folder.

or

JPATH_COMPONENT_ADMINISTRATOR - The path to the administration folder of the current component being executed.

for more refer-
https://docs.joomla.org/Constants

Let me know if still face any issue.

Title: Joomla current path

Body:
I have Joomla Component administrator/components/com_mycomp

And I have import.php file in this folder.

How I can access import.php from com_mycomp.php.

require_once('./import.php');

Gives error file not found. Because current path is /administrator , instead of administrator/components/com_mycomp.


问:
Show Google Map In Modal After Ajax Call
so I'm working on a site where I want to show a google map inside a modal after an ajax call. I'm using bootstrap to show a modal, the problem is the map just stays blank after the modal is opened.

Something weird that happens is when I hit f12 on chrome to bring up the developer tab the map magically shows up although not centered on the marker position.

This is my Ajax Call:

```<code>$('.btnSeeOrder').on("click", function(){
    $("#modalSeeOrder").modal("show"); //open bootstrap modal
    var order_id = $(this).attr("data-orderId");

    $.ajax({
      type: "POST",
      url: "get_order_details.php",
      data: {
        order_id: order_id
      },
      beforeSend: function(){
        $(".order-details-modal").html("<i class='glyphicon glyphicon-refresh spinning'></i>");
      },
      success: function(data){
        $(".order-details-modal").html(data);
      },
      error: function(){
        $(".order-details-modal").html("<b>Ooops... Error....</b>");
      }
    });
  });
</code>```

This is my get_order_details.php file:

```<code><?php
  require '../../../app/Functions.php';
  $obj = new Admin_Functions();

  //Get order info, user info and map
  $info = $obj->getOrderInfo($_POST['order_id']);

?>

<div class="row">
  <div class="col-lg-12" style="margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid #ccc;">
    <div class="row">
      <div id="map-canvas" style="width: 100%; height: 400px;"></div>

    </div>
  </div>
</div>

<script type="text/javascript">
// latitude and longitude are being loaded in from the database
// example coords from database: 50.44444,-19.444444

var myLatlng = new google.maps.LatLng(<?php echo explode(",", $info["lat_lng"])[0]; ?>,<?php echo explode(",", $info["lat_lng"])[1]; ?>);
var mapOptions = {
  zoom: 16,
  center: myLatlng,
  styles:
  [{"featureType":"landscape","elementType":"geometry","stylers":[{"saturation":"-100"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#e9e5dc"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels.text","stylers":[{"color":"#545454"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"saturation":"-87"},{"lightness":"-40"},{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.fill","stylers":[{"color":"#f0f0f0"},{"saturation":"-22"},{"lightness":"-16"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"labels.icon","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.local","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"saturation":"-52"},{"hue":"#00e4ff"},{"lightness":"-16"}]}]
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  icon: 'https://www.robotevents.com/images/maps/markers/orange.png'
});
</script>
</code>```

This is what the map looks like when loaded in:

Anyone know how I can fix or go about this issue? Any help is greatly appreciated!

答:
Here your Map is not loading due to the imitate call of the ajax the main reason for partial loading of map try to load the map after ajax call.

Instead of dynamic loading of Google Maps API you could utilize
google.maps.event.addDomListener(window, 'load', initialize);

were:
function initialize(){ //Map initialization code};

Body:
so I'm working on a site where I want to show a google map inside a modal after an ajax call. I'm using bootstrap to show a modal, the problem is the map just stays blank after the modal is opened.

Something weird that happens is when I hit f12 on chrome to bring up the developer tab the map magically shows up although not centered on the marker position.

This is my Ajax Call:

$('.btnSeeOrder').on("click", function(){
    $("#modalSeeOrder").modal("show"); //open bootstrap modal
    var order_id = $(this).attr("data-orderId");

    $.ajax({
      type: "POST",
      url: "get_order_details.php",
      data: {
        order_id: order_id
      },
      beforeSend: function(){
        $(".order-details-modal").html("");
      },
      success: function(data){
        $(".order-details-modal").html(data);
      },
      error: function(){
        $(".order-details-modal").html("Ooops... Error....");
      }
    });
  });

This is my get_order_details.php file:

<?php
  require '../../../app/Functions.php';
  $obj = new Admin_Functions();

  //Get order info, user info and map
  $info = $obj->getOrderInfo($_POST['order_id']);

?>

This is what the map looks like when loaded in:

Anyone know how I can fix or go about this issue? Any help is greatly appreciated!


问:
window.scrollTo not working in iOS chrome
We are using javascript code to scroll to a div with the given ID. I tried to use

```<code>jQuery.animate({scrollTop: number})

window.scrollTo(0, number)

setTimeout(function() {window.scrollTo(0, number);}, 1000)
</code>```

I also tried to add #element_id to the url to scroll to the element_id.

None of these options are working. Is there any way to get it to work?

iOS: 9.2.1

Chrome: 48.0.2564.87

http://jsfiddle.net/fXx6c/114/

答:
You can use window.scroll() instead. I tested in your jsfiddle and it worked. Usage would be the same as window.scrollTo().

For example: window.scroll(0, 485);

This answer might explain why window.scrollTo doesn't work

Body:
We are using javascript code to scroll to a div with the given ID. I tried to use

jQuery.animate({scrollTop: number})

window.scrollTo(0, number)

setTimeout(function() {window.scrollTo(0, number);}, 1000)

I also tried to add #element_id to the url to scroll to the element_id.

None of these options are working. Is there any way to get it to work?

iOS: 9.2.1

Chrome: 48.0.2564.87

http://jsfiddle.net/fXx6c/114/


问:
Django forms - rendering form and redirecting
I am trying to create an 'add user' feature which will simply add the user you've selected from a dropdown as your connection. I am using ModelChoiceField from Django Forms so that I may get the existing users from my User model in the dropdown.

forms.py

```<code>from django import forms
from django.contrib.auth.models import User

class NetworkForm(forms.Form):
    user_id = forms.ModelChoiceField(queryset=User.objects.all(), label='',
                                       widget=forms.Select(attrs={'class': 'all_users'}))
</code>```

views.py

```<code>@login_required
def index(request):
    user_list = User.objects.exclude(username=request.user)
    return render(request, 'chat/index.html', {'user_list': user_list})
</code>```

For now I am just printing the form to see output

```<code>@login_required
def add_user(request):
    form = NetworkForm()
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            print form
            return redirect(request.META['HTTP_REFERER'])

    errors = form.errors or None

    return render(request, 'chat/index.html', {
        'form': form,
        'errors': errors,
    })
</code>```

index.html

<form action="{% url 'chat:add_user' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>

```
</div>
</div>
</p>

<p><strong>urls.py</strong></p>

```urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^add_user/$', views.add_user, name='add_user'),]
```

<p>The way it is being rendered currently is: I have my main index page where I don't see any dropdown, i.e.,
<img src="https://i.stack.imgur.com/Idroe.png" alt="enter image description here"></p>

<p>When I click on the submit button, it moves me to index/add_user, where I get a dropdown with user (with a warning "this field is required) and a submit button again.
<img src="https://i.stack.imgur.com/iXJRp.png" alt="enter image description here"></p>

<p>Finally, when I choose a user in this new page and hit submit, finally the form is printed, which I want ultimately.<img src="https://i.stack.imgur.com/Wtjf4.png" alt="enter image description here"></p>

<p><strong><em>What I would want it, have the complete form with dropdown in the index page itself and remain there when I submit the form.</em></strong> I will then hook that to show user the users they have added beneath that form itself ('print' is just for debugging purpose - not a good way I've heard though).
I understand the post request will have to go to add_user page and I can redirect back from that. I have tried various alternatives for the past 6 hours, nothing works yet. Apologies for a long one, giving out information as much as possible. Thanks very much guys. You are awesome. </p>

<p><strong>Edit</strong>
Have been now rendering the form in index page (suggestion from @fazil-zaid ), but the issue remains as in only 'submit' button appears on index initially, unless when I hit submit after which the dropdown and submit appears. Again, on clicking the second time, the form is submitted. </p>

<p><strong>Edit-2</strong>
I am thinking that:</p>

```<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
{{ form.as_p }}
    <button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
```

<p>this might be where the problem is, as per current logic unless user takes form's action, i.e., clicks the button {{ form.as_p }} will not appear. Then I tried:</p>

```{{ form.as_p }}
<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
    <button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
```

Doesn't work still. POST request doesn't send any data (understandably so).

答:
Solution:
When the page is called in the first instance using GET, the form is not valid as it seeks a POST method. Hence, all the method need to be changed to POST in the view, i.e.,

```<code>@login_required
def index(request):
    user_list = User.objects.exclude(username=request.user)
    form = NetworkForm()
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            print form.data
            return redirect(request.META['HTTP_REFERER'])

    return render(request, 'chat/index.html', {
        'user_list': user_list,
        'form': form,
    })
</code>```

Earlier, index was using a GET to render data to index page, and using a POST to use the form. Now, everything works fine.
Special shout-out to @fazil-zaid for the heads-up since you mentioned to include everything in the index view itself, rather than making a separate view for form. Your code pointed that out in a way in addition to Stack here.

Body:
I am trying to create an 'add user' feature which will simply add the user you've selected from a dropdown as your connection. I am using ModelChoiceField from Django Forms so that I may get the existing users from my User model in the dropdown.

forms.py

from django import forms
from django.contrib.auth.models import User

class NetworkForm(forms.Form):
    user_id = forms.ModelChoiceField(queryset=User.objects.all(), label='',
                                       widget=forms.Select(attrs={'class': 'all_users'}))

views.py

@login_required
def index(request):
    user_list = User.objects.exclude(username=request.user)
    return render(request, 'chat/index.html', {'user_list': user_list})

For now I am just printing the form to see output

@login_required
def add_user(request):
    form = NetworkForm()
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            print form
            return redirect(request.META['HTTP_REFERER'])

    errors = form.errors or None

    return render(request, 'chat/index.html', {
        'form': form,
        'errors': errors,
    })

index.html

<form action="{% url 'chat:add_user' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>

urls.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^add_user/$', views.add_user, name='add_user'),]

The way it is being rendered currently is: I have my main index page where I don't see any dropdown, i.e.,

When I click on the submit button, it moves me to index/add_user, where I get a dropdown with user (with a warning "this field is required) and a submit button again.

Finally, when I choose a user in this new page and hit submit, finally the form is printed, which I want ultimately.

What I would want it, have the complete form with dropdown in the index page itself and remain there when I submit the form. I will then hook that to show user the users they have added beneath that form itself ('print' is just for debugging purpose - not a good way I've heard though).
I understand the post request will have to go to add_user page and I can redirect back from that. I have tried various alternatives for the past 6 hours, nothing works yet. Apologies for a long one, giving out information as much as possible. Thanks very much guys. You are awesome.

Edit
Have been now rendering the form in index page (suggestion from @fazil-zaid ), but the issue remains as in only 'submit' button appears on index initially, unless when I hit submit after which the dropdown and submit appears. Again, on clicking the second time, the form is submitted.

Edit-2
I am thinking that:

<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
{{ form.as_p }}
    <button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>

this might be where the problem is, as per current logic unless user takes form's action, i.e., clicks the button {{ form.as_p }} will not appear. Then I tried:

{{ form.as_p }}
<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
    <button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>

Doesn't work still. POST request doesn't send any data (understandably so).

Body:
Solution:
When the page is called in the first instance using GET, the form is not valid as it seeks a POST method. Hence, all the method need to be changed to POST in the view, i.e.,

@login_required
def index(request):
    user_list = User.objects.exclude(username=request.user)
    form = NetworkForm()
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            print form.data
            return redirect(request.META['HTTP_REFERER'])

    return render(request, 'chat/index.html', {
        'user_list': user_list,
        'form': form,
    })

Earlier, index was using a GET to render data to index page, and using a POST to use the form. Now, everything works fine.
Special shout-out to @fazil-zaid for the heads-up since you mentioned to include everything in the index view itself, rather than making a separate view for form. Your code pointed that out in a way in addition to Stack here.


问:
Chat server for Rails
As it is evident that AJAX based chats do not scale, so what would you use for chats? Custom servers? Or any other methods?

Since with Rails each chat connection will take lots of memory, it won't be feasible to even have Rails run for each message. What do you recommend for use here?

答:
Why create any kind of custom server for chat? IRC has been around for quite a while and is tried and tested.

The real question here should be about client-side implementations rather than trying to reinvent the wheel server side imo.

Title: Chat server for Rails


问:
Get Application parameters not working
I use the following lib to be access via code to CF,
https://github.com/prosociallearnEU/cf-nodejs-client

what I need to do is to get app for specific space and get the app env

currently i was able to get the all apps but not the env for specific app , any idea what I miss here ? I dont get any informative error to be able to understand what can be missed ...

```<code>const CloudController = new (require("cf-nodejs-client")).CloudController(endpoint, proxy);
    const UsersUAA = new (require("cf-nodejs-client")).UsersUAA;
    const Apps = new (require("cf-nodejs-client")).Apps(endpoint, proxy);
    const Orgs = new (require("cf-nodejs-client")).Organizations(endpoint, proxy);

    CloudController.getInfo()
        .then((result) => {
            console.log(result);
            UsersUAA.setEndPoint(result.authorization_endpoint, proxy);
            return UsersUAA.login(username, password);
        }).then((result) => {
        Apps.setToken(result);
         return Apps.getApps();
    }).then((result) => {
        Apps.setToken(result);
        console.log("app guid is: " + result.resources[0].metadata.guid);
        return result.resources[0].metadata.guid;
    }).then((guid) => {
       return Apps.getEnvironmentVariables(guid);
    }).then((result) => {
        console.log(result);
    }).catch((reason) => {
        console.error("Error: " + reason);
    });
</code>```

UPDATE

what I need is to get appEnv for specified app (and i've the org & space & App name ), I need that the code will be efficient (performance...) , is my code flow is OK?

答:
Based on your request (get app environment) and the documentation here: cf-nodejs-client v0.13 documentation, it appears that the getEnvirnmentVariables function would give you what you need. </p>

<p>As an alternative, you could do the following: </p>

```<code>var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
</code>```

Title: Get Application parameters not working

Body:
I use the following lib to be access via code to CF,
https://github.com/prosociallearnEU/cf-nodejs-client

what I need to do is to get app for specific space and get the app env

currently i was able to get the all apps but not the env for specific app , any idea what I miss here ? I dont get any informative error to be able to understand what can be missed ...

const CloudController = new (require("cf-nodejs-client")).CloudController(endpoint, proxy);
    const UsersUAA = new (require("cf-nodejs-client")).UsersUAA;
    const Apps = new (require("cf-nodejs-client")).Apps(endpoint, proxy);
    const Orgs = new (require("cf-nodejs-client")).Organizations(endpoint, proxy);

    CloudController.getInfo()
        .then((result) => {
            console.log(result);
            UsersUAA.setEndPoint(result.authorization_endpoint, proxy);
            return UsersUAA.login(username, password);
        }).then((result) => {
        Apps.setToken(result);
         return Apps.getApps();
    }).then((result) => {
        Apps.setToken(result);
        console.log("app guid is: " + result.resources[0].metadata.guid);
        return result.resources[0].metadata.guid;
    }).then((guid) => {
       return Apps.getEnvironmentVariables(guid);
    }).then((result) => {
        console.log(result);
    }).catch((reason) => {
        console.error("Error: " + reason);
    });

UPDATE

what I need is to get appEnv for specified app (and i've the org & space & App name ), I need that the code will be efficient (performance...) , is my code flow is OK?

Body:
Based on your request (get app environment) and the documentation here: cf-nodejs-client v0.13 documentation, it appears that the getEnvirnmentVariables function would give you what you need.

As an alternative, you could do the following:

var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();


问:
How to turn my JSON result into an array or object
I have been searching every where, but cannot get to the right answer. I receive a Json result with the following structure

```<code>    {
    result =     {
        "2ab5a003-0120-4c01-80f2-a237dcf4ba14" =         {
            icon = garden;
            id = "2ab5a003-0120-4c01-80f2-a237dcf4ba14";
            index = 1;
            name = "Tafel hoek";
            parent = "855113f1-f488-4223-b675-2f01270f573e";
        };
        "2afd6093-ca6d-4e52-aaca-336ab76ea454" =         {
            icon = default;
            id = "2afd6093-ca6d-4e52-aaca-336ab76ea454";
            index = 11;
            name = Badkamer;
            parent = "9919ee1e-ffbc-480b-bc4b-77fb047e9e68";
        };
};
    status = 200;
}
</code>```

Because I don't know the 1st key in the result I am lost to get the separate items. Is there any one who can help me ? Thanks in advance

my code is:

{               print("Error: ")
                print(error!)

```<code>        } else {  // no error

            if let urlContent = data {  // 3

                do {  // 4

                    let json = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                    print(json)

                } catch {

                    print("JSON processing failed")

                }  // end 4 do

            }  // end 3 let urlContent

        }  // end 2 if error}
</code>```

答:
Since you have the dictionary for key result, you can enumerate it as usual:

```<code>if let result = json["result"] as? [String:[String:Any]] {
    for (key, value) in result {
       let name = value["name"] as! String
       let index = value["index"] as! Int
       print (key, name, index)
    }
}
</code>```

Body:
I have been searching every where, but cannot get to the right answer. I receive a Json result with the following structure

    {
    result =     {
        "2ab5a003-0120-4c01-80f2-a237dcf4ba14" =         {
            icon = garden;
            id = "2ab5a003-0120-4c01-80f2-a237dcf4ba14";
            index = 1;
            name = "Tafel hoek";
            parent = "855113f1-f488-4223-b675-2f01270f573e";
        };
        "2afd6093-ca6d-4e52-aaca-336ab76ea454" =         {
            icon = default;
            id = "2afd6093-ca6d-4e52-aaca-336ab76ea454";
            index = 11;
            name = Badkamer;
            parent = "9919ee1e-ffbc-480b-bc4b-77fb047e9e68";
        };
};
    status = 200;
}

Because I don't know the 1st key in the result I am lost to get the separate items. Is there any one who can help me ? Thanks in advance

my code is:

{               print("Error: ")
                print(error!)

        } else {  // no error

            if let urlContent = data {  // 3

                do {  // 4

                    let json = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                    print(json)

                } catch {

                    print("JSON processing failed")

                }  // end 4 do

            }  // end 3 let urlContent

        }  // end 2 if error}

Body:
Since you have the dictionary for key result, you can enumerate it as usual:

if let result = json["result"] as? [String:[String:Any]] {
    for (key, value) in result {
       let name = value["name"] as! String
       let index = value["index"] as! Int
       print (key, name, index)
    }
}


问:
Using EventFlow to monitor ETW events from other Service Fabric processes
Curious if anyone has experience with using EventFlow out of process? The documentation suggests it's built for using in-process (in relation to what's being monitored) but I was hoping to run it in a separate process (Service Fabric service) and monitor EventSource inputs from a number of other Service Fabric services running on the same machine.

One of the reasons for doing this, is that I want to make sure I capture ETW events written when a service exceptions and is about to die. Currently, EventFlow running in the same process that is crashing, is not surprisingly only occasionally able to write the event to its output (in this case the event log).

Thanks,
Hans

答:
Yes, you can. Just configure the ETW input using the name of your EventSource.

From the docs:

This input captures data from Microsoft Event Tracing for Windows (ETW) providers. Both manifest-based providers as well as providers based on managed EventSource infrastructure are supported. The data is captured machine-wide

Make sure your service that captures the events using EventFlow runs on the same node as the service that emits the events. Best is to make it a Stateless Service with an InstanceCount of -1 so it runs on every node.

Do mind that if this logging service fails on a node no events are captured on that node until it has recovered. So I suppose it is best used as a backup or something.