问:
How do I access data in a class stored in a node through queue pointers?
In my current assignment I'm having trouble figuring out how I can access this particular piece of data.

To start off, the assignment calls for data to be pulled from a file to simulate a store operating normally. The only thing is, the data being pulled is about the customer. Specifically it's when the customer enters a queue and how long it takes for the cashiers to process their order.

Right now how I have customer data stored in an array of classes.

```<code>for(int i = 0; i < entries; i++)
{
  /* !!!!!IMPORTANT!!!!!
   * The way this program extracts file data assumes that the file will
follow a specific format
   * results will vary heavily based on how the file is set up
   *
   * before docking points please make sure that the file follows the format
   *
   *  "Number of entries"
   *  "Customer Number", "Arrival Time", "Service Time"
   *  "Customer Number", "Arrival Time", "Service Time"
   *  "Customer Number", "Arrival Time", "Service Time"
   */

  xfiles >> dataEntry;
  fileData[i].setNumber(dataEntry);
  //inserts a number from the file into the "number" variable in the customer class.
  xfiles >> dataEntry;
  fileData[i].setArrival(dataEntry);
  //inserts a number from the file into the "arrival" variable in the customer class.
  xfiles >> dataEntry;
  fileData[i].setServTime(dataEntry);
  //inserts a number from the file into the "servTime" variable in the customer class.
}

xfiles.close();
</code>```

It's not included with the code but there is a line that takes in account for entries earlier in the program.

In my next block I have to queue and process customers simultaneously through a period of time. I have an idea how what I should do to queue them but I'm not too sure how I should proceed on processing them. For what I know right now I believe I might want to do a conditional statement to check if a certain customer from the array have been queued or not.

The piece of data I'm currently trying to access would be the arrival time that was stored in the class.

So something like,

fileData[i].returnArrival();

but since that class is stored in a queue I'm not sure how I would be able to access it.

Right now how I have everything queued is

```<code>for(int x = 0; x < 570; x++)
{
  if(cusTime == x)
  {
     if(scully.isFull() = false)
        scully.enqueue(fileData[cusTime]);
     else if(mulder.isFull() = false)
        mulder.enqueue(fileData[cusTime]);
     else if(skinner.isFull() = false)
        skinner.enqueue(fileData[cusTime]);
     else
        cout << "queues are full, disposing..\n";
  }
  cusTime++;
}
</code>```

At first I thought it would be something like

```<code>scully.returnFront()->temp->returnClass()->fileData.returnArrival();
</code>```

but I'm unsure about since temp is only a pointer declared within the queue class.

There was another suggestion from a friend of mine who suggested it would probably be something like this instead, but I ended up getting segmentation errors when I ran the code.

```<code>scully.returnFront()->returnClass().returnArrival();
</code>```

答:
I think it should be the following:

```<code>scully.returnFront().returnArrival()
</code>```

Because you enqueue the items from your array. Thus, returnFront() retrieves an item on which your methods should be possible.

Body:
In my current assignment I'm having trouble figuring out how I can access this particular piece of data.

To start off, the assignment calls for data to be pulled from a file to simulate a store operating normally. The only thing is, the data being pulled is about the customer. Specifically it's when the customer enters a queue and how long it takes for the cashiers to process their order.

Right now how I have customer data stored in an array of classes.

for(int i = 0; i < entries; i++)
{
  /* !!!!!IMPORTANT!!!!!
   * The way this program extracts file data assumes that the file will
follow a specific format
   * results will vary heavily based on how the file is set up
   *
   * before docking points please make sure that the file follows the format
   *
   *  "Number of entries"
   *  "Customer Number", "Arrival Time", "Service Time"
   *  "Customer Number", "Arrival Time", "Service Time"
   *  "Customer Number", "Arrival Time", "Service Time"
   */

  xfiles >> dataEntry;
  fileData[i].setNumber(dataEntry);
  //inserts a number from the file into the "number" variable in the customer class.
  xfiles >> dataEntry;
  fileData[i].setArrival(dataEntry);
  //inserts a number from the file into the "arrival" variable in the customer class.
  xfiles >> dataEntry;
  fileData[i].setServTime(dataEntry);
  //inserts a number from the file into the "servTime" variable in the customer class.
}

xfiles.close();

It's not included with the code but there is a line that takes in account for entries earlier in the program.

In my next block I have to queue and process customers simultaneously through a period of time. I have an idea how what I should do to queue them but I'm not too sure how I should proceed on processing them. For what I know right now I believe I might want to do a conditional statement to check if a certain customer from the array have been queued or not.

The piece of data I'm currently trying to access would be the arrival time that was stored in the class.

So something like,

fileData[i].returnArrival();

but since that class is stored in a queue I'm not sure how I would be able to access it.

Right now how I have everything queued is

for(int x = 0; x < 570; x++)
{
  if(cusTime == x)
  {
     if(scully.isFull() = false)
        scully.enqueue(fileData[cusTime]);
     else if(mulder.isFull() = false)
        mulder.enqueue(fileData[cusTime]);
     else if(skinner.isFull() = false)
        skinner.enqueue(fileData[cusTime]);
     else
        cout << "queues are full, disposing..\n";
  }
  cusTime++;
}

At first I thought it would be something like

scully.returnFront()->temp->returnClass()->fileData.returnArrival();

but I'm unsure about since temp is only a pointer declared within the queue class.

There was another suggestion from a friend of mine who suggested it would probably be something like this instead, but I ended up getting segmentation errors when I ran the code.

scully.returnFront()->returnClass().returnArrival();

Body:
I think it should be the following:

scully.returnFront().returnArrival()

Because you enqueue the items from your array. Thus, returnFront() retrieves an item on which your methods should be possible.


来源: stackexchange

问:
Blank line after curly brace in function with uncrustify
I have configured xcode to use Uncrustify to beautify the code. I modified the Uncrustify configuration file and the resulting code is almost as desired.

One thing I don't like is the removal of a blank line between a closing curly brace and the next line of code. For example, this is what Uncrustify currently does:

Input:

```<code>if (jsonData != NULL)
{
    return [jsonData objectFromJSONData];
}

NSLog(@"Data read");
</code>```

Current output:

```<code>if (jsonData != NULL)
{
    return [jsonData objectFromJSONData];
}
NSLog(@"Data read");
</code>```

The desired output would be, in this case, the same as the input:

```<code>if (jsonData != NULL)
{
    return [jsonData objectFromJSONData];
}

NSLog(@"Data read");
</code>```

I already played around with nl_after_func_body = true but this doesn't help.

I now managed to get the behaviour I wanted using the following addition to the configuration file:

```<code>nl_before_if = force
nl_after_if = force
nl_before_for = force
nl_after_for = force
nl_before_while = force
nl_after_while = force
nl_before_switch = force
nl_after_switch = force
nl_before_do = force
nl_after_do = force
</code>```

答:
Try using

```<code>nl_after_if = add   # ignore/add/remove/force
</code>```

In your config.

Inspired by: Blank line after curly brace in function with uncrustify

ContentLicense: CC BY-SA 3.0

Body:
I have configured xcode to use Uncrustify to beautify the code. I modified the Uncrustify configuration file and the resulting code is almost as desired.

One thing I don't like is the removal of a blank line between a closing curly brace and the next line of code. For example, this is what Uncrustify currently does:

Input:

if (jsonData != NULL)
{
    return [jsonData objectFromJSONData];
}

NSLog(@"Data read");

Current output:

if (jsonData != NULL)
{
    return [jsonData objectFromJSONData];
}
NSLog(@"Data read");

The desired output would be, in this case, the same as the input:

if (jsonData != NULL)
{
    return [jsonData objectFromJSONData];
}

NSLog(@"Data read");

I already played around with nl_after_func_body = true but this doesn't help.

I now managed to get the behaviour I wanted using the following addition to the configuration file:

nl_before_if = force
nl_after_if = force
nl_before_for = force
nl_after_for = force
nl_before_while = force
nl_after_while = force
nl_before_switch = force
nl_after_switch = force
nl_before_do = force
nl_after_do = force

Body:
Try using

nl_after_if = add   # ignore/add/remove/force

In your config.

Inspired by: Blank line after curly brace in function with uncrustify


问:
Problem with strings in assembler [beginner]
I'm working in Visual Studio 2010 and here's a little bit of code I'm having trouble with:

```<code>void main()
{
int x;
char c1[100]="cd";
char c2[100]="abcdef";
_asm {
    lea edx,c2
    lea ecx,c1
    push edx
    push ecx
    call subsir
    add esp, 8
    mov x, eax
}
}

char subsir (char *c1, char *c2)
{
_asm {
mov ecx, c1
mov edx, c2
mov edi, 0
mov esi, 0
start: cmp [edx + edi], 0
je end
mov esi, 0
mov eax, [edx + edi]
cmp eax, [ecx + esi]
  .....
</code>```

This is the first part of a program that's meant to compare 2 words.

The problem I am having is that when I do

```<code> mov eax, [edx + edi]
</code>```

eax receives an adress and not the actual value.
I tested this by doing

```<code> cmp eax, 97
</code>```

which should activate a JE instruction (97 being the ASCII code for 'a') But it doesn't. If I do

```<code>      cmp [edx + edi], 97
</code>```

it does activate the JE jump.

I would be very grateful if you could tell me what am I doing wrong and how can I put the actual valuea in EAX instead of an adress.

答:
No, it is actually reading the memory at [edx + edi].  Problem is that it is reading 32-bits at a time.  Which is not okay, you are comparing string content.  That requires comparing one byte at a time.  Fix:</p>

```<code>start: cmp byte ptr [edx + edi], 0
je end
mov esi, 0
mov al, [edx + edi]
cmp al, [ecx + esi]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm working in Visual Studio 2010 and here's a little bit of code I'm having trouble with:

void main()
{
int x;
char c1[100]="cd";
char c2[100]="abcdef";
_asm {
    lea edx,c2
    lea ecx,c1
    push edx
    push ecx
    call subsir
    add esp, 8
    mov x, eax
}
}

char subsir (char *c1, char *c2)
{
_asm {
mov ecx, c1
mov edx, c2
mov edi, 0
mov esi, 0
start: cmp [edx + edi], 0
je end
mov esi, 0
mov eax, [edx + edi]
cmp eax, [ecx + esi]
  .....

This is the first part of a program that's meant to compare 2 words.

The problem I am having is that when I do

 mov eax, [edx + edi]

eax receives an adress and not the actual value.
I tested this by doing

 cmp eax, 97

which should activate a JE instruction (97 being the ASCII code for 'a') But it doesn't. If I do

      cmp [edx + edi], 97

it does activate the JE jump.

I would be very grateful if you could tell me what am I doing wrong and how can I put the actual valuea in EAX instead of an adress.

Body:
No, it is actually reading the memory at [edx + edi].  Problem is that it is reading 32-bits at a time.  Which is not okay, you are comparing string content.  That requires comparing one byte at a time.  Fix:

start: cmp byte ptr [edx + edi], 0
je end
mov esi, 0
mov al, [edx + edi]
cmp al, [ecx + esi]


问:
Preselect a MySQL populated Dropdown List with PHP
I have a form which will be filled with data from a mysql table:

```<code>$db = mysql_connect("localhost:3306", "user", "pass");
        mysql_select_db("db",$db);
        $sql = "Select * from wp_awa_upload where uid = '$_SESSION[id]' and project = '$_SESSION[project]'";
        //echo $sql;
        $ergebnis = mysql_query($sql);
        $row = mysql_fetch_object($ergebnis);

        $category = $row->cat;
