问:
Pasting user input based on current region
I am working on set of weekly data. Every week, I will add a new set of data to the worksheet. Then, I want to prompt user for input and paste it at the specific column within the current region range. For now, my script will prompt user for input, then finding the last row of the last set of data in the worksheet. Then, i use the current region to activate the first row of the set data. Since the data will be in col E to col O, I want the inputs entered by user to be on col A to col D.

However, when i run my script, it will not paste the user inputs from the first row of the set data and also did not stop on the last row of the set data. Based on the example, I am expecting the output to start from row 388 and last at row 406. The result that i get from my script will paste on row 404 till 811.

For now I just try on one worksheet named "setup" but then i need to modify my script for 20 worksheets with different names.

This is my script:

```<code>Option Explicit
Public week, datedone, data, location As Variant

Sub pqr()

week = InputBox("Week:")
datedone = InputBox("Date:")
data = InputBox("Data:")
location = InputBox("Location:")

Dim ws As Worksheet
Dim x As Workbook
Dim LastRow As Long
Dim FirstRow As Long

Set x = ThisWorkbook

For Each ws In x.Worksheets
    If ws.Name = "setup" Then
    LastRow = Cells(Rows.Count, "E").End(xlUp).Row
    ws.Range("E" & LastRow).Activate
    FirstRow = ActiveCell.CurrentRegion.Cells(1, 1).Activate

With ws.Range("A" & LastRow).CurrentRegion
    ws.Range(.Cells(FirstRow, 1), .Cells(LastRow, 1)).Value = week
    ws.Range(.Cells(FirstRow, 2), .Cells(LastRow, 2)).Value = datedone
    ws.Range(.Cells(FirstRow, 3), .Cells(LastRow, 3)).Value = data
    ws.Range(.Cells(FirstRow, 4), .Cells(LastRow, 4)).Value = location
End With

End If

Next

End Sub
</code>```

This is how the data looks like for the previous week (Week12) complete with user input data and current week (Week13) without user input data

This is the result that i get from the script

This is what i expected to get for the result

答:
You may try something like this...

```<code>Dim Rng As Range
Set Rng = ws.Range("E:E").SpecialCells(xlCellTypeConstants, 2)
Set Rng = Rng.Areas(Rng.Areas.Count).Cells(1)

FirstRow = Rng.Row
If ws.Cells(FirstRow, 1) = "" Then
    LastRow = FirstRow
Else
    LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row + 1
End If
ws.Cells(LastRow, 1) = week
ws.Cells(LastRow, 2) = datedone
ws.Cells(LastRow, 3) = Data
ws.Cells(LastRow, 4) = Location
</code>```

The complete code should look like this...

```<code>Public week, datedone, data, location As Variant

Sub pqr()
Dim ws As Worksheet
Dim x As Workbook
Dim LastRow As Long
Dim FirstRow As Long
Dim Rng As Range

week = InputBox("Week:")
datedone = InputBox("Date:")
data = InputBox("Data:")
location = InputBox("Location:")

Set x = ThisWorkbook
Set ws = Sheets("setup")

On Error Resume Next
Set Rng = ws.Range("E:E").SpecialCells(xlCellTypeConstants, 2)
On Error GoTo 0
If Not Rng Is Nothing Then
    Set Rng = Rng.Areas(Rng.Areas.Count).Cells(1)
    FirstRow = Rng.Row
    If ws.Cells(FirstRow, 1) = "" Then
        LastRow = FirstRow
    Else
        LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row + 1
    End If
    ws.Cells(LastRow, 1) = week
    ws.Cells(LastRow, 2) = datedone
    ws.Cells(LastRow, 3) = data
    ws.Cells(LastRow, 4) = location
End If
End Sub
</code>```

EDIT2:

```<code>Public week, datedone, data, location As Variant

Sub pqr()
Dim ws As Worksheet
Dim x As Workbook
Dim FirstRow As Long, LastRow As Long, n As Long

Dim Rng As Range

week = InputBox("Week:")
datedone = InputBox("Date:")
data = InputBox("Data:")
location = InputBox("Location:")

Set x = ThisWorkbook
Set ws = Sheets("setup")

On Error Resume Next
Set Rng = ws.Range("E:E").SpecialCells(xlCellTypeConstants, 2)
n = Rng.Areas(Rng.Areas.Count).Rows.Count
On Error GoTo 0
If Not Rng Is Nothing Then
    Set Rng = Rng.Areas(Rng.Areas.Count).Cells(1)
    FirstRow = Rng.Row
    LastRow = FirstRow + n - 1
    ws.Range(ws.Cells(FirstRow, 1), ws.Cells(LastRow, 1)) = week
    ws.Range(ws.Cells(FirstRow, 2), ws.Cells(LastRow, 2)) = datedone
    ws.Range(ws.Cells(FirstRow, 3), ws.Cells(LastRow, 3)) = data
    ws.Range(ws.Cells(FirstRow, 4), ws.Cells(LastRow, 4)) = location
End If
End Sub
</code>```

Body:
I am working on set of weekly data. Every week, I will add a new set of data to the worksheet. Then, I want to prompt user for input and paste it at the specific column within the current region range. For now, my script will prompt user for input, then finding the last row of the last set of data in the worksheet. Then, i use the current region to activate the first row of the set data. Since the data will be in col E to col O, I want the inputs entered by user to be on col A to col D.

However, when i run my script, it will not paste the user inputs from the first row of the set data and also did not stop on the last row of the set data. Based on the example, I am expecting the output to start from row 388 and last at row 406. The result that i get from my script will paste on row 404 till 811.

For now I just try on one worksheet named "setup" but then i need to modify my script for 20 worksheets with different names.

This is my script:

Option Explicit
Public week, datedone, data, location As Variant

Sub pqr()

week = InputBox("Week:")
datedone = InputBox("Date:")
data = InputBox("Data:")
location = InputBox("Location:")

Dim ws As Worksheet
Dim x As Workbook
Dim LastRow As Long
Dim FirstRow As Long

Set x = ThisWorkbook

For Each ws In x.Worksheets
    If ws.Name = "setup" Then
    LastRow = Cells(Rows.Count, "E").End(xlUp).Row
    ws.Range("E" & LastRow).Activate
    FirstRow = ActiveCell.CurrentRegion.Cells(1, 1).Activate

With ws.Range("A" & LastRow).CurrentRegion
    ws.Range(.Cells(FirstRow, 1), .Cells(LastRow, 1)).Value = week
    ws.Range(.Cells(FirstRow, 2), .Cells(LastRow, 2)).Value = datedone
    ws.Range(.Cells(FirstRow, 3), .Cells(LastRow, 3)).Value = data
    ws.Range(.Cells(FirstRow, 4), .Cells(LastRow, 4)).Value = location
End With

End If

Next

End Sub

This is how the data looks like for the previous week (Week12) complete with user input data and current week (Week13) without user input data

This is the result that i get from the script

This is what i expected to get for the result

Body:
You may try something like this...

Dim Rng As Range
Set Rng = ws.Range("E:E").SpecialCells(xlCellTypeConstants, 2)
Set Rng = Rng.Areas(Rng.Areas.Count).Cells(1)

FirstRow = Rng.Row
If ws.Cells(FirstRow, 1) = "" Then
    LastRow = FirstRow
Else
    LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row + 1
End If
ws.Cells(LastRow, 1) = week
ws.Cells(LastRow, 2) = datedone
ws.Cells(LastRow, 3) = Data
ws.Cells(LastRow, 4) = Location

The complete code should look like this...

Public week, datedone, data, location As Variant

Sub pqr()
Dim ws As Worksheet
Dim x As Workbook
Dim LastRow As Long
Dim FirstRow As Long
Dim Rng As Range

week = InputBox("Week:")
datedone = InputBox("Date:")
data = InputBox("Data:")
location = InputBox("Location:")

Set x = ThisWorkbook
Set ws = Sheets("setup")

On Error Resume Next
Set Rng = ws.Range("E:E").SpecialCells(xlCellTypeConstants, 2)
On Error GoTo 0
If Not Rng Is Nothing Then
    Set Rng = Rng.Areas(Rng.Areas.Count).Cells(1)
    FirstRow = Rng.Row
    If ws.Cells(FirstRow, 1) = "" Then
        LastRow = FirstRow
    Else
        LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row + 1
    End If
    ws.Cells(LastRow, 1) = week
    ws.Cells(LastRow, 2) = datedone
    ws.Cells(LastRow, 3) = data
    ws.Cells(LastRow, 4) = location
End If
End Sub

EDIT2:

Public week, datedone, data, location As Variant

Sub pqr()
Dim ws As Worksheet
Dim x As Workbook
Dim FirstRow As Long, LastRow As Long, n As Long

Dim Rng As Range

week = InputBox("Week:")
datedone = InputBox("Date:")
data = InputBox("Data:")
location = InputBox("Location:")

Set x = ThisWorkbook
Set ws = Sheets("setup")

On Error Resume Next
Set Rng = ws.Range("E:E").SpecialCells(xlCellTypeConstants, 2)
n = Rng.Areas(Rng.Areas.Count).Rows.Count
On Error GoTo 0
If Not Rng Is Nothing Then
    Set Rng = Rng.Areas(Rng.Areas.Count).Cells(1)
    FirstRow = Rng.Row
    LastRow = FirstRow + n - 1
    ws.Range(ws.Cells(FirstRow, 1), ws.Cells(LastRow, 1)) = week
    ws.Range(ws.Cells(FirstRow, 2), ws.Cells(LastRow, 2)) = datedone
    ws.Range(ws.Cells(FirstRow, 3), ws.Cells(LastRow, 3)) = data
    ws.Range(ws.Cells(FirstRow, 4), ws.Cells(LastRow, 4)) = location
End If
End Sub


来源: stackexchange

问:
Google similar image search API
I'm trying to find out if there is a way to do google similar image searches via an API?

I know the image search api is depreciated but is it still useable?
https://developers.google.com/image-search/

Also... It seems that you can do image searches with the custom search api but I can't seem to work out if a similar image search is possible.
http://thenextweb.com/dd/2012/02/14/googles-custom-search-api-now-supports-image-only-results/

Any leads on advice on working this our would be appreciated.

Thanks!

答:
That is deprecated.
But I need JSON format of similar images result.
So, I try to use google cse but this is not supported searching of similar images.
It's just displayed image search results in a custom domain.

Another method that i try is URL.

