问:
Search string and grab all contents between 2 key words VB .NET
I've seen a bunch of examples on this online but I can't seem to find the one I'm looking for which uses Regex. I've seen many that use a loop and use a lot of lines of code but I'd like to see an example of Regex.

What I'm trying to create is an app that will connect too a webpage take the source search for a keyword once its found copy the text from that keyword to another keyword and save it into a string or to a textbox whatever.

I'm already using web request to get the information and put it into a string I just need to search the string for what I am looking for.

The reason for this app is to search webpage for an updated version of some software I'm using. I want to monitor for updates and the app to notify me when an update is available. Just a simple app but having issues searching for what I need.

```<code>For Example:
first words to search for: Server 64-bit
second words/characters to search for: </div>
</code>```

grab first words everything in between and last word saved into a string.

EDIT: The information I am trying to grab is this....

```<code>Server 64-bit
                  <span class="version">
          3.0.13.6
                      </span>
              </h3>
                    <div class="checksum">SHA256: c7eeb1937b0bce0b99e7c7e20de030a4b71adcaf09750481801cfa361433522f</div>
</code>```

答:
Maybe not the prettiest solution, but i would save it into a string. Then iterate through it with the string.contain("Server 64-Bit") and then split the whole thing and then split the remaining part of the string at the next  and retrieve only the first part.

```<code>Dim Information As String
Dim Splitstring As String
If Information.Contains("Server 64-Bit") Then
        Dim parts As String() = Information.Split("Server 64-Bit")
        For Each part In parts
           SplitString As String = part(1)
        Next
   If SplitString.Contains("</div>") then
       Dim parts As String() = Information.Split("</div>")
       For Each part In parts
           Dim ResultString As String = part(0)
           'Displaying Result in a MsgBox
           MsgBox(ResultString)
        Next
   End If
End If
</code>```

Im currently only at my Phone, so I cant actually test this, but this should work.

Body:
I've seen a bunch of examples on this online but I can't seem to find the one I'm looking for which uses Regex. I've seen many that use a loop and use a lot of lines of code but I'd like to see an example of Regex.

What I'm trying to create is an app that will connect too a webpage take the source search for a keyword once its found copy the text from that keyword to another keyword and save it into a string or to a textbox whatever.

I'm already using web request to get the information and put it into a string I just need to search the string for what I am looking for.

The reason for this app is to search webpage for an updated version of some software I'm using. I want to monitor for updates and the app to notify me when an update is available. Just a simple app but having issues searching for what I need.

For Example:
first words to search for: Server 64-bit
second words/characters to search for:

grab first words everything in between and last word saved into a string.

EDIT: The information I am trying to grab is this....

Server 64-bit

          3.0.13.6

SHA256: c7eeb1937b0bce0b99e7c7e20de030a4b71adcaf09750481801cfa361433522f

Body:
Maybe not the prettiest solution, but i would save it into a string. Then iterate through it with the string.contain("Server 64-Bit") and then split the whole thing and then split the remaining part of the string at the next  and retrieve only the first part.

Dim Information As String
Dim Splitstring As String
If Information.Contains("Server 64-Bit") Then
        Dim parts As String() = Information.Split("Server 64-Bit")
        For Each part In parts
           SplitString As String = part(1)
        Next
   If SplitString.Contains("</div>") then
       Dim parts As String() = Information.Split("</div>")
       For Each part In parts
           Dim ResultString As String = part(0)
           'Displaying Result in a MsgBox
           MsgBox(ResultString)
        Next
   End If
End If

Im currently only at my Phone, so I cant actually test this, but this should work.


来源: stackexchange

问:
array_key_exists() expects parameter 2 to be array, string given
I have this bit of code:

```<code>if( array_key_exists('customtextcolor',$atts) ){
    // If in array, then check if none, if not none, add to CSS classes
    if ( 'none' !== $atts['customtextcolor'] ) {
        $custstyles[] = $atts['customtextcolor'];
    }
}
</code>```

Which is on line 90, and my php.log shows an error on line 90.

Apr  2 08:46:16 #####.net ool www: PHP Warning:  array_key_exists() expects parameter 2 to be array, string given in /var/www/####/wp-content/plugins/Fusion-Builder-Custom-Text-For-HP/fusion-builder-custom-text-for-hp.php on line 90

Which I thought was strange, because I was sure it is was an array, because the code works as expected. I also used echo gettype($atts); and it returns an array. When I var_dump($atts); it renders the full array.

Any idea what php.log is showing this error message?

If $atts is a string, why does gettype() identify it as an array? And why does var_dump() render it as an array?

I've looked at the other array_key_exists() questions on StackOverflow, but they aren't the same issue as far as I can tell.

答:
Just write the following line of code:

```<code> array_key_exists('customtextcolor', (array) $atts);
</code>```

This will cast the $atts-variable into an array if it's not already an array.

You can also just check if there is an array with a value per:

isset($atts['customtextcolor']);

ContentLicense: CC BY-SA 3.0

Body:
I have this bit of code:

if( array_key_exists('customtextcolor',$atts) ){
    // If in array, then check if none, if not none, add to CSS classes
    if ( 'none' !== $atts['customtextcolor'] ) {
        $custstyles[] = $atts['customtextcolor'];
    }
}

Which is on line 90, and my php.log shows an error on line 90.

Apr  2 08:46:16 #####.net ool www: PHP Warning:  array_key_exists() expects parameter 2 to be array, string given in /var/www/####/wp-content/plugins/Fusion-Builder-Custom-Text-For-HP/fusion-builder-custom-text-for-hp.php on line 90

Which I thought was strange, because I was sure it is was an array, because the code works as expected. I also used echo gettype($atts); and it returns an array. When I var_dump($atts); it renders the full array.

Any idea what php.log is showing this error message?

If $atts is a string, why does gettype() identify it as an array? And why does var_dump() render it as an array?

I've looked at the other array_key_exists() questions on StackOverflow, but they aren't the same issue as far as I can tell.

Body:
Just write the following line of code:

 array_key_exists('customtextcolor', (array) $atts);

This will cast the $atts-variable into an array if it's not already an array.

You can also just check if there is an array with a value per:

isset($atts['customtextcolor']);


问:
GridLayout border lines/visible separators?
I'm relatively new to android and I want to know how to put a visible divider/borders around images.

答:
You could try to add an android:background attribute to your ImageView with the value of your desired border color. Then add an android:padding attribute to the ImageView with the value of your desired border width. It's not the most elegant solution, but it's understandable and for a new developer will do a fine job. For example:

```<code><ImageView
    android:id="@+id/list_item_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/android_image"
    android:background="color/list_item_icon_border_color"
    android:padding="1dp"
    />
</code>```

Maybe the right way for performing this is by using custom XML drawables. You could check in Google for creating borders for ImageView using custom XML drawable. However being a little more complicated way than the upper mentioned method it could be an excellent way to start with XML defined custom drawables. Sooner or later you'll have to understand it, no other way. For circular border check this post - nice and clear explanation with custom XML drawable:
Create circular border around ImageView

Body:
You could try to add an android:background attribute to your ImageView with the value of your desired border color. Then add an android:padding attribute to the ImageView with the value of your desired border width. It's not the most elegant solution, but it's understandable and for a new developer will do a fine job. For example:

<ImageView
    android:id="@+id/list_item_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/android_image"
    android:background="color/list_item_icon_border_color"
    android:padding="1dp"
    />

Maybe the right way for performing this is by using custom XML drawables. You could check in Google for creating borders for ImageView using custom XML drawable. However being a little more complicated way than the upper mentioned method it could be an excellent way to start with XML defined custom drawables. Sooner or later you'll have to understand it, no other way. For circular border check this post - nice and clear explanation with custom XML drawable:
Create circular border around ImageView


问:
"Application has thrown an uncaught exception and is terminated: Error: listen EACCES 0.0.0.0:80"
I've searched on other questions in here about this error but I couldn't find a solution.

Yesterday I deployed a Node + Express + Socket.IO website to Azure, and it doesn't work. I get the error

```<code>Application has thrown an uncaught exception and is terminated: Error: listen EACCES 0.0.0.0:80
</code>```

in this code:

```<code>// more code ...

var app = express();

var server = require('http').Server(app);

var io = require('socket.io')(server);

// right here
server.listen(portNumber, function () {
  console.log('Server listening at port %d', portNumber);
});

// more code ...
</code>```

It looks as if another process is already listening on this port.. maybe IIS Server? I'm not sure.

答:
I don't know Azure , but i know this: Something is trying to listen to port 80, and this requires admin access (windows)/ sudo permission (ubuntu).
first of all, change your settings, port 80 is the main port for the computer to listen to anything from the outer world, don't change that.
Giving your app admin access/sudo permission can bring down the whole system if an error throws in your application, don't give these privileges to the app.
If you MUST listen to port 80, listen to another port, and proxy from port 80 to that port </p>

Body:
I've searched on other questions in here about this error but I couldn't find a solution.

Yesterday I deployed a Node + Express + Socket.IO website to Azure, and it doesn't work. I get the error

Application has thrown an uncaught exception and is terminated: Error: listen EACCES 0.0.0.0:80

in this code:

// more code ...

var app = express();

var server = require('http').Server(app);

var io = require('socket.io')(server);

// right here
server.listen(portNumber, function () {
  console.log('Server listening at port %d', portNumber);
});

// more code ...

It looks as if another process is already listening on this port.. maybe IIS Server? I'm not sure.


问:
Antlr4 - matching an identifier as a single token
```<code>BLOCK_COMMENT : '/*' .*? '*/' -> skip;
EOL_COMMENT : '//' ~[\r\n]* -> skip;
WS: [ \n\t\r]+ -> skip;

program: usingDirectives? EOF;

usingDirectives: usingDirective+;

usingDirective: USING
        fullyQualifiedType
        (usingAlias | USING_ALL)?
        END;

USING: 'using';

fullyQualifiedType: identifier (DOT identifier)*;

identifier: (LETTER | UNDERSCORE)
        (LETTER | DIGIT | UNDERSCORE)*;

DOT: '.';

usingAlias: AS identifier;

USING_ALL: '.*';

AS: 'as';

END: ';';

LETTER: [a-zA-Z];

DIGIT: [0-9];

UNDERSCORE: '_';
</code>```