</code>```

The variable $category contains the name of the Category the user previously has entered.

in this form I have a Dropdown List which will be populated with data from a mysql Table:

```<code><? $db = mysql_connect("localhost:3306", "user", "pass");
mysql_select_db("db",$db); mysql_query("SET CHARACTER SET 'utf8'"); $sql = "SELECT cat FROM subcategory order by cat asc";
$result = mysql_query($sql);

echo "<select name='parent_cat'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['cat'] . "'>" . $row['cat'] . "</option>";
}
echo "</select>"; ?>
</code>```

The Dropdown contains ALL the selectable Categories. What I now want to achieve is to Highlight (or set to position 1) the $category in the Dropdown.

Something like

```<code>if ($row['cat'] == $category) {

echo '<option value="'.$row['cat'] .'" selected="selected">'.$row['cat'] .'</option>'; } else {

echo '<option value="'.$value.'" selected="selected">'.$value.'</option>';

}

echo "</select>"; ?>
</code>```

How can I achieve this?

Thanks for your support!

Kind Regards,

Stefan

答:
You can achieve this with a ternary operator like so:

```<code><option value="<?= $row['cat']; ?>" <?= $row['cat'] == $category ? 'selected' : ''; ?>>
</code>```

The ternary operator checks true or false. The first option after the '?' is true and the second option after the ':' is false. If the row you are iterating through equals what you are trying to set as selected then php will echo out 'selected'.

Also, you notice I changed the styling a bit. A best practice in php is to let html be html and php to be php. Notice how I echoed the value and the ternary statement instead of echoing out the entire html block.

So following that here is your code from above:

```<code><?php
$db = mysql_connect("localhost:3306", "user", "pass");
mysql_select_db("db",$db); mysql_query("SET CHARACTER SET 'utf8'");
$sql = "SELECT cat FROM subcategory order by cat asc";
$result = mysql_query($sql); ?>

<select name='parent_cat'>
 <?php while ($row = mysql_fetch_array($result)) { ?>
 <option value="<?= $row['cat']; ?>" <?= $row['cat'] == $category ? ' selected' : ''; ?>>
   <?= $row['cat']; ?>
 </option>
 <?php } ?>
</select>
</code>```

You can see that it is much easier to identify the php from the html and vice versa.

Body:
I have a form which will be filled with data from a mysql table:

$db = mysql_connect("localhost:3306", "user", "pass");
        mysql_select_db("db",$db);
        $sql = "Select * from wp_awa_upload where uid = '$_SESSION[id]' and project = '$_SESSION[project]'";
        //echo $sql;
        $ergebnis = mysql_query($sql);
        $row = mysql_fetch_object($ergebnis);

        $category = $row->cat;

The variable $category contains the name of the Category the user previously has entered.

in this form I have a Dropdown List which will be populated with data from a mysql Table:

<? $db = mysql_connect("localhost:3306", "user", "pass");
mysql_select_db("db",$db); mysql_query("SET CHARACTER SET 'utf8'"); $sql = "SELECT cat FROM subcategory order by cat asc";
$result = mysql_query($sql);

echo "<select name='parent_cat'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['cat'] . "'>" . $row['cat'] . "</option>";
}
echo "</select>"; ?>

The Dropdown contains ALL the selectable Categories. What I now want to achieve is to Highlight (or set to position 1) the $category in the Dropdown.

Something like

if ($row['cat'] == $category) {

echo '<option value="'.$row['cat'] .'" selected="selected">'.$row['cat'] .'</option>'; } else {

echo '<option value="'.$value.'" selected="selected">'.$value.'</option>';

}

echo "</select>"; ?>

How can I achieve this?

Thanks for your support!

Kind Regards,

Stefan

Body:
You can achieve this with a ternary operator like so:

<option value="<?= $row['cat']; ?>" <?= $row['cat'] == $category ? 'selected' : ''; ?>>

The ternary operator checks true or false. The first option after the '?' is true and the second option after the ':' is false. If the row you are iterating through equals what you are trying to set as selected then php will echo out 'selected'.

Also, you notice I changed the styling a bit. A best practice in php is to let html be html and php to be php. Notice how I echoed the value and the ternary statement instead of echoing out the entire html block.

So following that here is your code from above:

<?php
$db = mysql_connect("localhost:3306", "user", "pass");
mysql_select_db("db",$db); mysql_query("SET CHARACTER SET 'utf8'");
$sql = "SELECT cat FROM subcategory order by cat asc";
$result = mysql_query($sql); ?>

<select name='parent_cat'>
 <?php while ($row = mysql_fetch_array($result)) { ?>
 <option value="<?= $row['cat']; ?>" <?= $row['cat'] == $category ? ' selected' : ''; ?>>
   <?= $row['cat']; ?>
 </option>
 <?php } ?>
</select>

You can see that it is much easier to identify the php from the html and vice versa.


问:
Unable to throw error in angular js promise
I have an as promise as :

```<code>try {
   myPromise().then(function(){
       console.log("ok");
     }, function(err) { throw err; });
} catch(e) {
    console.log("error");
}
</code>```

now my control goes to the function(err) and it throws the error but the error is not caught in catch().

答:
Because promises are asynchronous, flow control doesn't work the way you're thinking it will.  Your try...catch block is outside of the promise initialization code, and once it initializes the promise, it's done.  So the try...catch block is only handling promise initialization in the code above.  If the promise is rejected/errored (as you say it is doing in your code), the error function will fire within the error function closure only.

Consider a common error handler or you can refactor your try...catch block to be within the closure.

Here's the code with the common error handler:

```<code>try {
   myPromise().then(function(){
       console.log("ok");
     }, function(err) {
       errHandler(err);
     });
} catch(e) {
    errHandler(e);
}

function errHandler(err) {
   console.log("error");
}
</code>```

Body:
I have an as promise as :

try {
   myPromise().then(function(){
       console.log("ok");
     }, function(err) { throw err; });
} catch(e) {
    console.log("error");
}

now my control goes to the function(err) and it throws the error but the error is not caught in catch().

Body:
Because promises are asynchronous, flow control doesn't work the way you're thinking it will.  Your try...catch block is outside of the promise initialization code, and once it initializes the promise, it's done.  So the try...catch block is only handling promise initialization in the code above.  If the promise is rejected/errored (as you say it is doing in your code), the error function will fire within the error function closure only.

Consider a common error handler or you can refactor your try...catch block to be within the closure.

Here's the code with the common error handler:

try {
   myPromise().then(function(){
       console.log("ok");
     }, function(err) {
       errHandler(err);
     });
} catch(e) {
    errHandler(e);
}

function errHandler(err) {
   console.log("error");
}


问:
update between three tables using left join in mysql
I have three tables, and want to update some fields in these tables but the query doesn't work

This is my Query:

```<code>UPDATE
customers cust
    left JOIN
contract cont ON cust.Customer_id = cont.Customers_Customer_id
    left JOIN
payments pay ON cust.Customer_id = pay.Customers_Customer_id
SET
cust.Customer_Name = 'Sara',
cust.Customer_id = '1201941718',
cust.Customer_Mobile1 = '01258863956',
cust.Customer_Phone = '0224598755',
cust.Customer_Mail = 'sara@gmail.com',
cont.Customers_Customer_id = '1201941718',
pay.Customers_Customer_id = '1201941718'
where cust.Customer_id = '2';
</code>```

The error:

Error Code: 1451. Cannot delete or update a parent row: a foreign key
  constraint fails (alhawel.payments, CONSTRAINT
  fk_Payments_Customers1 FOREIGN KEY (Customers_Customer_id)
  REFERENCES customers (Customer_id) ON DELETE NO ACTION ON UPDATE
  NO ACTION)

答:
You have one or more payments associated to customer_id = 2

When you update customer_id = 2 to customer_id = '1201941718' that payment become orphan and the FK constraint detect the integrity violation.

What you can do is:

insert new Customer_id = '1201941718'

update payments to Customer_id = '1201941718'

delete Customer_id = 2

But in db you shouldn't change the id of a record. There is no benefit for it . If you need add some metadata to the entity add another field and leave the PK alone.

Body:
I have three tables, and want to update some fields in these tables but the query doesn't work

This is my Query:

UPDATE
customers cust
    left JOIN
contract cont ON cust.Customer_id = cont.Customers_Customer_id
    left JOIN
payments pay ON cust.Customer_id = pay.Customers_Customer_id
SET
cust.Customer_Name = 'Sara',
cust.Customer_id = '1201941718',
cust.Customer_Mobile1 = '01258863956',
cust.Customer_Phone = '0224598755',
cust.Customer_Mail = 'sara@gmail.com',
cont.Customers_Customer_id = '1201941718',
pay.Customers_Customer_id = '1201941718'
where cust.Customer_id = '2';

The error:

Error Code: 1451. Cannot delete or update a parent row: a foreign key
  constraint fails (alhawel.payments, CONSTRAINT
  fk_Payments_Customers1 FOREIGN KEY (Customers_Customer_id)
  REFERENCES customers (Customer_id) ON DELETE NO ACTION ON UPDATE
  NO ACTION)


问:
HTTP Header to Forbid Iframe On Page
There is the Header X-Frame-Options, which is served by the webserver when you want to forbid (or limit) other sites from embedding your page into theirs, using an iframe.

But, is there a Header which tells the browser: "Don't allow any Iframe to be loaded on this page"?

There are, of course, headers which tell the browser which scripts, from which domain, is it allowed to execute, but I want something more generic: "don't allow any iframe, or only iframes from certain origins, to be loaded on this page".

答:
Content-Security-Policy (CSP) can be used to restrict content on pages, including iframes. Specifically, the frame-src directive. If you set the following HTTP header, no iframes will be allowed on your page.

Content-Security-Policy: frame-src 'none'

If you want to only allow iframes from specific origins you could do the following to allow iframes from example.com, and all subdomains:

Content-Security-Policy: frame-src http://*.example.com

You can also set the CSP policy via meta tag.

Title: HTTP Header to Forbid Iframe On Page


问:
How to generate pdf from docbook 5.0
I've written a docbook 5.0 document with the header:

```<code><?xml version="1.0" encoding="UTF-8"?>
<book version="5.0" xmlns="http://docbook.org/ns/docbook"
      xmlns:xlink="http://www.w3.org/1999/xlink"
      xmlns:xi="http://www.w3.org/2001/XInclude"
      xmlns:svg="http://www.w3.org/2000/svg"
      xmlns:m="http://www.w3.org/1998/Math/MathML"
      xmlns:html="http://www.w3.org/1999/xhtml"
      xmlns:db="http://docbook.org/ns/docbook">