http://images.google.com/searchbyimage?image_url=YOUR_HOSTED_URL

But this is not solution what i need.
It is because able to use in the browser. I need JSON.

Conclude, I decide to use Vision API of Google.
This is very simple.

https://cloud.google.com/vision/

You can try on the top.

First, access the URL.

Second, upload your image file on the "Try API".

Third, click "JSON" tab menu on the result.

You can be seen JSON about similar images.

ContentLicense: CC BY-SA 3.0

Title: Google similar image search API

ContentLicense: CC BY-SA 4.0


问:
Formatting elements of a list into a specific string
I'm trying to take a list of terms and output them in a specific format.

For example, I have a list of verbs:

```<code>verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
</code>```

and I want my output to be a string, where each item in the list is also a string, delineated by a |

```<code>magic(verbs)
</code>```

output:

```<code>"eat" | "run" | "jump" | etc.
</code>```

I've tried using the .join method, but that just gives me one big string of the terms separated by pipes, instead of what I want. Any ideas? I'm pretty new to Python and I'm sorry if this is incredibly low-brow or something that has been answered elsewhere.

答:
Try with:

```<code>verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
print("|".join(['"'+e+'"' for e in verbs]))
</code>```

Output:

```<code>"eat"|"run"|"jump"|"play"|"walk"|"talk"|"send"
</code>```

Body:
I'm trying to take a list of terms and output them in a specific format.

For example, I have a list of verbs:

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']

and I want my output to be a string, where each item in the list is also a string, delineated by a |

magic(verbs)

output:

"eat" | "run" | "jump" | etc.

I've tried using the .join method, but that just gives me one big string of the terms separated by pipes, instead of what I want. Any ideas? I'm pretty new to Python and I'm sorry if this is incredibly low-brow or something that has been answered elsewhere.

Body:
Try with:

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
print("|".join(['"'+e+'"' for e in verbs]))

Output:

"eat"|"run"|"jump"|"play"|"walk"|"talk"|"send"


问:
Interop issue in .NET
I have a 32 bit managed assembly that access a 32 bit COM component. When i compile the assembly using the 64 bit flag, i get an error when i try to access the 32 bit COM component from it.

Is there a way around this problem?

答:
You can either try to use corflags (may/may not work), or set your app to compile in 32bit only.

```<code>corflags <assemblyname> /32bit-
</code>```

that removes the 32bit restriction on .Net assemblies.

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5

Title: Interop issue in .NET

Body:
You can either try to use corflags (may/may not work), or set your app to compile in 32bit only.

corflags <assemblyname> /32bit-

that removes the 32bit restriction on .Net assemblies.

OwnerDisplayName: Tom Anderson


问:
vim scrolls wrong window
I am using vim 7.4 under Ubuntu Linux.
When I split window by using ":sp hello.c",
if I click the upper window, then the mouse wheel scrolls the upper window.
But if I click the lower window, then depending on which part of the lower window I click, it scrolls either the upper window or the lower window.
Specifically, if I click inside the upper half of the lower window, it scrolls the upper window; if I click inside the lower half of the lower window, it scrolls the lower window.
How can I make it work correctly?
Thanks.</p>

答:
Here is my setting:</p>

```<code>  ambiwidth=double    helplang=ko       nomodeline            ruler               syntax=php          ttymouse=xterm2
  filetype=php        history=50          mouse=a             scroll=25           ttyfast
  backspace=indent,eol,start
  fileencoding=utf-8
  fileencodings=ucs-bom,utf-8,default,latin1
  printoptions=paper:a4
  runtimepath=~/.vim,/var/lib/vim/addons,/usr/share/vim/vimfiles,/usr/share/vim/vim74,/usr/share/vim/vimfiles/after,/var/lib/vi
m/addons/after,~/.vim/after
  suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc
</code>```

Title: vim scrolls wrong window

Body:
Here is my setting:

  ambiwidth=double    helplang=ko       nomodeline            ruler               syntax=php          ttymouse=xterm2
  filetype=php        history=50          mouse=a             scroll=25           ttyfast
  backspace=indent,eol,start
  fileencoding=utf-8
  fileencodings=ucs-bom,utf-8,default,latin1
  printoptions=paper:a4
  runtimepath=~/.vim,/var/lib/vim/addons,/usr/share/vim/vimfiles,/usr/share/vim/vim74,/usr/share/vim/vimfiles/after,/var/lib/vi
m/addons/after,~/.vim/after
  suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc


问:
Unicode characters in Listview c#
Here is the thing:
I need to display japanese character in listview in a SQL operated database manager I am currently building for a friendly company. Tried to google, but all answers led me to nothing really. Instead of displaying characters it just does "????". Have a look:

but I am loading a properly displayed .csv file from a machine that has a japanese installed on it. Also its been saved as utf8:

Font I am using is Meiryo UI. Tried Tahoma and the same thing is happening. Loading is being done including encoding:

3

And finally here's the code responsible for stuffing the data into a listview:

4

I would really appreciate if someone could help me. Thanks!

答:
I managed to solve this thing. While using SQL Server 2014 I simply forgot to change the collation encoding in database settings. It was set on Latin instead of Japanese-Unicode BIN. Thanks to Ben for pointing me right direction.

Fixed

Title: Unicode characters in Listview c#


答:
```<code>verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
x=(' | '.join('"' + item + '"' for item in verbs))
print(x)
</code>```

you can see ouput here

Title: Formatting elements of a list into a specific string

Body:
verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
x=(' | '.join('"' + item + '"' for item in verbs))
print(x)

you can see ouput here


问:
Javascript binding function to an object
```<code>const person = {
    name: "Mike",
    country: "New Zealand"
}

function personUpdate(name, country) {
    this.name = name
    this.country = country
}

personUpdate.bind(person)

personUpdate('Tony', 'Chile')
</code>```

Why doesn't this work? person still has original properties 'Mike' and 'New Zealand'. Why doesn't personUpdate.bind(person) I want to make it so that every call to personUpdate the this refers to the person object (and without using new).

答:
I have tried your code and I think nothing is wrong with it.

```<code>const person = {
name: "Mike",
country: "New Zealand"
}
function personUpdate(name, country) {
this.name = name;
this.country = country;

console.log(this.name);
console.log(this.country);
}
personUpdate.bind(person);
personUpdate('Tony', 'Chile');
</code>```

I tried to print it and it is giving me "Tony" and "Chile", or I misunderstood your question?

Body:
const person = {
    name: "Mike",
    country: "New Zealand"
}

function personUpdate(name, country) {
    this.name = name
    this.country = country
}

personUpdate.bind(person)

personUpdate('Tony', 'Chile')

Why doesn't this work? person still has original properties 'Mike' and 'New Zealand'. Why doesn't personUpdate.bind(person) I want to make it so that every call to personUpdate the this refers to the person object (and without using new).

Body:
I have tried your code and I think nothing is wrong with it.

const person = {
name: "Mike",
country: "New Zealand"
}
function personUpdate(name, country) {
this.name = name;
this.country = country;

console.log(this.name);
console.log(this.country);
}
personUpdate.bind(person);
personUpdate('Tony', 'Chile');

I tried to print it and it is giving me "Tony" and "Chile", or I misunderstood your question?


答:
This does what you want:</p>

```<code>def magic(terms):
    print(' | '.join('"%s"' % term for term in terms))

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
magic(verbs)  # -> "eat" | "run" | "jump" | "play" | "walk" | "talk" | "send"
</code>```

Body:
This does what you want:

def magic(terms):
    print(' | '.join('"%s"' % term for term in terms))

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
magic(verbs)  # -> "eat" | "run" | "jump" | "play" | "walk" | "talk" | "send"


问:
How to use "SELECT IN" in EF5
I sent this rare query, I really have difficulty being able to pass it to ef, can you please give me a hand with it?

Thank you very much in advance

```<code>SELECT
    c.*
FROM
    Company c
    JOIN [User] u ON c.id = u.id_company
WHERE
    (
        ( u.id_usertype = 3 )
        AND
        ( u.id = 2135 )
    )

UNION

SELECT
    c.*
FROM
    Company c
    JOIN Company mc ON c.id_company = mc.id
WHERE
    mc.id in
    (
        SELECT
            c.id
        FROM
            Company c
            JOIN [User] u ON c.id = u.id_company
        WHERE
        (
            ( u.id_usertype = 3 )
            AND
            ( u.id = 2135 )
        )
    )
</code>```

答:
Now that you've explained the Subcompany/Company relationship I see that the query can be changed to the query below:

```<code>SELECT
    Company.*
FROM
    [User]
    INNER JOIN Company ON [User].id_company = Company.id
WHERE
    [User].id = 2135

UNION

SELECT
    SubCompany .*
FROM
    [User]
    INNER JOIN Company ON [User].id_company = Company.id
    INNER JOIN Company AS SubCompany ON Company.id = SubCompany.id_company
WHERE
    [User].id = 2135
</code>```

This UNION-based query can be simplified into the single query below by changing the INNER JOIN Company As SubCompany so it uses an OR so it matches both the original company and the sub-companies.

```<code>SELECT
    SubCompany.*
FROM
    [User]
    INNER JOIN Company ON [User].id_company = Company.id
    LEFT OUTER JOIN Company AS SubCompany ON
    (
        Company.id = SubCompany.id_company
        OR
        Company.id = SubCompany.id
    )
WHERE
    [User].id = 2135
</code>```

However, in Linq you cannot use complex JOIN criteria if you're using Navigation Properties (you can if you use Linq's GroupBy or Join operations), so we must fall-back to a UNION via the Concat operation:

I assume you have a Company->SubCompany relationship defined in Entity Framework, in which case you can use SelectMany:

```<code>var query = dbContext
    .Users
    .Where( u => u.id == 2135 )
    .Select( u => u.Company )
    .Concat(
        dbContext
            .Users
            .Where( u => u.id == 2135 )
            .SelectMany( u => u.Company.SubCompanies )
    );
</code>```

Title: How to use "SELECT IN" in EF5

Body:
I sent this rare query, I really have difficulty being able to pass it to ef, can you please give me a hand with it?

Thank you very much in advance

SELECT
    c.*
FROM
    Company c
    JOIN [User] u ON c.id = u.id_company
WHERE
    (
        ( u.id_usertype = 3 )
        AND
        ( u.id = 2135 )
    )

UNION

SELECT
    c.*
FROM
    Company c
    JOIN Company mc ON c.id_company = mc.id
