问:
Postgresql query to find top voted tables within last 24 hours
I have a complex PostgreSQL DB query that I am having difficulties constructing. I have two tables: a post table and a votes table. Below is what they look like:

The post table- I've only included the id because other columns aren't important to my question

```<code> ----
| id |
 ----
</code>```

The votes table- vote_type can either be 1 (upvote), -1 (downvote), or 0 (neutral). The post_id is the id of the id of the post for the single vote.

```<code> ---- --------- ----------- --------------------------------
| id | post_id | vote_type | timestamp                      |
 ---- --------- ----------- --------------------------------
| 1  | 4       | 1         |  2017-03-30 12:17:12.246765-07 |
</code>```

Here's what I am trying to achieve: Query top 10 posts with the most votes within the last 24 hours

I've first constructed the following query:

```<code>SELECT postsTable.*, votesTable.votes
FROM posts AS postsTable
RIGHT JOIN (
  SELECT sum(vote_type) votes, post_id
  FROM votes
  WHERE (extract(day from age(now(), timestamp)) < 1)
  GROUP BY post_id)
  AS votesTable
  ON (postsTable.id = votesTable.post_id)
ORDER BY votes DESC NULLS LAST LIMIT 10;
</code>```

Returns something like:

```<code> ---- ---------------------- -------
| id | other_colums_between | votes |
 ---- ---------------------- -------
| 8  | ...                  | 1     |
</code>```