</code>```

and docbook2pdf on Ubuntu 9.10 prints many error messages and doesn't do any pdf document. The  errors are:

```<code>openjade:test.xml:2:0:E: prolog can't be omitted unless CONCUR NO and LINK EXPLICIT NO and either IMPLYDEF ELEMENT YES or IMPLYDEF DOCTYPE YES
openjade:test.xml:2:0:E: no document type declaration; will parse without validation
openjade:/usr/share/sgml/docbook/stylesheet/dsssl/modular/print/dbtitle.dsl:18:5:E: flow objects at the root must be all of class scroll or all of class page-sequence or simple-page-sequence
openjade:/usr/share/sgml/docbook/stylesheet/dsssl/modular/print/dbbibl.dsl:704:4:E: flow objects at the root must be all of class scroll or all of class page-sequence or simple-page-sequence
</code>```

docbook2pdf for document in the docbook 4.5 format with normal header like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
</code>```

works quite OK.

Is there any way to generate pdf from docbook 5.0?

答:
I see three options (available in Debian/Ubuntu) to generate pdf from docbook:

jade, which provides the docbook2pdf command the asker used. jade is ancient and works with SGML, which predates XML and does not support Unicode; it also lacks support for docbook 5.

the docbook-xsl stylesheets which go through XSL-FO. docbook-xsl is for docbook 4.5, docbook-xsl-ns is for docbook5. Use fop to go from XSL-FO to PDF. Pipeline: docbook5 —(xsl)—> xml.fo —(fop)—> pdf . Commands involved: xsltproc, fop.

dblatex, which is primarily targeting docbook4.5 but has been updated for some of docbook5.

xmlto can drive the last two, although it currently defaults to docbook-xsl and not docbook-xsl-ns.

A quick Docbook5 user guide

Prerequisites

```<code>sudo aptitude install docbook5 docbook-xsl-ns xsltproc fop xmlto libxml2-utils xmlstarlet
</code>```

Validation

```<code>xmlstarlet val --err --xsd /usr/share/xml/docbook/schema/xsd/5.0/docbook.xsd book.xml
</code>```

PDF output

```<code>xsltproc /usr/share/xml/docbook/stylesheet/docbook-xsl-ns/fo/docbook.xsl book.xml > book.fo
fop -fo book.fo -pdf book.pdf
</code>```

Title: How to generate pdf from docbook 5.0

Body:
I've written a docbook 5.0 document with the header:

<?xml version="1.0" encoding="UTF-8"?>
<book version="5.0" xmlns="http://docbook.org/ns/docbook"
      xmlns:xlink="http://www.w3.org/1999/xlink"
      xmlns:xi="http://www.w3.org/2001/XInclude"
      xmlns:svg="http://www.w3.org/2000/svg"
      xmlns:m="http://www.w3.org/1998/Math/MathML"
      xmlns:html="http://www.w3.org/1999/xhtml"
      xmlns:db="http://docbook.org/ns/docbook">

and docbook2pdf on Ubuntu 9.10 prints many error messages and doesn't do any pdf document. The  errors are:

openjade:test.xml:2:0:E: prolog can't be omitted unless CONCUR NO and LINK EXPLICIT NO and either IMPLYDEF ELEMENT YES or IMPLYDEF DOCTYPE YES
openjade:test.xml:2:0:E: no document type declaration; will parse without validation
openjade:/usr/share/sgml/docbook/stylesheet/dsssl/modular/print/dbtitle.dsl:18:5:E: flow objects at the root must be all of class scroll or all of class page-sequence or simple-page-sequence
openjade:/usr/share/sgml/docbook/stylesheet/dsssl/modular/print/dbbibl.dsl:704:4:E: flow objects at the root must be all of class scroll or all of class page-sequence or simple-page-sequence

docbook2pdf for document in the docbook 4.5 format with normal header like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">

works quite OK.

Is there any way to generate pdf from docbook 5.0?

Body:
I see three options (available in Debian/Ubuntu) to generate pdf from docbook:

jade, which provides the docbook2pdf command the asker used. jade is ancient and works with SGML, which predates XML and does not support Unicode; it also lacks support for docbook 5.

the docbook-xsl stylesheets which go through XSL-FO. docbook-xsl is for docbook 4.5, docbook-xsl-ns is for docbook5. Use fop to go from XSL-FO to PDF. Pipeline: docbook5 —(xsl)—> xml.fo —(fop)—> pdf . Commands involved: xsltproc, fop.

dblatex, which is primarily targeting docbook4.5 but has been updated for some of docbook5.

xmlto can drive the last two, although it currently defaults to docbook-xsl and not docbook-xsl-ns.

A quick Docbook5 user guide

Prerequisites

sudo aptitude install docbook5 docbook-xsl-ns xsltproc fop xmlto libxml2-utils xmlstarlet

Validation

xmlstarlet val --err --xsd /usr/share/xml/docbook/schema/xsd/5.0/docbook.xsd book.xml

PDF output

xsltproc /usr/share/xml/docbook/stylesheet/docbook-xsl-ns/fo/docbook.xsl book.xml > book.fo
fop -fo book.fo -pdf book.pdf


问:
How to prompt the user until the input matches any element of an array?
I'm writing a Perl program where I have to prompt the user for input until the input exists in an array @stops I created earlier. If the user input matches then the program stops prompting and stores it in the scalar variable $first.

This is not my full code - I have use strict; and use warnings; in my code, and I have code from earlier that puts values into the array @stops.

```<code>print "What is your input?\n";
my $first = <STDIN>;
chomp $first;

do {

    if ( grep { $_ eq $first } @stops ) {
        last;
    }
    else {
        print "Invalid stop $first. Enter input again\n";
        my $first = <STDIN>;
        chomp $first;
    }
}
</code>```

答:
I would use the while in the usual way, where the readline is the conditional expression. It helps people to understand your code if you use familiar idioms, and it means that the keyboard is read in only a single place

It would look like this. Note that there's no need for the if...else, as the last exits the loop anyway

use strict;
use warnings 'all';
use feature 'say';

my @stops = qw/ a b c /;

my $stop;

print "What is your input? ";

while ( $stop = <STDIN> ) {
    chomp $stop;

    last if grep { $_ eq $stop } @stops;

    print qq{Invalid stop "$stop". Enter input again: };
}

say qq{Found "$stop"};
```

<h3>output</h3>

<pre class="lang-none prettyprint-override"><code>$perl stop.pl
What is your input? d
Invalid stop "d". Enter input again: x
Invalid stop "x". Enter input again: b
Found "b"
</code>```

Body:
I'm writing a Perl program where I have to prompt the user for input until the input exists in an array @stops I created earlier. If the user input matches then the program stops prompting and stores it in the scalar variable $first.

This is not my full code - I have use strict; and use warnings; in my code, and I have code from earlier that puts values into the array @stops.

print "What is your input?\n";
my $first = <STDIN>;
chomp $first;

do {

    if ( grep { $_ eq $first } @stops ) {
        last;
    }
    else {
        print "Invalid stop $first. Enter input again\n";
        my $first = <STDIN>;
        chomp $first;
    }
}

Body:
I would use the while in the usual way, where the readline is the conditional expression. It helps people to understand your code if you use familiar idioms, and it means that the keyboard is read in only a single place

It would look like this. Note that there's no need for the if...else, as the last exits the loop anyway

use strict;
use warnings 'all';
use feature 'say';

my @stops = qw/ a b c /;

my $stop;

print "What is your input? ";

while ( $stop = <STDIN> ) {
    chomp $stop;

    last if grep { $_ eq $stop } @stops;

    print qq{Invalid stop "$stop". Enter input again: };
}

say qq{Found "$stop"};

output

$perl stop.pl
What is your input? d
Invalid stop "d". Enter input again: x
Invalid stop "x". Enter input again: b
Found "b"


问:
Immutable Object with ArrayList member variable - why can this variable be changed?
I have got one class with various member variables. There is a constructor and there are getter-methods, but no setter-methods. In fact, this object should be immutable.

```<code>public class Example {
   private ArrayList<String> list;
}
</code>```

Now I noticed the following: when I get the variable list with a getter-method, I can add new values and so on - I can change the ArrayList. When I call the next time get() for this variable, the changed ArrayList is returned. How can this be? I didn't set it again, I just worked on it!
With a String this behaviour isn't possible. So what is the difference here?

答:
One another solution is to return copy of the arraylist not the actual array list like this code</p>

```<code>import java.util.ArrayList;
import java.util.List;

public final class ImmutableExample {

    private final List<String> strings = new ArrayList<String>();

    public ImmutableExample() {
        strings.add("strin 1");
        strings.add("string 2");
    }

    public List<String> getStrings() {
        List<String> newStrings = new ArrayList<String>();
        strings.forEach(s -> newStrings.add(s));
        return newStrings;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ImmutableExample im = new ImmutableExample();
        System.out.println(im.getStrings());
        im.getStrings().add("string 3");
        System.out.println(im.getStrings());

    }
}
</code>```

Body:
I have got one class with various member variables. There is a constructor and there are getter-methods, but no setter-methods. In fact, this object should be immutable.

public class Example {
   private ArrayList<String> list;
}

Now I noticed the following: when I get the variable list with a getter-method, I can add new values and so on - I can change the ArrayList. When I call the next time get() for this variable, the changed ArrayList is returned. How can this be? I didn't set it again, I just worked on it!
With a String this behaviour isn't possible. So what is the difference here?

Body:
One another solution is to return copy of the arraylist not the actual array list like this code

import java.util.ArrayList;
import java.util.List;

public final class ImmutableExample {

    private final List<String> strings = new ArrayList<String>();

    public ImmutableExample() {
        strings.add("strin 1");
        strings.add("string 2");
    }

    public List<String> getStrings() {
        List<String> newStrings = new ArrayList<String>();
        strings.forEach(s -> newStrings.add(s));
        return newStrings;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ImmutableExample im = new ImmutableExample();
        System.out.println(im.getStrings());
        im.getStrings().add("string 3");
        System.out.println(im.getStrings());

    }
}


问:
Anchor dynamic element with click event
I am trying to dynamically add an anchor element through Javascript.  The problem I have is the onclick event is not firing.  I believe the problem is how I am generating the HTML.  I am creating an array and then push my HTML code to the array.  After I have created my output I am joining the array and then adding it to the div tag I have.