WHERE
    mc.id in
    (
        SELECT
            c.id
        FROM
            Company c
            JOIN [User] u ON c.id = u.id_company
        WHERE
        (
            ( u.id_usertype = 3 )
            AND
            ( u.id = 2135 )
        )
    )

Body:
Now that you've explained the Subcompany/Company relationship I see that the query can be changed to the query below:

SELECT
    Company.*
FROM
    [User]
    INNER JOIN Company ON [User].id_company = Company.id
WHERE
    [User].id = 2135

UNION

SELECT
    SubCompany .*
FROM
    [User]
    INNER JOIN Company ON [User].id_company = Company.id
    INNER JOIN Company AS SubCompany ON Company.id = SubCompany.id_company
WHERE
    [User].id = 2135

This UNION-based query can be simplified into the single query below by changing the INNER JOIN Company As SubCompany so it uses an OR so it matches both the original company and the sub-companies.

SELECT
    SubCompany.*
FROM
    [User]
    INNER JOIN Company ON [User].id_company = Company.id
    LEFT OUTER JOIN Company AS SubCompany ON
    (
        Company.id = SubCompany.id_company
        OR
        Company.id = SubCompany.id
    )
WHERE
    [User].id = 2135

However, in Linq you cannot use complex JOIN criteria if you're using Navigation Properties (you can if you use Linq's GroupBy or Join operations), so we must fall-back to a UNION via the Concat operation:

I assume you have a Company->SubCompany relationship defined in Entity Framework, in which case you can use SelectMany:

var query = dbContext
    .Users
    .Where( u => u.id == 2135 )
    .Select( u => u.Company )
    .Concat(
        dbContext
            .Users
            .Where( u => u.id == 2135 )
            .SelectMany( u => u.Company.SubCompanies )
    );


问:
Chain map with object on Spark
I'm creating an object for each line read of a file inside a map.

On a chained map, I try to access a variable from that object, but I receive an empty variable.
I'm using Spark Streamer

```<code>//..
val lines = ssc.textFileStream("CSVs/")
lines.map(line => new UserData(line))
     .map(userData => userData.myVar)
.print()
</code>```

And my UserData Class

```<code>class UserData(csvLine: String) extends Serializable{
  {
     myVar = csvLine
  }
  var myVar = ""
}
</code>```

答:
You can use a case class

```<code>case class UserData(csvLine: String)
</code>```

I'm not sure why you have userData.myVar in your code, it should probably be like this:

```<code>val lines = ssc.textFileStream("CSVs/")
lines.map(line => UserData(line))
  .map(userData => userData.csvLine)
  .print()

ssc.start()
ssc.awaitTermination()
</code>```

In addition, textFileStream only monitor a folder when the files are being added or updated. If you just want to read the files you can use spark.read or sparkContext.textFile.

Title: Chain map with object on Spark

Body:
I'm creating an object for each line read of a file inside a map.

On a chained map, I try to access a variable from that object, but I receive an empty variable.
I'm using Spark Streamer

//..
val lines = ssc.textFileStream("CSVs/")
lines.map(line => new UserData(line))
     .map(userData => userData.myVar)
.print()

And my UserData Class

class UserData(csvLine: String) extends Serializable{
  {
     myVar = csvLine
  }
  var myVar = ""
}

Body:
You can use a case class

case class UserData(csvLine: String)

I'm not sure why you have userData.myVar in your code, it should probably be like this:

val lines = ssc.textFileStream("CSVs/")
lines.map(line => UserData(line))
  .map(userData => userData.csvLine)
  .print()

ssc.start()
ssc.awaitTermination()

In addition, textFileStream only monitor a folder when the files are being added or updated. If you just want to read the files you can use spark.read or sparkContext.textFile.


答:
```<code>verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']

def magic(s):
    return ' | '.join('"%s"' % x for x in s)

print(magic(verbs))
# "eat" | "run" | "jump" | "play" | "walk" | "talk" | "send"
</code>```


问:
Set up CMakeLists to not change the include statements from TFS project in Android Studio
From a previous question a new one have arisen. I want to include 2 native TFS project libraries stored in two different folders, dependant from each other in my Android Studio project (stored in another folder). If i not specify "../my_lib_path/libFile.h" instead of simply the "libFile.h" i get the error the file is not found. But i dont want to change all includes since it is a TFS project and there are lots of file contained in the libraries!

Your help is highly appreciated!

答: Add the given directories to those the compiler uses to search for include files. Relative paths are interpreted as relative to the current source directory. So you have to specify "../my_lib_path/libFile.h", that means you need to change all includes, otherwise it will not work.</p>


问:
How to get the data from MVC view to controller
I'm working on a simple project. Following is the code. The thing is I'm unable to get all the information from the view to the controller. So I already have book ID, Name and price (which is coming from separate Productcontroller) in the Homecontroller and I'm able to view it as well and I want to post the quantity of books when I make a post request. So, when I try to make a post request and debug it, I can only see the quantity and I see null for book ID, Name and price.

I’m not sure what is going wrong. Any help would be really appreciated.
Thank You!

1.Product.cs

```<code>public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public decimal ProductPrice { get; set; }
        public int Quantity { get; set; }
    }
</code>```

2.Cart.cshtml

```<code>@model DAL.Models.Product
@{
    ViewBag.Title = "Purchase";
}

@ViewBag.bookName
<h2>Purchase</h2>

<div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6">
        @using (Html.BeginForm("Cart", "Home", FormMethod.Post))
        {
            <div class="panel panel-primary">

                <div class="panel-heading">Purchase Book</div>
                <div class="panel-body">
                    <div>
                        <dl class="dl-horizontal">
                            <dt>
                                @Html.DisplayNameFor(model => model.ProductName)
                            </dt>

                            <dd>
                                @Html.DisplayFor(model => model.ProductName)
                            </dd>

                            <dt>
                                @Html.DisplayNameFor(model => model.ProductPrice)
                            </dt>

                            <dd>
                                @Html.DisplayFor(model => model.ProductPrice)
                            </dd>

                        </dl>
                    </div>
                    @Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })
                    </div><br />

                    <div class="col-md-10">
                        <input type="submit" value="Submit" class="btn btn-default"/>
                    </div>
                </div>
            </div>
        }
    </div>
    <div class="col-md-3"></div>
</div>
</code>```

Following is the screen shot:

答:
Hi Marshall  I hope you got the solution from doug knudsen answer above, so here i would like show you the way ,Why DisplayFor does not post values to Action Method?

Short Answer: DisplayFor does not render an input field for the property,whereas  editorfor and hiddenfor render an input field. This is the reason you didn't get the value in the post.

Hope it helped you to understand more.

Thanks

Karthik

Body:
I'm working on a simple project. Following is the code. The thing is I'm unable to get all the information from the view to the controller. So I already have book ID, Name and price (which is coming from separate Productcontroller) in the Homecontroller and I'm able to view it as well and I want to post the quantity of books when I make a post request. So, when I try to make a post request and debug it, I can only see the quantity and I see null for book ID, Name and price.

I’m not sure what is going wrong. Any help would be really appreciated.
Thank You!

1.Product.cs

public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public decimal ProductPrice { get; set; }
        public int Quantity { get; set; }
    }

2.Cart.cshtml

@model DAL.Models.Product
@{
    ViewBag.Title = "Purchase";
}

@ViewBag.bookName

Purchase

        @using (Html.BeginForm("Cart", "Home", FormMethod.Post))
        {

Purchase Book

                                @Html.DisplayNameFor(model => model.ProductName)

                                @Html.DisplayFor(model => model.ProductName)

                                @Html.DisplayNameFor(model => model.ProductPrice)

                                @Html.DisplayFor(model => model.ProductPrice)

                    @Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })

                        <input type="submit" value="Submit" class="btn btn-default"/>

        }

Following is the screen shot:


问:
Font issue while rendering SSRS Reports
I need my report to be in "HiraginoKaku" font while exporting to PDF. I don't have this font installed on my SSRS. So i am trying to achieve it with this expression =IIF(Globals!RenderFormat.Name="PDF","HiraginoKaku","Arial") but no luck.

I tried this also =IIF(Globals!RenderFormat.Name="EXCELOPENXML","Arial","HiraginoKaku") still no luck.

I have used Arial as default while creating report.
Please help me how to get this font thing done.

答:
1.you need to download some fonts to download  like TAT files
2.after that put the file in c://windows/fonts
3.now restart your system and check </p>

Title: Font issue while rendering SSRS Reports