It works slightly with the right posts BUT the votes column only shows the sum of votes within the last 24 hours NOT the total votes made since the post has been made (and that's what I want). The reason is because I am summing the votes only made within the last 24 hours and NOT all votes since the post has been created.

Say the post with id 8 has 10 votes. The query only returns 1 vote because only one upvote has been made within the last 24 hours.

Thus the query should return:

```<code> ---- ---------------------- -------
| id | other_colums_between | votes |
 ---- ---------------------- -------
| 8  | ...                  | 10    |
</code>```

So I know what I have to fix but I don't know how to do it. I've tried the query below but it's not what I want but I feel like I am getting closer. I haven't included the filtering for posts within the last 24 hours on this one though.

```<code>SELECT postsTable.*, votesTable.vote_type, extract(day from age(now(), votesTable.timestamp)) age
FROM posts AS postsTable
RIGHT JOIN (SELECT * FROM votes)
AS votesTable ON (postsTable.id = votesTable.post_id)
ORDER BY vote_type DESC NULLS LAST LIMIT 10;
</code>```

Returns:

```<code> ---- ---------------------- ----------- -----
| id | other_colums_between | vote_type | age |
 ---- ---------------------- ----------- -----
| 8  | ...                  | 1         | 3   |
</code>```

As you can tell I am a beginner in SQL. I also ask for some advice as to how I can simplify the queries above. Thank you for your help.

答:
Please try...

```<code>SELECT posts.*,
       votesTotal AS Votes
FROM posts
JOIN
(
    SELECT post_id AS post_id,
           SUM( vote_type ) AS votesTotal
    FROM votes
    WHERE timestamp > NOW() + INTERVAL '-1 day'
    GROUP BY post_id
    ORDER BY votesTotal DESC
    LIMIT 10
) postCounter ON postCounter.post_id = posts.id;
</code>```

Firstly, a RIGHT JOIN would match all of the records from Posts with their corresponding records from the subquery whereas by using a JOIN (aka an INNER JOIN) above I have limited the results to the top 10 posts with votes from the past 24 hours.  If there are less than 10 posts with votes in the last 24 hours then it shall return only that number.  If you still require 10 records and are happy with the remaining records being a semirandom selection then change the JOIN to a RIGHT JOIN and add LIMIT 10 to the end of the outer SELECT statement.  If you require the extra records but with a specific sort pattern, then you will need to specify the pattern before I can code for it.

Secondly, NOW() + INTERVAL '-1 day' will produce the datetime 24 hours before the current datetime.  The WHERE statement of which it is part will limit our results to those votes from the past 24 hours.

Without GROUP BY the inner query would return as many rows with post_id and votesTotal as there are rows with that post_id meeting our WHERE criteria.  GROUP BY (in conjunction with SUM) has the effect of reducing that to one row for each post_id.

LIMIT 10 gives us the first 10 records produced by the rest of the inner query.  To ensure that they are also the top 10 I made sure that the list was sorted using ORDER BY.

Further reading...

http://www.sqlines.com/postgresql/how-to/dateadd

https://www.w3schools.com/sql/sql_groupby.asp

https://www.w3schools.com/sql/sql_join.asp (the Venn diagram can be especially helpful)

https://www.w3schools.com/sql/sql_orderby.asp

https://www.postgresql.org/docs/8.1/static/queries-limit.html

If you have any questions or comments, then please post a Comment accordingly.

Body:
I have a complex PostgreSQL DB query that I am having difficulties constructing. I have two tables: a post table and a votes table. Below is what they look like:

The post table- I've only included the id because other columns aren't important to my question

 ----
| id |
 ----

The votes table- vote_type can either be 1 (upvote), -1 (downvote), or 0 (neutral). The post_id is the id of the id of the post for the single vote.

 ---- --------- ----------- --------------------------------
| id | post_id | vote_type | timestamp                      |
 ---- --------- ----------- --------------------------------
| 1  | 4       | 1         |  2017-03-30 12:17:12.246765-07 |

Here's what I am trying to achieve: Query top 10 posts with the most votes within the last 24 hours

I've first constructed the following query:

SELECT postsTable.*, votesTable.votes
FROM posts AS postsTable
RIGHT JOIN (
  SELECT sum(vote_type) votes, post_id
  FROM votes
  WHERE (extract(day from age(now(), timestamp)) < 1)
  GROUP BY post_id)
  AS votesTable
  ON (postsTable.id = votesTable.post_id)
ORDER BY votes DESC NULLS LAST LIMIT 10;

Returns something like:

 ---- ---------------------- -------
| id | other_colums_between | votes |
 ---- ---------------------- -------
| 8  | ...                  | 1     |

It works slightly with the right posts BUT the votes column only shows the sum of votes within the last 24 hours NOT the total votes made since the post has been made (and that's what I want). The reason is because I am summing the votes only made within the last 24 hours and NOT all votes since the post has been created.

Say the post with id 8 has 10 votes. The query only returns 1 vote because only one upvote has been made within the last 24 hours.

Thus the query should return:

 ---- ---------------------- -------
| id | other_colums_between | votes |
 ---- ---------------------- -------
| 8  | ...                  | 10    |

So I know what I have to fix but I don't know how to do it. I've tried the query below but it's not what I want but I feel like I am getting closer. I haven't included the filtering for posts within the last 24 hours on this one though.

SELECT postsTable.*, votesTable.vote_type, extract(day from age(now(), votesTable.timestamp)) age
FROM posts AS postsTable
RIGHT JOIN (SELECT * FROM votes)
AS votesTable ON (postsTable.id = votesTable.post_id)
ORDER BY vote_type DESC NULLS LAST LIMIT 10;

Returns:

 ---- ---------------------- ----------- -----
| id | other_colums_between | vote_type | age |
 ---- ---------------------- ----------- -----
| 8  | ...                  | 1         | 3   |

As you can tell I am a beginner in SQL. I also ask for some advice as to how I can simplify the queries above. Thank you for your help.

Body:
Please try...

SELECT posts.*,
       votesTotal AS Votes
FROM posts
JOIN
(
    SELECT post_id AS post_id,
           SUM( vote_type ) AS votesTotal
    FROM votes
    WHERE timestamp > NOW() + INTERVAL '-1 day'
    GROUP BY post_id
    ORDER BY votesTotal DESC
    LIMIT 10
) postCounter ON postCounter.post_id = posts.id;

Firstly, a RIGHT JOIN would match all of the records from Posts with their corresponding records from the subquery whereas by using a JOIN (aka an INNER JOIN) above I have limited the results to the top 10 posts with votes from the past 24 hours.  If there are less than 10 posts with votes in the last 24 hours then it shall return only that number.  If you still require 10 records and are happy with the remaining records being a semirandom selection then change the JOIN to a RIGHT JOIN and add LIMIT 10 to the end of the outer SELECT statement.  If you require the extra records but with a specific sort pattern, then you will need to specify the pattern before I can code for it.

Secondly, NOW() + INTERVAL '-1 day' will produce the datetime 24 hours before the current datetime.  The WHERE statement of which it is part will limit our results to those votes from the past 24 hours.

Without GROUP BY the inner query would return as many rows with post_id and votesTotal as there are rows with that post_id meeting our WHERE criteria.  GROUP BY (in conjunction with SUM) has the effect of reducing that to one row for each post_id.

LIMIT 10 gives us the first 10 records produced by the rest of the inner query.  To ensure that they are also the top 10 I made sure that the list was sorted using ORDER BY.

Further reading...

http://www.sqlines.com/postgresql/how-to/dateadd

https://www.w3schools.com/sql/sql_groupby.asp

https://www.w3schools.com/sql/sql_join.asp (the Venn diagram can be especially helpful)

https://www.w3schools.com/sql/sql_orderby.asp

https://www.postgresql.org/docs/8.1/static/queries-limit.html

If you have any questions or comments, then please post a Comment accordingly.


来源: stackexchange

问:
Ball won't load up for game

// Main Javascript
//Variables to use
var canvas;
var context;
var ball;

canvas = documnet.getElementById("canvas");
context = canvas.getcontext("2d");

//Creates my ball function based off of what is on canvas for ball
ball = new Ball();```
</div>
</div>
</p>

<p>Well my ball is not showing up on screen and I am pretty sure I have done everything correctly but can someone look over it and find something I missed or made a mistake on? I really need some help and I appreciate the help!   </p>

<p><em>I have two Javascript files in here because I have one for my main javascript and ball</em></p>

```//ball.js
function ball() {
  //The ball itself
  this.startAngle = 0;
  this.endAngle = 360 * Math.PI * 2;
  this.radius = 40;
  this.drawBall = true;

  //location for my ball
  this.x = canvs / width / 2;
  this.y = canvas / height / 2;

  //coloring my ball
  this.color = " #00FFFF";

  //draw function
  this.draw = function () {
    context.fillStyle = this.color;
    context.beginPath();
    content.arc(this.x, this.y, this.redius, this.startAngle, this.Endangle, this.drawBall);
    context.fill();
  }
}
```

<p>My HTML:</p>

```<!DOCTYPE html>

<meta charset="utf-8" >
<title>Robert's Ball Game</title>
<link type="text/css" rel="stylesheet" href = css/robs.css" />

<canvas id="canvas" width="1000" height="720"></canvas>

//Javascript

```

答:
You've got lots of spelling and capitalisation errors, and you hadn't actually called the ball.draw() function.

I've added comments in the code below to show what I've changed to make it work (click "run" to see the result):

var canvas;
var context;
var ball;

canvas = document.getElementById("canvas"); // "document", not "documnet"
context = canvas.getContext("2d");   // needs capital "C" in getContext

//Creates my ball function based off of what is on canvas for ball
ball = new Ball();
ball.draw();   // you didn't call .draw()

//ball.js
function Ball() {
  //The ball itself
  this.startAngle = 0;
  this.endAngle = 360 * Math.PI * 2;
  this.radius = 40;
  this.drawBall = true;

  //location for my ball
  this.x = canvas.width / 2;    // you had canvs / width / 2
  this.y = canvas.height / 2;   // you had canvas / height / 2

  //coloring my ball
  this.color = "#00FFFF";

  //draw function
  this.draw = function () {
    context.fillStyle = this.color;
    context.beginPath();
    // on next line you had "content" instead of "context",
    // and "Endangle" instead of "endAngle", and "redius" instead of "radius":
    context.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle, this.drawBall);
    context.fill();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas" width="200" height="200"></canvas></code>```

ContentLicense: CC BY-SA 3.0

Title: Ball won't load up for game

Body:
// Main Javascript
//Variables to use
var canvas;
var context;
var ball;

canvas = documnet.getElementById("canvas");
context = canvas.getcontext("2d");

//Creates my ball function based off of what is on canvas for ball
ball = new Ball();

Well my ball is not showing up on screen and I am pretty sure I have done everything correctly but can someone look over it and find something I missed or made a mistake on? I really need some help and I appreciate the help!

I have two Javascript files in here because I have one for my main javascript and ball

//ball.js
function ball() {
  //The ball itself
  this.startAngle = 0;
  this.endAngle = 360 * Math.PI * 2;
  this.radius = 40;
  this.drawBall = true;

  //location for my ball
  this.x = canvs / width / 2;
  this.y = canvas / height / 2;

  //coloring my ball
  this.color = " #00FFFF";

  //draw function
  this.draw = function () {
    context.fillStyle = this.color;
    context.beginPath();
    content.arc(this.x, this.y, this.redius, this.startAngle, this.Endangle, this.drawBall);
    context.fill();
  }
}

My HTML:

<!DOCTYPE html>

<meta charset="utf-8" >
<title>Robert's Ball Game</title>
<link type="text/css" rel="stylesheet" href = css/robs.css" />

<canvas id="canvas" width="1000" height="720"></canvas>

//Javascript

Body:
You've got lots of spelling and capitalisation errors, and you hadn't actually called the ball.draw() function.

I've added comments in the code below to show what I've changed to make it work (click "run" to see the result):

var canvas;
var context;
var ball;

canvas = document.getElementById("canvas"); // "document", not "documnet"
context = canvas.getContext("2d");   // needs capital "C" in getContext

//Creates my ball function based off of what is on canvas for ball
ball = new Ball();
ball.draw();   // you didn't call .draw()

//ball.js
function Ball() {
  //The ball itself
  this.startAngle = 0;
  this.endAngle = 360 * Math.PI * 2;
  this.radius = 40;
  this.drawBall = true;

  //location for my ball
  this.x = canvas.width / 2;    // you had canvs / width / 2
  this.y = canvas.height / 2;   // you had canvas / height / 2

  //coloring my ball
  this.color = "#00FFFF";

  //draw function
  this.draw = function () {
    context.fillStyle = this.color;
    context.beginPath();
    // on next line you had "content" instead of "context",
    // and "Endangle" instead of "endAngle", and "redius" instead of "radius":
    context.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle, this.drawBall);
    context.fill();
  }
}

<canvas id="canvas" width="200" height="200"></canvas>


问:
SSRS - Excel data source error when report deployed to localhost report server
I need help with an SSRS report deployed to localhost which uses ODBC data source to retrieve data from excel file.
When the same report is previewed through BIDS 2008, it displays the results as expected. But after deploying the report to the Report Server on the same machine (localhost) where BIDS is running it gives the below error.

ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: , Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Cannot create a connection to data source 'dsInvoice'. ---> System.Data.Odbc.OdbcException: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I have tried shared data source as well as custom data source but both didn't work. When I looked up for this error it mentioned that I need to use 32-bit ODBC Administrator tool under %windir%\SysWOW64\odbcad32.exe and that's what I'm using but that also didn't work. I'm an Administrator on the local machine.

Below is some information about the machine:

Windows 7 64 bit

SQL Server 2008 R2

Office 2010 32 bit

Steps to reproduce the error:

Create a Microsoft Excel Driver User DSN - Test_Excel_Driver - under %windir%\SysWOW64\odbcad32.exe

Create an SSRS report using BIDS 2008 and select datasource as an ODBC Embedded Connection with following connection string - Dsn=Test_Excel_Driver;dbq=C:...\Test Excel.xlsx;defaultdir=C:...\;driverid=1046;fil=excel 12.0;maxbuffersize=2048;pagetimeout=5

Preview the report in BIDS - Works fine !

Deploy the report to localhost SSRS Report Server with full permissions. Click on the report in report manager and get the above error.

答:
First off using OLEDB instead of ODBC will be easier to get going, the connection string for OLEDB will look like:

```<code>Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;
Extended Properties="Excel 12.0 Xml;HDR=YES";
</code>```

Then in SSRS/BIDS when you click "Test Connection" in the DataSource screen you may see this error:

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

The documentation states MS Access drivers (including the OLEDB driver) only work under the x86 platform and is incompatible under the x64 or AnyCPU platform. However this appears to be untrue. Ref: https://stackoverflow.com/a/32760211/495455

First download the installer making sure you tick the _64.exe version: http://www.microsoft.com/en-us/download/details.aspx?id=13255

Extract the AccessDatabaseEngine_x64.exe to a folder to get the AceRedist.msi and Data.cab files.

Open command prompt in Admin mode

cd to the folder you extracted the download and execute the MSI with the passive argument:

AceRedist.msi /passive

After these steps I managed to run the application (and also SSRS without BIDS) after building in x64 or AnyCPU build configuration. This solves issue.

Body:
First off using OLEDB instead of ODBC will be easier to get going, the connection string for OLEDB will look like:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;
Extended Properties="Excel 12.0 Xml;HDR=YES";

Then in SSRS/BIDS when you click "Test Connection" in the DataSource screen you may see this error:

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

The documentation states MS Access drivers (including the OLEDB driver) only work under the x86 platform and is incompatible under the x64 or AnyCPU platform. However this appears to be untrue. Ref: https://stackoverflow.com/a/32760211/495455

First download the installer making sure you tick the _64.exe version: http://www.microsoft.com/en-us/download/details.aspx?id=13255

Extract the AccessDatabaseEngine_x64.exe to a folder to get the AceRedist.msi and Data.cab files.

Open command prompt in Admin mode

cd to the folder you extracted the download and execute the MSI with the passive argument:

AceRedist.msi /passive

After these steps I managed to run the application (and also SSRS without BIDS) after building in x64 or AnyCPU build configuration. This solves issue.


问:
Ruby/HAML no implicit conversion of Symbol into Integer
I have a database command that returns this:

```<code>[{:score=>66.54}]
</code>```

to the @score object

In HAML I am trying to get that score value, and I am calling it like this:
Score: #{@score}, but it is just showing up like this: [{:score=>66.54}]

And when I try this #{@score[:score]} it says no implicit conversion of Symbol into Integer.

How do I get the proper result?

答:
Because its an array I had to do this to get the result.

```<code>@score[0][:score]
</code>```

fixed it

Body:
I have a database command that returns this:

[{:score=>66.54}]

to the @score object

In HAML I am trying to get that score value, and I am calling it like this:
Score: #{@score}, but it is just showing up like this: [{:score=>66.54}]

And when I try this #{@score[:score]} it says no implicit conversion of Symbol into Integer.

How do I get the proper result?

Body:
Because its an array I had to do this to get the result.

@score[0][:score]

fixed it


问:
Python flask azure connection and driver needed azure driver needed
How do I find the SQL azure driver for my pypyodbc application.

 [gte 2.0] -->
Content relevant to Named Framework versions 2.0 and greater.

答: There was an existing SO thread pypyodbc: [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionWrite (send()), which got some issue when using pypyodbc. Based on your short & unclear description, I don't know why you want to use it to connect SQL Azure, and whether you will also get the similar issue. So I suggest you can consider for using Azure offical recommended Python driver pyodbc or pymssql, please see the document for them to knwo how to install & use these driver.


问:
Recursively splitting a list into two using LISP
Using LISP, i need to create a function that splits a list into two lists. The first list consists of 1st, 3rd, 5th, 7th, etc elements and the second list consists of 2nd, 4th, 6th, etc elements.

Output Examples:

```<code>(SPLIT-LIST ( )) => (NIL NIL)

(SPLIT-LIST '(A B C D 1 2 3 4 5)) => ((A C 1 3 5) (B D 2 4))

(SPLIT-LIST '(B C D 1 2 3 4 5)) => ((B D 2 4) (C 1 3 5))

(SPLIT-LIST '(A)) => ((A) NIL)
</code>```

The function need to be recursive.

This is my code so far.

```<code>(defun SPLIT-LIST (L)
  (cond
    ((null L) NIL)
    ((= 1 (length L)) (list (car L)))
    (t (cons (cons (car L) (SPLIT-LIST (cddr L))) (cadr L)))))
);cond
);defun
</code>```

i'm going to try to use flatten later on so that i end up w/ two lists, but for now, i just can't seem to get the sequence correctly.

MY CODE:

```<code>> (SPLIT-LIST '(1 2 3 4))
((1 (3) . 4) . 2)
</code>```

I just can't seem to make the code print 1 3 2 4 instead of 1 3 4 2.

```<code>> (SPLIT-LIST '(1 2 3 4 5 6))
((1 (3 (5) . 6) . 4) . 2)
</code>```

I can't make the second half of the expected output to print in the correct sequence.

答:
```<code>(defun split-list (L)
    (if (endp L)
    '(nil nil)
    (let ((X (split-list (cdr L))))
        (list (cons (car L) (cadr X)) (car X))
)))
</code>```

Body:
Using LISP, i need to create a function that splits a list into two lists. The first list consists of 1st, 3rd, 5th, 7th, etc elements and the second list consists of 2nd, 4th, 6th, etc elements.

Output Examples:

(SPLIT-LIST ( )) => (NIL NIL)

(SPLIT-LIST '(A B C D 1 2 3 4 5)) => ((A C 1 3 5) (B D 2 4))

(SPLIT-LIST '(B C D 1 2 3 4 5)) => ((B D 2 4) (C 1 3 5))

(SPLIT-LIST '(A)) => ((A) NIL)

The function need to be recursive.

This is my code so far.

(defun SPLIT-LIST (L)
  (cond
    ((null L) NIL)
    ((= 1 (length L)) (list (car L)))
    (t (cons (cons (car L) (SPLIT-LIST (cddr L))) (cadr L)))))
);cond
);defun

i'm going to try to use flatten later on so that i end up w/ two lists, but for now, i just can't seem to get the sequence correctly.

MY CODE:

> (SPLIT-LIST '(1 2 3 4))
((1 (3) . 4) . 2)

I just can't seem to make the code print 1 3 2 4 instead of 1 3 4 2.

> (SPLIT-LIST '(1 2 3 4 5 6))
((1 (3 (5) . 6) . 4) . 2)

I can't make the second half of the expected output to print in the correct sequence.


问:
Add extra column in sql to show ratio with previous row
I have a SQL table with a format like this:

```<code>SELECT period_id, amount FROM table;
+--------------------+
| period_id | amount |
+-----------+--------+
| 1         |    12  |
| 2         |    11  |
| 3         |    15  |
| 4         |    20  |
| ..        |    ..  |
+-----------+--------+
</code>```

I'd like to add an extra column (just in my select statement) that calculates the growth ratio with the previous amount, like so:

```<code>SELECT period_id, amount, [insert formula here] AS growth FROM table;
+-----------------------------+
| period_id | amount | growth |
+-----------+-----------------+
| 1         |    12  |        |
| 2         |    11  |   0.91 |  <-- 11/12
| 3         |    15  |   1.36 |  <-- 15/11
| 4         |    20  |   1.33 |  <-- 20/15
| ..        |    ..  |     .. |
+-----------+-----------------+
</code>```

Just need to work out how to perform the operation with the line before. Not interested in adding to the table. Any help appreciated :)

** also want to point out that period_id is in order but not necessarily increasing incrementally

答:
The window function Lag() would be a good fit here.

You may notice that we use (amount+0.0).  This is done just in case AMOUNT is an INT, and NullIf() to avoid the dreaded divide by zero

```<code>Declare @YourTable table (period_id int,amount int)
Insert Into @YourTable values
( 1,12),
( 2,11),
( 3,15),
( 4,20)

Select period_id
      ,amount
      ,growth  = cast((amount+0.0) / NullIf(lag(amount,1) over (Order By Period_ID),0) as decimal(10,2))
 From  @YourTable
</code>```

Returns

```<code>period_id   amount  growth
1           12      NULL
2           11      0.92
3           15      1.36
4           20      1.33
</code>```

Body:
I have a SQL table with a format like this:

SELECT period_id, amount FROM table;
+--------------------+
| period_id | amount |
+-----------+--------+
| 1         |    12  |
| 2         |    11  |
| 3         |    15  |
| 4         |    20  |
| ..        |    ..  |
+-----------+--------+

I'd like to add an extra column (just in my select statement) that calculates the growth ratio with the previous amount, like so:

SELECT period_id, amount, [insert formula here] AS growth FROM table;
+-----------------------------+
| period_id | amount | growth |
+-----------+-----------------+
| 1         |    12  |        |
| 2         |    11  |   0.91 |  <-- 11/12
| 3         |    15  |   1.36 |  <-- 15/11
| 4         |    20  |   1.33 |  <-- 20/15
| ..        |    ..  |     .. |
+-----------+-----------------+

Just need to work out how to perform the operation with the line before. Not interested in adding to the table. Any help appreciated :)

** also want to point out that period_id is in order but not necessarily increasing incrementally

Body:
The window function Lag() would be a good fit here.

You may notice that we use (amount+0.0).  This is done just in case AMOUNT is an INT, and NullIf() to avoid the dreaded divide by zero

Declare @YourTable table (period_id int,amount int)
Insert Into @YourTable values
( 1,12),
( 2,11),
( 3,15),
( 4,20)

Select period_id
      ,amount
      ,growth  = cast((amount+0.0) / NullIf(lag(amount,1) over (Order By Period_ID),0) as decimal(10,2))
 From  @YourTable

Returns

period_id   amount  growth
1           12      NULL
2           11      0.92
3           15      1.36
4           20      1.33


问:
How can I show this Toast message only if I click the second Tab?
I have a navigation bar with three tabs each tab is a Fragment.
I wrote in the onCreateView method of my second fragment this toast message:

```<code>public class SecondFragment extends Fragment{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.second_layout,container,false);

        Toast.makeText(getContext(), "Test", Toast.LENGTH_LONG).show();

        return rootView;
    }
</code>```

What I want is that only if I click this tab the message displays.
But the problem is that if I start the application the message displays directly, but why?

Here is my MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity{
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         *Setup the DrawerLayout and NavigationView
         */

        mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

        /**
         * Lets inflate the very first fragment
         * Here , we are inflating the TabFragment as the first Fragment
         */

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();

    }

}
</code>```

And (I think this is Important for this question) my TabFragment:

```<code>public class TabFragment extends Fragment {
    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /**
         *Inflate tab_layout and setup Views.
         */
            View x =  inflater.inflate(R.layout.tab_layout,null);
            tabLayout = (TabLayout) x.findViewById(R.id.tabs);
            viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                    tabLayout.setupWithViewPager(viewPager);
                   }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {

            if(position == 0){
                return new FirstFragment();
            }
            if(position == 1){
                return new SecondFragment();
            }
            if(position == 2){
                return new ThirdFragment();
            }

        return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "First";
                case 1 :
                    return "Second";
                case 2 :
                    return "Third";
            }
                return null;
        }
    }

}
</code>```

So where do I have to say Toast.makeText(getContext(), "Test", Toast.LENGTH_LONG).show(); to display it only by pressing on the second tab?

答: Wait! if you have multiple tabs then each tabs must be containing individual fragment and for each fragment there is java class and a layout file for the same then the coding part will be inside onCreate method of java file and xml/layout part will be in .xml file thats it. </p>

Body:
I have a navigation bar with three tabs each tab is a Fragment.
I wrote in the onCreateView method of my second fragment this toast message:

public class SecondFragment extends Fragment{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.second_layout,container,false);

        Toast.makeText(getContext(), "Test", Toast.LENGTH_LONG).show();

        return rootView;
    }

What I want is that only if I click this tab the message displays.
But the problem is that if I start the application the message displays directly, but why?

Here is my MainActivity.java:

public class MainActivity extends AppCompatActivity{
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         *Setup the DrawerLayout and NavigationView
         */

        mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

        /**
         * Lets inflate the very first fragment
         * Here , we are inflating the TabFragment as the first Fragment
         */

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();

    }

}

And (I think this is Important for this question) my TabFragment:

public class TabFragment extends Fragment {
    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /**
         *Inflate tab_layout and setup Views.
         */
            View x =  inflater.inflate(R.layout.tab_layout,null);
            tabLayout = (TabLayout) x.findViewById(R.id.tabs);
            viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                    tabLayout.setupWithViewPager(viewPager);
                   }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {

            if(position == 0){
                return new FirstFragment();
            }
            if(position == 1){
                return new SecondFragment();
            }
            if(position == 2){
                return new ThirdFragment();
            }

        return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "First";
                case 1 :
                    return "Second";
                case 2 :
                    return "Third";
            }
                return null;
        }
    }

}

So where do I have to say Toast.makeText(getContext(), "Test", Toast.LENGTH_LONG).show(); to display it only by pressing on the second tab?


问:
SSIS how to automatically map a newly added source column into all subsequent transformations and destinations
I have this ETL project in SSIS that collects some data in a Firebird database, makes some transformations, and insert them into a dimensional model in a SQL Server database.
I had to make a change in the model adding some columns and had to map them manually in all components from source throughout the project.
My question is: is there any way to automatically map newly added columns without having to check them manually in all subsequent transformation components?

Thanks,

答:
We use BIML along with some metadata that we store in a database to generate our SSIS packages.  If a new source attribute is introduced, we simply add that attribute to our metadata and regenerate the packages. The benefit with this approach is that you can regeneration multiple packages in one go.

Generating SSIS packages using BIML does rely on your solution using very strict, reusable patterns.

Marius


问:
Delphi 7 GIF in picture Dialog
I am using Delphi 7 and the OpenPictureDialog to open / preview various images. This works fine when opening a bmp, jpg, etc.; however, if I try to do the same with a gif I get the following error. Anyone got any idea why or have a fix for it?

thanks

Colin

答:
If you use our free syngdiplus unit, you'll get GIF, JPEG and TIFF image support at once, by using the gdiplus library, available on every Windows since Windows XP. It supports loading and saving pictures, and the preview in TPictureDialog. And your exe size with increase much less than with GraphicEx or TGifImage.

Works from Delphi 6 up to Delphi XE.

And you'll be able to draw any TCanvas with anti-aliaising.

See http://synopse.info/forum/viewforum.php?id=4

ContentLicense: CC BY-SA 2.5

Title: Delphi 7 GIF in picture Dialog


问:
Target WSGI script not found or unable to stat
Target WSGI script not found or unable to stat: /opt/python/current/app/application.py

I contain my app in a file called application.py, and my application's configuration looks like this:

I also tried uploading the sample app that AWS provides, which only contains 'application.py`, and yet I still get this error.