var itemLink = new Object();
itemLink.LinkName = "Edit User";
itemLink.LinkListClass = "";
itemLink.LinkListRole = "";
itemLink.LinkFunction = function() {
  //do something specific with rowItem variable
  alert(rowItem);
}

var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;

var output = [];

output.push('
');
output.push('
');
output.push('
col1	col2
');
output.push('
');
output.push('
');
output.push('
col1 data	col2 data
');
output.push('

')

var d1 = document.createElement('div');
d1.appendChild(aTag);
output.push(d1.innerHTML);

var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mainViewer"></div></code>```

When I generate the output without the use of the array and joining of the output, the anchor element gets created and the onclick event works just fine.

Any ideas?

I will have multiple anchor links and I don't want to hardcode the function name.  I want the onclick event to fire whatever function the itemLink Object has set.

答:
What's the problem? You bind a function to a temp DOM element, then append its html, not its events (that's how innerHTML works). So when a link appended to the DOM, it's a different DOM link, so although the link looks the same it's not.

So, what is the solution? to push a DOM element instead of string, something like this:

//var itemLink = new Object();
//itemLink.LinkName = "Edit User";
//itemLink.LinkListClass = "";
//itemLink.LinkListRole = "";
//itemLink.LinkFunction = function() {
//do something specific with rowItem variable
//alert(rowItem);
//}

var itemLink = {
  LinkName: "Edit User",
  LinkListClass: "",
  LinkListRole: "",
  LinkFunction: function() {
    //do something specific with rowItem variable
    alert(rowItem);
  }
};

var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;

var output = [];

output.push('
');
output.push('
');
output.push('
col1	col2
');
output.push('
');
output.push('
');
output.push('
col1 data	col2 data
');
output.push('

')

var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');

var d1 = document.createElement('div');
d1.appendChild(aTag);
mainView.appendChild(d1)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mainViewer"></div></code>```

Thanks to @David Thomas for his comment :)

Title: Anchor dynamic element with click event

Body:
I am trying to dynamically add an anchor element through Javascript.  The problem I have is the onclick event is not firing.  I believe the problem is how I am generating the HTML.  I am creating an array and then push my HTML code to the array.  After I have created my output I am joining the array and then adding it to the div tag I have.

var itemLink = new Object();
itemLink.LinkName = "Edit User";
itemLink.LinkListClass = "";
itemLink.LinkListRole = "";
itemLink.LinkFunction = function() {
  //do something specific with rowItem variable
  alert(rowItem);
}

var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;

var output = [];

output.push('
');
output.push('
');
output.push('
col1	col2
');
output.push('
');
output.push('
');
output.push('
col1 data	col2 data
');
output.push('

')

var d1 = document.createElement('div');
d1.appendChild(aTag);
output.push(d1.innerHTML);

var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');

When I generate the output without the use of the array and joining of the output, the anchor element gets created and the onclick event works just fine.

Any ideas?

I will have multiple anchor links and I don't want to hardcode the function name.  I want the onclick event to fire whatever function the itemLink Object has set.

Body:
What's the problem? You bind a function to a temp DOM element, then append its html, not its events (that's how innerHTML works). So when a link appended to the DOM, it's a different DOM link, so although the link looks the same it's not.

So, what is the solution? to push a DOM element instead of string, something like this:

//var itemLink = new Object();
//itemLink.LinkName = "Edit User";
//itemLink.LinkListClass = "";
//itemLink.LinkListRole = "";
//itemLink.LinkFunction = function() {
//do something specific with rowItem variable
//alert(rowItem);
//}

var itemLink = {
  LinkName: "Edit User",
  LinkListClass: "",
  LinkListRole: "",
  LinkFunction: function() {
    //do something specific with rowItem variable
    alert(rowItem);
  }
};

var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;

var output = [];

output.push('<table>');
output.push('<thead>');
output.push('<tr><th>col1</th><th>col2</th></tr>');
output.push('</thead>');
output.push('<tbody>');
output.push('<tr><td>col1 data</td><td>col2 data</td></tr>');
output.push('</tbody></table>')

var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');

var d1 = document.createElement('div');
d1.appendChild(aTag);
mainView.appendChild(d1)

<div id="mainViewer"></div>

Thanks to @David Thomas for his comment :)


问:
Visual Studio - project shows up as "Miscellaneous Files"
This is a weird one. I have a C# Class Library project within my solution. If I open a .cs file within this project, the Project drop-down on the code editor shows that it belongs to 'Miscellaneous Files'.

Other symptoms: if I go to the properties of the project and look at Assembly Information, all values are blank, despite the values existing in the AssemblyInfo.cs file.

Both of these are annoying, but the problem is that

I don't get intellisense on any files in the project

I can't seem to step through it in the debugger (it tells me that the files do not belong to the solution and so can't be debugged).

I have tried:

Combing through the .csproj file and comparing to others in the solution (no joy)

Re-creating the .csproj file and overwriting the old one (worked until I merged the branch into trunk, then the problem re-appeared)

Banging my head on the keyboard (headache)

Google has turned up nothing. Does anyone have any ideas as to what's going on here?

答:
I have this issue in VS 2017 also.

I found that this miscellaneous files are files added outside the VS. So if switch to another git branch (where there are new files) whithout closing the VS and click to "Reload" button in VS (when it checks that sln/csproj files are modified outside the VS) then these new files are not correctly parsed by VS and "marked" as miscellaneous.

As workaround I close VS, remove folder .vs from disk and run VS again. After VS will fully initialized these new files are parsed successfully.
Note this way clears you custom settings like StartUp Project and so on.

ContentLicense: CC BY-SA 4.0


问:
is it possible to open Settings App using openURL?
I know an app can launch other apps by using this code: <code>[[UIApplication sharedApplication] openURL:appUrl];</code>. And I know the scheme of URL to open safari and mail, but I did some searches and found nothing about the scheme of settings.app. </p>

答:
Swift 4 version:

```<code>if let url = URL(string: UIApplicationOpenSettingsURLString) {
    UIApplication.shared.openURL(url)
}
</code>```

Body: I know an app can launch other apps by using this code: [[UIApplication sharedApplication] openURL:appUrl];. And I know the scheme of URL to open safari and mail, but I did some searches and found nothing about the scheme of settings.app.

Body:
Swift 4 version:

if let url = URL(string: UIApplicationOpenSettingsURLString) {
    UIApplication.shared.openURL(url)
}


问:
How to include a YAML file inside a YAML file in Ruby
Is there a custom tag in YAML for ruby to include a YAML file inside a YAML file?

```<code>#E.g.:
--- !include
filename: another.yml
</code>```

A similar question was asked some time ago and there was no relevant answer.

I am wondering if there is some custom tag for Ruby similar to this one for Python.

答:
If you just want to inherit from another YAML file, there is a gem providing this functionality you are asking for by extending the ruby YAML library:

https://github.com/entwanderer/yaml_extend

https://rubygems.org/gems/yaml_extend

Usage

yaml_extend adds the method YAML#ext_load_file to YAML.

This method works like the original YAML#load_file, by extending it with file inheritance.

Examples

```<code># start.yml
extends: 'super.yml'
data:
    name: 'Mr. Superman'
    age: 134
    favorites:
        - 'Raspberrys'
</code>```

-

```<code># super.yml
data:
    name: 'Unknown'
    power: 2000
    favorites:
        - 'Bananas'
        - 'Apples'
</code>```

Basic Inheritance

```<code>YAML.ext_load_file('start.yml')
</code>```

results in

```<code>data:
    name: 'Mr. Superman'
    age: 134
    power: 2000
    favorites:
        - 'Bananas'
        - 'Apples'
        - 'Raspberrys'
</code>```

Body:
Is there a custom tag in YAML for ruby to include a YAML file inside a YAML file?

#E.g.:
--- !include
filename: another.yml

A similar question was asked some time ago and there was no relevant answer.

I am wondering if there is some custom tag for Ruby similar to this one for Python.

Body:
If you just want to inherit from another YAML file, there is a gem providing this functionality you are asking for by extending the ruby YAML library:

https://github.com/entwanderer/yaml_extend

https://rubygems.org/gems/yaml_extend

Usage

yaml_extend adds the method YAML#ext_load_file to YAML.

This method works like the original YAML#load_file, by extending it with file inheritance.

Examples

# start.yml
extends: 'super.yml'
data:
    name: 'Mr. Superman'
    age: 134
    favorites:
        - 'Raspberrys'

-

# super.yml
data:
    name: 'Unknown'
    power: 2000
    favorites:
        - 'Bananas'
        - 'Apples'

Basic Inheritance

YAML.ext_load_file('start.yml')

results in

data:
    name: 'Mr. Superman'
    age: 134
    power: 2000
    favorites:
        - 'Bananas'
        - 'Apples'
        - 'Raspberrys'


问:
Thread.Abort() and delay after finally
When Thread.Abort() is called, and that thread is executing finally block, then thread won't abort until finally block is finished. But, as i see, ThreadAbortException is generated not right after the end of finally block, but after some delay:

```<code>private static volatile int val1 = 0;

public static void Func1()
{
    try
    {
    }
    finally
    {
        Thread.Sleep(5000);
    }
    //Func2();

    while (true)
        val1++;
}

public static void Main()
{
    var thread = new Thread(Func1);
    thread.Start();

    Thread.Sleep(1000);

    thread.Abort();
    thread.Join();

    Console.WriteLine(val1);  // val1 is non-zero!
}
</code>```

In this example, val1 at the end of Main() will be non-zero. Why does it happen?

If i uncomment call to Func2() (Func2 is any method, possibly empty), output for val1 will show "0". Why does adding of method affect point of thread abortion?

答:
In this case it could be usefull to surround the increment with a lock. The lock controlls the access on that member. The Abort method just notify the thread "Hey, you can stop now" but it does not kill the Thread. So the thread can be alive for a few moments after the Abort. Accessing the lock the thread checks if it got aborted and kills it self if needed.

Here is your example code edited

using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        private static volatile int val1 = 0;
        static Object Locker = new Object();

        public static void Func1()
        {
            try
            {
            }
            finally
            {
                Thread.Sleep(5000);
            }
            //Func2();

            while (true)
            {
                //Lock the access to the member
                lock (Locker)
                    val1++;
            }
        }

        public static void Main()
        {
            var thread = new Thread(Func1);
            thread.Start();

            Thread.Sleep(1000);
            //Not needed. Just to make sure
            lock (Locker)
            {
                thread.Abort();
                thread.Join();
            }

            Console.WriteLine(val1);  // val1 is non-zero!
                                      // Now it is zero
            Console.ReadLine();
        }
    }
}
```

Sorry for late answer

Title: Thread.Abort() and delay after finally

Body:
When Thread.Abort() is called, and that thread is executing finally block, then thread won't abort until finally block is finished. But, as i see, ThreadAbortException is generated not right after the end of finally block, but after some delay:

private static volatile int val1 = 0;

public static void Func1()
{
    try
    {
    }
    finally
    {
        Thread.Sleep(5000);
    }
    //Func2();

    while (true)
        val1++;
}

public static void Main()
{
    var thread = new Thread(Func1);
    thread.Start();

    Thread.Sleep(1000);

    thread.Abort();
    thread.Join();

    Console.WriteLine(val1);  // val1 is non-zero!
}

In this example, val1 at the end of Main() will be non-zero. Why does it happen?

If i uncomment call to Func2() (Func2 is any method, possibly empty), output for val1 will show "0". Why does adding of method affect point of thread abortion?

Body:
In this case it could be usefull to surround the increment with a lock. The lock controlls the access on that member. The Abort method just notify the thread "Hey, you can stop now" but it does not kill the Thread. So the thread can be alive for a few moments after the Abort. Accessing the lock the thread checks if it got aborted and kills it self if needed.

Here is your example code edited

using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        private static volatile int val1 = 0;
        static Object Locker = new Object();

        public static void Func1()
        {
            try
            {
            }
            finally
            {
                Thread.Sleep(5000);
            }
            //Func2();

            while (true)
            {
                //Lock the access to the member
                lock (Locker)
                    val1++;
            }
        }

        public static void Main()
        {
            var thread = new Thread(Func1);
            thread.Start();

            Thread.Sleep(1000);
            //Not needed. Just to make sure
            lock (Locker)
            {
                thread.Abort();
                thread.Join();
            }

            Console.WriteLine(val1);  // val1 is non-zero!
                                      // Now it is zero
            Console.ReadLine();
        }
    }
}

Sorry for late answer


问:
Database Query failed error when inserting Row into Table
I am getting Database query failed error while trying to insert a new row into a table. This table (pages) has a column (subject_id) referencing another table (subjects). I am passing the value of the of the subject_id from the url and it is passed on the form correctly. All the values seem to be passed correctly on the form using php, but i get error while i try to insert the row. The form submits to itself.

select_all_pages_by_subject($sid) is a function that selects all rows (pages) from the current subject (passed from the url). It works fine for the position field.

I suspect this error is probably a MySQL syntax error somewhere in my code, but i just cant seem to figure it out yet. I appreciate some help. Thank you.

Here is my code:

```<code><div class="body_content">
<?php
    $sid = null;
if(isset($_GET["subject"])) {
    $sid = $_GET["subject"];
}
?>
<form action="create_page.php" method="post">
Menu Name:  <input type="text" name="menu" /> <br>
Position:   <select name="position">
                <?php
                $new_page_query = select_all_pages_by_subject($sid);
                $page_count = mysqli_num_rows($new_page_query);
                for($count=1; $count<=($page_count + 1); $count++) {
                            echo "<option value=\"$count\">$count</option>";
                }
                ?>
            </select> <br>
Visible:<br>
No <input type="radio" name="visible" value="0" />
Yes <input type="radio" name="visible" value="1" /> <br>
Subject ID: <input type="text" name="subject_id" value="<?php echo $sid; ?>" /> <br>
Content: <br>
<textarea rows="5" cols="40" name="content"></textarea> <br>
<input type="submit" value="Create Page" name="submit" /> <br>
<a href="admin.php">Cancel</a> <br>
</form>
<?php
        if(isset($_POST['submit'])) {
        $menu_name = $_POST["menu"];
        $position = (int) $_POST["position"];
        $visible = (int) $_POST["visible"];
        $content = $_POST["content"];
        $subject_id = (int) $_POST["$sid"];
        $insert_query = "INSERT INTO pages (subject_id, menu_name, position,
                          visible, content) VALUES ({$subject_id},'{$menu_name}', {$position},
                          {$visible}, '{content}')";
        $page_insert = mysqli_query($connection, $insert_query);
        if($page_insert) {
            $_SESSION["message"] = "Page created successfully";
            redirect_to("admin.php");
        } else {
        $_SESSION["message"] = "Page creation failed";
        redirect_to("create_page.php?subject=$sid");
    }
}
?>
</div>
</code>```

Edit: removed the WHERE statement

答:
So after some troubleshooting, i decided to separate the form and form processing into 2 different pages, then i realized the problem, in the form action, i did not specify the subject id in the URL since i was passing the id from the URL:

<form action="create_page.php" method="post">

should be:

```<code><form action="create_page.php?subject=<?php echo $sid; ?>" method="post">
</code>```

Edit: I have also noticed that the "Database query failed" error was being called on the Position form field where i was making a database connection on the "pages" table to pull the number of rows. So when the insert statement failed due to the absence of subject id from the url, php did not process the page past the position form field, it called the error on the field and stopped execution. When insert query fails, parts of the form are displayed on the screen (only the menu name field and the position field with empty values). When i tried to view source code for errors, it requested the page be reloaded again (felt like an infinite loop running or something)

Body:
I am getting Database query failed error while trying to insert a new row into a table. This table (pages) has a column (subject_id) referencing another table (subjects). I am passing the value of the of the subject_id from the url and it is passed on the form correctly. All the values seem to be passed correctly on the form using php, but i get error while i try to insert the row. The form submits to itself.

select_all_pages_by_subject($sid) is a function that selects all rows (pages) from the current subject (passed from the url). It works fine for the position field.

I suspect this error is probably a MySQL syntax error somewhere in my code, but i just cant seem to figure it out yet. I appreciate some help. Thank you.

Here is my code:

<?php
    $sid = null;
if(isset($_GET["subject"])) {
    $sid = $_GET["subject"];
}
?>
<form action="create_page.php" method="post">
Menu Name:  <input type="text" name="menu" />

Position:   <select name="position">
                <?php
                $new_page_query = select_all_pages_by_subject($sid);
                $page_count = mysqli_num_rows($new_page_query);
                for($count=1; $count<=($page_count + 1); $count++) {
                            echo "<option value=\"$count\">$count</option>";
                }
                ?>
            </select>

Visible:

No <input type="radio" name="visible" value="0" />
Yes <input type="radio" name="visible" value="1" />

Subject ID: <input type="text" name="subject_id" value="<?php echo $sid; ?>" />

Content:

<textarea rows="5" cols="40" name="content"></textarea>

<input type="submit" value="Create Page" name="submit" />

Cancel

</form>
<?php
        if(isset($_POST['submit'])) {
        $menu_name = $_POST["menu"];
        $position = (int) $_POST["position"];
        $visible = (int) $_POST["visible"];
        $content = $_POST["content"];
        $subject_id = (int) $_POST["$sid"];
        $insert_query = "INSERT INTO pages (subject_id, menu_name, position,
                          visible, content) VALUES ({$subject_id},'{$menu_name}', {$position},
                          {$visible}, '{content}')";
        $page_insert = mysqli_query($connection, $insert_query);
        if($page_insert) {
            $_SESSION["message"] = "Page created successfully";
            redirect_to("admin.php");
        } else {
        $_SESSION["message"] = "Page creation failed";
        redirect_to("create_page.php?subject=$sid");
    }
}
?>

Edit: removed the WHERE statement

Body:
So after some troubleshooting, i decided to separate the form and form processing into 2 different pages, then i realized the problem, in the form action, i did not specify the subject id in the URL since i was passing the id from the URL:

<form action="create_page.php" method="post">

should be:

<form action="create_page.php?subject=<?php echo $sid; ?>" method="post">

Edit: I have also noticed that the "Database query failed" error was being called on the Position form field where i was making a database connection on the "pages" table to pull the number of rows. So when the insert statement failed due to the absence of subject id from the url, php did not process the page past the position form field, it called the error on the field and stopped execution. When insert query fails, parts of the form are displayed on the screen (only the menu name field and the position field with empty values). When i tried to view source code for errors, it requested the page be reloaded again (felt like an infinite loop running or something)


问:
Bash script, case statement and sub-menus
I wish to run a script with a case statement leading to choices between other lists of choices (sort of sub-menus) between scripts :

```<code>#!/bin/bash

echo "Your choice ?"
echo "1) Foo"
echo "2) Bar"
echo "3) Stuff"
read case;

case $case in

#and this is where I would like to allow
#(here a simplified example I do not manage to code)

1) What script ?    # may I use another case statement ?
    a) Foo1;;
    b) Foo2;;
2) What script ?    # d°
    a) Bar1;;
    b) Bar2;;
    c) Bar3;;

esac
</code>```

Foo1, Foo2, Bar1, Bar2 and Bar3 being in fact bash scripts, I would like to call, eg, sh Foo1 from within the script.

How must I proceed :
May I include a case statement within a case statement (better than if statement, if the choices are numerous) ?
And how do I call a script from within another script ?

Thanks in advance for your help

ThG

答:
Dennis' answer should do what you want. Just to illustrate how to do it with functions, so as to make the script more readable:

```<code>function which_foo {
    local foo_options=("foo1" "foo2" "cancel")
    local PS3="Select foo: "

    select foo in "${foo_options[@]}"
    do
        case $REPLY in
            1) ./foo1.sh
               break ;;

            2) ./foo2.sh
               break ;;

            3) break ;;
        esac
    done
}

ACTIONS=("foo" "bar" "quit")
PS3="Select action: "

select action in "${ACTIONS[@]}"
do
    case $action in
         "foo") which_foo
                break ;;

         "bar") which_bar # Not present in this example
                break ;;

        "quit") break ;;
    esac