问:
Text-mining with the tm-package - word stemming
I am doing some text mining in R with the tm-package. Everything works very smooth. However, one problem occurs after stemming (http://en.wikipedia.org/wiki/Stemming). Obviously, there are some words, which have the same stem, but it is important that they are not "thrown together" (as those words mean different things).

For an example see the 4 texts below. Here you cannnot use "lecturer" or "lecture" ("association" and "associate") interchangeable. However, this is what is done in step 4.

Is there any elegant solution how to implement this for some cases/words manually (e.g. that "lecturer" and "lecture" are kept as two different things)?

```<code>texts <- c("i am member of the XYZ association",
"apply for our open associate position",
"xyz memorial lecture takes place on wednesday",
"vote for the most popular lecturer")

# Step 1: Create corpus
corpus <- Corpus(DataframeSource(data.frame(texts)))

# Step 2: Keep a copy of corpus to use later as a dictionary for stem completion
corpus.copy <- corpus

# Step 3: Stem words in the corpus
corpus.temp <- tm_map(corpus, stemDocument, language = "english")

inspect(corpus.temp)

# Step 4: Complete the stems to their original form
corpus.final <- tm_map(corpus.temp, stemCompletion, dictionary = corpus.copy)

inspect(corpus.final)
</code>```

答:
You can also use the following package for steeming words: https://cran.r-project.org/web/packages/SnowballC/SnowballC.pdf.

You just need to use the function wordStem, passing the vector of words to be stemmed and also the language you are dealing with. To know the exactly language string you need to use, you can refer to the method getStemLanguages, which will return all possible options for it.

Kind Regards

Body:
I am doing some text mining in R with the tm-package. Everything works very smooth. However, one problem occurs after stemming (http://en.wikipedia.org/wiki/Stemming). Obviously, there are some words, which have the same stem, but it is important that they are not "thrown together" (as those words mean different things).

For an example see the 4 texts below. Here you cannnot use "lecturer" or "lecture" ("association" and "associate") interchangeable. However, this is what is done in step 4.

Is there any elegant solution how to implement this for some cases/words manually (e.g. that "lecturer" and "lecture" are kept as two different things)?

texts <- c("i am member of the XYZ association",
"apply for our open associate position",
"xyz memorial lecture takes place on wednesday",
"vote for the most popular lecturer")

# Step 1: Create corpus
corpus <- Corpus(DataframeSource(data.frame(texts)))

# Step 2: Keep a copy of corpus to use later as a dictionary for stem completion
corpus.copy <- corpus

# Step 3: Stem words in the corpus
corpus.temp <- tm_map(corpus, stemDocument, language = "english")

inspect(corpus.temp)

# Step 4: Complete the stems to their original form
corpus.final <- tm_map(corpus.temp, stemCompletion, dictionary = corpus.copy)

inspect(corpus.final)


问:
Scheduling algorithm/problem
I'm bored, and this problem just haunted me again. Back at university, I used to always wonder how they schedule exams. The ability to schedule 10k student to do exams in 2 weeks and guarantee that no student will have an exam in two consecutive periods. I'm assuming some form of heuristics be applied.

I'm bored tonight, and if you give me the right tools, I'll work on it tonight and up to the weekend

cheers,
dassouki

EDIT 1:
I guess the assumption would be that all we know is the following:

Number of students and the courses that they're each enrolled in

Number of exam period spots

答: Drools Planner has an exam scheduling example (called examination, see download and reference manual). The problem is specified in the ITC2007 competition track 1.</p>

Title: Scheduling algorithm/problem


问:
How to gain access tokens using Azure Easy Auth?
I have a Single Page Appplication (SPA) built using React and a Web API, both of which are hosted on Azure's App Service. Authentication is provided by Azure AD.

I have been using the Active Directory Authentication Library (ADAL) for JavaScript. While all the examples seem to be about Angular, I have managed to get the pure JavaScript version of the library working with the React application. I have used the OAuth2 implicit grant flow to utimately provide authenticated access to the Web API via the SPA.

Everything works fine with ADAL, but this approach requires you to have a login and logout mechanism (eg. via a button). The authorization code is added to the URL as a fragment and ADAL conveniently does the rest. However, I would like the entire application to be secure/authenticated and so I have setup "Easy Auth" - authentication via the App Service.

When working with "Easy Auth" you sign-on to the application but there is no fragment returned in the URL and so ADAL cannot be used to acquire an access token for the API.

What is the best way to gain access tokens like those needed for implicit grant when using "Easy Auth"? Is there a way to incorporate ADAL into an "Easy Auth" flow?

Thank you.

答:
If you deploy the single page application and web API into the same Azure's app service and protect the app service using the Easy Auth, there is no necessary to use adal in the single page application to call the web API now.

In this scenario, you are able to login the app service via the server-flow and then you can call the web API directly since the Easy Auth will authenticate the request via the cookies. And if the web API also server other clients you want to call using the token, you need to get the id_token/access_token using the Azure AD app which you protect the app service and exchange the authentication token using id_token/access_token issued by Azure AD. This progress is called client-flow.

More detail about these two flows, you can refer link here.


问:
Kotlin generics
How is it possible to enforce a generic type for a method in Kotlin?
I know for instance you can do the following:

```<code>var someVar: MutableSet<out SomeType> = hashSetOf()
</code>```

How can you do the same for a method?

```<code>fun <T> doSomething() {
}
</code>```

I'd like to enforce T to be of type X or a sub-type of it.

Thanks.

答:
as @s1m0nw1 quoted, you can use

fun <T : X> doSomething() {
}

to limit T subtype of X,

additional, you can use

fun <T> doSomething where T : Comparable, T : Cloneable {
}

to limit T should implement both Comparable and Cloneable

as referenced here https://kotlinlang.org/docs/reference/generics.html

Title: Kotlin generics

Body:
How is it possible to enforce a generic type for a method in Kotlin?
I know for instance you can do the following:

var someVar: MutableSet<out SomeType> = hashSetOf()

How can you do the same for a method?

fun <T> doSomething() {
}

I'd like to enforce T to be of type X or a sub-type of it.

Thanks.


问:
Redirect sub domain with source port to destination port
I want redirect subdomain:port to subdomain:destination_port . It possible ? i see use SRV Record but can't use subdomain:port.

Example:

sub.domain.com:1234 to sub.domain.com:2345

答: No, this is not possible via dns. The only (reasonable) ways to accomplish this would be to either redirect the client to the new url (eg, http 302) if the protocol supports it, or to either proxy the connection from the old port to the new, or to redirect it through for example, iptables nat/mangle rules.</p>


问:
iOS - #import "GoogleMaps/GoogleMaps.h" not found
I'm sorry, I'm newbie in iOS development.
I use library from here to get direction of two place in Google Maps. I have ever used Google Maps. After I import Google Maps Framework, I still get error...

This is the problem :

How to import get GoogleMaps header ?

答: Removing and adding Google Map SDK again works for me :)</p>


问:
Return a list of Max values
```<code>Myfile = open('GG.txt')
c = [i[:] for i in Myfile]

def cole():
    x = 0

    for line in c:
        a = line.strip().split(' ')
        for m in a:

            if(int(m) > x):
                x = int(m)

    for line in c:
        if str(x) in line:
            return ('[' + line.strip() + ']')

print(cole())
</code>```

Here is my code that takes a 2D list and find the max value in each column, and returns a list containing the max values.

Here's the output:

My question is how can I make it so it it separated by commas?

So like,
Expected output:

[62, 998, 4, 25, 936, 126, 553, 634, 316, 760, 197, 181, 427, 175, 259, 210]

答:
When you're creating the c list, call strip, split, and int, so you don't have to do that repeatedly in the other loops.

You can also save the line containing the max value in a variable at the same time as you update the max value, so you don't need a second loop.

There's no need to use both strip() and split(). If you omit the argument to split(), it splits on any whitespace, so the newlines will be ignored.

```<code>Myfile = open('GG.txt')
allLines = [[int(num) for num in line.split()] for line in Myfile]

def cole(c):
    x = 0
    bigLine = []
    for line in c:
        for m in line:
            if (m > x):
                x = m
                bigLine = line
    return bigLine

print(cole(allLines))
</code>```

Title: Return a list of Max values

Body:
Myfile = open('GG.txt')
c = [i[:] for i in Myfile]

def cole():
    x = 0

    for line in c:
        a = line.strip().split(' ')
        for m in a:

            if(int(m) > x):
                x = int(m)

    for line in c:
        if str(x) in line:
            return ('[' + line.strip() + ']')

print(cole())

Here is my code that takes a 2D list and find the max value in each column, and returns a list containing the max values.

Here's the output:

My question is how can I make it so it it separated by commas?

So like,
Expected output:

[62, 998, 4, 25, 936, 126, 553, 634, 316, 760, 197, 181, 427, 175, 259, 210]

Body:
When you're creating the c list, call strip, split, and int, so you don't have to do that repeatedly in the other loops.

You can also save the line containing the max value in a variable at the same time as you update the max value, so you don't need a second loop.

There's no need to use both strip() and split(). If you omit the argument to split(), it splits on any whitespace, so the newlines will be ignored.

Myfile = open('GG.txt')
allLines = [[int(num) for num in line.split()] for line in Myfile]

def cole(c):
    x = 0
    bigLine = []
    for line in c:
        for m in line:
            if (m > x):
                x = m
                bigLine = line
    return bigLine

print(cole(allLines))


问:
Google Custom Search API Search Image by Image URL
I am working on an application which will have an option for users to upload images. Once uploaded, the application will show other images from the web which look exactly similar, whether or not of the same size.

For this, I will create a temporary URL for the image so that I could provide Google custom search API the URL of the image. I would expect in response, URL's of images that are exactly the same or similar to it, perhaps in JSON format.

I did find a similar question posted in January. Till then Google did not support anything like this, apparently:

Google Javascript Custom Search API: Search images by image url

One can also simply do:

http://images.google.com/searchbyimage?site=search&image_url={Image URL}

Since that is not part of an official API, it may not be right to use this method.

Can someone help me?

答:
Would you need a simple result?

If you are, you can use Vision API of Google.

This is very simple.

https://cloud.google.com/vision/

You can try on the top.

First, access the URL.

Second, upload your image file on the "Try API"

Third, click "JSON" tab menu on the result.

You can be seen JSON about similar images.


问:
export/import build definition from/to JSon file (TFS 2013)
I'm trying to export and import build definitions from tfs2013, following this link and this, but none of them are working for me. I know there are some plugins for tfs which do this, but I can't use any of them due to company policies restrictions.

GetDefinitionAsync and GetFullDefinitionsAsync methods are fine, but they don't retrieve ProcessParameters property, so I can't export a full build definition which includes this important information. I've tried to get this property calling IBuildServer.QueryBuildDefinitions, but when I try to create new build definition I can't because the data type is Microsoft.TeamFoundation.Build.Client.IBuildDefinition and I can't create new instance of Microsoft.TeamFoundation.Build.Client.BuildDefinition due to it's a sealed class. how can I copy ProcessParameters and the other info to import the full build definition?

Thanks

答:
For XAML build, you need to use IBuildServer.GetBuildDefinition  method to get the build definition first and then do the copy.

First start by getting a reference to the build server via a call to the GetService method on the TfsTeamProjectCollection instance.  Once you have the build server reference  you can then load the build definition that you are making a copy of.

If you want to copy the build definitions with process parameters you should first copy the template also. Sample code sinnper

```<code>  // Copy Process parameters
  newBuildDefinition.Process = buildDefinitionToCopy.Process;
  var processParams = WorkflowHelpers.DeserializeProcessParameters(buildDefinitionToCopy.ProcessParameters);
  var copyProcessParams = WorkflowHelpers.DeserializeProcessParameters(newBuildDefinition.ProcessParameters);
 foreach (KeyValuePair<string, object> entry in processParams)
  {
      copyProcessParams.Add(entry.Key.ToString(), entry.Value);
  }
 newBuildDefinition.ProcessParameters = WorkflowHelpers.SerializeProcessParameters(copyProcessParams);
</code>```

More details about how to achieve the copy through API, you could refer this blog --Copying a TFS Build Definition

Body:
For XAML build, you need to use IBuildServer.GetBuildDefinition  method to get the build definition first and then do the copy.

First start by getting a reference to the build server via a call to the GetService method on the TfsTeamProjectCollection instance.  Once you have the build server reference  you can then load the build definition that you are making a copy of.

If you want to copy the build definitions with process parameters you should first copy the template also. Sample code sinnper

  // Copy Process parameters
  newBuildDefinition.Process = buildDefinitionToCopy.Process;
  var processParams = WorkflowHelpers.DeserializeProcessParameters(buildDefinitionToCopy.ProcessParameters);
  var copyProcessParams = WorkflowHelpers.DeserializeProcessParameters(newBuildDefinition.ProcessParameters);
 foreach (KeyValuePair<string, object> entry in processParams)
  {
      copyProcessParams.Add(entry.Key.ToString(), entry.Value);
  }
 newBuildDefinition.ProcessParameters = WorkflowHelpers.SerializeProcessParameters(copyProcessParams);

More details about how to achieve the copy through API, you could refer this blog --Copying a TFS Build Definition


问:
Formatting elements of a list into a specific string
I'm trying to take a list of terms and output them in a specific format.

For example, I have a list of verbs:

```<code>verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
</code>```

and I want my output to be a string, where each item in the list is also a string, delineated by a |

```<code>magic(verbs)
</code>```

output:

```<code>"eat" | "run" | "jump" | etc.
</code>```

I've tried using the .join method, but that just gives me one big string of the terms separated by pipes, instead of what I want. Any ideas? I'm pretty new to Python and I'm sorry if this is incredibly low-brow or something that has been answered elsewhere.

答:
Between each quote-enclosed verb, put a pipe:</p>

```<code>" | ".join('"{0}"'.format(verb) for verb in verbs)
</code>```

```<code>>>> verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
>>> print(" | ".join('"{0}"'.format(verb) for verb in verbs))
"eat" | "run" | "jump" | "play" | "walk" | "talk" | "send"
</code>```

Body:
I'm trying to take a list of terms and output them in a specific format.

For example, I have a list of verbs:

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']

and I want my output to be a string, where each item in the list is also a string, delineated by a |

magic(verbs)

output:

"eat" | "run" | "jump" | etc.

I've tried using the .join method, but that just gives me one big string of the terms separated by pipes, instead of what I want. Any ideas? I'm pretty new to Python and I'm sorry if this is incredibly low-brow or something that has been answered elsewhere.

Body:
Between each quote-enclosed verb, put a pipe:

" | ".join('"{0}"'.format(verb) for verb in verbs)

>>> verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
>>> print(" | ".join('"{0}"'.format(verb) for verb in verbs))
"eat" | "run" | "jump" | "play" | "walk" | "talk" | "send"


问:
Sum in rows some other column rows values grouped by other column ID
Is it possible to do a query like this? I have the ID, some IN value, Out value and the last column TOTAL is the sum of the difference between IN and OUT. I just really need the complete sum.
The ID2 rows that are equals must be summed in the SUM column. There is no ID2 quantity fixed, some times it would be just one row to sum, other cases there will be more. I could also add a difference column, to just sum the value in that row for the same ID2.

My doubt here is, is it possible to sum in a row, the accumulated in some rows at other columns?

```<code>ID  ID2 IN  OUT TOTAL (IN-OUT)
1   2   200 150 blank-null-space-or whatever but a character
2   2   350 250 doesn't matter, also it can have the same SUM result as below
3   2   600 400 350 ( = 200 - 150 + 350 - 250 + 600 - 400)
4   3   100  80  20
</code>```

Or I have to do it at the client side in JavaScript? Which is better or you do suggest? Maybe it is easier in JavaScript but I wanted to do it all in one step to reduce the pool connections.

A simple verifiable example would be

```<code>CREATE TABLE "table1" (
  "ID" int NOT NULL,
  "ID2" int DEFAULT NULL,
  "`EXT_ID" int DEFAULT NULL,
  "IN" int DEFAULT NULL
  "OUT" int DEFAULT NULL
);