What could be causing the error?

答:
For me, I had my app instance stored in a variable called app, which wasn't recognised by Elastic Beanstalk. As soon as I changed the variable to application, it started working.

```<code># In application.py or manage.py, after initialising the app
application = app
</code>```

should do the trick.

Body:
For me, I had my app instance stored in a variable called app, which wasn't recognised by Elastic Beanstalk. As soon as I changed the variable to application, it started working.

# In application.py or manage.py, after initialising the app
application = app

should do the trick.


问:
Angular2 to Angular4 updates error
I have updated my angular2 to the current release but I got the following errors:  It seems there's an issue in the jasmine index file.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:40:37
  A parameter initializer is only allowed in a function or constructor implementation.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:40:45
  Cannot find name 'keyof'.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:40:51
  '=' expected.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:42:45
  A parameter initializer is only allowed in a function or constructor implementation.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:42:55
  Cannot find name 'keyof'.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:42:61
  '=' expected.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:58:41
  Cannot find name 'Partial'.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:99:21
  Cannot find name 'Partial'.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:99:34
  Cannot find name 'Partial'.

Here's my package.json file:

```<code>{
  "name": "buy-practice-test",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.10",
    "@angular/compiler": "^2.4.10",
    "@angular/core": "^2.4.10",
    "@angular/forms": "^2.4.10",
    "@angular/http": "^2.4.10",
    "@angular/platform-browser": "^2.4.10",
    "@angular/platform-browser-dynamic": "^2.4.10",
    "@angular/router": "^3.4.10",
    "angular2-datatable": "^0.5.3",
    "core-js": "^2.4.1",
    "ng2-pagination": "^0.5.1",
    "ng2-table": "^1.3.2",
    "rxjs": "5.0.0-beta.12",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "@types/jasmine": "^2.5.47",
    "@types/node": "^6.0.68",
    "angular-cli": "1.0.0-beta.18",
    "codelyzer": "1.0.0-beta.1",
    "jasmine-core": "2.4.1",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "4.0.9",
    "ts-node": "1.2.1",
    "tslint": "3.13.0",
    "typescript": "~2.0.3"
  }
}
</code>```