done
</code>```

As an aside, note:

the use of $REPLY in the case inside which_foo, which is automatically set to the number selected by the user, instead of the text of the option.

the use of break in each case options. Without them, select puts you in a loop, so the user would be asked to enter a choice again.

that select never changes the value of PS3 for you, so you have to do it yourself when switching between the different levels of your menu.

Body:
I wish to run a script with a case statement leading to choices between other lists of choices (sort of sub-menus) between scripts :

#!/bin/bash

echo "Your choice ?"
echo "1) Foo"
echo "2) Bar"
echo "3) Stuff"
read case;

case $case in

#and this is where I would like to allow
#(here a simplified example I do not manage to code)

1) What script ?    # may I use another case statement ?
    a) Foo1;;
    b) Foo2;;
2) What script ?    # d°
    a) Bar1;;
    b) Bar2;;
    c) Bar3;;

esac

Foo1, Foo2, Bar1, Bar2 and Bar3 being in fact bash scripts, I would like to call, eg, sh Foo1 from within the script.

How must I proceed :
May I include a case statement within a case statement (better than if statement, if the choices are numerous) ?
And how do I call a script from within another script ?

Thanks in advance for your help

ThG

Body:
Dennis' answer should do what you want. Just to illustrate how to do it with functions, so as to make the script more readable:

function which_foo {
    local foo_options=("foo1" "foo2" "cancel")
    local PS3="Select foo: "

    select foo in "${foo_options[@]}"
    do
        case $REPLY in
            1) ./foo1.sh
               break ;;

            2) ./foo2.sh
               break ;;

            3) break ;;
        esac
    done
}

ACTIONS=("foo" "bar" "quit")
PS3="Select action: "

select action in "${ACTIONS[@]}"
do
    case $action in
         "foo") which_foo
                break ;;

         "bar") which_bar # Not present in this example
                break ;;

        "quit") break ;;
    esac
done

As an aside, note:

the use of $REPLY in the case inside which_foo, which is automatically set to the number selected by the user, instead of the text of the option.

the use of break in each case options. Without them, select puts you in a loop, so the user would be asked to enter a choice again.

that select never changes the value of PS3 for you, so you have to do it yourself when switching between the different levels of your menu.


问:
Android. HTTP error fetching URL. Status=403
I'm trying to get data from site.
When I use this code in Intellij IDEA everything works fine, but when I use this code in Android Studio and real device, I get:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403

Here is my code:

```<code>private static final String URL = "http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM";