This is my grammar.

```<code>using IO.Console.Print as Print;
using IO.Console; // same as using IO.Console as Console;
using IO.Console.*;
</code>```

This is my test data.

The grammar works as intended, but each letter in an identifier becomes a single token, which is a bit useless.

If I try to make identifier a lexer rule (IDENTIFIER), then I get the following error, when running the test:

```<code>line 1:23 extraneous input 'as' expecting {'.', '.*', 'as', ';'}
</code>```

Even if I try to have IDENTIFIER be only [a-zA-Z], without subrules, the same happens.

If it matters, I'm using Python3 as the target language.
Please point out any other rookie mistakes as well, as this is my first project using Antlr. Thanks!

答:
right now you tell your lexer to yield a collection of characters suitable for a identifier instead of a identifier as a whole. Following simplified grammar(lexer and parser) should work for you:

```<code>grammar test;

root
    : identifier*;

identifier
    : IdentifierChars;

IdentifierChars
    : [a-zA-Z0-9_]+;

WhiteSpace
   : [ \r\n\t]+ -> skip;
</code>```

here is a sample Java code i used to check:

```<code>    InputStream input = IntegrationMain.class.getResourceAsStream("test.txt");
    ANTLRInputStream inputStream = new ANTLRInputStream(input);
    TokenSource tokenSource = new testLexer(inputStream);
    CommonTokenStream tokenStream = new CommonTokenStream(tokenSource);
    testParser parser = new testParser(tokenStream);
    testParser.RootContext root = parser.root();

    root.identifier().forEach(identifier -> System.out.println(identifier.getText()));
</code>```

and here is the result from stdout:

```<code>abc
a0bc
a_bc
</code>```

Body:
BLOCK_COMMENT : '/*' .*? '*/' -> skip;
EOL_COMMENT : '//' ~[\r\n]* -> skip;
WS: [ \n\t\r]+ -> skip;

program: usingDirectives? EOF;

usingDirectives: usingDirective+;

usingDirective: USING
        fullyQualifiedType
        (usingAlias | USING_ALL)?
        END;

USING: 'using';

fullyQualifiedType: identifier (DOT identifier)*;

identifier: (LETTER | UNDERSCORE)
        (LETTER | DIGIT | UNDERSCORE)*;

DOT: '.';

usingAlias: AS identifier;

USING_ALL: '.*';

AS: 'as';

END: ';';

LETTER: [a-zA-Z];

DIGIT: [0-9];

UNDERSCORE: '_';

This is my grammar.

using IO.Console.Print as Print;
using IO.Console; // same as using IO.Console as Console;
using IO.Console.*;

This is my test data.

The grammar works as intended, but each letter in an identifier becomes a single token, which is a bit useless.

If I try to make identifier a lexer rule (IDENTIFIER), then I get the following error, when running the test:

line 1:23 extraneous input 'as' expecting {'.', '.*', 'as', ';'}

Even if I try to have IDENTIFIER be only [a-zA-Z], without subrules, the same happens.

If it matters, I'm using Python3 as the target language.
Please point out any other rookie mistakes as well, as this is my first project using Antlr. Thanks!

Body:
right now you tell your lexer to yield a collection of characters suitable for a identifier instead of a identifier as a whole. Following simplified grammar(lexer and parser) should work for you:

grammar test;

root
    : identifier*;

identifier
    : IdentifierChars;

IdentifierChars
    : [a-zA-Z0-9_]+;

WhiteSpace
   : [ \r\n\t]+ -> skip;

here is a sample Java code i used to check:

    InputStream input = IntegrationMain.class.getResourceAsStream("test.txt");
    ANTLRInputStream inputStream = new ANTLRInputStream(input);
    TokenSource tokenSource = new testLexer(inputStream);
    CommonTokenStream tokenStream = new CommonTokenStream(tokenSource);
    testParser parser = new testParser(tokenStream);
    testParser.RootContext root = parser.root();

    root.identifier().forEach(identifier -> System.out.println(identifier.getText()));

and here is the result from stdout:

abc
a0bc
a_bc


问:
SQL Server 2005 - How to take a record from one table and loop through another table looking for match
I have 2 tables. for this example I will use only one users records.
The first table has the user name and an evaluation date as such:

```<code>USER  EVALDATE
--------------
bobr  6/7/2010
bobr  9/20/2010
bobr  9/21/2010
</code>```

The above table needs to be joined against this user history table, which has the history of the ID's and the dates they were valid, to look for a match (the NULL date means current):

```<code>USER   STARTDATE   ENDDATE
----------------------------
bobr   2/20/2006   4/18/2010
bobr2  4/19/2010   9/7/2010
bobr   9/8/2010    null
</code>```

What I'm trying to do in SQL Server 2005 is take the first record from the first table, loop it through the second table and when(if) the EVALDATE is within one of these date ranges and the IDs match, then flag that record from the first table as valid.

The current code takes the record from the first table and runs against all rows of the second table and kicks out a record for each invalid evaldate, so it kicks out a record when joined against the second table because the evaldate is not between the dates of the first record on the history table, even though the record is fine because the evaldate is between the start and end dates of the third record in the history table.

I hope this makes sense! In something like SAS I can create an array and loop through checking against each record in the history table. How do I do this in SQL? What I was trying to do was just update the first table with a flag if the records dates are invalid. Any ideas? Thanks!!!

答:
try something like:</p>

```<code>select * from [table2] t2
join [table1] t1 on t1.user = t2.user
--or better yet the foreign key
where t1.user = t2.user and t1.evaldate
between t2.startdate and t2.enddate
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have 2 tables. for this example I will use only one users records.
The first table has the user name and an evaluation date as such:

USER  EVALDATE
--------------
bobr  6/7/2010
bobr  9/20/2010
bobr  9/21/2010

The above table needs to be joined against this user history table, which has the history of the ID's and the dates they were valid, to look for a match (the NULL date means current):

USER   STARTDATE   ENDDATE
----------------------------
bobr   2/20/2006   4/18/2010
bobr2  4/19/2010   9/7/2010
bobr   9/8/2010    null

What I'm trying to do in SQL Server 2005 is take the first record from the first table, loop it through the second table and when(if) the EVALDATE is within one of these date ranges and the IDs match, then flag that record from the first table as valid.

The current code takes the record from the first table and runs against all rows of the second table and kicks out a record for each invalid evaldate, so it kicks out a record when joined against the second table because the evaldate is not between the dates of the first record on the history table, even though the record is fine because the evaldate is between the start and end dates of the third record in the history table.

I hope this makes sense! In something like SAS I can create an array and loop through checking against each record in the history table. How do I do this in SQL? What I was trying to do was just update the first table with a flag if the records dates are invalid. Any ideas? Thanks!!!

Body:
try something like:

select * from [table2] t2
join [table1] t1 on t1.user = t2.user
--or better yet the foreign key
where t1.user = t2.user and t1.evaldate
between t2.startdate and t2.enddate


问:
android ProgressBar is changing height dimension of parent LinearLayout
I have a bunch of RelativeLayout inside LinearLayout. Inside this will be ProgressBar and other elements.

The problem at the moment is that the ProgressBar is extending the height dimension of the parent LinearLayout when placed inside the RelativeLayout.

Here's the basics of what I have.

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1"
    android:weightSum="2">

    <RelativeLayout
        android:id="@+id/timer1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/darker_gray">

        <ProgressBar
            android:layout_width="200dp"
            android:layout_height="20dp"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:layout_centerInParent="true"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/timer2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"/>

</LinearLayout>
</code>```

The ProgressBar looks like it is extending height of the parent LinearLayout by the height of the ProgressBar. Which of course is not wanted.

Bare in mind that the above LinearLayout is inside another vertical LinearLayout where weightSum="3". So this distortion of the height means all will not fit in the screen vertically.

The one flaw I may have in my thinking is that because I have not yet completed the code (not put ProgressBar in each of the three levels) that it's just a quirk. I'll do that and report back. But it still seems to me this can't be a good thing.

答:
Well there you go. After I filled all three levels of the outer LinearLayout (not visible in example code above), the layout seemed to sort itself out.

All height parameters are the same (each taking up one third of the height of the screen) and this is true in both the xml Preview pane and when tested on an emulator.

So it looks to me that if you have a weightSum of 3, then the layout will not balance out until you have actually written the code for all three weight divisions.

For example, this would work:

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:wieghtSum="3" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
<LinearLayout/>
</code>```

But the following would potentially show a distorted height of the text views because the code is incomplete. weightSum is set to 3 but only code for two of the three divisions is written.

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:wieghtSum="3" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
<LinearLayout/>
</code>```

Body:
I have a bunch of RelativeLayout inside LinearLayout. Inside this will be ProgressBar and other elements.

The problem at the moment is that the ProgressBar is extending the height dimension of the parent LinearLayout when placed inside the RelativeLayout.

Here's the basics of what I have.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1"
    android:weightSum="2">

    <RelativeLayout
        android:id="@+id/timer1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/darker_gray">

        <ProgressBar
            android:layout_width="200dp"
            android:layout_height="20dp"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:layout_centerInParent="true"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/timer2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"/>

</LinearLayout>

The ProgressBar looks like it is extending height of the parent LinearLayout by the height of the ProgressBar. Which of course is not wanted.

Bare in mind that the above LinearLayout is inside another vertical LinearLayout where weightSum="3". So this distortion of the height means all will not fit in the screen vertically.

The one flaw I may have in my thinking is that because I have not yet completed the code (not put ProgressBar in each of the three levels) that it's just a quirk. I'll do that and report back. But it still seems to me this can't be a good thing.

Body:
Well there you go. After I filled all three levels of the outer LinearLayout (not visible in example code above), the layout seemed to sort itself out.

All height parameters are the same (each taking up one third of the height of the screen) and this is true in both the xml Preview pane and when tested on an emulator.

So it looks to me that if you have a weightSum of 3, then the layout will not balance out until you have actually written the code for all three weight divisions.

For example, this would work:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:wieghtSum="3" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
<LinearLayout/>