答:
keyof was introduced in Typescript 2.1, and in your package.json I see Typescript 2.0.3.

Unfortunately, there is a dependency on typescript 2.0.10 by @angular-cli/ast-tools@1.0.16, so you might not be able to upgrade to the latest typescript version (2.2.2). However, you may be able to downgrade jasmine or @types/jasmine.

I recommend that you upgrade in smaller steps. i.e. use npm outdated to see what version you can upgrade to based on all your dependencies. Upgrade a few libraries at a time - periodically check to make sure you haven't broken anything.  After you've upgraded what you can, next upgrade @angular to 4.0.

Title: Angular2 to Angular4 updates error

Body:
I have updated my angular2 to the current release but I got the following errors:  It seems there's an issue in the jasmine index file.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:40:37
  A parameter initializer is only allowed in a function or constructor implementation.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:40:45
  Cannot find name 'keyof'.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:40:51
  '=' expected.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:42:45
  A parameter initializer is only allowed in a function or constructor implementation.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:42:55
  Cannot find name 'keyof'.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:42:61
  '=' expected.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:58:41
  Cannot find name 'Partial'.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:99:21
  Cannot find name 'Partial'.

ERROR in [default] C:\src\Angular2\BuyPracticeTest_AV4\node_modules\@types\jasmine\index.d.ts:99:34
  Cannot find name 'Partial'.

Here's my package.json file:

{
  "name": "buy-practice-test",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.10",
    "@angular/compiler": "^2.4.10",
    "@angular/core": "^2.4.10",
    "@angular/forms": "^2.4.10",
    "@angular/http": "^2.4.10",
    "@angular/platform-browser": "^2.4.10",
    "@angular/platform-browser-dynamic": "^2.4.10",
    "@angular/router": "^3.4.10",
    "angular2-datatable": "^0.5.3",
    "core-js": "^2.4.1",
    "ng2-pagination": "^0.5.1",
    "ng2-table": "^1.3.2",
    "rxjs": "5.0.0-beta.12",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "@types/jasmine": "^2.5.47",
    "@types/node": "^6.0.68",
    "angular-cli": "1.0.0-beta.18",
    "codelyzer": "1.0.0-beta.1",
    "jasmine-core": "2.4.1",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "4.0.9",
    "ts-node": "1.2.1",
    "tslint": "3.13.0",
    "typescript": "~2.0.3"
  }
}


问:
Save DOM as xml in a file with javascript
In my javascript I have the following:

```<code>let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

let xml = person;
</code>```

How do I save my "xml" variable in a file (using javascript only)?
OBS: The content should not be presented in a single line, but in the tree structure:

```<code><person>
    <name></name>
    <surname></surname>
</person>
</code>```

答:
There's a very simple way to serialize your document to XML using XMLSerializer.

Here is the process:

give an elment to XMLSerializer to serialize to XHTML (which is valid XML).

optionally remove the xhtml namespace using String.prototype.replace

use vkbeautify to pretty print (no native way to pretty print)

let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

// 1.) use XMLSerializer
let xml = new XMLSerializer().serializeToString(person);

// 2.) remove xml namespace
let xmlWithoutNamespace = xml.replace(' xmlns="http://www.w3.org/1999/xhtml"', '');

// 3.) use vkbeautify or your other favorite library to pretty print
console.log(vkbeautify.xml(xmlWithoutNamespace));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/vkbeautify/vkbeautify.0.99.00.beta.js"></script></code>```

Body:
In my javascript I have the following:

let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

let xml = person;