private static final String useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
                "AppleWebKit/537.36 (KHTML, like Gecko) " +
                "Chrome/52.0.2743.116 Safari/537.36";

Document document = Jsoup.connect(URL)
                        .userAgent(useragent)
                        .ignoreContentType(true)
                        .timeout(5000)
                        .execute() //  <-- on this line I get error
                        .parse();
</code>```

All information that I have found is only about "userAgent()" method, but It didn't help.

UPD: Sorry, it was my bad in question. Correct url: http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM, but I still have the same problem.

Error:  org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403,
  URL=http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM

答:
I've added the missing header in the request and I was able to retrieve the website content, the code I've used is:

```<code>Document document = Jsoup.connect(URL)
                            .userAgent("Mozilla")
                            .header("Accept", "text/html")
                            .header("Accept-Encoding", "gzip,deflate")
                            .header("Accept-Language", "it-IT,en;q=0.8,en-US;q=0.6,de;q=0.4,it;q=0.2,es;q=0.2")
                            .header("Connection", "keep-alive")
                            .ignoreContentType(true)
                            .get();
</code>```

Body:
I'm trying to get data from site.
When I use this code in Intellij IDEA everything works fine, but when I use this code in Android Studio and real device, I get:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403

Here is my code:

private static final String URL = "http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM";

private static final String useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
                "AppleWebKit/537.36 (KHTML, like Gecko) " +
                "Chrome/52.0.2743.116 Safari/537.36";

Document document = Jsoup.connect(URL)
                        .userAgent(useragent)
                        .ignoreContentType(true)
                        .timeout(5000)
                        .execute() //  <-- on this line I get error
                        .parse();

All information that I have found is only about "userAgent()" method, but It didn't help.

UPD: Sorry, it was my bad in question. Correct url: http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM, but I still have the same problem.

Error:  org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403,
  URL=http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM

Body:
I've added the missing header in the request and I was able to retrieve the website content, the code I've used is:

Document document = Jsoup.connect(URL)
                            .userAgent("Mozilla")
                            .header("Accept", "text/html")
                            .header("Accept-Encoding", "gzip,deflate")
                            .header("Accept-Language", "it-IT,en;q=0.8,en-US;q=0.6,de;q=0.4,it;q=0.2,es;q=0.2")
                            .header("Connection", "keep-alive")
                            .ignoreContentType(true)
                            .get();


问:
Web API post method to send image
I need to code a method in a WebAPI application where I need to send an Image, this is what I'm doing:

```<code> public IHttpActionResult PostPicture(string xmit, int contactNum, [FromBody] byte[] picture)
    {
        Image img = null;
        using (var ms = new MemoryStream(picture))
        {
            img = Image.FromStream(ms);
        }
        if (img != null)
        {
            return Ok();
        }
        else {
            return BadRequest();
        }
    }
</code>```

The problem is that when I'm sending the byte[] into the body in the request the value of the picture parameter is always null.
I'm using Postman to test the method and the request body is being send as a x-www-form-urlencoded.

Could anyone help me to find what I'm doing wrong?

答: Thanks to @Nkosi, this solved the problem: Another option would be to remove the parameter and read it directly from the request imageStream = await Request.Content.ReadAsStreamAsync() actually it didn't work before because the way I was doing the request in Postman. Thanks again

Title: Web API post method to send image

Body:
I need to code a method in a WebAPI application where I need to send an Image, this is what I'm doing:

 public IHttpActionResult PostPicture(string xmit, int contactNum, [FromBody] byte[] picture)
    {
        Image img = null;
        using (var ms = new MemoryStream(picture))
        {
            img = Image.FromStream(ms);
        }
        if (img != null)
        {
            return Ok();
        }
        else {
            return BadRequest();
        }
    }

The problem is that when I'm sending the byte[] into the body in the request the value of the picture parameter is always null.
I'm using Postman to test the method and the request body is being send as a x-www-form-urlencoded.

Could anyone help me to find what I'm doing wrong?


问:
display current logged username
im trying to display the username of the current logged user

the table looks like this: Table Name: system_users   , u_userid - gets the id u_username - gets the user name

i want to display the u_username... it works at the momment but it display all users.

this is the code, it display all users, i want to display only the logged user

```<code><?php
 $connection = mysql_connect('localhost', 'SQLUSER', 'SQLPW'); //The Blank
 string is the password
 mysql_select_db('comenzi.highmob');

 $query = "SELECT * FROM system_users"; //You don't need a ; like you do in SQL
 $result = mysql_query($query);

 echo "<table>"; // start a table tag in the HTML

 while($row = mysql_fetch_array($result)){   //Creates a loop to loop through
 results
 echo "<tr><td>" . $row['u_username'] . "</td></tr>";  //$row['index'] the index
 here is a field name
 }

  echo "</table>"; //Close the table in HTML

 mysql_close(); //Make sure to close out the database connection
     ?>
</code>```

答:
You have to use where condition

For Example

```<code>$query = "SELECT * FROM system_users WHERE UserID = 2"
</code>```

in your case you can get the userid from the session

Title: display current logged username

Body:
im trying to display the username of the current logged user

the table looks like this: Table Name: system_users   , u_userid - gets the id u_username - gets the user name

i want to display the u_username... it works at the momment but it display all users.

this is the code, it display all users, i want to display only the logged user

<?php
 $connection = mysql_connect('localhost', 'SQLUSER', 'SQLPW'); //The Blank
 string is the password
 mysql_select_db('comenzi.highmob');

 $query = "SELECT * FROM system_users"; //You don't need a ; like you do in SQL
 $result = mysql_query($query);

 echo "
"; // start a table tag in the HTML

 while($row = mysql_fetch_array($result)){   //Creates a loop to loop through
 results
 echo "
" . $row['u_username'] . "
";  //$row['index'] the index
 here is a field name
 }

  echo "
"; //Close the table in HTML

 mysql_close(); //Make sure to close out the database connection
     ?>

Body:
You have to use where condition

For Example

$query = "SELECT * FROM system_users WHERE UserID = 2"

in your case you can get the userid from the session


问:
GeoMesa on HBase faster import
I am using GeoMesa v1.4.0 on HBase v1.2.6.
Currently I am importing and indexing my data with the help of the HBaseQuickStart class. Unfortunately, the runtime for large files is very long.
Does someone know of a bulkLoad with GeoMesa to speed up my process?
Thanks in advance!

答:
Out of the box, GeoMesa provides ingest through the binary distribution command line tools. You have to define a 'converter' file that has the mappings from your input files to your simple feature type. Once you have that, you can run locally with multiple threads, or remotely using map/reduce. The documentation for the Accumulo command is here, the HBase command will work the same but have slightly different parameters. The documentation on installing the HBase tools is here.

If you want to keep your Java ingestion code, then you'll need to do something custom. There is an example of writing a map-reduce ingestion here.

Title: GeoMesa on HBase faster import


问:
How to check if relativedelta object is negative
I have some problem with using relativedelta objects - cannot determine if "delta is negative". What I'm trying is:

```<code>from dateutil.relativedelta import relativedelta
print relativedelta(seconds=-5) > 0
</code>```

that gives me True which is counter intuitive.

```<code>print relativedelta(seconds=5) > 0
</code>```

also return True. Is there a way to check if "delta" represented by relativedata object is negative?

I'm currently using a workaround in the form of separate function to check if delta is negative but I expected that there is more elegant solution. Here is code I'm using:

```<code>def is_relativedelta_positive(rel_delta):
    is_positive = True
    is_positive &= rel_delta.microseconds >= 0
    is_positive &= rel_delta.seconds >= 0
    is_positive &= rel_delta.minutes >= 0
    is_positive &= rel_delta.hours >= 0
    is_positive &= rel_delta.days >= 0
    return is_positive
</code>```

答:
TL;DR There is not a clear and intuitive definition of comparison between relativedelta objects, so comparison is not implemented in dateutil. If you want to compare them, you'll need to make an arbitrary choice about the ordering.

The problem

The semantics of comparisons between relativedelta are undefined because relativedelta objects themselves don't represent a fixed period of time. You can see this issue on github as to why this is a problem.

There are two major problems with comparisons between relativedelta objeccts. The more straightforward one is that relativedelta has "absolute" components (the singular arguments) such as day, hour, etc. So consider:

```<code>from dateutil.relativedelta import relativedelta
from datetime import datetime

rd1 = relativedelta(day=5, hours=5)
rd2 = relativedelta(hours=8)

for i in range(4, 7):
    dt = datetime(2014, 1, i)
    print((dt + rd1) > (dt + rd2))

# Result:
# True
# False
# False
</code>```

Since each relativedelta does not represent a fixed amount of time, it's not necessarily meaningful to compare which one is "bigger" or "smaller" than the other.

The other problem is that even if you restrict yourself to the "relative" components of the relativedelta, all units larger than week depend on what they are being added to, so:

```<code>rd3 = relativedelta(months=1)
rd4 = relativedelta(days=30)

for i in range(1, 4):
    dt = datetime(2015, i, 1)
    print((dt + rd3) > (dt + rd4))

# Result:
# True
# False
# True
</code>```

Possible comparison operations

That said, there are a few possible definitions that you can meaningfully use if you want a semi-arbitrary but consistent definition of "less than" for relativedelta.

One somewhat limited version of this is to say that "absolute" components will throw an error and to set a fixed value for the "relative" components:

```<code>def rd_to_td(rd):
    for comp in ['year', 'month', 'day', 'hour', 'minute', 'second',
                 'microsecond', 'weekday', 'leapdays']:
        if getattr(rd, comp) is not None:
            raise ValueError('Conversion not supported with component ' + comp)

    YEAR_LEN = 365.25
    MON_LEN = 30

    days = (rd.years or 0) * YEAR_LEN
    days += (rd.months or 0) * MON_LEN
    return timedelta(days=days, hours=rd.hours, minutes=rd.minutes,
                     seconds=rd.seconds, microseconds=rd.microseconds)