INSERT INTO "table1" ("ID", "ID2", "EXT_ID", "IN", "OUT") VALUES
(1, 2, 1, 200, 150),
(2, 2, 2, 350, 250),
(3, 2, 2, 600, 400),
(4, 3, 4, 100,  80),
(5, 3, 5, 130, 100),
(6, 4, 6, 100,  80),
(7, 4, 7, 120,  70),
(8, 4, 7, 150,  90);
</code>```

EDIT: Added an foreign ID column "EXT_ID" that have a condition show only one row and the one that has MAX value from the same "ID2".

Corrected SQL syntax.

答:
try this?

```<code>select (SUM(`IN` - `OUT`)) as 'Total'
from (
  select *
  from table1
  where ID2 IN (select ID2 from table1 where ID = "3")
) as temptable;
</code>```

but this can only get result of 1 row, you might have to edit it.

Body:
Is it possible to do a query like this? I have the ID, some IN value, Out value and the last column TOTAL is the sum of the difference between IN and OUT. I just really need the complete sum.
The ID2 rows that are equals must be summed in the SUM column. There is no ID2 quantity fixed, some times it would be just one row to sum, other cases there will be more. I could also add a difference column, to just sum the value in that row for the same ID2.

My doubt here is, is it possible to sum in a row, the accumulated in some rows at other columns?

ID  ID2 IN  OUT TOTAL (IN-OUT)
1   2   200 150 blank-null-space-or whatever but a character
2   2   350 250 doesn't matter, also it can have the same SUM result as below
3   2   600 400 350 ( = 200 - 150 + 350 - 250 + 600 - 400)
4   3   100  80  20

Or I have to do it at the client side in JavaScript? Which is better or you do suggest? Maybe it is easier in JavaScript but I wanted to do it all in one step to reduce the pool connections.

A simple verifiable example would be

CREATE TABLE "table1" (
  "ID" int NOT NULL,
  "ID2" int DEFAULT NULL,
  "`EXT_ID" int DEFAULT NULL,
  "IN" int DEFAULT NULL
  "OUT" int DEFAULT NULL
);

INSERT INTO "table1" ("ID", "ID2", "EXT_ID", "IN", "OUT") VALUES
(1, 2, 1, 200, 150),
(2, 2, 2, 350, 250),
(3, 2, 2, 600, 400),
(4, 3, 4, 100,  80),
(5, 3, 5, 130, 100),
(6, 4, 6, 100,  80),
(7, 4, 7, 120,  70),
(8, 4, 7, 150,  90);

EDIT: Added an foreign ID column "EXT_ID" that have a condition show only one row and the one that has MAX value from the same "ID2".

Corrected SQL syntax.

Body:
try this?

select (SUM(`IN` - `OUT`)) as 'Total'
from (
  select *
  from table1
  where ID2 IN (select ID2 from table1 where ID = "3")
) as temptable;

but this can only get result of 1 row, you might have to edit it.


问:
List index out of range in perceptron example
I have this piece of code that aims to change the value of a cell of a 2D array to a 1 or a 0 according to whether or not it is equal to Iris-versicolor.

```<code>for row in data:
    if (row[4] == "Iris-versicolor"):
        row[4] == 1
    else:
        row[4] == 0
</code>```

The issue is that it gives me an error on the line of the if statement saying "IndexError : list index out of range". I understand the error (I think) saying that I'm trying to access a cell that doesn't exist, except that I have checked and my data array does have a 5th column (indexed as 4) and I don't see where else the error can come from.

Any help is greatly appreciated,

Mindoo

Edit: Here is a link to the database I'm using.
Its the well known Iris database.

答:
Try to change

```<code>row[4] == 1
</code>```

to

```<code>row[4] = 1
</code>```

also with the row[4] = 0

Body:
I have this piece of code that aims to change the value of a cell of a 2D array to a 1 or a 0 according to whether or not it is equal to Iris-versicolor.

for row in data:
    if (row[4] == "Iris-versicolor"):
        row[4] == 1
    else:
        row[4] == 0

The issue is that it gives me an error on the line of the if statement saying "IndexError : list index out of range". I understand the error (I think) saying that I'm trying to access a cell that doesn't exist, except that I have checked and my data array does have a 5th column (indexed as 4) and I don't see where else the error can come from.

Any help is greatly appreciated,

Mindoo

Edit: Here is a link to the database I'm using.
Its the well known Iris database.

Body:
Try to change

row[4] == 1

to

row[4] = 1

also with the row[4] = 0


问:
How to compare a session variable with a string in C#?
i edited the question

it still does not work, the user writes appendix then press OK in Login, nothing happens

here is the login (vb.net)

```<code>Partial Class login
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Session("passcode") = TextBox1.Text
    Response.Redirect("Default.aspx")

End Sub
End Class
</code>```

and here is the default page C#

```<code>public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (Session["passcode"] == "appendix")
    {
       Response.Write("OK !");
    }
    else
    {
        Response.Redirect("login.aspx");
    }
}

}
</code>```

答:
You probably mean

```<code>Session["passcode"] == "Appendix"
</code>```

In C# (unlike VB), == is the equality operator and = is the assignment operator.

Body:
i edited the question

it still does not work, the user writes appendix then press OK in Login, nothing happens

here is the login (vb.net)

Partial Class login
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Session("passcode") = TextBox1.Text
    Response.Redirect("Default.aspx")

End Sub
End Class

and here is the default page C#

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (Session["passcode"] == "appendix")
    {
       Response.Write("OK !");
    }
    else
    {
        Response.Redirect("login.aspx");
    }
}

}

Body:
You probably mean

Session["passcode"] == "Appendix"

In C# (unlike VB), == is the equality operator and = is the assignment operator.


问:
How can I set the size of my div equal to the size of background image?
I have a problem in the content inside of my container. Because I already set some method to get the height of the background image equal to my container. My problem is when I put a content inside my container it detects my invisible image that I set.

Here's my code:

```<code><div class="parent">
  <div class="hidden-image">
    <img src="http://placehold.it/350x350" />
  </div>
  <h1>
    text
  </h1>
</div>
</code>```

CSS:

```<code>.parent {
  border: 1px solid red;
  width: 350px;
  height: auto;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('http://placehold.it/350x350');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}
.parent img {
  visibility: hidden;
  width: 100%;
  height: auto;
}
</code>```

If you check my fiddle, the text moved to the right because I think that it is because of the image I set.

fiddle:
https://jsfiddle.net/kdu9691c/

答: This is because visibility: hidden doesn't remove the element from flow. It still takes up the same space it normally would, it's just invisible. You might try using position: absolute on either the image or the text div; or if the idea is just to keep the div a certain proportion to match the image, google css padded box aspect ratio for some neat workarounds. You also have the option of background-size: cover, which may be helpful depending on your particular constraints.