How do I save my "xml" variable in a file (using javascript only)?
OBS: The content should not be presented in a single line, but in the tree structure:

<person>
    <name></name>
    <surname></surname>
</person>

Body:
There's a very simple way to serialize your document to XML using XMLSerializer.

Here is the process:

give an elment to XMLSerializer to serialize to XHTML (which is valid XML).

optionally remove the xhtml namespace using String.prototype.replace

use vkbeautify to pretty print (no native way to pretty print)

let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

// 1.) use XMLSerializer
let xml = new XMLSerializer().serializeToString(person);

// 2.) remove xml namespace
let xmlWithoutNamespace = xml.replace(' xmlns="http://www.w3.org/1999/xhtml"', '');

// 3.) use vkbeautify or your other favorite library to pretty print
console.log(vkbeautify.xml(xmlWithoutNamespace));

<script src="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/vkbeautify/vkbeautify.0.99.00.beta.js"></script>


问:
C# Method Return
I am writing a program which is about simple calculation in 3 different methods.
My code is working okay, but it doesn't grab the result back to Main.

Can anyone help me to find what is the problem for me?

Here is my code

```<code>static void Main(string[] args)
{
    Console.Write("Enter the first number\t");
    int number1 = Convert.ToInt32(Console.ReadLine());
    Console.Write("Enter the second number\t");
    int number2 = Convert.ToInt32(Console.ReadLine());

    sum(number1, number2);
    difference(number1, number2);
    multiplies(number1, number2);
}

public static int sum(int number1, int number2)
{
    Console.WriteLine("Sum is:");
    return number1 + number2;
}

public static int difference(int number1, int number2)
{
    Console.WriteLine("difference is:");
    return number1 - number2;
}

public static int multiplies(int number1, int number2)
{
    Console.WriteLine("multiplies:");
    return number1 - number2;
}
</code>```

Thank you in advance. :)

答:
Solution 1 :

```<code>static void Main(string[] args)
        {

            Console.Write("Enter the first number\t");
            int number1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the second number\t");
            int number2 = Convert.ToInt32(Console.ReadLine());

            sum(number1, number2);
            difference(number1, number2);
            multiplies(number1, number2);
        }

        public static void sum(int number1, int number2)
        {
            Console.WriteLine(string.Format("Sum is: {0}", number1 + number2));
        }

        public static void difference(int number1, int number2)
        {
            Console.WriteLine(string.Format("difference is: {0}", number1 - number2));
        }
        public static void multiplies(int number1, int number2)
        {
            Console.WriteLine(string.Format("multiplies : {0}", number1 * number2));
        }
</code>```

Solution 2 :

```<code>static void Main(string[] args)
        {

            Console.Write("Enter the first number\t");
            int number1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the second number\t");
            int number2 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine(sum(number1, number2));
            Console.WriteLine(difference(number1, number2));
            Console.WriteLine(multiplies(number1, number2));

        }

        public static int sum(int number1, int number2)
        {
            Console.WriteLine("Sum is:");
            return number1 + number2;
        }

        public static int difference(int number1, int number2)
        {
            Console.WriteLine("difference is:");
            return number1 - number2;
        }
        public static int multiplies(int number1, int number2)
        {
            Console.WriteLine("multiplies:");
            return number1 * number2;
        }
</code>```

The issue is that you are not printing the result to the console.

Title: C# Method Return

Body:
I am writing a program which is about simple calculation in 3 different methods.
My code is working okay, but it doesn't grab the result back to Main.

Can anyone help me to find what is the problem for me?

Here is my code

static void Main(string[] args)
{
    Console.Write("Enter the first number\t");
    int number1 = Convert.ToInt32(Console.ReadLine());
    Console.Write("Enter the second number\t");
    int number2 = Convert.ToInt32(Console.ReadLine());

    sum(number1, number2);
    difference(number1, number2);
    multiplies(number1, number2);
}

public static int sum(int number1, int number2)
{
    Console.WriteLine("Sum is:");
    return number1 + number2;
}

public static int difference(int number1, int number2)
{
    Console.WriteLine("difference is:");
    return number1 - number2;
}

public static int multiplies(int number1, int number2)
{
    Console.WriteLine("multiplies:");
    return number1 - number2;
}

Thank you in advance. :)

Body:
Solution 1 :

static void Main(string[] args)
        {

            Console.Write("Enter the first number\t");
            int number1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the second number\t");
            int number2 = Convert.ToInt32(Console.ReadLine());

            sum(number1, number2);
            difference(number1, number2);
            multiplies(number1, number2);
        }

        public static void sum(int number1, int number2)
        {
            Console.WriteLine(string.Format("Sum is: {0}", number1 + number2));
        }

        public static void difference(int number1, int number2)
        {
            Console.WriteLine(string.Format("difference is: {0}", number1 - number2));
        }
        public static void multiplies(int number1, int number2)
        {
            Console.WriteLine(string.Format("multiplies : {0}", number1 * number2));
        }

Solution 2 :

static void Main(string[] args)
        {

            Console.Write("Enter the first number\t");
            int number1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the second number\t");
            int number2 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine(sum(number1, number2));
            Console.WriteLine(difference(number1, number2));
            Console.WriteLine(multiplies(number1, number2));

        }

        public static int sum(int number1, int number2)
        {
            Console.WriteLine("Sum is:");
            return number1 + number2;
        }

        public static int difference(int number1, int number2)
        {
            Console.WriteLine("difference is:");
            return number1 - number2;
        }
        public static int multiplies(int number1, int number2)
        {
            Console.WriteLine("multiplies:");
            return number1 * number2;
        }

The issue is that you are not printing the result to the console.


问:
C header file loops
I have a couple of header files, which boil down to:

tree.h:

```<code>#include "element.h"

typedef struct tree_
{
    struct *tree_ first_child;
    struct *tree_ next_sibling;
    int tag;
    element *obj;
    ....
} tree;
</code>```

and element.h:

```<code>#include "tree.h"

typedef struct element_
{
    tree *tree_parent;
    char *name;
    ...
} element;
</code>```

The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included.

This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known.

How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)?

答:
A simple solution is to just not have separate header files. After all, if they're dependent on each other you're never going to use one without the other, so why separate them? You can have separate .c files that both use the same header but provide the more focused functionality.

I know this doesn't answer the question of how to use all the fancy stuff correctly, but I found it helpful when I was looking for a quick fix to a similar problem.

OwnerDisplayName: Scooby

Title: C header file loops

Body:
I have a couple of header files, which boil down to:

tree.h:

#include "element.h"

typedef struct tree_
{
    struct *tree_ first_child;
    struct *tree_ next_sibling;
    int tag;
    element *obj;
    ....
} tree;

and element.h:

#include "tree.h"

typedef struct element_
{
    tree *tree_parent;
    char *name;
    ...
} element;

The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included.

This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known.

How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)?

LastEditorDisplayName: Prakash


问:
grep to match filename in full path
I want to "extract" the file name in a full path string using grep.

For example:

In /etc/network/interfaces I want to match "interfaces".

In /home/user/Documents/report.pdf I want to match "report.pdf".

Basically I want the opposite of:

```<code>$ ls /etc/network/interfaces | grep "^.*/"
</code>```

I tried:

```<code>$ ls -p /etc/network/interfaces | grep "/.*$"
</code>```

But it won't be the last slash (/), all chars (.*), until the end ($). Since slashes are chars as well, it matches all the path.