</code>```

Closest to universal comparison

The above works for limited cases, but probably most universal comparison method you can define is to simply add both to a fixed date and compare the results:

```<code>from datetime import datetime

def lt_at_dt(rd1, rd2, dt=datetime(1970, 1, 1)):
    return (dt + rd1) < (dt + rd2)
</code>```

If you want this as a key for sorting (rather than for pairwise comparisons), this same definition of "less than" can be used to convert relativedelta to timedelta (which is a fixed period of time):

```<code>def rd_to_td_at_dt(rd, dt=datetime(1970, 1, 1)):
    return (dt + rd1) - dt
</code>```

Note The previous two definitions are about the more general operation of comparison between relativedelta objects. To know if one of these is negative, just compare the result to a relativedelta representing zero, or convert to timedelta by one of the above methods and compare to timedelta(0).

Finally, I will note that in the forthcoming 2.7.0 release of dateutil, relativedelta will define __abs__ (GH PR #472), so your original definition of positivity can be reduced to abs(rd) == rd. However, as Martijn points out, abs(relativedelta(days=20, hours=-1)) != relativedelta(days=20, hours=-1), but by most reasonable definitions, that relative delta is always a positive offset.

Body:
I have some problem with using relativedelta objects - cannot determine if "delta is negative". What I'm trying is:

from dateutil.relativedelta import relativedelta
print relativedelta(seconds=-5) > 0

that gives me True which is counter intuitive.

print relativedelta(seconds=5) > 0

also return True. Is there a way to check if "delta" represented by relativedata object is negative?

I'm currently using a workaround in the form of separate function to check if delta is negative but I expected that there is more elegant solution. Here is code I'm using:

def is_relativedelta_positive(rel_delta):
    is_positive = True
    is_positive &= rel_delta.microseconds >= 0
    is_positive &= rel_delta.seconds >= 0
    is_positive &= rel_delta.minutes >= 0
    is_positive &= rel_delta.hours >= 0
    is_positive &= rel_delta.days >= 0
    return is_positive

Body:
TL;DR There is not a clear and intuitive definition of comparison between relativedelta objects, so comparison is not implemented in dateutil. If you want to compare them, you'll need to make an arbitrary choice about the ordering.

The problem

The semantics of comparisons between relativedelta are undefined because relativedelta objects themselves don't represent a fixed period of time. You can see this issue on github as to why this is a problem.

There are two major problems with comparisons between relativedelta objeccts. The more straightforward one is that relativedelta has "absolute" components (the singular arguments) such as day, hour, etc. So consider:

from dateutil.relativedelta import relativedelta
from datetime import datetime

rd1 = relativedelta(day=5, hours=5)
rd2 = relativedelta(hours=8)

for i in range(4, 7):
    dt = datetime(2014, 1, i)
    print((dt + rd1) > (dt + rd2))

# Result:
# True
# False
# False

Since each relativedelta does not represent a fixed amount of time, it's not necessarily meaningful to compare which one is "bigger" or "smaller" than the other.

The other problem is that even if you restrict yourself to the "relative" components of the relativedelta, all units larger than week depend on what they are being added to, so:

rd3 = relativedelta(months=1)
rd4 = relativedelta(days=30)

for i in range(1, 4):
    dt = datetime(2015, i, 1)
    print((dt + rd3) > (dt + rd4))

# Result:
# True
# False
# True

Possible comparison operations

That said, there are a few possible definitions that you can meaningfully use if you want a semi-arbitrary but consistent definition of "less than" for relativedelta.

One somewhat limited version of this is to say that "absolute" components will throw an error and to set a fixed value for the "relative" components:

def rd_to_td(rd):
    for comp in ['year', 'month', 'day', 'hour', 'minute', 'second',
                 'microsecond', 'weekday', 'leapdays']:
        if getattr(rd, comp) is not None:
            raise ValueError('Conversion not supported with component ' + comp)

    YEAR_LEN = 365.25
    MON_LEN = 30

    days = (rd.years or 0) * YEAR_LEN
    days += (rd.months or 0) * MON_LEN
    return timedelta(days=days, hours=rd.hours, minutes=rd.minutes,
                     seconds=rd.seconds, microseconds=rd.microseconds)

Closest to universal comparison

The above works for limited cases, but probably most universal comparison method you can define is to simply add both to a fixed date and compare the results:

from datetime import datetime

def lt_at_dt(rd1, rd2, dt=datetime(1970, 1, 1)):
    return (dt + rd1) < (dt + rd2)

If you want this as a key for sorting (rather than for pairwise comparisons), this same definition of "less than" can be used to convert relativedelta to timedelta (which is a fixed period of time):

def rd_to_td_at_dt(rd, dt=datetime(1970, 1, 1)):
    return (dt + rd1) - dt

Note The previous two definitions are about the more general operation of comparison between relativedelta objects. To know if one of these is negative, just compare the result to a relativedelta representing zero, or convert to timedelta by one of the above methods and compare to timedelta(0).

Finally, I will note that in the forthcoming 2.7.0 release of dateutil, relativedelta will define __abs__ (GH PR #472), so your original definition of positivity can be reduced to abs(rd) == rd. However, as Martijn points out, abs(relativedelta(days=20, hours=-1)) != relativedelta(days=20, hours=-1), but by most reasonable definitions, that relative delta is always a positive offset.


问:
jquery validation script not resetting when another ajax call is made
hey, I'm using a jquery plugin and when i focus in on a field and focus out it alerts me of a validation error.

now in my set up I have a menu that loads content from another page via ajax, and with in that content I have another sub menu that also calls content in with another ajax request.

Scenario

I click on Files from main menu, then click on View from sub menu, then on Create from there (using another ajax request)

on the Create content is where I am using the validation plugin, so like I said when I focus in and out it works, BUT if I click on Files again from the main menu the validation error remain in place where they popped up. If i click on View from the sub menu then the validation error fade out.

I tried to isolate the issue as to why the error fade out with an ajax call from the sub menu but now with the main menu.

Main menu script:

```<code>//------------------------------------------------------------------
// Pidget menu
//------------------------------------------------------------------
var content = '#main-content',
    wrap = '#wrap';