But the following would potentially show a distorted height of the text views because the code is incomplete. weightSum is set to 3 but only code for two of the three divisions is written.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:wieghtSum="3" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/example_text" />
<LinearLayout/>


问:
Mysql: Multiple Insert with Select, foreign key fails
I try to "duplicate" several rows in my table A. This table (A) has only two fields wich are foreign keys. One referencing to table B and the other one to table C.

Now I'd like to take several rows from A and re-insert (duplicate) them into A. Doing that I am changing one of the foreign keys (FK1).

```<code>INSERT INTO `A` (`FK1`, `FK2`) VALUES (".$newFK.", 1);
</code>```

This code works without any problem. But I need to duplicate more than just one row. Of course, I can do an SELECT-Statement and use the fetch_array to insert every row one by one but I'd like to solve it more elegant. Like this:

```<code>INSERT INTO A (`FK1`, `FK2`) SELECT ".$newFK.", `FK2` FROM `A` WHERE `FK1` = '".$tobeduplicatedFK."';
</code>```

As well I have tried

```<code>INSERT INTO `A` SET `FK1` = ".$newFK.", `FK2` = (SELECT `FK2` FROM `A` WHERE `FK1` = '".$tobeduplicatedFK."');
</code>```

Unfortunately neither of those work. But I do receive the "Cannot add or update a child row: a foreign key constraint fails" - Error related with FK1. Since the inelegant version is working the new FK1 ($newFK) exists. I have checked the old FK1 ($tobeduplicatedFK) as well and it exists, too.

I thought maybe something messes up because the select statement is on the same table and using the FK that has to be changed in WHERE-Clause. I have tried to perform the SELECT-Statement selecting from A as Asource but it is failing as well.

Any idea why it is failing?

答:
Try a subquery:</p>

```<code>"INSERT INTO A
(
    FK1,
    FK2
)
SELECT
    FK1,
    FK2
FROM
    (SELECT
        {$newFK} AS FK1,
        FK2
    FROM
        A
    WHERE
        FK1 = {$tobeduplicatedFK}) x0;"
</code>```

Body:
I try to "duplicate" several rows in my table A. This table (A) has only two fields wich are foreign keys. One referencing to table B and the other one to table C.

Now I'd like to take several rows from A and re-insert (duplicate) them into A. Doing that I am changing one of the foreign keys (FK1).

INSERT INTO `A` (`FK1`, `FK2`) VALUES (".$newFK.", 1);

This code works without any problem. But I need to duplicate more than just one row. Of course, I can do an SELECT-Statement and use the fetch_array to insert every row one by one but I'd like to solve it more elegant. Like this:

INSERT INTO A (`FK1`, `FK2`) SELECT ".$newFK.", `FK2` FROM `A` WHERE `FK1` = '".$tobeduplicatedFK."';

As well I have tried

INSERT INTO `A` SET `FK1` = ".$newFK.", `FK2` = (SELECT `FK2` FROM `A` WHERE `FK1` = '".$tobeduplicatedFK."');

Unfortunately neither of those work. But I do receive the "Cannot add or update a child row: a foreign key constraint fails" - Error related with FK1. Since the inelegant version is working the new FK1 ($newFK) exists. I have checked the old FK1 ($tobeduplicatedFK) as well and it exists, too.

I thought maybe something messes up because the select statement is on the same table and using the FK that has to be changed in WHERE-Clause. I have tried to perform the SELECT-Statement selecting from A as Asource but it is failing as well.

Any idea why it is failing?

Body:
Try a subquery:

"INSERT INTO A
(
    FK1,
    FK2
)
SELECT
    FK1,
    FK2
FROM
    (SELECT
        {$newFK} AS FK1,
        FK2
    FROM
        A
    WHERE
        FK1 = {$tobeduplicatedFK}) x0;"


问:
c++ function calling function not working
I have 3 functions:

First function takes an int a and prints the that number of dots.

The second function takes an int b and prints that number of stars.

The third function takes a and b and calls the dots function and stars function. When I call it in main, it returns 0 without any output.

Each of the functions work fine on their own - why doesn't the third one work then?

EDIT: Tried initializing i=0, code still compiles with the same result. Again, both functions dots() and stars() work fine when called on their own.

```<code>void dots(int a){
    for(int i; i<a; i++){
        cout << ".";
    }
}
void stars(int a){
    for(int i; i<a; i++){
        cout << "*";
    }
}

//(not working):
void dotsstars(int a, int b){
    dots(a);
    stars(b);
}

int main(){
    dotsstars(5, 6);

    return 0;
}
</code>```