Body:
I have a problem in the content inside of my container. Because I already set some method to get the height of the background image equal to my container. My problem is when I put a content inside my container it detects my invisible image that I set.

Here's my code:

    text

CSS:

.parent {
  border: 1px solid red;
  width: 350px;
  height: auto;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('http://placehold.it/350x350');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}
.parent img {
  visibility: hidden;
  width: 100%;
  height: auto;
}

If you check my fiddle, the text moved to the right because I think that it is because of the image I set.

fiddle:
https://jsfiddle.net/kdu9691c/


问:
React, is there a way to avoid needing to wrap a div inside a div?
I have the following:

```<code>const errorMessage = ({meta}) =>
  <div>
    {meta.error && meta.touched && <div className="alert alert-info" role="alert">{meta.error}</div>}
  </div>
</code>```

If I remove the outer div wrapper in the above I get an error... Is there a way to get errorMessage to work without the extra DIV?

Thanks

答:
You can write it like this by using {}:

```<code>const ErrorMessage = ({meta}) => {

    if(meta.error && meta.touched)
        return <div className="alert alert-info" role="alert">{meta.error}</div>

    return null;
}
</code>```

Or remove the outer div and remove the {} also, use ternary operator to put the condition, like this:

```<code>const ErrorMessage = ({meta}) => meta.error && meta.touched ?
    <div className="alert alert-info" role="alert">{meta.error}</div>
    : null;
</code>```

You need to use ErrorMessage instead of errorMessage, check the reason here:

Html is not rendering in the browser - React js

Check this answer why it was failing when you removed the outer div:

```<code>const errorMessage = ({meta}) =>
    {meta.error && meta.touched && <div className="alert alert-info" role="alert">{meta.error}</div>}
</code>```

Body:
I have the following:

const errorMessage = ({meta}) =>

    {meta.error && meta.touched &&
{meta.error}
}

If I remove the outer div wrapper in the above I get an error... Is there a way to get errorMessage to work without the extra DIV?

Thanks

Body:
You can write it like this by using {}:

const ErrorMessage = ({meta}) => {

    if(meta.error && meta.touched)
        return <div className="alert alert-info" role="alert">{meta.error}</div>

    return null;
}

Or remove the outer div and remove the {} also, use ternary operator to put the condition, like this:

const ErrorMessage = ({meta}) => meta.error && meta.touched ?
    <div className="alert alert-info" role="alert">{meta.error}</div>
    : null;

You need to use ErrorMessage instead of errorMessage, check the reason here:

Html is not rendering in the browser - React js

Check this answer why it was failing when you removed the outer div:

const errorMessage = ({meta}) =>
    {meta.error && meta.touched && <div className="alert alert-info" role="alert">{meta.error}</div>}


问:
returning data in console.log with angular but not displaying on HTML page
I am new to angular and I am developing a Web application. I am getting data in console.log but not able to display it on HTML page. table is displaying blank value.

Here is my HTML page:

```<code><div class="bs-example" data-example-id="panel-without-body-with-table">
    <div class="panel panel-default">
        <div class="panel-heading">Account list</div>
        <table class="table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>AWS Account</th>
                    <th>VPC</th>
                    <th>Subnet</th>
                    <th>Instance Type</th>
                    <th>Port</th>
                    <th></th>

                </tr>
            </thead>
            <tbody>
           <!-- {% raw %}-->
                 <tr ng-repeat="Account in Accounts ">
                <!--{% for account in myaccounts %}track by $index-->
                <tr>

                    <th scope="row">// $index+1 //</th>
                    <td> // Account.name // </td>
                    <td>// Account.vpc //</td>
                    <td>// Account.subnet //</td>
                    <td>// Account.instance_type //</td>

                    <td><span style="cursor:pointer;" ng-click="editAccount(Account.id)" class="glyphicon glyphicon-pencil" aria-hidden="true"></span></td>
                </tr>
               <!--{% endfor %}-->
              <!-- {% endraw %}-->
            </tbody>
        </table>
    </div>
</div>
</code>```

Here is my Angular controller:

```<code>angular.module('pushButtonAdmin', [])

 .config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('//');
    $interpolateProvider.endSymbol('//');
  })

  .controller('adminCtrl', function($scope, $http) {

                $scope.info = {};

                $scope.showAdd = true;

                $scope.showAddPopUp = function(){
                    $scope.showAdd = true;
                    $scope.info = {};
                    //$('#addPopUp').modal('show');
                }

                $scope.test = function(){
                    console.log("sfasd");
                }

                $scope.showlist = function(){
                    $http({
                        method: 'POST',
                        url: '/getAccountList',
                    }).then(function(response) {
                        $scope.Accounts = response.data;
                        console.log('mm',$scope.Accounts);
                    }, function(error) {
                        console.log(error);
                    });
                }

                $scope.showlist();
            });
</code>```

答:
These changes are needed in your html file:

The first major problem is that you are not using angular's html interpolation symbols to access your ng-repeat iterator. You need to surround Account.name with {{ Account.name }} and do the same for all of your other Account properties.

The other problem is that you have an extra
 that is not allowing the scope of your ng-repeat to reach the s below it. Remove the
 right before

EDIT: Disregard the first point about interpolation symbols, I was informed that the OP is using // for this.

Body:
I am new to angular and I am developing a Web application. I am getting data in console.log but not able to display it on HTML page. table is displaying blank value.

Here is my HTML page:

Account list

                    #
                    AWS Account
                    VPC
                    Subnet
                    Instance Type
                    Port

                    // $index+1 //
                     // Account.name //
                    // Account.vpc //
                    // Account.subnet //
                    // Account.instance_type //

Here is my Angular controller:

angular.module('pushButtonAdmin', [])

 .config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('//');
    $interpolateProvider.endSymbol('//');
  })

  .controller('adminCtrl', function($scope, $http) {

                $scope.info = {};

                $scope.showAdd = true;

                $scope.showAddPopUp = function(){
                    $scope.showAdd = true;
                    $scope.info = {};
                    //$('#addPopUp').modal('show');
                }

                $scope.test = function(){
                    console.log("sfasd");
                }

                $scope.showlist = function(){
                    $http({
                        method: 'POST',
                        url: '/getAccountList',
                    }).then(function(response) {
                        $scope.Accounts = response.data;
                        console.log('mm',$scope.Accounts);
                    }, function(error) {
                        console.log(error);
                    });
                }

                $scope.showlist();
            });

Body:
These changes are needed in your html file:

The first major problem is that you are not using angular's html interpolation symbols to access your ng-repeat iterator. You need to surround Account.name with {{ Account.name }} and do the same for all of your other Account properties.

The other problem is that you have an extra <tr> that is not allowing the scope of your ng-repeat to reach the <td>s below it. Remove the <tr> right before <th scope="row">

EDIT: Disregard the first point about interpolation symbols, I was informed that the OP is using // for this.


问:
Program throws 'Access-Control-Allow-Origin' header in JavaScript? Works in Postman, not through browser
Solved

I have been working on this program since 07:00. This has been driving me crazy. I have written multiple full stack web apps and have not had this problem.

Basically I have a form in html that allows a user to input data. Whenever the submit button is clicked, it sends that data to a collection in mongoDB. I have tested this in postman and it works. However, when I run the program through a webbrowser, I get this error:

XMLHttpRequest cannot load http://localhost:8080/articles/addArticle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

I tried installing CORS and configuring the endpoint

I tried going into the javascript file and changing the

This is my JavaScript file

```<code>alert('JS is linked to page!');

function Article(id = 1, title = "", authors="", content = "", genre = "", date = 1497484623) {
    console.log("JavaScript file loaded successfully");
    var self = this;
    self.Id = id;
    self.Title = title;
    self.Authors = authors;
    self.Content = content;
    self.Genre = genre;
    self.Date = date;
    self.Save = function() {
        var settings = {
            url: 'http://localhost:8080/articles/addArticle',
            method: 'POST',
            dataType: "json",
              beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
        };
        var myData = {
            "Id" : self.Id,
            "Title": self.Title,
            "Authors": self.Authors,
            "Content": self.Content,
            "Genre": self.Genre,
            "Date": self.Date
        };
        settings.data = myData;

        $.ajax(settings).done(function(article) {
         var myArticle = new Article(article.Id, article.Title, article.Authors,
                article.Content, article.Genre, article.Date);
        });
    };
}

function addArticle(Article) {
    alert('addArticle Activated');
    var settings = {
        url: 'http://localhost:8080/articles/addArticle',
        method: 'POST',
        dataType: "json",
          beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
    };
    var myData = {
        "Title": Article.Title,
        "Authors" : Article.Authors,
        "Content": Article.Content,
        "Genre" : Article.Genre,
        "Date": Article.Date
    };
    settings.data = myData;

    $.ajax(settings).done(function(Article) {
        var myArticle = new Article(article.Id, article.Title, article.Authors, article.Content,
            article.Genre, article.Date);
        console.log("Article Created");
    });
}

$(document).ready(function() {

    $(document).on("submit", "#add-article", function(e) {
        e.preventDefault();
            alert('submit Activated');
        var title, authors, genre, content;
        title = $("#Title").val();
        director = $("#Authors").val();
        rating = $("#Genre").val();
        notes = $("#Content").val();
        var myArticle = new Article(0, title, authors, genre, content, 1497484623);
        alert(myArticle.Title);
        addArticle(myArticle);
        $("#add-article")[0].reset();
        $("#title").focus();

    });

});

/*function CreateSuccessRow(Article) {
    var successDataRow = `<tr id="Article-${Article.Id}"><td>${Article.Title}</td>
                <td>${Article.Authors}</td>
                <td>${Article.Genre}</td>
</code>```

Due to popular demand, this is the server-side code:

```<code>package com.stereoscopics.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.stereoscopics.app.models.Article;
import com.stereoscopics.app.repo.ArticleRepo;

@RestController
@RequestMapping("/articles")
public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List<Article> findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle) {
    articleRepo.save(newArticle);
    return newArticle;
}
</code>```

}

I have no idea how to fix this. Please help.

UPDATE

This still isn't working. I've updated the code as per some suggestions and I'm either doing it wrong or it's incorrect. The changes are shown below:

```<code>  @RestController
  @RequestMapping("/articles")
  public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List<Article> findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final
HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
  }
}
</code>```

THIS IS NOT SOLVED YET

答:
Deal your CORS problem that you need to set the crossDomain first.

```<code>$.ajax({
  crossDomain:true
})
</code>```

Next, you gonna to set the xhrFields in withCredentials.

```<code>$.ajax({
  crossDomain:true,
  xhrFields: {
    withCredentials: true
  }
})
</code>```

In you Code , it's look like following this setting config.

```<code>let settings = {
    url: 'http://localhost:8080/articles/addArticle',
    method: 'POST',
    crossDomain:true,
    xhrFields: {
      withCredentials: true
    }
    dataType: "json",
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Accept", "application/json");
    }
};
</code>```

Body:
Solved

I have been working on this program since 07:00. This has been driving me crazy. I have written multiple full stack web apps and have not had this problem.

Basically I have a form in html that allows a user to input data. Whenever the submit button is clicked, it sends that data to a collection in mongoDB. I have tested this in postman and it works. However, when I run the program through a webbrowser, I get this error:

XMLHttpRequest cannot load http://localhost:8080/articles/addArticle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

I tried installing CORS and configuring the endpoint

I tried going into the javascript file and changing the

This is my JavaScript file

alert('JS is linked to page!');

function Article(id = 1, title = "", authors="", content = "", genre = "", date = 1497484623) {
    console.log("JavaScript file loaded successfully");
    var self = this;
    self.Id = id;
    self.Title = title;
    self.Authors = authors;
    self.Content = content;
    self.Genre = genre;
    self.Date = date;
    self.Save = function() {
        var settings = {
            url: 'http://localhost:8080/articles/addArticle',
            method: 'POST',
            dataType: "json",
              beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
        };
        var myData = {
            "Id" : self.Id,
            "Title": self.Title,
            "Authors": self.Authors,
            "Content": self.Content,
            "Genre": self.Genre,
            "Date": self.Date
        };
        settings.data = myData;

        $.ajax(settings).done(function(article) {
         var myArticle = new Article(article.Id, article.Title, article.Authors,
                article.Content, article.Genre, article.Date);
        });
    };
}

function addArticle(Article) {
    alert('addArticle Activated');
    var settings = {
        url: 'http://localhost:8080/articles/addArticle',
        method: 'POST',
        dataType: "json",
          beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
    };
    var myData = {
        "Title": Article.Title,
        "Authors" : Article.Authors,
        "Content": Article.Content,
        "Genre" : Article.Genre,
        "Date": Article.Date
    };
    settings.data = myData;

    $.ajax(settings).done(function(Article) {
        var myArticle = new Article(article.Id, article.Title, article.Authors, article.Content,
            article.Genre, article.Date);
        console.log("Article Created");
    });
}

$(document).ready(function() {

    $(document).on("submit", "#add-article", function(e) {
        e.preventDefault();
            alert('submit Activated');
        var title, authors, genre, content;
        title = $("#Title").val();
        director = $("#Authors").val();
        rating = $("#Genre").val();
        notes = $("#Content").val();
        var myArticle = new Article(0, title, authors, genre, content, 1497484623);
        alert(myArticle.Title);
        addArticle(myArticle);
        $("#add-article")[0].reset();
        $("#title").focus();

    });

});

/*function CreateSuccessRow(Article) {
    var successDataRow = `
${Article.Title}
                ${Article.Authors}
                ${Article.Genre}

Due to popular demand, this is the server-side code:

package com.stereoscopics.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.stereoscopics.app.models.Article;
import com.stereoscopics.app.repo.ArticleRepo;

@RestController
@RequestMapping("/articles")
public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List
 findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle) {
    articleRepo.save(newArticle);
    return newArticle;
}

}

I have no idea how to fix this. Please help.

UPDATE

This still isn't working. I've updated the code as per some suggestions and I'm either doing it wrong or it's incorrect. The changes are shown below:

  @RestController
  @RequestMapping("/articles")
  public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List
 findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final
HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
  }
}

THIS IS NOT SOLVED YET

Body:
Deal your CORS problem that you need to set the crossDomain first.

$.ajax({
  crossDomain:true
})

Next, you gonna to set the xhrFields in withCredentials.

$.ajax({
  crossDomain:true,
  xhrFields: {
    withCredentials: true
  }
})

In you Code , it's look like following this setting config.

let settings = {
    url: 'http://localhost:8080/articles/addArticle',
    method: 'POST',
    crossDomain:true,
    xhrFields: {
      withCredentials: true
    }
    dataType: "json",
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Accept", "application/json");
    }
};


问:
About PHP underscore naming convention (as in "_method" or "_property")
This is a sort of general inquiry I've been wondering about. I've noticed a lot of this through other people's code, and never really knew the actual reason, just followed the trends, so here goes.

How come some methods and properties are named with an underscore in front, and others aren't?
For example, when specifically would one use function _method(), and when would one use function method(), or, in other words, private $_someVariable vs. private $someVariable?

答:
***Follow the PSR-2 coding guideline:

Property names SHOULD NOT be prefixed with a single underscore to
  indicate protected or private visibility`

Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md

***Reason :

No underscores before the property name, like $_income, instead use
  $income.  The underscore was used in some frameworks and can be
  confused with PHP magic variables.

Source : http://www.geekgumbo.com/2013/05/19/psr-2-coding-style-guide/


问:
tensorflow autoencoder is not learning in training
I am trying to generate synthetic data with tensorflow autoencoder that is very close to given original data. But, autoencoder is not learning in training phase. My cost function is not decreasing generally and synthetic data unrelated with original data. My code is given below:</p>

```<code>x = tf.placeholder("float", [None, COLUMN])
# Weights and biases to hidden layer
Wh = tf.Variable(tf.random_uniform((COLUMN, UNITS_OF_HIDDEN_LAYER), -1.0 / mpmath.sqrt(COLUMN), 1.0 / mpmath.sqrt(COLUMN)))
bh = tf.Variable(tf.zeros([UNITS_OF_HIDDEN_LAYER]))
h = tf.nn.sigmoid(tf.matmul(x, Wh) + bh)
# Weights and biases to output layer
Wo = tf.transpose(Wh) # tied weights
bo = tf.Variable(tf.zeros([COLUMN]))
y = tf.nn.sigmoid(tf.matmul(h, Wo) + bo)

# Objective functions
cross_entropy = tf.reduce_mean(tf.pow(x - y, 2))
optimizer = tf.train.RMSPropOptimizer(LEARNING_RATE).minimize(cross_entropy)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

train_number, _ = x_train.shape

for j in range(TRAINING_EPOCHS):
    sample = np.random.randint(train_number, size=BATCH_SIZE)
    batch_xs = x_train[sample][:]
    _, cost = sess.run([optimizer, cross_entropy], feed_dict={x: batch_xs})
    print("COST: ", cost)

encodedTensor = tf.nn.sigmoid(tf.add(tf.matmul(x_train, Wh), bh))
encodedData = sess.run(encodedTensor)

decodedTensor = tf.nn.sigmoid(tf.add(tf.matmul(encodedData, Wo), bo))
decodedData = sess.run(decodedTensor)
return decodedData
</code>```

答: Your loss function is MSE. It would be better if you switch to cross-entropy loss for auto-encoders. Here you can find a detailed information about it link. </p>

Body:
I am trying to generate synthetic data with tensorflow autoencoder that is very close to given original data. But, autoencoder is not learning in training phase. My cost function is not decreasing generally and synthetic data unrelated with original data. My code is given below:

x = tf.placeholder("float", [None, COLUMN])
# Weights and biases to hidden layer
Wh = tf.Variable(tf.random_uniform((COLUMN, UNITS_OF_HIDDEN_LAYER), -1.0 / mpmath.sqrt(COLUMN), 1.0 / mpmath.sqrt(COLUMN)))
bh = tf.Variable(tf.zeros([UNITS_OF_HIDDEN_LAYER]))
h = tf.nn.sigmoid(tf.matmul(x, Wh) + bh)
# Weights and biases to output layer
Wo = tf.transpose(Wh) # tied weights
bo = tf.Variable(tf.zeros([COLUMN]))
y = tf.nn.sigmoid(tf.matmul(h, Wo) + bo)

# Objective functions
cross_entropy = tf.reduce_mean(tf.pow(x - y, 2))
optimizer = tf.train.RMSPropOptimizer(LEARNING_RATE).minimize(cross_entropy)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

train_number, _ = x_train.shape

for j in range(TRAINING_EPOCHS):
    sample = np.random.randint(train_number, size=BATCH_SIZE)
    batch_xs = x_train[sample][:]
    _, cost = sess.run([optimizer, cross_entropy], feed_dict={x: batch_xs})
    print("COST: ", cost)

encodedTensor = tf.nn.sigmoid(tf.add(tf.matmul(x_train, Wh), bh))
encodedData = sess.run(encodedTensor)

decodedTensor = tf.nn.sigmoid(tf.add(tf.matmul(encodedData, Wo), bo))
decodedData = sess.run(decodedTensor)
return decodedData


问:
How do you create a blog post in rails without a topic?
I am doing a Ruby on Rails course and I am on a part where I am trying to create a blog post but it is giving me an error. It says:

1 error prohibited this blog from being saved:

Topic must exist

my code

What do I change to fix it?

答:
You can force saving like so:</p>

```<code>post.save(validate: false)
</code>```

Body:
You can force saving like so:

post.save(validate: false)


问:
Reading nested tags with sax parser
i am trying to read a xml file with following tag, but the sax parser is unable to read nested tags like

```<code><active-prod-ownership>
  <ActiveProdOwnership>
    <Product code="3N3" component="TRI_SCORE" orderNumber="1-77305469" />
  </ActiveProdOwnership>