$("nav a.files-menu-link").live('click', function({
    $.validationEngine.closePrompt('.formError',true);
    $(content).hide(200, function(){
        $(wrap).load('files.php' + content, function(){
            $(this).hide().html(data).slideDown(500);
        });
    })
    return false;
});
</code>```

sub menu script

```<code>$('a#prospect-file-link').live('click', function(){
    $.validationEngine.closePrompt('.formError',true);
    $.post('resources/ajax/ajax.php', {
        action : 'prospects',
        uid    : uid
    }, function(data){
        $('#files-right-pane').hide().html(data).slideDown(500);
        $(".alpha").click(function() {
            $(this).find("span").toggleClass("expand-alpha-down");
            $(this).next(".show").slideToggle();
            return false;
        });
    });
    return false;
});
</code>```

then the create new script

```<code>//-- Create new prospect
$('a.new-prospect').live('click', function(){
    $('#files-right-pane').fadeOut(200);
    $.post('resources/ajax/ajax.php', {
        action : 'create_prospect',
        uid    : uid
    }, function(data){
        $('#files-right-pane').hide().html(data).slideDown(500);
        selectBox('prospect-type', 'prospect-type-td');
        selectBox('status', 'status-td');
        selectBox('primary-number', 'primary-td');
        selectBox('secondary-number', 'secondary-td');
        mce('new-prospect-comments');
        $("#new-prospect-form").validationEngine();
        $('.state').autoSuggest('resources/ajax/suggest.php', {minChars: 2, matchCase: false, startText: '', asHtmlID: 'state'});
    });
    return false;
});
</code>```

html markup

```<code>...
<td><input type="text" id="first_name" name="first_name" class="validate[required]" /></td>
<td><input type="text" id="middle_name" name="middle_name" /></td>
<td><input type="text" id="last_name" name="last_name" class="validate[required]" /></td>
...
</code>```

Thats my setup, I can't figure out the .closePromp() works in the view but not with the main menu link

答:
Looks to me like you are missing a parenthesis after 'function('.

Instead of:

```<code>$("nav a.files-menu-link").live('click', function({
</code>```

it should be:

```<code>$("nav a.files-menu-link").live('click', function(){
</code>```

Body:
hey, I'm using a jquery plugin and when i focus in on a field and focus out it alerts me of a validation error.

now in my set up I have a menu that loads content from another page via ajax, and with in that content I have another sub menu that also calls content in with another ajax request.

Scenario

I click on Files from main menu, then click on View from sub menu, then on Create from there (using another ajax request)

on the Create content is where I am using the validation plugin, so like I said when I focus in and out it works, BUT if I click on Files again from the main menu the validation error remain in place where they popped up. If i click on View from the sub menu then the validation error fade out.

I tried to isolate the issue as to why the error fade out with an ajax call from the sub menu but now with the main menu.

Main menu script:

//------------------------------------------------------------------
// Pidget menu
//------------------------------------------------------------------
var content = '#main-content',
    wrap = '#wrap';
$("nav a.files-menu-link").live('click', function({
    $.validationEngine.closePrompt('.formError',true);
    $(content).hide(200, function(){
        $(wrap).load('files.php' + content, function(){
            $(this).hide().html(data).slideDown(500);
        });
    })
    return false;
});

sub menu script

$('a#prospect-file-link').live('click', function(){
    $.validationEngine.closePrompt('.formError',true);
    $.post('resources/ajax/ajax.php', {
        action : 'prospects',
        uid    : uid
    }, function(data){
        $('#files-right-pane').hide().html(data).slideDown(500);
        $(".alpha").click(function() {
            $(this).find("span").toggleClass("expand-alpha-down");
            $(this).next(".show").slideToggle();
            return false;
        });
    });
    return false;
});

then the create new script

//-- Create new prospect
$('a.new-prospect').live('click', function(){
    $('#files-right-pane').fadeOut(200);
    $.post('resources/ajax/ajax.php', {
        action : 'create_prospect',
        uid    : uid
    }, function(data){
        $('#files-right-pane').hide().html(data).slideDown(500);
        selectBox('prospect-type', 'prospect-type-td');
        selectBox('status', 'status-td');
        selectBox('primary-number', 'primary-td');
        selectBox('secondary-number', 'secondary-td');
        mce('new-prospect-comments');
        $("#new-prospect-form").validationEngine();
        $('.state').autoSuggest('resources/ajax/suggest.php', {minChars: 2, matchCase: false, startText: '', asHtmlID: 'state'});
    });
    return false;
});

html markup

...
<input type="text" id="first_name" name="first_name" class="validate[required]" />
<input type="text" id="middle_name" name="middle_name" />
<input type="text" id="last_name" name="last_name" class="validate[required]" />
...

Thats my setup, I can't figure out the .closePromp() works in the view but not with the main menu link

Body:
Looks to me like you are missing a parenthesis after 'function('.

Instead of:

$("nav a.files-menu-link").live('click', function({

it should be:

$("nav a.files-menu-link").live('click', function(){


问:
Ignore part of a string when splitting using regular expression in R
I'm trying to split a string in R (using strsplit) at some specific points (dash, -) however not if the dash are within a string in brackets ([).

Example:

```<code>xx <- c("Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
xx
  [1] "Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]"
  [2] "Total Internet-Time Spent Online-Past 7 Days"
</code>```

should give me something like:

```<code>list(c("Radio Stations","Listened to Past Week","Toronto [FM-CFXJ-93.5 (93.5 The Move)]"), c("Total Internet","Time Spent Online","Past 7 Days"))
  [[1]]
  [1] "Radio Stations"                         "Listened to Past Week"
  [3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"

  [[2]]
  [1] "Total Internet"    "Time Spent Online" "Past 7 Days"
</code>```

Is there a way with regular expression to do this?  The position and the number of dashs change within each elements of the vector, and there is not always brackets.  However, when there are brackets, they are always at the end.

I've tried different things, but none are working:

```<code>## Trying to match "-" before "[" in Perl
strsplit(xx, split = "-(?=\\[)", perl=T)
# does nothing

## trying to first extract what follow "[" then splitting what is preceding that
temp <- strsplit(xx, "[", fixed = T)
temp <- lapply(temp, function(yy) substr(head(yy, -1),"-"))
# doesn't work as there are some elements with no brackets...
</code>```

Any help would be appreciated.

答:
1) gsubfn Assuming square brackets are balanced and not nested, gsubfn locates each [...] and within those uses gsub to convert dashes to exclamation marks.  We then split what is left on the remaining dashes and replace the exclamation marks with dashes.

The regular expression means match a [ followed by the shortest string until the next ].

```<code>library(gsubfn)

s <- strsplit(gsubfn("\\[.*?\\]", ~ gsub("-", "!", x), xx), "-")
lapply(s, gsub, pattern = "!", replacement = "-")
</code>```

which could be expressed using a magrittr pipeline:

```<code>library(gsubfn)
library(magrittr)

xx %>%
   gsubfn(pattern = "\\[.*?\\]", replacement = ~ gsub("-", "!", x)) %>%
   strsplit("-") %>%
   lapply(gsub, pattern = "!", replacement = "-")
</code>```

2) readLines  This alternative uses no packages, does not use strsplit and uses only simple fixed regular expressions. It also assumes balanced non-nested square brackets.

Using gsub it first prepends each [ with a newline and suffixes each ] with a new line.  Then for each input string it reads the result into r, and for the odd positioned strings replaces dash with newline.  Finally it pastes r back together again and re-reads it which has the effect of splitting it at the newlines (which were previously dashes.

```<code>lapply(gsub("\\]", "]\n", gsub("\\[", "\n[", xx)), function(x) {
   r <- readLines(textConnection(x))
   i  <- seq(1, length(r), 2)
   r[i] <- gsub("-", "\n", r[i])
   readLines(textConnection(paste(r, collapse = "")))
})
</code>```

Body:
I'm trying to split a string in R (using strsplit) at some specific points (dash, -) however not if the dash are within a string in brackets ([).

Example:

xx <- c("Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
xx
  [1] "Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]"
  [2] "Total Internet-Time Spent Online-Past 7 Days"

should give me something like:

list(c("Radio Stations","Listened to Past Week","Toronto [FM-CFXJ-93.5 (93.5 The Move)]"), c("Total Internet","Time Spent Online","Past 7 Days"))
  [[1]]
  [1] "Radio Stations"                         "Listened to Past Week"
  [3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"

  [[2]]
  [1] "Total Internet"    "Time Spent Online" "Past 7 Days"

Is there a way with regular expression to do this?  The position and the number of dashs change within each elements of the vector, and there is not always brackets.  However, when there are brackets, they are always at the end.

I've tried different things, but none are working:

## Trying to match "-" before "[" in Perl
strsplit(xx, split = "-(?=\\[)", perl=T)
# does nothing

## trying to first extract what follow "[" then splitting what is preceding that
temp <- strsplit(xx, "[", fixed = T)
temp <- lapply(temp, function(yy) substr(head(yy, -1),"-"))
# doesn't work as there are some elements with no brackets...

Any help would be appreciated.

Body:
1) gsubfn Assuming square brackets are balanced and not nested, gsubfn locates each [...] and within those uses gsub to convert dashes to exclamation marks.  We then split what is left on the remaining dashes and replace the exclamation marks with dashes.

The regular expression means match a [ followed by the shortest string until the next ].

library(gsubfn)

s <- strsplit(gsubfn("\\[.*?\\]", ~ gsub("-", "!", x), xx), "-")
lapply(s, gsub, pattern = "!", replacement = "-")

which could be expressed using a magrittr pipeline:

library(gsubfn)
library(magrittr)

xx %>%
   gsubfn(pattern = "\\[.*?\\]", replacement = ~ gsub("-", "!", x)) %>%
   strsplit("-") %>%
   lapply(gsub, pattern = "!", replacement = "-")

2) readLines  This alternative uses no packages, does not use strsplit and uses only simple fixed regular expressions. It also assumes balanced non-nested square brackets.

Using gsub it first prepends each [ with a newline and suffixes each ] with a new line.  Then for each input string it reads the result into r, and for the odd positioned strings replaces dash with newline.  Finally it pastes r back together again and re-reads it which has the effect of splitting it at the newlines (which were previously dashes.

lapply(gsub("\\]", "]\n", gsub("\\[", "\n[", xx)), function(x) {
   r <- readLines(textConnection(x))
   i  <- seq(1, length(r), 2)
   r[i] <- gsub("-", "\n", r[i])
   readLines(textConnection(paste(r, collapse = "")))
})


答:
If you're referring to the MySQL user:

```<code>SELECT CURRENT_USER();
</code>```

If you're referring to the logged in user for your application, it depends on the application. Are you modifying an existing application you can provide a link to?

You probably want something like

```<code>SELECT * FROM system_users WHERE u_userid = (your user id here)
</code>```

Title: display current logged username

Body:
If you're referring to the MySQL user:

SELECT CURRENT_USER();

If you're referring to the logged in user for your application, it depends on the application. Are you modifying an existing application you can provide a link to?

You probably want something like

SELECT * FROM system_users WHERE u_userid = (your user id here)


问:
Can't get height-attribute in Bootstrap 4 alpha to work
I'm learning Bootstrap, and I can't get the height attribute in v4 (e.g.: "row h-25") to work.

I've tried to add another CSS which sets the height of "container-fluid" as well as html and body to 100%, which someone proposed as a solution in another answer. Still doesn't work, I'm afraid. I'm using Visual Studio, and when I open "NuGet - Solution", it says that the bootstrap version is 'v4.0.0-alpha'.

Any help would be greatly appreciated.

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/custom.css" rel="stylesheet" />
    <script src="scripts/angular.min.js"></script>
</head>
<body>
    <div class="container-fluid" style="background-color: #e7fdd6">
        <div class="row h-25" style="background-color: #eee">
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Customer</p><!-- These are just rough drafts while I learn the grid system. --></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Power</p></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Panels</p></div>
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Projects</p></div>
        </div>

        <div class="row h-25" style="background-color: #eee">
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Customer-slider</p></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Power amount</p></div>
            <div class="col-md-3 col-lg-3 hidden-xs hidden-sm"><p>Panels</p></div>
            <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3"><p>Projects-slider</p></div>
        </div>

        <div class="row h-25">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"><img src="Content/picture.jpg" alt="Park" align="middle" /> <!-- Bilde --></div>
        </div>

        <div class="row h-25">
            <div class="col-lg-6 col-md-6-col-sm-12 col-xs-12"><!-- Graph 1 --></div>
            <div class="col-lg-6 col-md-6 hidden-sm hidden-xs"><!-- Graph 2 --></div>
        </div>

    </div>
</body>
</html>
</code>```

custom.css:

```<code>.container-fluid {
    height: 100%;
}

html, body {
    height: 100%;
}
</code>```

答: The h- (like h-25) classes were introduced in Bootstrap Alpha v6, so you need to upgrade your Bootstrap version to use these.

Body:
I'm learning Bootstrap, and I can't get the height attribute in v4 (e.g.: "row h-25") to work.

I've tried to add another CSS which sets the height of "container-fluid" as well as html and body to 100%, which someone proposed as a solution in another answer. Still doesn't work, I'm afraid. I'm using Visual Studio, and when I open "NuGet - Solution", it says that the bootstrap version is 'v4.0.0-alpha'.

Any help would be greatly appreciated.

<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/custom.css" rel="stylesheet" />

Customer

Power

Panels

Projects

Customer-slider

Power amount

Panels

Projects-slider

custom.css:

.container-fluid {
    height: 100%;
}

html, body {
    height: 100%;
}


问:
Path of Node Red node on PI
I try to install the sensorTag package with npm.
GitHub Link

In the readme I have to set executable by non-root user, with the following command:

```<code>sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)
</code>```

I'm new with PI, Node Red and Raspbian. Can someone say what 'which node' mean? Where can I find the path?

Is the path from process.execPath the correct path?

答:
which is a linux command to find where 'node' is installed
setcap set's same file permissions to cap_net.. as found for the link where node is installed...

all abit complicate, basically it allows users to access cap_net as mentioned on the github side

Title: Path of Node Red node on PI

Body:
I try to install the sensorTag package with npm.
GitHub Link

In the readme I have to set executable by non-root user, with the following command:

sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)

I'm new with PI, Node Red and Raspbian. Can someone say what 'which node' mean? Where can I find the path?

Is the path from process.execPath the correct path?


问:
Creating Custom Angular Button Component with Disabled Attribute
I was wondering how it would be possible for me to create a custom Angular component that was based off of the native HTML button element and contained its own disabled property.

We currently have our own implementation of the button element that does not contain a disabled property and I wanted to know how I can add this functionality and make sure that it remains unusable and un-clickable.

Thanks

答:
```<code>import { Component, Input } from '@angular/core';

@Component({
  selector: 'my-button',
  template: `<button [disabled]="disabledValue">button</button>`
})
export class MyButtonComponent  {
@Input()
public disabledValue: boolean;
}
//usage: <my-button [disabledValue]="true"><my-button/>
</code>```