Does anyone know a way to match only the last part? Something like (from last slash until the end.

Thank you,

答:
How about simply matching on not /? Also, for extraction, you need the -o flag to grep.

```<code>ls -p /etc/network/interfaces | grep -o '[^/]*$'
</code>```

Title: grep to match filename in full path

Body:
I want to "extract" the file name in a full path string using grep.

For example:

In /etc/network/interfaces I want to match "interfaces".

In /home/user/Documents/report.pdf I want to match "report.pdf".

Basically I want the opposite of:

$ ls /etc/network/interfaces | grep "^.*/"

I tried:

$ ls -p /etc/network/interfaces | grep "/.*$"

But it won't be the last slash (/), all chars (.*), until the end ($). Since slashes are chars as well, it matches all the path.

Does anyone know a way to match only the last part? Something like (from last slash until the end.

Thank you,

Body:
How about simply matching on not /? Also, for extraction, you need the -o flag to grep.

ls -p /etc/network/interfaces | grep -o '[^/]*$'


问:
Display page length and pagination in the same line jquery dataTables
Is there any way to display the page-length option and paginate option in the same line? This is how I got:

Is there any way to override their css and display them in the same line? They both are in two separate div. I've added "jquery.dataTables.min.css" and "bootstrap.min.css".

答:
edit: Ah, I realized I can't reply to a comments in comment, I hope the OP can sees this.

simply add the character i for information

as example, if you want to have i after l, then put as below

```<code>var table = $('#example').DataTable({
    dom: "<'row'<'col-sm-12'tr>>" +
         "<'row'<'col-sm-4'li><'col-sm-8'p>>"
});
</code>```

else you can even let i have it's own col-sm, as follows (note that I decreases pagination, p from 8 to 4 in order to fit into 12 division of 'row' by bootstrap standard.

```<code>var table = $('#example').DataTable({
    dom: "<'row'<'col-sm-12'tr>>" +
         "<'row'<'col-sm-4'l><'col-sm-4'i><'col-sm-4'p>>"
});
</code>```

Body:
edit: Ah, I realized I can't reply to a comments in comment, I hope the OP can sees this.

simply add the character i for information

as example, if you want to have i after l, then put as below

var table = $('#example').DataTable({
    dom: "<'row'<'col-sm-12'tr>>" +
         "<'row'<'col-sm-4'li><'col-sm-8'p>>"
});

else you can even let i have it's own col-sm, as follows (note that I decreases pagination, p from 8 to 4 in order to fit into 12 division of 'row' by bootstrap standard.

var table = $('#example').DataTable({
    dom: "<'row'<'col-sm-12'tr>>" +
         "<'row'<'col-sm-4'l><'col-sm-4'i><'col-sm-4'p>>"
});


问:
How do I know which jhipster version I am using?
I need to duplicate a jhipster project. Since I have created this project I have updated jhipster versions. I want to duplicate the project with the same jhipster version of the first project.

How do I know which version of Jhipster I am using on my first application?

答:
If you have not used grunt during your applicaton setup, you can also find this information in the.yo-rc </p>

<p>"jhipsterVersion":xxx</p>

ContentLicense: CC BY-SA 4.0

Body:
If you have not used grunt during your applicaton setup, you can also find this information in the.yo-rc

"jhipsterVersion":xxx


问:
Basic Authentication in Squid Server(behind NAT) over internet
I have googled for "basic authentication not working over internet in squid server" kind of searches with no appropriate answer for my problem.

Here is my problem:
I have set up a squid proxy server behind a firewall. I have forwarded a port (54321) to port 9999 where squid proxy is listening. Now everything is fine. I can connect to this proxy from anywhere. But I needed some kind of authentication, thus enabled basic_ncsa_auth. Now, I can access internet after authentication from my LAN computers. Fine, everything is going as I wanted to but,

from internet I have popup for username/password (firefox), and after authentication I get "cache access denied" message from squid proxy.

I would really appreciate if someone points me what I'm doing wrong here.

Here is my squid.conf file:

```<code>http_port 9999
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwd
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
</code>```

Network setup:
Firewall static IP: Port: 54321 forwarded to Proxy server: 10.11.12.8:9999.

答:
Does your Squid configuration permit http_reply_access?

```<code>http_reply_access allow all
</code>```

If your passwords are longer than 8 characters, you also need to make sure you are not using DES hashing, which is the default for the htpasswd command.

Here's how to create a new password file using the MD5 hashing algorithm:

```<code>[root@localhost ~] htpasswd -cm /tmp/passwd testuser
New password:
Re-type new password:
Adding password for user testuser
</code>```

Check the contents of the file:

```<code>[root@localhost ~] cat /tmp/password
testuser:$apr1$VxCDyltg$krZ6v7VrnULVOiuS0u6KD1
</code>```

Verify password using basic_ncsa_auth:

```<code>[root@localhost ~] /usr/lib64/squid/basic_ncsa_auth /tmp/passwd
testuser superspurs
OK
</code>```

Now verify at the CLI:

```<code>[root@TLABprx00 ~]# http_proxy=http://localhost:9999/ curl http://www.msftncsi.com/ncsi.txt --proxy-user testuser:superspurs
Microsoft NCSI
</code>```

Body:
I have googled for "basic authentication not working over internet in squid server" kind of searches with no appropriate answer for my problem.

Here is my problem:
I have set up a squid proxy server behind a firewall. I have forwarded a port (54321) to port 9999 where squid proxy is listening. Now everything is fine. I can connect to this proxy from anywhere. But I needed some kind of authentication, thus enabled basic_ncsa_auth. Now, I can access internet after authentication from my LAN computers. Fine, everything is going as I wanted to but,

from internet I have popup for username/password (firefox), and after authentication I get "cache access denied" message from squid proxy.

I would really appreciate if someone points me what I'm doing wrong here.

Here is my squid.conf file:

http_port 9999
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwd
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Network setup:
Firewall static IP: Port: 54321 forwarded to Proxy server: 10.11.12.8:9999.

Body:
Does your Squid configuration permit http_reply_access?

http_reply_access allow all

If your passwords are longer than 8 characters, you also need to make sure you are not using DES hashing, which is the default for the htpasswd command.

Here's how to create a new password file using the MD5 hashing algorithm:

[root@localhost ~] htpasswd -cm /tmp/passwd testuser
New password:
Re-type new password:
Adding password for user testuser

Check the contents of the file:

[root@localhost ~] cat /tmp/password
testuser:$apr1$VxCDyltg$krZ6v7VrnULVOiuS0u6KD1

Verify password using basic_ncsa_auth:

[root@localhost ~] /usr/lib64/squid/basic_ncsa_auth /tmp/passwd
testuser superspurs
OK

Now verify at the CLI:

[root@TLABprx00 ~]# http_proxy=http://localhost:9999/ curl http://www.msftncsi.com/ncsi.txt --proxy-user testuser:superspurs
Microsoft NCSI


问:
Can you run a local copy of AWS DynamoDB somehow?
If you want to write code to use AWS DynamoDB, is there any way to have it run on your local development environment? Or do you have to use the actual product?

Do you have to provision a development environment on AWS? Isn't that annoying because you'd have to work with vim and not have access to your favorite IDE? Or you have to push code to it every time you want to see if what you wrote is working?

答:
There is a lightweight version of DynamoDB which can be run locally, see:

https://aws.amazon.com/blogs/aws/dynamodb-local-for-desktop-development/

I found it a bit of a pain to remember all of the setup steps, so also created a Docker Image which wraps it, meaning you can also run DynamoDB Local with this command:

```<code># Run DynamoDB
docker run -p 8000:8000 dwmkerr/dynamodb

# Open the shell to show it's working!
open http://localhost:8000/shell
</code>```

The Docker image is available at:

https://hub.docker.com/r/dwmkerr/dynamodb/

Body:
There is a lightweight version of DynamoDB which can be run locally, see:

https://aws.amazon.com/blogs/aws/dynamodb-local-for-desktop-development/

I found it a bit of a pain to remember all of the setup steps, so also created a Docker Image which wraps it, meaning you can also run DynamoDB Local with this command:

# Run DynamoDB
docker run -p 8000:8000 dwmkerr/dynamodb

# Open the shell to show it's working!
open http://localhost:8000/shell

The Docker image is available at:

https://hub.docker.com/r/dwmkerr/dynamodb/


答:
You can do this in the following way:</p>

```<code> static void Main(string[] args)
        {
            Console.Write("Enter the first number\t");
            int number1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the second number\t");
            int number2 = Convert.ToInt32(Console.ReadLine());
            int result1=sum(number1, number2);
            Console.WriteLine(result1);
            int result2=difference(number1, number2);
            Console.WriteLine(result2);
            int result3=multiplies(number1, number2);
            Console.WriteLine(result3);
            Console.ReadLine();
        }
        public  static int sum(int number1, int number2)
        {
            Console.WriteLine("Sum is:");
            return number1 + number2;
        }

        public static int difference(int number1, int number2)
        {
            Console.WriteLine("difference is:");
            return number1 - number2;
        }
        public static int multiplies(int number1, int number2)
        {
            Console.WriteLine("multiplies:");
            return number1*number2;
        }
</code>```

Title: C# Method Return

Body:
You can do this in the following way:

 static void Main(string[] args)
        {
            Console.Write("Enter the first number\t");
            int number1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the second number\t");
            int number2 = Convert.ToInt32(Console.ReadLine());
            int result1=sum(number1, number2);
            Console.WriteLine(result1);
            int result2=difference(number1, number2);
            Console.WriteLine(result2);
            int result3=multiplies(number1, number2);
            Console.WriteLine(result3);
            Console.ReadLine();
        }
        public  static int sum(int number1, int number2)
        {
            Console.WriteLine("Sum is:");
            return number1 + number2;
        }

        public static int difference(int number1, int number2)
        {
            Console.WriteLine("difference is:");
            return number1 - number2;
        }
        public static int multiplies(int number1, int number2)
        {
            Console.WriteLine("multiplies:");
            return number1*number2;
        }


问:
MODAL HELP - how to pull row data per user id w/ PHP
Here is my code which I've revised so that it properly opens up my modal. I'm still facing issues passing table variables to the modal so that they can be edited according to which row you wish to edit with the click of the edit buttion.

```<code>   <html>
    <head>
        <title>Admin View</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>

    <body background=http://wallpapercave.com/wp/ItmVuT6.jpg>

        <!-- container with table headers / user records / edit function / approve function -->
        <div class="container">
        <table class="table table-hover table-striped">
                <center>
                    <thead>
                        <tr style="font-size: 24; color: white;">
                            <th>ID</th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email</th>
                            <th>Status</th>
                            <th colspan="2">Actions</th>
                        </tr>
                    </thead>
                </center>

                <tbody style="background-color: #F0F8FF">
                    <?php
                    $i = 1; foreach($users as $u)
                    {
                    ?>
                    <tr style="font-size: 20;">

                        <td width="5%;"> <?php echo $i; ?></td>
                        <td><?php echo $u->first_name; ?></td>
                        <td><?php echo $u->last_name; ?></td>
                        <td><?php echo $u->email; ?></td>
                        <td><?php echo ($u->approved) ? "Approved" : "Pending"; ?></td>

                        <!--edit button-->
                        <td><a href="" data-toggle="modal" data-target="#editModal"><span class='glyphicon glyphicon-edit'></span></a></td>

                        <!--approve button-->
                        <td><a href= "/ci/index.php/myform/approve/?user_id=<?php echo $u->id;?>"><span class="glyphicon glyphicon-ok gi-15x" style='color: green'></span></a></td>

                    </tr>
                    <?php $i++; } ?>
                </tbody>
                <table class="table table-hover table-striped">
            <center>
                <thead>
                    <tr style="font-size: 24; color: white;">
                        <th>ID</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email</th>
                        <th>Status</th>
                        <th colspan="2">Actions</th>
                    </tr>
                </thead>
            </center>

            <tbody style="background-color: #F0F8FF">
                <?php
                $i = 1; foreach($users as $u) {
                ?>
                <tr style="font-size: 20;">

                    <td width="5%;"> <?php echo $i++; ?></td>
                    <td><?php echo $u->first_name; ?></td>
                    <td><?php echo $u->last_name; ?></td>
                    <td><?php echo $u->email; ?></td>
                    <td><?php echo ($u->approved) ? "Approved" : "Pending"; ?></td>

                    <!--edit button-->
                    <td><a data-toggle="modal" data-target="#editModal<?php echo $u->id;?>"><span class='glyphicon glyphicon-edit'></span></a></td>

                    <!--approve button-->
                    <td><a href= "/ci/index.php/myform/approve/?user_id=<?php echo $u->id;?>"><span class="glyphicon glyphicon-ok gi-15x" style='color: green'></span></a></td>

                </tr>

    <!--modal-->

<div class='modal fade' id='editModal' tabindex='-1' role='dialog' aria-labelledby='editModalLabel' aria-hidden='true'>
        <div class='modal-dialog'>
            <div class='modal-content'>
                <div class='modal-header'>
                    <button type='button' class='close' data-dismiss='modal'><span class='glyphicon glyphicon-remove'></span></button>
                    <h3 class="modal-title" id='modalHeading'>Entry for User ID <?php echo $u->$id; ?></h3>
                </div>
                <!--modal body-->
                <div class='modal-body'>
                    <form action='' method='post'>

                        <div class='form-group'>
                            <label for='First Name'>First Name</label>
                            <input class='form-control' type='text' name='first_name' value="<?php echo $first_name; ?>"><br/>
                        </div>

                        <div class='form-group'>
                            <label for='Last Name'>Last Name</label>
                            <input class='form-control' type='text' name='last_name' value="<?php echo $last_name; ?>"/><br/>
                        </div>

                        <div class='form-group'>
                            <label for='Email'>Email</label>
                            <input class='form-control' type='text' name='email' value="<?php echo $email; ?>"/><br/>
                        </div>

                        <div class='form-group'>
                            <label for='Approved'>Approved</label>
                            <input class='form-control' type='text' name='email' value="<?php echo $approved; ?>"/><br/>
                        </div>
                </div>

                <!--modal footer-->
                <div class='modal-footer'>
                    <button type="button" class="btn btn-primary">Update</button>
                </div>
                </form>
            </div>
        </div>
    </div>

                <?php } ?>
            </tbody>
        </table>

     <!--attempt at ajax function for approve success class
    <script>

      $('.edit').on("click", function(){
        // user id stored when row edit clicked
        var userid = $(this).data('id');

        $ajax({

          url: $(this).attr('href'),
          method: 'POST',
          success: function (data) {

            $('#row_' + userid).addClass('success')
          },

          error: function (data) {

            $('#row_' + userid).addClass('danger')
          }
        });
      });

    </script>
    -->

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

Please help!

答:
You just need to put the modal inside your foreach and  make your data-toggle="modal" data-target="#editModal<?php echo $u->id;?>"> and your <div class='modal fade' id='editModal<?php echo $u->id;?>' tabindex='-1' role='dialog' aria-labelledby='editModalLabel' aria-hidden='true'> . I also have my whole code for that using MySQLi Object-oriented, I hope that this will help your problem.

```<code><?php
$servername = "localhost";
$username = "username"; //username
$password = "password"; //password
$dbname = "myDB"; //myDB

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>ACE | aice09</title>
    <!--Bootstrap 3.3.7 CSS-->
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!--Data Tables-->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
    <!--Fonts-->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
    <!--Date Timepicker-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">
</head>
<body>
    <nav class="navbar navbar-default mynavbar">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="javascript:;" onclick="window.location.href = '#'">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li class="active"><a href="javascript:;" onclick="window.location.href = '#'">Link <span class="sr-only">(current)</span></a></li>
            <li><a href="javascript:;" onclick="window.location.href = '#'">Link</a></li>
            <li class="dropdown">
              <a href="javascript:;" onclick="window.location.href = '#'" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="javascript:;" onclick="window.location.href = '#'">Action</a></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Another action</a></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Something else here</a></li>
                <li role="separator" class="divider"></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Separated link</a></li>
                <li role="separator" class="divider"></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">One more separated link</a></li>
              </ul>
            </li>
          </ul>
          <form class="navbar-form navbar-left">
            <div class="form-group">
              <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="javascript:;" onclick="window.location.href = '#'">Link</a></li>
            <li class="dropdown">
              <a href="javascript:;" onclick="window.location.href = '#'" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="javascript:;" onclick="window.location.href = '#'">Action</a></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Another action</a></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Something else here</a></li>
                <li role="separator" class="divider"></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Separated link</a></li>
              </ul>
            </li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav><!--/navbar navbar-default mynavbar-->

    <ol class="breadcrumb">
      <li><a href="javascript:;" onclick="window.location.href = '#'"><span class="fa fa-home"></span></a></li>
      <li><a href="javascript:;" onclick="window.location.href = '#'">Users</a></li>
      <li class="active"><b>Data</b></li>
    </ol><!--/breadcrumb-->

<!--////////////Start the Content Here//////////////////-->

<div class="container-fluid" style="">
    <!-- Data Table Here -->
    <table id="example" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th rowspan="2" style="width: 3%">NO</th>
                <th rowspan="2" style="text-align: center; width: 10%;">CLIENT ID</th>
                <th rowspan="2" style="text-align: center;width: 10%">NAME</th>
                <th colspan="4" style="text-align: center">ADDRESS</th>
                <th rowspan="2" style="width: 5%"></th>
            </tr>
            <tr>
                <th style="text-align: center; width: 18%">BARANGAY </th>
                <th style="text-align: center; width: 18%;">MUNICIPALITY </th>
                <th style="text-align: center; width: 18%;">PROVINCE </th>
                <th style="text-align: center; width: 18%;">COUNTRY </th>
            </tr>
        </thead>
        <tbody>
            <?php
                $sql = "SELECT * FROM users";
                $result = $conn->query($sql);
                if ($result->num_rows > 0) {
                    $id=1;
                    while($row = $result->fetch_assoc()) {
            ?>

            <tr>
                <td><?php echo $id++;?></td>
                <td ><?php echo $row['clientid'] ?></td>
                <td><a data-toggle="popover" title="Popover title" data-content="<div class='media'><a href='#'' class='pull-left'><img src='<?php echo $row['image'] ?>' class='media-object' alt='<?php echo $row['name'] ?> Image'></a><div class='media-body'><h4 class='media-heading'><?php echo $row['name'] ?></h4><p>Excellent Bootstrap popover! I really love it.</p></div></div>"><?php echo $row['name'] ?></a></td>
                <td><?php echo $row['barangay'] ?></td>
                <td><?php echo $row['municipality'] ?></td>
                <td><?php echo $row['province'] ?></td>
                <td><?php echo $row['country'] ?></td>
                <th><a href="" class="btn btn-primary btn-sm"  data-toggle="modal" data-target="#myModal<?php echo $row['clientid'] ?>">EDIT</a> <a href="" class="btn btn-danger btn-sm"><span class="lnr lnr-trash"></span> </a> </th>
            </tr>
            <!-- Modal -->
            <div class="modal fade" id="myModal<?php echo $row['clientid'] ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
              <div class="modal-dialog" role="document">
                <div class="modal-content">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">ADD SOMETHING</h4>
                  </div>
                  <div class="modal-body">
                     <p>This for <?php echo $row['name'] ?> modal</p>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary">Submit</button>
                  </div>
                </div>
              </div>
            </div>

            <?php
                 }
            } else {
                echo "0 results";
            }
            $conn->close();
            ?>
        </tbody>
    </table>

</div><!--/container-fluid-->

<!--////////////End of Content Here//////////////////-->

<!--Data Table JS-->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
</body>
</html>

<style type="text/css">
    .mynavbar{
        margin-bottom: 0px;
    }
    .mymodalbutton{
        margin-bottom: 5px;
    }
</style>

<script type="text/javascript">
$(document).ready(function() {

    //data-table
    $('#example').DataTable();
});
</script>
</code>```

Body:
Here is my code which I've revised so that it properly opens up my modal. I'm still facing issues passing table variables to the modal so that they can be edited according to which row you wish to edit with the click of the edit buttion.

        <title>Admin View</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                            ID
                            First Name
                            Last Name
                            Email
                            Status
                            Actions

                    <?php
                    $i = 1; foreach($users as $u)
                    {
                    ?>

                         <?php echo $i; ?>
                        <?php echo $u->first_name; ?>
                        <?php echo $u->last_name; ?>
                        <?php echo $u->email; ?>
                        <?php echo ($u->approved) ? "Approved" : "Pending"; ?>

                        <a href= "/ci/index.php/myform/approve/?user_id=<?php echo $u->id;?>">

                    <?php $i++; } ?>

                        ID
                        First Name
                        Last Name
                        Email
                        Status
                        Actions

                <?php
                $i = 1; foreach($users as $u) {
                ?>

                     <?php echo $i++; ?>
                    <?php echo $u->first_name; ?>
                    <?php echo $u->last_name; ?>
                    <?php echo $u->email; ?>
                    <?php echo ($u->approved) ? "Approved" : "Pending"; ?>

                    <a data-toggle="modal" data-target="#editModal<?php echo $u->id;?>">

                    <a href= "/ci/index.php/myform/approve/?user_id=<?php echo $u->id;?>">

                    <button type='button' class='close' data-dismiss='modal'></button>

Entry for User ID <?php echo $u->$id; ?>

                    <form action='' method='post'>

                            First Name
                            <input class='form-control' type='text' name='first_name' value="<?php echo $first_name; ?>">

                            Last Name
                            <input class='form-control' type='text' name='last_name' value="<?php echo $last_name; ?>"/>

                            Email
                            <input class='form-control' type='text' name='email' value="<?php echo $email; ?>"/>

                            Approved
                            <input class='form-control' type='text' name='email' value="<?php echo $approved; ?>"/>

                    <button type="button" class="btn btn-primary">Update</button>

                </form>

                <?php } ?>

Please help!

Body:
You just need to put the modal inside your foreach and  make your <a data-toggle="modal" data-target="#editModal<?php echo $u->id;?>"><span class='glyphicon glyphicon-edit'> and your <div class='modal fade' id='editModal<?php echo $u->id;?>' tabindex='-1' role='dialog' aria-labelledby='editModalLabel' aria-hidden='true'> . I also have my whole code for that using MySQLi Object-oriented, I hope that this will help your problem.

<?php
$servername = "localhost";
$username = "username"; //username
$password = "password"; //password
$dbname = "myDB"; //myDB

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>ACE | aice09</title>
    <!--Bootstrap 3.3.7 CSS-->
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!--Data Tables-->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
    <!--Fonts-->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
    <!--Date Timepicker-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">
</head>
<body>
    <nav class="navbar navbar-default mynavbar">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="javascript:;" onclick="window.location.href = '#'">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li class="active"><a href="javascript:;" onclick="window.location.href = '#'">Link <span class="sr-only">(current)</span></a></li>
            <li><a href="javascript:;" onclick="window.location.href = '#'">Link</a></li>
            <li class="dropdown">
              <a href="javascript:;" onclick="window.location.href = '#'" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="javascript:;" onclick="window.location.href = '#'">Action</a></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Another action</a></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Something else here</a></li>
                <li role="separator" class="divider"></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Separated link</a></li>
                <li role="separator" class="divider"></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">One more separated link</a></li>
              </ul>
            </li>
          </ul>
          <form class="navbar-form navbar-left">
            <div class="form-group">
              <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="javascript:;" onclick="window.location.href = '#'">Link</a></li>
            <li class="dropdown">
              <a href="javascript:;" onclick="window.location.href = '#'" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="javascript:;" onclick="window.location.href = '#'">Action</a></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Another action</a></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Something else here</a></li>
                <li role="separator" class="divider"></li>
                <li><a href="javascript:;" onclick="window.location.href = '#'">Separated link</a></li>
              </ul>
            </li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav><!--/navbar navbar-default mynavbar-->

    <ol class="breadcrumb">
      <li><a href="javascript:;" onclick="window.location.href = '#'"><span class="fa fa-home"></span></a></li>
      <li><a href="javascript:;" onclick="window.location.href = '#'">Users</a></li>
      <li class="active"><b>Data</b></li>
    </ol><!--/breadcrumb-->

<!--////////////Start the Content Here//////////////////-->

<div class="container-fluid" style="">
    <!-- Data Table Here -->
    <table id="example" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th rowspan="2" style="width: 3%">NO</th>
                <th rowspan="2" style="text-align: center; width: 10%;">CLIENT ID</th>
                <th rowspan="2" style="text-align: center;width: 10%">NAME</th>
                <th colspan="4" style="text-align: center">ADDRESS</th>
                <th rowspan="2" style="width: 5%"></th>
            </tr>
            <tr>
                <th style="text-align: center; width: 18%">BARANGAY </th>
                <th style="text-align: center; width: 18%;">MUNICIPALITY </th>
                <th style="text-align: center; width: 18%;">PROVINCE </th>
                <th style="text-align: center; width: 18%;">COUNTRY </th>
            </tr>
        </thead>
        <tbody>
            <?php
                $sql = "SELECT * FROM users";
                $result = $conn->query($sql);
                if ($result->num_rows > 0) {
                    $id=1;
                    while($row = $result->fetch_assoc()) {
            ?>

            <tr>
                <td><?php echo $id++;?></td>
                <td ><?php echo $row['clientid'] ?></td>
                <td><a data-toggle="popover" title="Popover title" data-content="<div class='media'><a href='#'' class='pull-left'><img src='<?php echo $row['image'] ?>' class='media-object' alt='<?php echo $row['name'] ?> Image'></a><div class='media-body'><h4 class='media-heading'><?php echo $row['name'] ?></h4><p>Excellent Bootstrap popover! I really love it.</p></div></div>"><?php echo $row['name'] ?></a></td>
                <td><?php echo $row['barangay'] ?></td>
                <td><?php echo $row['municipality'] ?></td>
                <td><?php echo $row['province'] ?></td>
                <td><?php echo $row['country'] ?></td>
                <th><a href="" class="btn btn-primary btn-sm"  data-toggle="modal" data-target="#myModal<?php echo $row['clientid'] ?>">EDIT</a> <a href="" class="btn btn-danger btn-sm"><span class="lnr lnr-trash"></span> </a> </th>
            </tr>
            <!-- Modal -->
            <div class="modal fade" id="myModal<?php echo $row['clientid'] ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
              <div class="modal-dialog" role="document">
                <div class="modal-content">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">ADD SOMETHING</h4>
                  </div>
                  <div class="modal-body">
                     <p>This for <?php echo $row['name'] ?> modal</p>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary">Submit</button>
                  </div>
                </div>
              </div>
            </div>

            <?php
                 }
            } else {
                echo "0 results";
            }
            $conn->close();
            ?>
        </tbody>
    </table>

</div><!--/container-fluid-->

<!--////////////End of Content Here//////////////////-->

<!--Data Table JS-->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
</body>
</html>

<style type="text/css">
    .mynavbar{
        margin-bottom: 0px;
    }
    .mymodalbutton{
        margin-bottom: 5px;
    }
</style>

<script type="text/javascript">
$(document).ready(function() {

    //data-table
    $('#example').DataTable();
});
</script>


问:
void pointer in function call in C++ vs C
I have this piece of code that works in C but not C++, is that any way to make it work on both C and C++ ?

```<code>void foo(void* b)
{
   int *c = b;
   printf("%d\n",*c);

}

int main ()
{
 int a = 1000;

 foo(&a);
 return 0;
}
</code>```

output:

C++:

```<code>1 In function 'void foo(void*)':
2 Line 3: error: invalid conversion from 'void*' to 'int*'
3 compilation terminated due to -Wfatal-errors.
</code>```

C:

```<code>1000
</code>```

Please help

答:
invalid conversion from void* to int*

In order to make an conversion from void* to int* you will need to cast b as int* when assigning it to c. Do:

```<code>int *c = (int*) b;
</code>```

This works in C++ and in C.

Body:
I have this piece of code that works in C but not C++, is that any way to make it work on both C and C++ ?

void foo(void* b)
{
   int *c = b;
   printf("%d\n",*c);

}

int main ()
{
 int a = 1000;

 foo(&a);
 return 0;
}

output:

C++:

1 In function 'void foo(void*)':
2 Line 3: error: invalid conversion from 'void*' to 'int*'
3 compilation terminated due to -Wfatal-errors.

C:

1000

Please help

Body:
invalid conversion from void* to int*

In order to make an conversion from void* to int* you will need to cast b as int* when assigning it to c. Do:

int *c = (int*) b;

This works in C++ and in C.