答:
The variable i at the moment has garbage value so most probably the for loop will always be false (i.e it won't run)
so you need to initialize i

```<code>for(int i = 0; i < number_of_times ; i++)
</code>```

If your console closes quickly and you are not able to see the result then add getch(); in the end, you'll have to include the #include <conio.h> library

P.S i know using getch() is not a good practice and it makes the program OS dependent.

Body:
I have 3 functions:

First function takes an int a and prints the that number of dots.

The second function takes an int b and prints that number of stars.

The third function takes a and b and calls the dots function and stars function. When I call it in main, it returns 0 without any output.

Each of the functions work fine on their own - why doesn't the third one work then?

EDIT: Tried initializing i=0, code still compiles with the same result. Again, both functions dots() and stars() work fine when called on their own.

void dots(int a){
    for(int i; i<a; i++){
        cout << ".";
    }
}
void stars(int a){
    for(int i; i<a; i++){
        cout << "*";
    }
}

//(not working):
void dotsstars(int a, int b){
    dots(a);
    stars(b);
}

int main(){
    dotsstars(5, 6);

    return 0;
}

Body:
The variable i at the moment has garbage value so most probably the for loop will always be false (i.e it won't run)
so you need to initialize i

for(int i = 0; i < number_of_times ; i++)

If your console closes quickly and you are not able to see the result then add getch(); in the end, you'll have to include the #include <conio.h> library

P.S i know using getch() is not a good practice and it makes the program OS dependent.


问:
SQL Error: ORA-01846: not a valid day of the week
Why do I get this error:

```<code>Error starting at line 1 in command:
select name,major, lpad(to_char(date_birth,'dd'),10) "Date of birth",
to_char(next_day(date_birth,'sunday'),'dd') - to_char(date_birth,'dd') "Different in days"
from students
</code>```

SQL Error: ORA-01846: not a valid day of the week
  01846. 00000 -  "not a valid day of the week"

when I run the following query?

```<code>select name,major, lpad(to_char(date_birth,'dd'),10) "date of birth",
to_char(next_day(date_birth,'sunday'),'dd') - to_char(date_birth,'dd') "Different in days" from students
</code>```

答:
You have to write the name of the days in the language that you have set on sql developer, which is most likely not english.
But best practice is to set integers, like @user4507518 said.</p>

Body:
Why do I get this error:

Error starting at line 1 in command:
select name,major, lpad(to_char(date_birth,'dd'),10) "Date of birth",
to_char(next_day(date_birth,'sunday'),'dd') - to_char(date_birth,'dd') "Different in days"
from students

SQL Error: ORA-01846: not a valid day of the week
  01846. 00000 -  "not a valid day of the week"

when I run the following query?

select name,major, lpad(to_char(date_birth,'dd'),10) "date of birth",
to_char(next_day(date_birth,'sunday'),'dd') - to_char(date_birth,'dd') "Different in days" from students


问:
Linear regression with tensorflow
I trying to understand linear regression... here is script that I tried to understand:

```<code>'''
A linear regression learning algorithm example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''

from __future__ import print_function

import tensorflow as tf
from numpy import *
import numpy
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.0001
training_epochs = 1000
display_step = 50

# Training Data
train_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
                         7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
                         2.827,3.465,1.65,2.904,2.42,2.94,1.3])

train_X=numpy.asarray(train_X)
train_Y=numpy.asarray(train_Y)
n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    # Graphic display
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()
</code>```

Question is what this part represent:

```<code># Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")
</code>```

And why are there random float numbers?

Also could you show me some math with formals represents cost, pred, optimizer variables?

答:
let's try to put up some intuition&sources together with the tfapproach.

General intuition:

Regression as presented here is a supervised learning problem. In it, as defined in Russel&Norvig's Artificial Intelligence, the task is:

given a training set (X, y) of m input-output pairs (x1, y1), (x2, y2), ... , (xm, ym), where each output was generated by an unknown function y = f(x), discover a function h that approximates the true function f

For that sake, the h hypothesis function combines somehow each x with the to-be-learned parameters, in order to have an output that is as close to the corresponding y as possible, and this for the whole dataset. The hope is that the resulting function will be close to f.

But how to learn this parameters? in order to be able to learn, the model has to be able to evaluate. Here comes the cost  (also called loss, energy, merit...) function to play: it is a metric function that compares the output of h with the corresponding y, and penalizes big differences.

Now it should be clear what is exactly the "learning" process here: alter the parameters in order to achieve a lower value for the cost function.

Linear Regression:

The example that you are posting performs a parametric linear regression, optimized with gradient descent based on the mean squared error as cost function. Which means:

Parametric: The set of parameters is fixed. They are held in the exact same memory placeholders thorough the learning process.

Linear: The output of h is merely a linear (actually, affine) combination between the input x and your parameters. So if x and w are real-valued vectors of the same dimensionality, and b is a real number, it holds that h(x,w, b)= w.transposed()*x+b. Page 107 of the Deep Learning Book brings more quality insights and intuitions into that.

Cost function: Now this is the interesting part. The average squared error is a convex function. This means it has a single, global optimum, and furthermore, it can be directly found with the set of normal equations (also explained in the DLB). In the case of your example, the stochastic (and/or minibatch) gradient descent method is used: this is the preferred method when optimizing non-convex cost functions (which is the case in more advanced models like neural networks) or when your dataset has a huge dimensionality (also explained in the DLB).

Gradient descent: tf deals with this for you, so it is enough to say that GD minimizes the cost function by following its derivative "downwards", in small steps, until reaching a saddle point. If you totally need to know, the exact technique applied by TF is called automatic differentiation, kind of a compromise between the numeric and symbolic approaches. For convex functions like yours this point will be the global optimum, and (if your learning rate is not too big) it will always converge to it, so it doesn't matter which values you initialize your Variables with. The random initialization is necessary in more complex architectures like neural networks. There is some extra code regarding the management of the minibatches, but I won't get into that because it is not the main focus of your question.

The TensorFlow approach:

Deep Learning frameworks are nowadays about nesting lots of functions by building computational graphs (you may want to take a look at the presentation on DL frameworks that I did some weeks ago). For constructing and running the graph, TensoFlow follows a declarative style, which means that the graph has to be first completely defined and compiled, before it is deployed and executed. It is very reccommended to read this short wiki article, if you haven't yet. In this context, the setup is split in two parts:

Firstly, you define your computational Graph, where you put your dataset and parameters in memory placeholders, define the hypothesis and cost functions building on them, and tell tf which optimization technique to apply.

Then you run the computation in a Session and the library will be able to (re)load the data placeholders and perform the optimization.

The code:

The code of the example follows this approach closely:

Define the test data X and labels Y, and prepare a placeholder in the Graph for them (which is fed in the feed_dict part).

Define the 'W' and 'b' placeholders for the parameters. They have to be Variables because they will be updated during the Session.

Define pred (our hypothesis) and cost as explained before.

From this, the rest of the code should be clearer. Regarding the optimizer, as I said, tf already knows how to deal with this but you may want to look into gradient descent for more details (again, the DLB is a pretty good reference for that)

Cheers!
Andres

CODE EXAMPLES: GRADIENT DESCENT VS. NORMAL EQUATIONS

This small snippets generate simple multi-dimensional datasets and test both approaches. Notice that the normal equations approach doesn't require looping, and brings better results. For small dimensionality (DIMENSIONS<30k) is probably the preferred approach:

```<code>from __future__ import absolute_import, division, print_function
import numpy as np
import tensorflow as tf

####################################################################################################
### GLOBALS
####################################################################################################
DIMENSIONS = 5
f = lambda(x): sum(x) # the "true" function: f = 0 + 1*x1 + 1*x2 + 1*x3 ...
noise = lambda: np.random.normal(0,10) # some noise

####################################################################################################
### GRADIENT DESCENT APPROACH
####################################################################################################
# dataset globals
DS_SIZE = 5000
TRAIN_RATIO = 0.6 # 60% of the dataset is used for training
_train_size = int(DS_SIZE*TRAIN_RATIO)
_test_size = DS_SIZE - _train_size
ALPHA = 1e-8 # learning rate
LAMBDA = 0.5 # L2 regularization factor
TRAINING_STEPS = 1000

# generate the dataset, the labels and split into train/test
ds = [[np.random.rand()*1000 for d in range(DIMENSIONS)] for _ in range(DS_SIZE)] # synthesize data
# ds = normalize_data(ds)
ds = [(x, [f(x)+noise()]) for x in ds] # add labels
np.random.shuffle(ds)
train_data, train_labels = zip(*ds[0:_train_size])
test_data, test_labels = zip(*ds[_train_size:])

# define the computational graph
graph = tf.Graph()
with graph.as_default():
  # declare graph inputs
  x_train = tf.placeholder(tf.float32, shape=(_train_size, DIMENSIONS))
  y_train = tf.placeholder(tf.float32, shape=(_train_size, 1))
  x_test = tf.placeholder(tf.float32, shape=(_test_size, DIMENSIONS))
  y_test = tf.placeholder(tf.float32, shape=(_test_size, 1))
  theta = tf.Variable([[0.0] for _ in range(DIMENSIONS)])
  theta_0 = tf.Variable([[0.0]]) # don't forget the bias term!
  # forward propagation
  train_prediction = tf.matmul(x_train, theta)+theta_0
  test_prediction  = tf.matmul(x_test, theta) +theta_0
  # cost function and optimizer
  train_cost = (tf.nn.l2_loss(train_prediction - y_train)+LAMBDA*tf.nn.l2_loss(theta))/float(_train_size)
  optimizer = tf.train.GradientDescentOptimizer(ALPHA).minimize(train_cost)
  # test results
  test_cost = (tf.nn.l2_loss(test_prediction - y_test)+LAMBDA*tf.nn.l2_loss(theta))/float(_test_size)

# run the computation
with tf.Session(graph=graph) as s:
  tf.initialize_all_variables().run()
  print("initialized"); print(theta.eval())
  for step in range(TRAINING_STEPS):
    _, train_c, test_c = s.run([optimizer, train_cost, test_cost],
                               feed_dict={x_train: train_data, y_train: train_labels,
                                          x_test: test_data, y_test: test_labels })
    if (step%100==0):
      # it should return bias close to zero and parameters all close to 1 (see definition of f)
      print("\nAfter", step, "iterations:")
      #print("   Bias =", theta_0.eval(), ", Weights = ", theta.eval())
      print("   train cost =", train_c); print("   test cost =", test_c)
  PARAMETERS_GRADDESC = tf.concat(0, [theta_0, theta]).eval()
  print("Solution for parameters:\n", PARAMETERS_GRADDESC)

####################################################################################################
### NORMAL EQUATIONS APPROACH
####################################################################################################
# dataset globals
DIMENSIONS = 5
DS_SIZE = 5000
TRAIN_RATIO = 0.6 # 60% of the dataset isused for training
_train_size = int(DS_SIZE*TRAIN_RATIO)
_test_size = DS_SIZE - _train_size
f = lambda(x): sum(x) # the "true" function: f = 0 + 1*x1 + 1*x2 + 1*x3 ...
noise = lambda: np.random.normal(0,10) # some noise
# training globals
LAMBDA = 1e6 # L2 regularization factor

# generate the dataset, the labels and split into train/test
ds = [[np.random.rand()*1000 for d in range(DIMENSIONS)] for _ in range(DS_SIZE)]
ds = [([1]+x, [f(x)+noise()]) for x in ds] # add x[0]=1 dimension and labels
np.random.shuffle(ds)
train_data, train_labels = zip(*ds[0:_train_size])
test_data, test_labels = zip(*ds[_train_size:])

# define the computational graph
graph = tf.Graph()
with graph.as_default():
  # declare graph inputs
  x_train = tf.placeholder(tf.float32, shape=(_train_size, DIMENSIONS+1))
  y_train = tf.placeholder(tf.float32, shape=(_train_size, 1))
  theta = tf.Variable([[0.0] for _ in range(DIMENSIONS+1)]) # implicit bias!
  # optimum
  optimum = tf.matrix_solve_ls(x_train, y_train, LAMBDA, fast=True)

# run the computation: no loop needed!
with tf.Session(graph=graph) as s:
  tf.initialize_all_variables().run()
  print("initialized")
  opt = s.run(optimum, feed_dict={x_train:train_data, y_train:train_labels})
  PARAMETERS_NORMEQ = opt
  print("Solution for parameters:\n",PARAMETERS_NORMEQ)

####################################################################################################
### PREDICTION AND ERROR RATE
####################################################################################################

# generate test dataset
ds = [[np.random.rand()*1000 for d in range(DIMENSIONS)] for _ in range(DS_SIZE)]
ds = [([1]+x, [f(x)+noise()]) for x in ds] # add x[0]=1 dimension and labels
test_data, test_labels = zip(*ds)
# define hypothesis
h_gd = lambda(x): PARAMETERS_GRADDESC.T.dot(x)
h_ne = lambda(x): PARAMETERS_NORMEQ.T.dot(x)
# define cost
mse = lambda pred, lab: ((pred-np.array(lab))**2).sum()/DS_SIZE
# make predictions!
predictions_gd = np.array([h_gd(x) for x in test_data])
predictions_ne = np.array([h_ne(x) for x in test_data])
# calculate and print total error
cost_gd = mse(predictions_gd, test_labels)
cost_ne = mse(predictions_ne, test_labels)
print("total cost with gradient descent:", cost_gd)
print("total cost with normal equations:", cost_ne)
</code>```

Title: Linear regression with tensorflow

Body:
I trying to understand linear regression... here is script that I tried to understand:

'''
A linear regression learning algorithm example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''

from __future__ import print_function

import tensorflow as tf
from numpy import *
import numpy
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.0001
training_epochs = 1000
display_step = 50

# Training Data
train_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
                         7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
                         2.827,3.465,1.65,2.904,2.42,2.94,1.3])

train_X=numpy.asarray(train_X)
train_Y=numpy.asarray(train_Y)
n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    # Graphic display
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()

Question is what this part represent:

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

And why are there random float numbers?

Also could you show me some math with formals represents cost, pred, optimizer variables?

Body:
let's try to put up some intuition&sources together with the tfapproach.

General intuition:

Regression as presented here is a supervised learning problem. In it, as defined in Russel&Norvig's Artificial Intelligence, the task is:

given a training set (X, y) of m input-output pairs (x1, y1), (x2, y2), ... , (xm, ym), where each output was generated by an unknown function y = f(x), discover a function h that approximates the true function f

For that sake, the h hypothesis function combines somehow each x with the to-be-learned parameters, in order to have an output that is as close to the corresponding y as possible, and this for the whole dataset. The hope is that the resulting function will be close to f.

But how to learn this parameters? in order to be able to learn, the model has to be able to evaluate. Here comes the cost  (also called loss, energy, merit...) function to play: it is a metric function that compares the output of h with the corresponding y, and penalizes big differences.

Now it should be clear what is exactly the "learning" process here: alter the parameters in order to achieve a lower value for the cost function.

Linear Regression:

The example that you are posting performs a parametric linear regression, optimized with gradient descent based on the mean squared error as cost function. Which means:

Parametric: The set of parameters is fixed. They are held in the exact same memory placeholders thorough the learning process.

Linear: The output of h is merely a linear (actually, affine) combination between the input x and your parameters. So if x and w are real-valued vectors of the same dimensionality, and b is a real number, it holds that h(x,w, b)= w.transposed()*x+b. Page 107 of the Deep Learning Book brings more quality insights and intuitions into that.

Cost function: Now this is the interesting part. The average squared error is a convex function. This means it has a single, global optimum, and furthermore, it can be directly found with the set of normal equations (also explained in the DLB). In the case of your example, the stochastic (and/or minibatch) gradient descent method is used: this is the preferred method when optimizing non-convex cost functions (which is the case in more advanced models like neural networks) or when your dataset has a huge dimensionality (also explained in the DLB).

Gradient descent: tf deals with this for you, so it is enough to say that GD minimizes the cost function by following its derivative "downwards", in small steps, until reaching a saddle point. If you totally need to know, the exact technique applied by TF is called automatic differentiation, kind of a compromise between the numeric and symbolic approaches. For convex functions like yours this point will be the global optimum, and (if your learning rate is not too big) it will always converge to it, so it doesn't matter which values you initialize your Variables with. The random initialization is necessary in more complex architectures like neural networks. There is some extra code regarding the management of the minibatches, but I won't get into that because it is not the main focus of your question.

The TensorFlow approach:

Deep Learning frameworks are nowadays about nesting lots of functions by building computational graphs (you may want to take a look at the presentation on DL frameworks that I did some weeks ago). For constructing and running the graph, TensoFlow follows a declarative style, which means that the graph has to be first completely defined and compiled, before it is deployed and executed. It is very reccommended to read this short wiki article, if you haven't yet. In this context, the setup is split in two parts:

Firstly, you define your computational Graph, where you put your dataset and parameters in memory placeholders, define the hypothesis and cost functions building on them, and tell tf which optimization technique to apply.

Then you run the computation in a Session and the library will be able to (re)load the data placeholders and perform the optimization.

The code:

The code of the example follows this approach closely:

Define the test data X and labels Y, and prepare a placeholder in the Graph for them (which is fed in the feed_dict part).

Define the 'W' and 'b' placeholders for the parameters. They have to be Variables because they will be updated during the Session.

Define pred (our hypothesis) and cost as explained before.

From this, the rest of the code should be clearer. Regarding the optimizer, as I said, tf already knows how to deal with this but you may want to look into gradient descent for more details (again, the DLB is a pretty good reference for that)

Cheers!
Andres

CODE EXAMPLES: GRADIENT DESCENT VS. NORMAL EQUATIONS

This small snippets generate simple multi-dimensional datasets and test both approaches. Notice that the normal equations approach doesn't require looping, and brings better results. For small dimensionality (DIMENSIONS<30k) is probably the preferred approach:

from __future__ import absolute_import, division, print_function
import numpy as np
import tensorflow as tf

####################################################################################################
### GLOBALS
####################################################################################################
DIMENSIONS = 5
f = lambda(x): sum(x) # the "true" function: f = 0 + 1*x1 + 1*x2 + 1*x3 ...
noise = lambda: np.random.normal(0,10) # some noise

####################################################################################################
### GRADIENT DESCENT APPROACH
####################################################################################################
# dataset globals
DS_SIZE = 5000
TRAIN_RATIO = 0.6 # 60% of the dataset is used for training
_train_size = int(DS_SIZE*TRAIN_RATIO)
_test_size = DS_SIZE - _train_size
ALPHA = 1e-8 # learning rate
LAMBDA = 0.5 # L2 regularization factor
TRAINING_STEPS = 1000

# generate the dataset, the labels and split into train/test
ds = [[np.random.rand()*1000 for d in range(DIMENSIONS)] for _ in range(DS_SIZE)] # synthesize data
# ds = normalize_data(ds)
ds = [(x, [f(x)+noise()]) for x in ds] # add labels
np.random.shuffle(ds)
train_data, train_labels = zip(*ds[0:_train_size])
test_data, test_labels = zip(*ds[_train_size:])

# define the computational graph
graph = tf.Graph()
with graph.as_default():
  # declare graph inputs
  x_train = tf.placeholder(tf.float32, shape=(_train_size, DIMENSIONS))
  y_train = tf.placeholder(tf.float32, shape=(_train_size, 1))
  x_test = tf.placeholder(tf.float32, shape=(_test_size, DIMENSIONS))
  y_test = tf.placeholder(tf.float32, shape=(_test_size, 1))
  theta = tf.Variable([[0.0] for _ in range(DIMENSIONS)])
  theta_0 = tf.Variable([[0.0]]) # don't forget the bias term!
  # forward propagation
  train_prediction = tf.matmul(x_train, theta)+theta_0
  test_prediction  = tf.matmul(x_test, theta) +theta_0
  # cost function and optimizer
  train_cost = (tf.nn.l2_loss(train_prediction - y_train)+LAMBDA*tf.nn.l2_loss(theta))/float(_train_size)
  optimizer = tf.train.GradientDescentOptimizer(ALPHA).minimize(train_cost)
  # test results
  test_cost = (tf.nn.l2_loss(test_prediction - y_test)+LAMBDA*tf.nn.l2_loss(theta))/float(_test_size)

# run the computation
with tf.Session(graph=graph) as s:
  tf.initialize_all_variables().run()
  print("initialized"); print(theta.eval())
  for step in range(TRAINING_STEPS):
    _, train_c, test_c = s.run([optimizer, train_cost, test_cost],
                               feed_dict={x_train: train_data, y_train: train_labels,
                                          x_test: test_data, y_test: test_labels })
    if (step%100==0):
      # it should return bias close to zero and parameters all close to 1 (see definition of f)
      print("\nAfter", step, "iterations:")
      #print("   Bias =", theta_0.eval(), ", Weights = ", theta.eval())
      print("   train cost =", train_c); print("   test cost =", test_c)
  PARAMETERS_GRADDESC = tf.concat(0, [theta_0, theta]).eval()
  print("Solution for parameters:\n", PARAMETERS_GRADDESC)

####################################################################################################
### NORMAL EQUATIONS APPROACH
####################################################################################################
# dataset globals
DIMENSIONS = 5
DS_SIZE = 5000
TRAIN_RATIO = 0.6 # 60% of the dataset isused for training
_train_size = int(DS_SIZE*TRAIN_RATIO)
_test_size = DS_SIZE - _train_size
f = lambda(x): sum(x) # the "true" function: f = 0 + 1*x1 + 1*x2 + 1*x3 ...
noise = lambda: np.random.normal(0,10) # some noise
# training globals
LAMBDA = 1e6 # L2 regularization factor

# generate the dataset, the labels and split into train/test
ds = [[np.random.rand()*1000 for d in range(DIMENSIONS)] for _ in range(DS_SIZE)]
ds = [([1]+x, [f(x)+noise()]) for x in ds] # add x[0]=1 dimension and labels
np.random.shuffle(ds)
train_data, train_labels = zip(*ds[0:_train_size])
test_data, test_labels = zip(*ds[_train_size:])

# define the computational graph
graph = tf.Graph()
with graph.as_default():
  # declare graph inputs
  x_train = tf.placeholder(tf.float32, shape=(_train_size, DIMENSIONS+1))
  y_train = tf.placeholder(tf.float32, shape=(_train_size, 1))
  theta = tf.Variable([[0.0] for _ in range(DIMENSIONS+1)]) # implicit bias!
  # optimum
  optimum = tf.matrix_solve_ls(x_train, y_train, LAMBDA, fast=True)

# run the computation: no loop needed!
with tf.Session(graph=graph) as s:
  tf.initialize_all_variables().run()
  print("initialized")
  opt = s.run(optimum, feed_dict={x_train:train_data, y_train:train_labels})
  PARAMETERS_NORMEQ = opt
  print("Solution for parameters:\n",PARAMETERS_NORMEQ)

####################################################################################################
### PREDICTION AND ERROR RATE
####################################################################################################

# generate test dataset
ds = [[np.random.rand()*1000 for d in range(DIMENSIONS)] for _ in range(DS_SIZE)]
ds = [([1]+x, [f(x)+noise()]) for x in ds] # add x[0]=1 dimension and labels
test_data, test_labels = zip(*ds)
# define hypothesis
h_gd = lambda(x): PARAMETERS_GRADDESC.T.dot(x)
h_ne = lambda(x): PARAMETERS_NORMEQ.T.dot(x)
# define cost
mse = lambda pred, lab: ((pred-np.array(lab))**2).sum()/DS_SIZE
# make predictions!
predictions_gd = np.array([h_gd(x) for x in test_data])
predictions_ne = np.array([h_ne(x) for x in test_data])
# calculate and print total error
cost_gd = mse(predictions_gd, test_labels)
cost_ne = mse(predictions_ne, test_labels)
print("total cost with gradient descent:", cost_gd)
print("total cost with normal equations:", cost_ne)

ContentLicense: CC BY-SA 4.0


问:
Error trying to save PDF or HTML using Knit button in R Markdown
I am getting an error when I try to save a file in R Markdown using Knit

'Error in yaml::yaml.load(string, ...) :
  Scanner error: while scanning for the next token at line 7, column 1found character that cannot start any token at line 7, column 1
Calls:  ... parse_yaml_front_matter -> yaml_load_utf8 ->  -> .Call
Execution halted'

Can you please how to fix this? I cant save anything at the moment

答:
The YAML header had to look like this:

```<code>---
title: "Microarray analysis 2"
author: "Ania"
date: "3/9/2017"
output: html_document
---
</code>```

You can implement your R code after this header. Note that your R code has to be implemented in this way:

```<code>```{r}
source("http://bioconductor.org/biocLite.R")
```
</code>```

The way you tried will not work, because (1) the source command was not in an R-environment, (2) the URL http://bioconductor.org/biocLite.R [1] was not found.
```

Body:
The YAML header had to look like this:

---
title: "Microarray analysis 2"
author: "Ania"
date: "3/9/2017"
output: html_document
---

You can implement your R code after this header. Note that your R code has to be implemented in this way:

```{r}
source("http://bioconductor.org/biocLite.R")
```

The way you tried will not work, because (1) the source command was not in an R-environment, (2) the URL http://bioconductor.org/biocLite.R [1] was not found.
```


问:
Building a custom, portable Lua binary
I need to create a Lua binary for Windows that is fully portable, meaning that I can have it on a flash drive and it will work on any Windows computer (well, Windows 7 computer). I need at least a few additional libraries including Lua socket, a library that allows the proper storage (without rounding at all) and computation of large numbers (around 81 digits in total), and the rs232 library.

The problem is that I don't know how to compile them together into a binary, or if I can use some method to just use a plain Lua binary and use require to add the others. I've been researching this for a long time (a few weeks now) and haven't been able to find a solution. If anyone can help, it would be greatly appreciated.

If it makes the process any easier, I do have a Linux operating system I can use if necessary.

答: Answer: if you are using Windows, you can get the .dll files for each library and add them to your Lua directory. I now have a version of Lua with all of the libraries I wanted, plus a few more. Thank you everyone for your help.</p>

Title: Building a custom, portable Lua binary


问:
Make a div as heigh as needed
In my example below when the content in the top right div is too high, the content of the bottom div flows over the content of the top div.

I would like the top div to push the bottom div down so that content in both divs stays visible in the situation below.

How could I solve this?

.left {
  background-color: grey;
  min-height: 200px;
  float: left;
}

.right {
  height: auto;
  float: left;
}

.top {
  background-color: lightblue;
  height: 150px;

}

.bottom {
  background-color: lightgreen;
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="left">
    left
  </div>
  <div class="right">
    <div class="top">
      top right<br/> top right<br/> top right<br/> top right<br/> top right<br/> top right<br/>top right<br/>top right<br/>top right<br/>

    </div>
    <div class="bottom">
      bottom right
    </div>

  </div>

  <div></code>```

Edit

What I didn't mention before is that the bottom div should be on the bottom by default. This means that if there is enough space the bottom line of the bottom div should align with the bottom line of the left div

答:
It's happening because, you have given a fixed height of 150pxto the .top div, due to which it does not resize itself as the content inside it increases.

```<code>.top {
  background-color: lightblue;
  height: 150px;
}
</code>```

To solve it, just change the value of height to auto or give it a min-height of 150px instead of a fixed one.

Like this:

```<code>.top {
  background-color: lightblue;
  height: auto;
}
</code>```

Or this:

```<code>.top {
  background-color: lightblue;
  min-height: 150px;
}
</code>```

Title: Make a div as heigh as needed

Body:
In my example below when the content in the top right div is too high, the content of the bottom div flows over the content of the top div.

I would like the top div to push the bottom div down so that content in both divs stays visible in the situation below.

How could I solve this?

.left {
  background-color: grey;
  min-height: 200px;
  float: left;
}

.right {
  height: auto;
  float: left;
}

.top {
  background-color: lightblue;
  height: 150px;

}

.bottom {
  background-color: lightgreen;
  height: 50px;
}

    left

      top right
 top right
 top right
 top right
 top right
 top right
top right
top right
top right

      bottom right

Edit

What I didn't mention before is that the bottom div should be on the bottom by default. This means that if there is enough space the bottom line of the bottom div should align with the bottom line of the left div

Body:
It's happening because, you have given a fixed height of 150pxto the .top div, due to which it does not resize itself as the content inside it increases.

.top {
  background-color: lightblue;
  height: 150px;
}

To solve it, just change the value of height to auto or give it a min-height of 150px instead of a fixed one.

Like this:

.top {
  background-color: lightblue;
  height: auto;
}

Or this:

.top {
  background-color: lightblue;
  min-height: 150px;
}


问:
Unity touch input for Rolling Sky x axis control
I have written some code that I would image would be a very simplistic version of something found in the player controller of a game like Rolling Sky.

```<code>void Update () {
    if (Input.GetMouseButton(0)) {
        NewX = Camera.main.ScreenToViewportPoint (Input.mousePosition).x;
        float xMotion = (LastX - NewX) * -NavigationMultiplier / Screen.width;
        this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);
    }
    LastX = Camera.main.ScreenToViewportPoint(Input.mousePosition).x;
}
</code>```

This code works well on desktop, but as expected, it doesn't perform so well on mobile (the platform of choice)
Interestingly it just appears as if the player follows the finger similarly to simply using:

```<code>this.transform.position = new Vector3 (Input.mousePosition.x, this.transform.position.y, this.transform.position.z);
</code>```

Can anyone help make the first code block work correctly on mobile?

Desktop behavior (Desired)
https://www.youtube.com/watch?v=PjSzEresQI8

Mobile behavior (undesired)
https://www.youtube.com/watch?v=OooJ_NJW7V0

Thanks in advance

答:
For some reason, Input.GetMouseButton is always true on Android (not sure about other platforms), so to force the repositioning to happen only when the user has "pressed down" on the screen I used this code:</p>

```<code>if (Input.GetTouch(0).phase == TouchPhase.Moved){
        NewX = Camera.main.ScreenToViewportPoint (Input.mousePosition).x;
        float xMotion = (LastX - NewX) * -NavigationMultiplier / Screen.width;
        this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);
    }
    LastX = Camera.main.ScreenToViewportPoint(Input.mousePosition).x;
</code>```

Body:
I have written some code that I would image would be a very simplistic version of something found in the player controller of a game like Rolling Sky.

void Update () {
    if (Input.GetMouseButton(0)) {
        NewX = Camera.main.ScreenToViewportPoint (Input.mousePosition).x;
        float xMotion = (LastX - NewX) * -NavigationMultiplier / Screen.width;
        this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);
    }
    LastX = Camera.main.ScreenToViewportPoint(Input.mousePosition).x;
}

This code works well on desktop, but as expected, it doesn't perform so well on mobile (the platform of choice)
Interestingly it just appears as if the player follows the finger similarly to simply using:

this.transform.position = new Vector3 (Input.mousePosition.x, this.transform.position.y, this.transform.position.z);

Can anyone help make the first code block work correctly on mobile?

Desktop behavior (Desired)
https://www.youtube.com/watch?v=PjSzEresQI8

Mobile behavior (undesired)
https://www.youtube.com/watch?v=OooJ_NJW7V0

Thanks in advance

Body:
For some reason, Input.GetMouseButton is always true on Android (not sure about other platforms), so to force the repositioning to happen only when the user has "pressed down" on the screen I used this code:

if (Input.GetTouch(0).phase == TouchPhase.Moved){
        NewX = Camera.main.ScreenToViewportPoint (Input.mousePosition).x;
        float xMotion = (LastX - NewX) * -NavigationMultiplier / Screen.width;
        this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);
    }
    LastX = Camera.main.ScreenToViewportPoint(Input.mousePosition).x;


答:
Try this:</p>

```<code>SELECT  [USER]
       ,[EVALDATE]
       ,CASE WHEN ( SELECT  COUNT(*)
                    FROM    [UserStartEndDates] b
                    WHERE   [a].[USER] = [b].[User]
                            AND [EVALDATE] BETWEEN [STARTDATE]
                                               AND COALESE([ENDDATE],[EVALDATE])
                  ) > 0 THEN 1
             ELSE 0
        END AS [IsValid]
FROM    [Evaluations] a
</code>```

Title: SQL Server 2005 - How to take a record from one table and loop through another table looking for match

Body:
Try this:

SELECT  [USER]
       ,[EVALDATE]
       ,CASE WHEN ( SELECT  COUNT(*)
                    FROM    [UserStartEndDates] b
                    WHERE   [a].[USER] = [b].[User]
                            AND [EVALDATE] BETWEEN [STARTDATE]
                                               AND COALESE([ENDDATE],[EVALDATE])
                  ) > 0 THEN 1
             ELSE 0
        END AS [IsValid]
FROM    [Evaluations] a


问:
How you can save appends to variables an then convert them to php so you can save them in a database?
```<code><html>
<head>
  <meta charset="utf-8">

  <title>Test page for Query YQL</title>

  <link rel="stylesheet" href="http://hail2u.github.io/css/natural.css">

  <!--[if lt IE 9]><script src="http://hail2u.github.io/js/html5shiv.min.js"></script><![endif]-->
</head>
<body>
  <h1>Test page for Query YQL</h1>

  <div id="content"></div>

  <input type="button" name="bt1" value="click" onclick="pesquisa()">

  <form name="s2">
    <input type="text" name="s1">
  </form>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  <script src="jquery.query-yql.min.js"></script>
  <script type="text/javascript">

    function pesquisa(){

      $(function () {

        var t = $('#content').empty();
        var url= document.s2.s1.value;
        var statement = 'select * from feed where url="'+url+'"';

        $.queryYQL(statement, function (data) {
          $('<h2/>').text('Test: select * from feed').appendTo(t);
          var r = data.query.results;
          var ul = $('<ul/>');

          $.each(r.item, function () {

            $('<li/>').append(this.title).appendTo(ul);
            $('<li/>').append(this.link).appendTo(ul);

            <?php

              $titulo = "<script>document.write(titulo);</script>";

              $site = "<script>document.write(site);</script>";

              //echo $titulo;
              //echo  $site;

            ?>
          });
          ul.appendTo(t);
        });
      });
    };

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

How can you save the this.title and the this.link values into 2 different variables an then call them into php so you can insert the data into a DB?

It's just a simple YQL query to search on rss feeds.

After doing the query, I want the results to be saved in a database, but I can't discover how to do that.

答:
First of all, you have to understand that you are working on a Client-Server architecture.

This means:

Let's say that this file you are showing us is called "TestYQL.php" (because you did not say the name of it). This file is executed by php (server side), which reads line by line the contents of it, and generates another new file from the original. For educational purposes, let's say the generated file is called "GeneratedTestYQL.html". This file no longer has any php code inside, since it is directly html and js flat. It knows nothing about php. So there are no php functions, variables, nothing. This last file is the one that reaches the client, and the code is executed by a web browser like Chrome, Firefox, etc.

In your case, the file "TestYQL.php" all you have of php is what is inside the <? Php ....?> Tags. With php you creates 2 variables, each with a tag inside, but without any purpose since they are not used in any way. So, the generated "GeneratedTestYQL.html" file is the same as the original, but without the lines inside the <? Php ...?>.

This means that: The contents of the variables that you use in PHP can be sent to the browser, because with PHP you will generate the file that will be executed in the browser.

Now, when the file "GeneratedTestYQL.html" arrives, the browser starts to show all the contents of the file, it generates the form in which, when you click the button, executes the function pesquisa() and now starts javascript (JQuery) bringing data of the feeds, and for the first time, these variables "this.title" and "this.link" begin to exist in javascript.

Since there is no such thing as php here, you can NOT access those variables from php.

So, how to save that data in a DB?, well, the common way is to send all the data you want from the browser, to the server, then the server sees what to do with that data. To send data from the browser to the server, you do it by making GET or POST requests to a php file from the server (preferably another file, let's say it will be called "saveFeeds.php").

Data can be sent with a GET request, but it is semantically incorrect since GET means you want to fetch data from the server. So to send that data to the server, you will have to make a POST request from the browser, which is more appropriate.

There are now 2 simple ways to make a POST request. The first and most common of these is from a form in the browser, the other way is using Ajax.

How to do it from a form?

Currently in your code, you have already put a form (That is called "s2"), although currently the same is not necessary, but leave that now.
If you wanted to send the data through a form, you should do 2 things. First and most obvious, create the form; second, the data received from the internet (title and link of feed), send them to the server.

Assuming you fetch data from a single feed per url, and the designated file in charge of receiving the request will be "saveFeeds.php". So, you could create a form like the following after the previous one:

```<code><Form class = "sender" action = "saveFeeds.php" method = "post">
  <Input type = "hidden" name = "title" value = ""> <br>
  <Input type = "hidden" name = "link" value = ""> <br>
  <Input type = "submit">
</ Form>
</code>```

Then you need to put the feed data inside the form, because, at this moment, you can't send anything. You could add a function like:

```<code>Function appendFeedToForm (title, link) {
  Var form = $ (". Sender");
  Form.title.value = title;
  Form.link.value = value;
}
</code>```

And then call it from inside the $ .each of the result as
AppendFeedToForm(this.title, this.link);

The second case, the easiest way to make a request to the same file using Ajax is with a JQuery shortcut:

```<code>$.post("saveFeeds.php", r.item);
</code>```

If you are interested in validations, you can take a look at the JQuery documentation. The important thing about ajax requests is that you can send all the data you want without having to force you to reload the page. Therefore, you can send as many feeds as you want in the same way you would send one.

Now with the data sent from the client to the server, it is necessary to handle the reception of the data. Currently we were pointing all the data to the file "saveFeeds.php", so, now, finally we can put the content from javascript. To access them, simply in that file, you should check the fields:

```<code>$ _POST ['title']     // This names are from input names of form
$ _POST ['link']      // or properties sended through Ajax
</code>```

So, here, you have tp prepare the connection to your database and save those parameters. Currently you did not mention which database engine you are using, so, for this moment, I'll shorten the answer here.

Note: I was not giving you the best practices to solve your problem, but rather the minimum necessary.

Body:
  <meta charset="utf-8">

  <title>Test page for Query YQL</title>

  <link rel="stylesheet" href="http://hail2u.github.io/css/natural.css">

Test page for Query YQL

  <input type="button" name="bt1" value="click" onclick="pesquisa()">

  <form name="s2">
    <input type="text" name="s1">
  </form>

  ";

              $site = "";

              //echo $titulo;
              //echo  $site;

            ?>
          });
          ul.appendTo(t);
        });
      });
    };

  </script>

How can you save the this.title and the this.link values into 2 different variables an then call them into php so you can insert the data into a DB?

It's just a simple YQL query to search on rss feeds.

After doing the query, I want the results to be saved in a database, but I can't discover how to do that.

Body:
First of all, you have to understand that you are working on a Client-Server architecture.

This means:

Let's say that this file you are showing us is called "TestYQL.php" (because you did not say the name of it). This file is executed by php (server side), which reads line by line the contents of it, and generates another new file from the original. For educational purposes, let's say the generated file is called "GeneratedTestYQL.html". This file no longer has any php code inside, since it is directly html and js flat. It knows nothing about php. So there are no php functions, variables, nothing. This last file is the one that reaches the client, and the code is executed by a web browser like Chrome, Firefox, etc.

In your case, the file "TestYQL.php" all you have of php is what is inside the <? Php ....?> Tags. With php you creates 2 variables, each with a tag inside, but without any purpose since they are not used in any way. So, the generated "GeneratedTestYQL.html" file is the same as the original, but without the lines inside the <? Php ...?>.

This means that: The contents of the variables that you use in PHP can be sent to the browser, because with PHP you will generate the file that will be executed in the browser.

Now, when the file "GeneratedTestYQL.html" arrives, the browser starts to show all the contents of the file, it generates the form in which, when you click the button, executes the function pesquisa() and now starts javascript (JQuery) bringing data of the feeds, and for the first time, these variables "this.title" and "this.link" begin to exist in javascript.

Since there is no such thing as php here, you can NOT access those variables from php.

So, how to save that data in a DB?, well, the common way is to send all the data you want from the browser, to the server, then the server sees what to do with that data. To send data from the browser to the server, you do it by making GET or POST requests to a php file from the server (preferably another file, let's say it will be called "saveFeeds.php").

Data can be sent with a GET request, but it is semantically incorrect since GET means you want to fetch data from the server. So to send that data to the server, you will have to make a POST request from the browser, which is more appropriate.

There are now 2 simple ways to make a POST request. The first and most common of these is from a form in the browser, the other way is using Ajax.

How to do it from a form?

Currently in your code, you have already put a form (That is called "s2"), although currently the same is not necessary, but leave that now.
If you wanted to send the data through a form, you should do 2 things. First and most obvious, create the form; second, the data received from the internet (title and link of feed), send them to the server.

Assuming you fetch data from a single feed per url, and the designated file in charge of receiving the request will be "saveFeeds.php". So, you could create a form like the following after the previous one:

<Form class = "sender" action = "saveFeeds.php" method = "post">
  <Input type = "hidden" name = "title" value = ""> <br>
  <Input type = "hidden" name = "link" value = ""> <br>
  <Input type = "submit">
</ Form>

Then you need to put the feed data inside the form, because, at this moment, you can't send anything. You could add a function like:

Function appendFeedToForm (title, link) {
  Var form = $ (". Sender");
  Form.title.value = title;
  Form.link.value = value;
}

And then call it from inside the $ .each of the result as
AppendFeedToForm(this.title, this.link);

The second case, the easiest way to make a request to the same file using Ajax is with a JQuery shortcut:

$.post("saveFeeds.php", r.item);

If you are interested in validations, you can take a look at the JQuery documentation. The important thing about ajax requests is that you can send all the data you want without having to force you to reload the page. Therefore, you can send as many feeds as you want in the same way you would send one.

Now with the data sent from the client to the server, it is necessary to handle the reception of the data. Currently we were pointing all the data to the file "saveFeeds.php", so, now, finally we can put the content from javascript. To access them, simply in that file, you should check the fields:

$ _POST ['title']     // This names are from input names of form
$ _POST ['link']      // or properties sended through Ajax

So, here, you have tp prepare the connection to your database and save those parameters. Currently you did not mention which database engine you are using, so, for this moment, I'll shorten the answer here.

Note: I was not giving you the best practices to solve your problem, but rather the minimum necessary.


问:
Taking dot products of high dimensional numpy arrays
I am trying to take the dot product between three numpy arrays. However, I am struggling with wrapping my head around this.

The problem is as follows:

I have two (4,) shaped numpy arrays a and b respectively, as well as a numpy array with shape (4, 4, 3), c.

```<code>import numpy as np

a = np.array([0, 1, 2, 3])
b = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
          [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
          [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
          [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]])
c = np.array([4, 5, 6, 7])
</code>```

I want to compute the dot product in such a way that my result is a 3-tuple. That is, first dot a with b and then dotting with c, taking transposes if needed. In other words, I want to compute the dot product between a, b and c as if c was of shape (4, 4), but I want a 3-tuple as result.

I have tried:

Reshaping a and c, and then computing the dot product:

```<code>a = np.reshape(a, (4, 1))
c = np.reshape(c, (4, 1))

tmp = np.dot(a.T, b) # now has shape (1, 4, 3)
result = np.dot(tmp, c)
</code>```

Ideally, I should now have:

```<code>print(result.shape)
>> (1, 1, 3)
</code>```

but I get the error

ValueError: shapes (1,4,3) and (4,1) not aligned: 3 (dim 2) != 4 (dim 0)

I have also tried using the tensordot function from numpy, but without luck.

答:
You are multiplying (1,4,3) matrix by (4,1) matrix so it is impossible because you have 3 pages of (1,4) matrices in b. If you want to do multiplication of each page of matrix b by c just multiply each page separately.

```<code>a = np.array([0, 1, 2, 3])
b = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
      [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
      [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
      [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]])
c = np.array([4, 5, 6, 7])

a = np.reshape(a, (4, 1))
c = np.reshape(c, (4, 1))

tmp = np.dot(a.T, b) # now has shape (1, 4, 3)
result = np.dot(tmp[:,:,0], c)
for i in range(1,3):
    result = np.dstack((result, np.dot(tmp[:,:,i], c)))
print np.shape(result)
</code>```

So you have result of size (1,1,3)

Body:
I am trying to take the dot product between three numpy arrays. However, I am struggling with wrapping my head around this.

The problem is as follows:

I have two (4,) shaped numpy arrays a and b respectively, as well as a numpy array with shape (4, 4, 3), c.

import numpy as np

a = np.array([0, 1, 2, 3])
b = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
          [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
          [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
          [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]])
c = np.array([4, 5, 6, 7])

I want to compute the dot product in such a way that my result is a 3-tuple. That is, first dot a with b and then dotting with c, taking transposes if needed. In other words, I want to compute the dot product between a, b and c as if c was of shape (4, 4), but I want a 3-tuple as result.

I have tried:

Reshaping a and c, and then computing the dot product:

a = np.reshape(a, (4, 1))
c = np.reshape(c, (4, 1))

tmp = np.dot(a.T, b) # now has shape (1, 4, 3)
result = np.dot(tmp, c)

Ideally, I should now have:

print(result.shape)
>> (1, 1, 3)

but I get the error

ValueError: shapes (1,4,3) and (4,1) not aligned: 3 (dim 2) != 4 (dim 0)

I have also tried using the tensordot function from numpy, but without luck.

Body:
You are multiplying (1,4,3) matrix by (4,1) matrix so it is impossible because you have 3 pages of (1,4) matrices in b. If you want to do multiplication of each page of matrix b by c just multiply each page separately.

a = np.array([0, 1, 2, 3])
b = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
      [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
      [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
      [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]])
c = np.array([4, 5, 6, 7])

a = np.reshape(a, (4, 1))
c = np.reshape(c, (4, 1))

tmp = np.dot(a.T, b) # now has shape (1, 4, 3)
result = np.dot(tmp[:,:,0], c)
for i in range(1,3):
    result = np.dstack((result, np.dot(tmp[:,:,i], c)))
print np.shape(result)

So you have result of size (1,1,3)


问:
RecyclerView uses old ViewHolder when data fully changed
I have a recyclerview that shows "no content" layout before data has been loaded.
After I receive data I do:

```<code>    mItems.addAll(newItems);
    notifyDataSetChanged();
</code>```

After that everything is fine, except the last element is still "no content" layout. I have checked the behaviour and I know that RecyclerView uses the old layout. The problem is that that I need to use a different layout. And furthermore, why the old layout at last position and not at first as originally it has been?
How do I force RecyclerView to re-create that ViewHolder?

答: So, after some more reading today I found out that the way to fix this problem is to create another type for view "no content view" in  getViewType. So it works like this: first time onCreateViewHolder creates viewHolder for empty content. Next time when data is loaded getViewType returns different view type and onCreateViewHolder creates different view holder.

Body:
I have a recyclerview that shows "no content" layout before data has been loaded.
After I receive data I do:

    mItems.addAll(newItems);
    notifyDataSetChanged();

After that everything is fine, except the last element is still "no content" layout. I have checked the behaviour and I know that RecyclerView uses the old layout. The problem is that that I need to use a different layout. And furthermore, why the old layout at last position and not at first as originally it has been?
How do I force RecyclerView to re-create that ViewHolder?


问:
GL_QUADS draws a concave pentagon instead of recangle
I'm using this code to generate the rectangle

```<code>glBegin(GL_QUADS);
glColor3f(0,0,0);
glVertex2f(-0.9,-0.9);
glVertex2f(-0.9,+0.9);
glVertex2f(+0.9,-0.9);
glVertex2f(+0.9,+0.9);
glEnd();
</code>```

Draws this

My window is setup with this code:

```<code>glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(600,600);
glutInitWindowPosition(0,0);
glutCreateWindow("Atari Breakout!");
glClearColor(0,1,0,1);
glOrtho(-1.0f, +1.0f, -1.0f,+1.0f,1,1);
glutDisplayFunc(display);
glutIdleFunc(display);

glutMainLoop();
</code>```

答: The order of your vertices are like the letter N which flips the winding around mid primitive. You have to submit the vertices in a consistent winding order.

Body:
I'm using this code to generate the rectangle

glBegin(GL_QUADS);
glColor3f(0,0,0);
glVertex2f(-0.9,-0.9);
glVertex2f(-0.9,+0.9);
glVertex2f(+0.9,-0.9);
glVertex2f(+0.9,+0.9);
glEnd();

Draws this

My window is setup with this code:

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(600,600);
glutInitWindowPosition(0,0);
glutCreateWindow("Atari Breakout!");
glClearColor(0,1,0,1);
glOrtho(-1.0f, +1.0f, -1.0f,+1.0f,1,1);
glutDisplayFunc(display);
glutIdleFunc(display);

glutMainLoop();


问:
How to get flat clustering corresponding to color clusters in the dendrogram created by scipy
Using the code posted here, I created a nice hierarchical clustering:

Let's say the the dendrogram on the left was created by doing something like

```<code>Y = sch.linkage(D, method='average') # D is a distance matrix
cutoff = 0.5*max(Y[:,2])
Z = sch.dendrogram(Y, orientation='right', color_threshold=cutoff)
</code>```

Now how do I get the indices of the members of each of the colored clusters?  To simplify this situation, ignore the clustering on the top, and focus only on the dendrogram on the left of the matrix.

This information should be stored in the dendrogram Z stored variable.  There is a function that should do just what I want called fcluster (see documentation here). However I cannot see where I can give fcluster the same cutoff as I specified in the creation of the dendrogram.  It seems that the threshold variable in fcluster, t has to be in terms of various obscure measurements (inconsistent, distance, maxclust, monocrit).  Any ideas?

答:
I wrote some code to decondense the linkage matrix. It returns a dictionary containing the indexes of labels that are grouped by each agglomeration step. I've only tried it out on the results of the complete linkage clusters. The keys of the dict start at len(labels)+1 because initially, each label is treated as its own cluster. This may answer your question.

```<code>import pandas as pd
import numpy as np
from scipy.cluster.hierarchy import linkage

np.random.seed(123)
labels = ['ID_0','ID_1','ID_2','ID_3','ID_4']

X = np.corrcoef(np.random.random_sample([5,3])*10)
row_clusters = linkage(x_corr, method='complete')

def extract_levels(row_clusters, labels):
    clusters = {}
    for row in xrange(row_clusters.shape[0]):
        cluster_n = row + len(labels)
        # which clusters / labels are present in this row
        glob1, glob2 = row_clusters[row, 0], row_clusters[row, 1]

        # if this is a cluster, pull the cluster
        this_clust = []
        for glob in [glob1, glob2]:
            if glob > (len(labels)-1):
                this_clust += clusters[glob]
            # if it isn't, add the label to this cluster
            else:
                this_clust.append(glob)

        clusters[cluster_n] = this_clust
    return clusters
</code>```

Returns:

```<code>{5: [0.0, 2.0],
 6: [3.0, 4.0],
 7: [1.0, 0.0, 2.0],
 8: [3.0, 4.0, 1.0, 0.0, 2.0]}
</code>```

Body:
Using the code posted here, I created a nice hierarchical clustering:

Let's say the the dendrogram on the left was created by doing something like

Y = sch.linkage(D, method='average') # D is a distance matrix
cutoff = 0.5*max(Y[:,2])
Z = sch.dendrogram(Y, orientation='right', color_threshold=cutoff)

Now how do I get the indices of the members of each of the colored clusters?  To simplify this situation, ignore the clustering on the top, and focus only on the dendrogram on the left of the matrix.

This information should be stored in the dendrogram Z stored variable.  There is a function that should do just what I want called fcluster (see documentation here). However I cannot see where I can give fcluster the same cutoff as I specified in the creation of the dendrogram.  It seems that the threshold variable in fcluster, t has to be in terms of various obscure measurements (inconsistent, distance, maxclust, monocrit).  Any ideas?

Body:
I wrote some code to decondense the linkage matrix. It returns a dictionary containing the indexes of labels that are grouped by each agglomeration step. I've only tried it out on the results of the complete linkage clusters. The keys of the dict start at len(labels)+1 because initially, each label is treated as its own cluster. This may answer your question.

import pandas as pd
import numpy as np
from scipy.cluster.hierarchy import linkage

np.random.seed(123)
labels = ['ID_0','ID_1','ID_2','ID_3','ID_4']

X = np.corrcoef(np.random.random_sample([5,3])*10)
row_clusters = linkage(x_corr, method='complete')

def extract_levels(row_clusters, labels):
    clusters = {}
    for row in xrange(row_clusters.shape[0]):
        cluster_n = row + len(labels)
        # which clusters / labels are present in this row
        glob1, glob2 = row_clusters[row, 0], row_clusters[row, 1]

        # if this is a cluster, pull the cluster
        this_clust = []
        for glob in [glob1, glob2]:
            if glob > (len(labels)-1):
                this_clust += clusters[glob]
            # if it isn't, add the label to this cluster
            else:
                this_clust.append(glob)

        clusters[cluster_n] = this_clust
    return clusters

Returns:

{5: [0.0, 2.0],
 6: [3.0, 4.0],
 7: [1.0, 0.0, 2.0],
 8: [3.0, 4.0, 1.0, 0.0, 2.0]}


问:
How to create a this HTML layout, by CSS?
I am newbie with CSS; so, I do not want to use CSS frameworks.

After reading some questions about fixed header and footer with CSS (on StackOverflow), I tried to create a HTML layout, as this:

In this layout, both header and menu are fixed.

I have created an HTML file with 2 column: left for menu, right for content. But, it comes with an scrolled-menu:

#menu {
  width: 33%;
  height: 100%;
  float: left;
}

#page {
  width: 66%;
  height: 100%;
  float: left;
}

#header {
  width: 100%;
  height: 100px;
  position: fixed;
}

#content {
  width: 100%;
  position: absolute;
  top: 100px;
}

#footer {
  width: 100%;
  height: 100px;
  position: fixed;
  bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="menu">
  MENU
</div>
<div id="page">
  <div id="header">Header</div>
  <div id="content">
    <p>Some content...</p>
  </div>
  <div id="footer">Footer</div>
</div></code>```

When I add this line: position: fixed; in #menu, the layout will be broken. Could help help me to fix it?

答:
Currently you could use the Tag directly as    you need to establish position : block. I would like to recommend that you uses a Framework like Bootstrap, today is commonly uses for design webpages, if you are new un webpages it Will be useful for you

http://getbootstrap.com/

Body:
I am newbie with CSS; so, I do not want to use CSS frameworks.

After reading some questions about fixed header and footer with CSS (on StackOverflow), I tried to create a HTML layout, as this:

In this layout, both header and menu are fixed.

I have created an HTML file with 2 column: left for menu, right for content. But, it comes with an scrolled-menu:

#menu {
  width: 33%;
  height: 100%;
  float: left;
}

#page {
  width: 66%;
  height: 100%;
  float: left;
}

#header {
  width: 100%;
  height: 100px;
  position: fixed;
}

#content {
  width: 100%;
  position: absolute;
  top: 100px;
}

#footer {
  width: 100%;
  height: 100px;
  position: fixed;
  bottom: 0;
}

  MENU

Header

Some content...

Footer

When I add this line: position: fixed; in #menu, the layout will be broken. Could help help me to fix it?

Body:
Currently you could use the Tag directly as <header> <body> <footer> you need to establish position : block. I would like to recommend that you uses a Framework like Bootstrap, today is commonly uses for design webpages, if you are new un webpages it Will be useful for you

http://getbootstrap.com/