</active-prod-ownership>
</code>```

here is the code i am using

```<code>public class LoginConsumerResponseParser extends DefaultHandler {
 // ===========================================================
 // Fields
 // ===========================================================
 static String str="default";
 private boolean in_errorCode=false;
 private boolean in_Ack=false;
 private boolean in_activeProdOwnership= false;
 private boolean in_consumerId= false;
 private boolean in_consumerAccToken=false;

  public void startDocument() throws SAXException {
  Log.e("i am ","in start document");
 }

 public void endDocument() throws SAXException {
  // Nothing to do
  Log.e("doc read", " ends here");
 }

 /** Gets be called on opening tags like:
  * <tag>
  * Can provide attribute(s), when xml was like:
  * <tag attribute="attributeValue">*/

 public void startElement(String namespaceURI, String localName,
   String qName, Attributes atts) throws SAXException {
  if(localName.equals("ack")){
   in_Ack=true;
  }
  if(localName.equals("error-code")){
   in_errorCode=true;
  }
  if(localName.equals("active-prod-ownership")){
   Log.e("in", "active product ownership");
   in_activeProdOwnership=true;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= true;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= true;
  }
 }

 /** Gets be called on closing tags like:
  * </tag> */

 public void endElement(String namespaceURI, String localName, String qName)
 throws SAXException {
  if(localName.equals("ack")){
   in_Ack=false;
  }
  if(localName.equals("error-code")){
   in_errorCode=false;
  }
  if(localName.equals("active-prod-ownership")){
   in_activeProdOwnership=false;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= false;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= false;
  }
 }

 /** Gets be called on the following structure:
  * <tag>characters</tag> */

 public void characters(char ch[], int start, int length) {

  if(in_Ack){
  str= new String(ch,start,length);
  }
  if(str.equalsIgnoreCase("success")){
  if(in_consumerId){

  }
  if(in_consumerAccToken){

  }
  if(in_activeProdOwnership){
   str= new String(ch,start,length);
   Log.e("active prod",str);
  }
  }
 }
}
</code>```

but on reaching the tag in_activeProdOwnersip read only "<" as the contents of the tag

please help i need to the whole data to be read

答:
I suspect this is what's going wrong:

```<code>new String(ch,start,length);
</code>```

Here, you're passing a char[] to the String constructor, but the constructor is supposed to take a byte[]. The end result is you get a mangled String.

I suggest instead that you make the str field a StringBuilder, not a String, and then use this:

```<code>builder.append(ch,start,length);
</code>```

You then need to clear the StringBuilder each time startElement() is called.

Title: Reading nested tags with sax parser

Body:
i am trying to read a xml file with following tag, but the sax parser is unable to read nested tags like

<active-prod-ownership>
  <ActiveProdOwnership>
    <Product code="3N3" component="TRI_SCORE" orderNumber="1-77305469" />
  </ActiveProdOwnership>
</active-prod-ownership>

here is the code i am using

public class LoginConsumerResponseParser extends DefaultHandler {
 // ===========================================================
 // Fields
 // ===========================================================
 static String str="default";
 private boolean in_errorCode=false;
 private boolean in_Ack=false;
 private boolean in_activeProdOwnership= false;
 private boolean in_consumerId= false;
 private boolean in_consumerAccToken=false;

  public void startDocument() throws SAXException {
  Log.e("i am ","in start document");
 }

 public void endDocument() throws SAXException {
  // Nothing to do
  Log.e("doc read", " ends here");
 }

 /** Gets be called on opening tags like:
  * <tag>
  * Can provide attribute(s), when xml was like:
  * <tag attribute="attributeValue">*/

 public void startElement(String namespaceURI, String localName,
   String qName, Attributes atts) throws SAXException {
  if(localName.equals("ack")){
   in_Ack=true;
  }
  if(localName.equals("error-code")){
   in_errorCode=true;
  }
  if(localName.equals("active-prod-ownership")){
   Log.e("in", "active product ownership");
   in_activeProdOwnership=true;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= true;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= true;
  }
 }

 /** Gets be called on closing tags like:
  * </tag> */

 public void endElement(String namespaceURI, String localName, String qName)
 throws SAXException {
  if(localName.equals("ack")){
   in_Ack=false;
  }
  if(localName.equals("error-code")){
   in_errorCode=false;
  }
  if(localName.equals("active-prod-ownership")){
   in_activeProdOwnership=false;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= false;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= false;
  }
 }

 /** Gets be called on the following structure:
  * <tag>characters</tag> */

 public void characters(char ch[], int start, int length) {

  if(in_Ack){
  str= new String(ch,start,length);
  }
  if(str.equalsIgnoreCase("success")){
  if(in_consumerId){

  }
  if(in_consumerAccToken){

  }
  if(in_activeProdOwnership){
   str= new String(ch,start,length);
   Log.e("active prod",str);
  }
  }
 }
}

but on reaching the tag in_activeProdOwnersip read only "<" as the contents of the tag

please help i need to the whole data to be read

Body:
I suspect this is what's going wrong:

new String(ch,start,length);

Here, you're passing a char[] to the String constructor, but the constructor is supposed to take a byte[]. The end result is you get a mangled String.

I suggest instead that you make the str field a StringBuilder, not a String, and then use this:

builder.append(ch,start,length);

You then need to clear the StringBuilder each time startElement() is called.


问:
Export SQL server data into a CSV file
I've just taken care of a project that requires converting data from the old website (built in C# web form) to the new one (using PHP).

In the old database, there is a product table contains 1600 products that I need to export into a CSV file then import to the new database but I have no idea to do that.

I can access the current server but I don't see any .cs file (code-behind file). I also have no idea how to export that table to a CSV file using myLittleTools (The SQL server management tool that Plesk provide).

Can any have me please?

Thank you very much.

答:
Try SQL Server Import and Export Wizard. This is a tool provided by MSSQL .

Reference links here:
https://learn.microsoft.com/en-us/sql/integration-services/import-export-data/import-and-export-data-with-the-sql-server-import-and-export-wizard

https://learn.microsoft.com/en-us/sql/integration-services/import-export-data/get-started-with-this-simple-example-of-the-import-and-export-wizard

You can export to either or excel or directly map two tables of different databases and transfer data

Title: Export SQL server data into a CSV file


问:
How to load a sublevel JSON file into DynamoDB using Boto3?
I got problems trying to load my JSON file into AWS dynamoDB with Python and Boto3, when this file have a sublevel json.

For exaple i have this code bellow:

```<code>from __future__ import print_function # Python 2/3 compatibility
import boto3

dynamodb = boto3.resource('dynamodb', region_name='sa-east-1', aws_access_key_id='AWS ACCESS KEY', aws_secret_access_key='AWS SECRET KEY')
table = dynamodb.create_table(
    TableName='Movies',
    KeySchema=[
        {
            'AttributeName': 'year',
            'KeyType': 'HASH'  #Partition key
        },
        {
            'AttributeName': 'title',
            'KeyType': 'RANGE'  #Sort key
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'year',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'title',
            'AttributeType': 'S'
        },

    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10
    }
)

print("Table status:", table.table_status)
</code>```

In this layout i create a table in AWS dynamoDB, but only for JSON on one level structure, like:

```<code>[
    {
        "year": 2013,
        "title": "Rush"
    }
]
</code>```

But if i want to put a JSON file with sublevel? How i have to create this table with Boto3? And how to input the file? like this:

```<code>[
    {
        "year": 2013,
        "title": "Rush",
        "info": {
            "directors": ["Ron Howard"],
            "release_date": "2013-09-02T00:00:00Z",
            "rating": 8.3,
            "genres": [
                "Action",
                "Biography",
                "Drama",
                "Sport"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQyMDE0MTY0OV5BMl5BanBnXkFtZTcwMjI2OTI0OQ@@._V1_SX400_.jpg",
            "plot": "A re-creation of the merciless 1970s rivalry between Formula One rivals James Hunt and Niki Lauda.",
            "rank": 2,
            "running_time_secs": 7380,
            "actors": [
                "Daniel Bruhl",
                "Chris Hemsworth",
                "Olivia Wilde"
            ]
        }
    }
]
</code>```

I read Boto3 Docs and search some tutorials on the internet, but I can not find how to do this. It should be simple, I know I must have a way to do this, but I can not get it yet. Someone have some tip for me?

答:
Using you example above, I think you can simply use the table.update_item() method.</p>

```<code>key = {'year': '2013'},{'title': 'Rush'}
attribute_name = 'info'
attribute_value = {} # build your info as a dictionary
attribute_value['directors'] = ['Ron Howard']
...

response = table.update_item(
    Key = key,
    UpdateExpression="SET " + attribute_name + " = :val",
    ExpressionAttributeValues={':val': attribute_value},
    ReturnValues="UPDATED_NEW"
)
</code>```

Body:
I got problems trying to load my JSON file into AWS dynamoDB with Python and Boto3, when this file have a sublevel json.

For exaple i have this code bellow:

from __future__ import print_function # Python 2/3 compatibility
import boto3

dynamodb = boto3.resource('dynamodb', region_name='sa-east-1', aws_access_key_id='AWS ACCESS KEY', aws_secret_access_key='AWS SECRET KEY')
table = dynamodb.create_table(
    TableName='Movies',
    KeySchema=[
        {
            'AttributeName': 'year',
            'KeyType': 'HASH'  #Partition key
        },
        {
            'AttributeName': 'title',
            'KeyType': 'RANGE'  #Sort key
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'year',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'title',
            'AttributeType': 'S'
        },

    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10
    }
)

print("Table status:", table.table_status)

In this layout i create a table in AWS dynamoDB, but only for JSON on one level structure, like:

[
    {
        "year": 2013,
        "title": "Rush"
    }
]

But if i want to put a JSON file with sublevel? How i have to create this table with Boto3? And how to input the file? like this:

[
    {
        "year": 2013,
        "title": "Rush",
        "info": {
            "directors": ["Ron Howard"],
            "release_date": "2013-09-02T00:00:00Z",
            "rating": 8.3,
            "genres": [
                "Action",
                "Biography",
                "Drama",
                "Sport"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQyMDE0MTY0OV5BMl5BanBnXkFtZTcwMjI2OTI0OQ@@._V1_SX400_.jpg",
            "plot": "A re-creation of the merciless 1970s rivalry between Formula One rivals James Hunt and Niki Lauda.",
            "rank": 2,
            "running_time_secs": 7380,
            "actors": [
                "Daniel Bruhl",
                "Chris Hemsworth",
                "Olivia Wilde"
            ]
        }
    }
]

I read Boto3 Docs and search some tutorials on the internet, but I can not find how to do this. It should be simple, I know I must have a way to do this, but I can not get it yet. Someone have some tip for me?

Body:
Using you example above, I think you can simply use the table.update_item() method.

key = {'year': '2013'},{'title': 'Rush'}
attribute_name = 'info'
attribute_value = {} # build your info as a dictionary
attribute_value['directors'] = ['Ron Howard']
...

response = table.update_item(
    Key = key,
    UpdateExpression="SET " + attribute_name + " = :val",
    ExpressionAttributeValues={':val': attribute_value},
    ReturnValues="UPDATED_NEW"
)