问:
Sparklyr - Decimal precision 8 exceeds max precision 7
I'm trying to copy a big database into Spark using spark_read_csv, but I'm getting the following error as output:

Error: org.apache.spark.SparkException: Job aborted due to stage
  failure: Task 0 in stage 16.0 failed 4 times, most recent failure:
  Lost task 0.3 in stage 16.0 (TID 176, 10.1.2.235):
  java.lang.IllegalArgumentException: requirement failed: Decimal
  precision 8 exceeds max precision 7

```<code>data_tbl <- spark_read_csv(sc, "data", "D:/base_csv", delimiter = "|", overwrite = TRUE)
</code>```

It's a big data set, about 5.8 million of records, with my dataset I have data of types Int, num and chr.

答:
I think you have a couple options depending on the spark version that you're using

Spark >=1.6.1

from here: https://docs.databricks.com/spark/latest/sparkr/functions/read.df.html
it seems, you can specifically specify your schema to force it to use doubles

```<code>csvSchema <- structType(structField("carat", "double"), structField("color", "string"))
diamondsLoadWithSchema<- read.df("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv",
                                 source = "csv", header="true", schema = csvSchema)
</code>```

Spark < 1.6.1
consider test.csv

```<code>1,a,4.1234567890
2,b,9.0987654321
</code>```

you can easily make this more efficient, but I think you get the gist

```<code>linesplit <- function(x){
  tmp <- strsplit(x,",")
  return ( tmp)
}

lineconvert <- function(x){
  arow <- x[[1]]
  converted <- list(as.integer(arow[1]), as.character(arow[2]),as.double(arow[3]))
  return (converted)
}
rdd <- SparkR:::textFile(sc,'/path/to/test.csv')
lnspl <- SparkR:::map(rdd, linesplit)
ll2 <- SparkR:::map(lnspl,lineconvert)
ddf <- createDataFrame(sqlContext,ll2)
head(ddf)

  _1 _2           _3
1  1  a 4.1234567890
2  2  b 9.0987654321
</code>```

NOTE: the SparkR::: methods are private for a reason, the docs say 'be careful when you use this'

Body:
I'm trying to copy a big database into Spark using spark_read_csv, but I'm getting the following error as output:

Error: org.apache.spark.SparkException: Job aborted due to stage
  failure: Task 0 in stage 16.0 failed 4 times, most recent failure:
  Lost task 0.3 in stage 16.0 (TID 176, 10.1.2.235):
  java.lang.IllegalArgumentException: requirement failed: Decimal
  precision 8 exceeds max precision 7

data_tbl <- spark_read_csv(sc, "data", "D:/base_csv", delimiter = "|", overwrite = TRUE)

It's a big data set, about 5.8 million of records, with my dataset I have data of types Int, num and chr.

Body:
I think you have a couple options depending on the spark version that you're using

Spark >=1.6.1

from here: https://docs.databricks.com/spark/latest/sparkr/functions/read.df.html
it seems, you can specifically specify your schema to force it to use doubles

csvSchema <- structType(structField("carat", "double"), structField("color", "string"))
diamondsLoadWithSchema<- read.df("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv",
                                 source = "csv", header="true", schema = csvSchema)

Spark < 1.6.1
consider test.csv

1,a,4.1234567890
2,b,9.0987654321

you can easily make this more efficient, but I think you get the gist

linesplit <- function(x){
  tmp <- strsplit(x,",")
  return ( tmp)
}

lineconvert <- function(x){
  arow <- x[[1]]
  converted <- list(as.integer(arow[1]), as.character(arow[2]),as.double(arow[3]))
  return (converted)
}
rdd <- SparkR:::textFile(sc,'/path/to/test.csv')
lnspl <- SparkR:::map(rdd, linesplit)
ll2 <- SparkR:::map(lnspl,lineconvert)
ddf <- createDataFrame(sqlContext,ll2)
head(ddf)

  _1 _2           _3
1  1  a 4.1234567890
2  2  b 9.0987654321

NOTE: the SparkR::: methods are private for a reason, the docs say 'be careful when you use this'


来源: stackexchange

问:
Hive - select data from group with at least one row containing
Suppose i have a table in hive like so:

```<code>|Id|Data |Data2 |Groupkey|
|1 |One  |      |Group1  |
|2 |Two  |Stuff |Group1  |
|3 |Shoes|Some  |Group2  |
|4 |four |Stuff |Group2  |
|5 |Three|Notme |Group3  |
</code>```

For each group  that contains 'Stuff' in Data2 i want to get the row that has Groupkey and Data from the row other than the Stuff, and Data2 from 'Stuff' row.

So resulting data set would look something like

```<code>|Group |Data |Data2|
|Group1|One  |Two  |
|Group2|Shoes|four |
</code>```

I was hoping to get something going with a GROUP BY, i started going with

SELECT Data, Groupkey FROM (SELECT Data, GroupKey FROM MyTable GROUP BY Groupkey) WHERE Data2 <> 'Stuff' but this fails suggesting i need to include Data in the group by but that is not what i want to group by?

And i'm not sure how to select just the groups containing one row with certain data.

答:
```<code>select      Groupkey                                            as `Group`
           ,min (case when Data2 <> 'Stuff' then Data end)      as Data
           ,min (case when Data2 =  'Stuff' then Data end)      as Data2

from        MyTable

group by    Groupkey

having      count (case when Data2 = 'Stuff' then 1 end) > 0
;
</code>```

<hr>

```<code>+--------+-------+-------+
| group  | data  | data2 |
+--------+-------+-------+
| Group1 | One   | Two   |
| Group2 | Shoes | four  |
+--------+-------+-------+
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose i have a table in hive like so:

|Id|Data |Data2 |Groupkey|
|1 |One  |      |Group1  |
|2 |Two  |Stuff |Group1  |
|3 |Shoes|Some  |Group2  |
|4 |four |Stuff |Group2  |
|5 |Three|Notme |Group3  |

For each group  that contains 'Stuff' in Data2 i want to get the row that has Groupkey and Data from the row other than the Stuff, and Data2 from 'Stuff' row.

So resulting data set would look something like

|Group |Data |Data2|
|Group1|One  |Two  |
|Group2|Shoes|four |

I was hoping to get something going with a GROUP BY, i started going with

SELECT Data, Groupkey FROM (SELECT Data, GroupKey FROM MyTable GROUP BY Groupkey) WHERE Data2 <> 'Stuff' but this fails suggesting i need to include Data in the group by but that is not what i want to group by?

And i'm not sure how to select just the groups containing one row with certain data.

Body:
select      Groupkey                                            as `Group`
           ,min (case when Data2 <> 'Stuff' then Data end)      as Data
           ,min (case when Data2 =  'Stuff' then Data end)      as Data2

from        MyTable

group by    Groupkey

having      count (case when Data2 = 'Stuff' then 1 end) > 0
;

+--------+-------+-------+
| group  | data  | data2 |
+--------+-------+-------+
| Group1 | One   | Two   |
| Group2 | Shoes | four  |
+--------+-------+-------+


问:
invalid method (createTableViewRow) passed to UIModule
i am having this error when i run my app on the device ( iPhone 7 ), but when i run it in the emulator works fine.
Its really strange.

The code is:

```<code>   Ti.API.info( json );
   var renglon = Ti.UI.createTableViewRow({
     id: id,
        width: Ti.UI.FILL,
        height: '80dp',
   });
</code>```

In the emulator works OK, but in the device i got an error, the error appears just after the json is printed in the log.

```<code>[WARN] :   Attempted to load TiUITableViewRowProxy: Could not find class definition.
[ERROR] :  Script Error {
[ERROR] :      column = 2875;
[ERROR] :      line = 1;
[ERROR] :      message = "invalid method (createTableViewRow) passed to  UIModule";
[ERROR] :      sourceURL =    "file:///var/containers/Bundle/Application/B99CA23F-183D-4C5F-A5DC-FA9CFC614186/CarWash.app/src/vistas/personal.js";
[ERROR] :      stack = "[native code]\nagregarRenglonPersonal@file:///var/containers/Bundle/Application/B99CA23F-183D-4C5F-A5DC- FA9CFC614186/CarWash.app/src/vistas/personal.js:1:2875\nonload@file:///var/contain  ers/Bundle/Application/B99CA23F-183D-4C5F-A5DC-  FA9CFC614186/CarWash.app/src/vistas/personal.js:1:3651";
[ERROR] :  }
-- End application log -------------------------------------------------------
</code>```

i'm using:

Titanium appcelerator studio build: 4.9.0.201705302345

SDK: 6.1.0GA

Thanks in advance.

答: Did you try with older sdks? If not then try this code with older sdk and still you get same error then i would like to see more code.</p>

Body:
i am having this error when i run my app on the device ( iPhone 7 ), but when i run it in the emulator works fine.
Its really strange.

The code is:

   Ti.API.info( json );
   var renglon = Ti.UI.createTableViewRow({
     id: id,
        width: Ti.UI.FILL,
        height: '80dp',
   });

In the emulator works OK, but in the device i got an error, the error appears just after the json is printed in the log.

[WARN] :   Attempted to load TiUITableViewRowProxy: Could not find class definition.
[ERROR] :  Script Error {
[ERROR] :      column = 2875;
[ERROR] :      line = 1;
[ERROR] :      message = "invalid method (createTableViewRow) passed to  UIModule";
[ERROR] :      sourceURL =    "file:///var/containers/Bundle/Application/B99CA23F-183D-4C5F-A5DC-FA9CFC614186/CarWash.app/src/vistas/personal.js";
[ERROR] :      stack = "[native code]\nagregarRenglonPersonal@file:///var/containers/Bundle/Application/B99CA23F-183D-4C5F-A5DC- FA9CFC614186/CarWash.app/src/vistas/personal.js:1:2875\nonload@file:///var/contain  ers/Bundle/Application/B99CA23F-183D-4C5F-A5DC-  FA9CFC614186/CarWash.app/src/vistas/personal.js:1:3651";
[ERROR] :  }
-- End application log -------------------------------------------------------

i'm using:

Titanium appcelerator studio build: 4.9.0.201705302345

SDK: 6.1.0GA

Thanks in advance.


问:
BFS function not returning path right
Hey guys, what's up ya'll. For this, I have to create a BFS function that finds shortest path between a destination and source for the game called Quoridor, I'm sure some of ya'll played this before. When I run it, no errors were found but I want the shortest path function to return the path as one I did in searchBFS function. Also, sorry for the sloppy post, it's my first one.

Here's the code....

```<code>from interface import *
import engine

#public routines

def init(gameFile, playerId, numPlayers, playerHomes, wallsRemaining):

"""
    For all parts the engine calls this method so the player can initialize their data.
        gameFile - a string which is the file containing the initial board state.
        playerId - the numeric Id of the player (0-4).
        numPlayers - the number of players (2 or 4).
        playerHomes - a list of coordinates for each players starting cell (PO-P4).
        wallsRemaining - the number of walls remaining (same for all players at start)."""

    # log any message string to standard output and the current log file
    engine.log_msg("player.init called for player " + str(playerId) + " File=" + gameFile +
                   ', playerId=' + str(playerId) + ', numPlayers=' + str(numPlayers) + ', playerHomes=' +
                   str(playerHomes) + ', wallsRemaining=' + str(wallsRemaining))

    playerData = None

    # initialize your data structure here, and then return it.  It will be
    # passed back to you as 'playerData' in the shortest_path function.

    return playerData

def shortest_path(playerData, source, dest):

"""Returns a list of coordinates representing the shortest path on the
    board between the start and finish coordinates.
        playerData - The player's data
        source - the start coordinate
        dest - the end coordinate"""

    engine.log_msg("player.shortest_path called.  Source: " + str(source) +
                   ", Dest: " + str(dest))

    path = []

def searchBFS(graph, source, dest):

"""Performs a BFS search between source and destination nodes using a queue.
    It returns the path as a list of graph nodes (or an empty list if no path exists)."""

    dispenser = myQueue.Queue()
    myQueue.enqueue(source, dispenser)

    #construct the visited list.

    visited = set()
    visited.add(source)

    #loop untill either the destination is found or the dispenser
    #is empty (no path)

    while not myQueue.empty(dispenser):
        current = myQueue.front(dispenser)
        myQueue.dequeue(dispenser)
        if current == dest:
            break
        # loop over all neighbors of current
        for neighbor in current.neighbors:
            # process unvisited neighbors
            if neighbor not in visited:
                neighbor.previous = current
                visited.add(neighbor)
                myQueue.enqueue(neighbor, dispenser)
    return constructPath(visited, source, dest)

def constructPath(visited, source, dest):

"""Returns the path as a list of nodes from source to destination"""

    #construct the path using a stack and traversing from the destination
    #node back to the source node using Node's previous
    stack = myStack.Stack()
    if dest in visited:
        temp = dest
        while tmp != source:
            myStack.push(tmp, stack)
            tmp = tmp.previous
        myStack.push(source, stack)

    path = []
    while not myStack.empty(stack):
        path.append(myStack.top(stack))
        myStack.pop(stack)
    return path
</code>```

答:
```<code>stack = myStack.Stack()
if dest in visited:
    temp = dest
    while tmp != source:
        myStack.push(tmp, stack)
        tmp = tmp.previous
</code>```

I think the tmp and temp variables here should be the same? Although I would expect an error since tmp isn't assigned before you use it.

ContentLicense: CC BY-SA 2.5

Title: BFS function not returning path right

Body:
Hey guys, what's up ya'll. For this, I have to create a BFS function that finds shortest path between a destination and source for the game called Quoridor, I'm sure some of ya'll played this before. When I run it, no errors were found but I want the shortest path function to return the path as one I did in searchBFS function. Also, sorry for the sloppy post, it's my first one.

Here's the code....

from interface import *
import engine

#public routines

def init(gameFile, playerId, numPlayers, playerHomes, wallsRemaining):

"""
    For all parts the engine calls this method so the player can initialize their data.
        gameFile - a string which is the file containing the initial board state.
        playerId - the numeric Id of the player (0-4).
        numPlayers - the number of players (2 or 4).
        playerHomes - a list of coordinates for each players starting cell (PO-P4).
        wallsRemaining - the number of walls remaining (same for all players at start)."""

    # log any message string to standard output and the current log file
    engine.log_msg("player.init called for player " + str(playerId) + " File=" + gameFile +
                   ', playerId=' + str(playerId) + ', numPlayers=' + str(numPlayers) + ', playerHomes=' +
                   str(playerHomes) + ', wallsRemaining=' + str(wallsRemaining))

    playerData = None

    # initialize your data structure here, and then return it.  It will be
    # passed back to you as 'playerData' in the shortest_path function.

    return playerData

def shortest_path(playerData, source, dest):

"""Returns a list of coordinates representing the shortest path on the
    board between the start and finish coordinates.
        playerData - The player's data
        source - the start coordinate
        dest - the end coordinate"""

    engine.log_msg("player.shortest_path called.  Source: " + str(source) +
                   ", Dest: " + str(dest))

    path = []

def searchBFS(graph, source, dest):

"""Performs a BFS search between source and destination nodes using a queue.
    It returns the path as a list of graph nodes (or an empty list if no path exists)."""

    dispenser = myQueue.Queue()
    myQueue.enqueue(source, dispenser)

    #construct the visited list.

    visited = set()
    visited.add(source)

    #loop untill either the destination is found or the dispenser
    #is empty (no path)

    while not myQueue.empty(dispenser):
        current = myQueue.front(dispenser)
        myQueue.dequeue(dispenser)
        if current == dest:
            break
        # loop over all neighbors of current
        for neighbor in current.neighbors:
            # process unvisited neighbors
            if neighbor not in visited:
                neighbor.previous = current
                visited.add(neighbor)
                myQueue.enqueue(neighbor, dispenser)
    return constructPath(visited, source, dest)

def constructPath(visited, source, dest):

"""Returns the path as a list of nodes from source to destination"""

    #construct the path using a stack and traversing from the destination
    #node back to the source node using Node's previous
    stack = myStack.Stack()
    if dest in visited:
        temp = dest
        while tmp != source:
            myStack.push(tmp, stack)
            tmp = tmp.previous
        myStack.push(source, stack)

    path = []
    while not myStack.empty(stack):
        path.append(myStack.top(stack))
        myStack.pop(stack)
    return path

Body:
stack = myStack.Stack()
if dest in visited:
    temp = dest
    while tmp != source:
        myStack.push(tmp, stack)
        tmp = tmp.previous

I think the tmp and temp variables here should be the same? Although I would expect an error since tmp isn't assigned before you use it.


问:
Openpyxl: How to copy a row after checking if a cell contains specific value
I have a worksheet that is updated every week with thousands of rows and would need to transfer rows from this worksheet after filtering. I am using the current code to find the cells which has the value I need and then transfer the entire row to another sheet but after saving the file, I get the "IndexError: list index out of range" exception.

The code I use is as follows:

```<code>import openpyxl

wb1 = openpyxl.load_workbook('file1.xlsx')
wb2 = openpyxl.load_workbook('file2.xlsx')

ws1 = wb1.active
ws2 = wb2.active

for row in ws1.iter_rows():
    for cell in row:
        if cell.value == 'TrueValue':
            n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
            for row2 in ws1.iter_rows(n):
                ws2.append(row2)

wb2.save("file2.xlsx")
</code>```

The original code I used that used to work is below and has to be modified because of the large files which causes MS Excel not to open them (over 40mb).

```<code>n = 'A3' + ':' + ('GH'+ str(ws1.max_row))
for row in ws1.iter_rows(n):
    ws2.append(row)
</code>```

Thanks.

答:
Question:  I get the "IndexError: list index out of range" exception.

I get, from ws1.iter_rows(n)

```<code>UserWarning: Using a range string is deprecated. Use ws[range_string]
</code>```

and from ws2.append(row2).

```<code>ValueError: Cells cannot be copied from other worksheets
</code>```

The Reason are row2 does hold a list of Cell objects instead of a list of Values

Question: ... need to transfer rows from this worksheet after filtering

The following do what you want, for instance:

```<code># If you want to Start at Row 2 to append Row Data
# Set Private self._current_row to 1
ws2.cell(row=1, column=1).value = ws2.cell(row=1, column=1).value

# Define min/max Column Range to copy
from openpyxl.utils import range_boundaries
min_col, min_row, max_col, max_row = range_boundaries('A:GH')

# Define Cell Index (0 Based) used to Check Value
check = 0 # == A

for row in ws1.iter_rows():
    if row[check].value == 'TrueValue':
        # Copy Row Values
        # We deal with Tuple Index 0 Based, so min_col must have to be -1
        ws2.append((cell.value for cell in row[min_col-1:max_col]))
</code>```

Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2

Body:
I have a worksheet that is updated every week with thousands of rows and would need to transfer rows from this worksheet after filtering. I am using the current code to find the cells which has the value I need and then transfer the entire row to another sheet but after saving the file, I get the "IndexError: list index out of range" exception.

The code I use is as follows:

import openpyxl

wb1 = openpyxl.load_workbook('file1.xlsx')
wb2 = openpyxl.load_workbook('file2.xlsx')

ws1 = wb1.active
ws2 = wb2.active

for row in ws1.iter_rows():
    for cell in row:
        if cell.value == 'TrueValue':
            n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
            for row2 in ws1.iter_rows(n):
                ws2.append(row2)

wb2.save("file2.xlsx")

The original code I used that used to work is below and has to be modified because of the large files which causes MS Excel not to open them (over 40mb).

n = 'A3' + ':' + ('GH'+ str(ws1.max_row))
for row in ws1.iter_rows(n):
    ws2.append(row)

Thanks.

Body:
Question:  I get the "IndexError: list index out of range" exception.

I get, from ws1.iter_rows(n)

UserWarning: Using a range string is deprecated. Use ws[range_string]

and from ws2.append(row2).

ValueError: Cells cannot be copied from other worksheets

The Reason are row2 does hold a list of Cell objects instead of a list of Values

Question: ... need to transfer rows from this worksheet after filtering

The following do what you want, for instance:

# If you want to Start at Row 2 to append Row Data
# Set Private self._current_row to 1
ws2.cell(row=1, column=1).value = ws2.cell(row=1, column=1).value

# Define min/max Column Range to copy
from openpyxl.utils import range_boundaries
min_col, min_row, max_col, max_row = range_boundaries('A:GH')

# Define Cell Index (0 Based) used to Check Value
check = 0 # == A

for row in ws1.iter_rows():
    if row[check].value == 'TrueValue':
        # Copy Row Values
        # We deal with Tuple Index 0 Based, so min_col must have to be -1
        ws2.append((cell.value for cell in row[min_col-1:max_col]))

Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2


问:
Is it possible to rename png files by the time of creation, not after
I am using  File[] imageFile = PdfUtilities.convertPdf2Png(new File("MYPATH")) command to generate png from pdf , which is giving file name as "workingimage01","workingimage02"...."workingimage0n" and so on, is it possible to change this name setting by the time png's are generated. Thanks in advance.
I am trying this command for 10 pdf parallel, so it is overlapping. thats why i need to know is there a way or i am asking out of the box question. </p>

答: The name is hard coded in the source. You can create an overloaded method that takes another parameter for the working files' name.</p>


问:
Checking for Int in Array . Swift 3, iOS
I have the following code:

```<code>print (sender.tag) // prints 21  (example)
print(DictPl2) // prints [0, 1, 20, 21, 84, 94, 26, 27, 37, 55, 56, 66, 52, 53, 54, 55, 72, 73, 74, 75]
var DictPl2 = [Int]()
if playeractive == 1 {
 for i in DictPl2 {
                if i == sender.tag {
                    print("Well done")
                    sender.backgroundColor = UIColor.red

                }

                else {    //always goes this
                    print("Bad")
                    sender.backgroundColor = UIColor.brown
                }
            }
</code>```

I am checking if sender.tag does equal to any of elements in array DictPl2. But if it does or doesn't equal, the code always goes the marked way. Anyone knows, what might be the mistake?
Thank you

答:
In Swift 3.2

```<code>if DictPL2.contains(where: {$0 == sender.tag) {
    print("Well done")
} else {
    print("Bad")
}
</code>```

Please check Apple Guide.

Body:
I have the following code:

print (sender.tag) // prints 21  (example)
print(DictPl2) // prints [0, 1, 20, 21, 84, 94, 26, 27, 37, 55, 56, 66, 52, 53, 54, 55, 72, 73, 74, 75]
var DictPl2 = [Int]()
if playeractive == 1 {
 for i in DictPl2 {
                if i == sender.tag {
                    print("Well done")
                    sender.backgroundColor = UIColor.red

                }

                else {    //always goes this
                    print("Bad")
                    sender.backgroundColor = UIColor.brown
                }
            }

I am checking if sender.tag does equal to any of elements in array DictPl2. But if it does or doesn't equal, the code always goes the marked way. Anyone knows, what might be the mistake?
Thank you

Body:
In Swift 3.2

if DictPL2.contains(where: {$0 == sender.tag) {
    print("Well done")
} else {
    print("Bad")
}

Please check Apple Guide.


问:
jQuery if button is not pressed
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

```<code>$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}
</code>```

Am I doing something wrong?

答:
How about:

$('#btmmdl').mousedown((function(){
    //SCROLLSDOWN
});
$('#btmmdl').mouseup((function(){
   //SHOWSANIMATION
});```

Title: jQuery if button is not pressed

Body:
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}

Am I doing something wrong?


答:
1) Why sub $0x10, %rsp?

It is actually subtracting 16 bytes, in other words, its making space for the two 'long' arguments. try printing 'sizeof(long)' and I'm pretty sure you'll get '8' as the answer on the machine you're on.

2) Why move register values to memory?

Again this is where the computer is loading the two long values from the registers 'rcx' and 'rdx' into the memory space it made in '1)'. 0x10 and 0x18 have a difference of 8 bytes.

3) Why is the return value stored in the mov  %rax,-0x8(%rbp)?

It's stored temporarily because before leaving the function, the %rax register is used for some other computations. Therefore if it was not saved it would have been over written, and you can see that after those computations are done the value is again loaded into rax.

```<code>mov%rax,-0x8(%rbp) <--- saving
jmp    0x100401114 <absdiff+52>
...
mov    %rax,-0x8(%rbp)
-0x8(%rbp),%rax" < -- retrieving
</code>```

A Suggestion

I'm pretty sure you'll find this link really helpful:

https://www.recurse.com/blog/7-understanding-c-by-learning-assembly

Title: unable to understand the base pointer calculation in assembly code

Body:
I am trying to understand the assembly code for the following function by doing a disassembler. I am unable to get why all the operations are relative to the base pointer.

Why are the register values of rcx and rdx moved to memory location offset by 10 and 18?
( mov  0x10(%rbp),%rax and mov  %rdx,0x18(%rbp) ).

Why is the return value stored in the
mov  %rax,-0x8(%rbp)

long absdiff(long x, long y)
{
    long result;
    if (x>y)
        result = x-y;
    else
        result = y-x;
    return result;
}
0x00000001004010e0 <+0>:     push   %rbp
0x00000001004010e1 <+1>:     mov    %rsp,%rbp
0x00000001004010e4 <+4>:     sub    $0x10,%rsp
0x00000001004010e8 <+8>:     mov    %rcx,0x10(%rbp)
0x00000001004010ec <+12>:    mov    %rdx,0x18(%rbp)
0x00000001004010f0 <+16>:    mov    0x10(%rbp),%rax
0x00000001004010f4 <+20>:    cmp    0x18(%rbp),%rax
0x00000001004010f8 <+24>:    jle    0x100401108 <absdiff+40>
0x00000001004010fa <+26>:    mov    0x10(%rbp),%rax
0x00000001004010fe <+30>:    sub    0x18(%rbp),%rax
0x0000000100401102 <+34>:    mov    %rax,-0x8(%rbp)
0x0000000100401106 <+38>:    jmp    0x100401114 <absdiff+52>
0x0000000100401108 <+40>:    mov    0x18(%rbp),%rax
0x000000010040110c <+44>:    sub    0x10(%rbp),%rax
0x0000000100401110 <+48>:    mov    %rax,-0x8(%rbp)
0x0000000100401114 <+52>:    mov    -0x8(%rbp),%rax
0x0000000100401118 <+56>:    add    $0x10,%rsp
0x000000010040111c <+60>:    pop    %rbp
0x000000010040111d <+61>:    retq

Body:
1) Why sub $0x10, %rsp?

It is actually subtracting 16 bytes, in other words, its making space for the two 'long' arguments. try printing 'sizeof(long)' and I'm pretty sure you'll get '8' as the answer on the machine you're on.

2) Why move register values to memory?

Again this is where the computer is loading the two long values from the registers 'rcx' and 'rdx' into the memory space it made in '1)'. 0x10 and 0x18 have a difference of 8 bytes.

3) Why is the return value stored in the mov  %rax,-0x8(%rbp)?

It's stored temporarily because before leaving the function, the %rax register is used for some other computations. Therefore if it was not saved it would have been over written, and you can see that after those computations are done the value is again loaded into rax.

mov%rax,-0x8(%rbp) <--- saving
jmp    0x100401114 <absdiff+52>
...
mov    %rax,-0x8(%rbp)
-0x8(%rbp),%rax" < -- retrieving

A Suggestion

I'm pretty sure you'll find this link really helpful:

https://www.recurse.com/blog/7-understanding-c-by-learning-assembly


问:
Can't Return String Array in VBA
I have been combing the internet for an answer to this and can't find anything. For the life of me, I can't return a string array from a function. I've tried as a variant as well, but all I get is syntax errors.</p>

```<code>Private Function set_device_list(ByVal deviceListSize As Integer) As Variant()

    Dim loopIndex As Integer
    loopIndex = 0

    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim firstColumn As Integer
    Dim lastColumn As Integer

    firstRow = 2
    lastRow = 2
    firstColumn = 4
    lastColumn = 63

    Dim deviceStartIndex As String
    Dim deviceEndIndex As String

    Dim deviceList() As Variant
    ReDim deviceList(0 To (deviceListSize - 1))

    deviceStartIndex = Cells(firstRow, firstColumn)
    deviceEndIndex = Cells(lastRow, lastColumn)

    For i = firstColumn To lastColumn

        deviceList(loopIndex) = Cells(firstRow, i).Value

        loopIndex = loopIndex + 1
        Next i
    Return deviceList

End Function
</code>```

答:
Please drop the parentheses at the end of function declaration:
"...As Variant"   not   "...As Variant()"

Try instead of "Return deviceList" enter "set_device_list = deviceList"

Title: Can't Return String Array in VBA

Body:
I have been combing the internet for an answer to this and can't find anything. For the life of me, I can't return a string array from a function. I've tried as a variant as well, but all I get is syntax errors.

Private Function set_device_list(ByVal deviceListSize As Integer) As Variant()

    Dim loopIndex As Integer
    loopIndex = 0

    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim firstColumn As Integer
    Dim lastColumn As Integer

    firstRow = 2
    lastRow = 2
    firstColumn = 4
    lastColumn = 63

    Dim deviceStartIndex As String
    Dim deviceEndIndex As String

    Dim deviceList() As Variant
    ReDim deviceList(0 To (deviceListSize - 1))

    deviceStartIndex = Cells(firstRow, firstColumn)
    deviceEndIndex = Cells(lastRow, lastColumn)

    For i = firstColumn To lastColumn

        deviceList(loopIndex) = Cells(firstRow, i).Value

        loopIndex = loopIndex + 1
        Next i
    Return deviceList

End Function


问:
Adding textbox which has an onkeyup event and display value on other textbox
I want to get the sum of the textbox which has an onkeyup event. units multiplied by grades and display its sum to the third textbox which is the a and b, after that I want to add the a and b and display the sum on the total textbox.

But it's not displaying the sum on the total textbox. I think the problem is on the onkeyup="s();">.

This is my code:

function suma(){
var unitsA = document.getElementById('unitsA').value;
var gradesA = document.getElementById('gradesA').value;
var result = parseInt(unitsA)  * parseInt(gradesA);
if (!isNaN(result)) {
document.getElementById('a').value = result;
}
}

function sumb(){
var unitsB = document.getElementById('unitsB').value;
var gradeB = document.getElementById('gradeB').value;
var result = parseInt(unitsB)  * parseInt(gradeB);
if (!isNaN(result)) {
document.getElementById('b').value = result;
}
}
function s(){
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var result = parseInt(a)  + parseInt(b);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text"  id="unitsA"/>
<input type="text"  id="gradeA"  onkeyup="suma();"/>
<input type="text"  id="a" name="a" size="7" onkeyup="s();"/>

<input type="text"  id="unitsB"/>
<input type="text"  id="gradeB"  onkeyup="sumb();"/>
<input type="text"  id="b" name="b" size="7" onkeyup="s();"/>
<input type="text"  id="total" readonly="readonly" /></code>```

答:
you are using wrong id name, this code works:

function suma(){
var unitsA = document.getElementById('unitsA').value;
var gradesA = document.getElementById('gradesA').value;
var result = parseInt(unitsA)  * parseInt(gradesA);
if (!isNaN(result)) {
document.getElementById('a').value = result;
s();
}
}

function sumb(){
var unitsB = document.getElementById('unitsB').value;
var gradeB = document.getElementById('gradeB').value;
var result = parseInt(unitsB)  * parseInt(gradeB);
if (!isNaN(result)) {
document.getElementById('b').value = result;
s();
}
}
function s(){
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var result = parseInt(a)  + parseInt(b);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text"  id="unitsA"/>
<input type="text"  id="gradesA"  onkeyup="suma();"/>
<input type="text"  id="a" name="a" size="7" onchange="s();"/>

<input type="text"  id="unitsB"/>
<input type="text"  id="gradeB"  onkeyup="sumb();"/>
<input type="text"  id="b" name="b" size="7" onchange="s();"/>
<input type="text"  id="total" readonly="readonly" /></code>```

Body:
I want to get the sum of the textbox which has an onkeyup event. units multiplied by grades and display its sum to the third textbox which is the a and b, after that I want to add the a and b and display the sum on the total textbox.

But it's not displaying the sum on the total textbox. I think the problem is on the onkeyup="s();">.

This is my code:

function suma(){
var unitsA = document.getElementById('unitsA').value;
var gradesA = document.getElementById('gradesA').value;
var result = parseInt(unitsA)  * parseInt(gradesA);
if (!isNaN(result)) {
document.getElementById('a').value = result;
}
}

function sumb(){
var unitsB = document.getElementById('unitsB').value;
var gradeB = document.getElementById('gradeB').value;
var result = parseInt(unitsB)  * parseInt(gradeB);
if (!isNaN(result)) {
document.getElementById('b').value = result;
}
}
function s(){
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var result = parseInt(a)  + parseInt(b);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}

<input type="text"  id="unitsA"/>
<input type="text"  id="gradeA"  onkeyup="suma();"/>
<input type="text"  id="a" name="a" size="7" onkeyup="s();"/>

<input type="text"  id="unitsB"/>
<input type="text"  id="gradeB"  onkeyup="sumb();"/>
<input type="text"  id="b" name="b" size="7" onkeyup="s();"/>
<input type="text"  id="total" readonly="readonly" />

Body:
you are using wrong id name, this code works:

function suma(){
var unitsA = document.getElementById('unitsA').value;
var gradesA = document.getElementById('gradesA').value;
var result = parseInt(unitsA)  * parseInt(gradesA);
if (!isNaN(result)) {
document.getElementById('a').value = result;
s();
}
}

function sumb(){
var unitsB = document.getElementById('unitsB').value;
var gradeB = document.getElementById('gradeB').value;
var result = parseInt(unitsB)  * parseInt(gradeB);
if (!isNaN(result)) {
document.getElementById('b').value = result;
s();
}
}
function s(){
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var result = parseInt(a)  + parseInt(b);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}

<input type="text"  id="unitsA"/>
<input type="text"  id="gradesA"  onkeyup="suma();"/>
<input type="text"  id="a" name="a" size="7" onchange="s();"/>

<input type="text"  id="unitsB"/>
<input type="text"  id="gradeB"  onkeyup="sumb();"/>
<input type="text"  id="b" name="b" size="7" onchange="s();"/>
<input type="text"  id="total" readonly="readonly" />


问:
Get property value from xml file in Jenkinsfile
I have a Jenkinsfile in which I need a property from my .csproj file (dotnet core project)

I have tried this:

def versionPrefix =  sh(script: 'cat ./src/project.csproj | grep (?<=<VersionPrefix>).*(?=</VersionPrefix>)')

I know I'm probably far off, so I'm not necessarily looking for something close to this, but I am looking for a solution not requiring plugins (preferably).

答:
Have a look at the Groovy library called "XmlSlurper" which could be helfpul for you.

It was not allowed in Jenkins pipelines but that issue was resolved some time ago! Someone tried to do similar things here.

Hope this helps!


问:
Radio groups in MFC

How can I group several mfc radio boxes into a single group?

Is it possible to bind a variable (preferably integer indicating the checked radio or boolean array) to such group. By binding I mean using DDX_*.

答:
The radio buttons must be adjacent in Tab order. The tab order is editable from Visual Studio's Dialog Editor (Find a 'Tab Order' menu item, Ctrl-D was the shortcut in VS 2005). Then you have to arrange the radio buttons by clicking them in order. For the first radio button in the tab group you have to set its Group property to True. You should also select the control that follows your group of radio buttons and set its Group property to True too. This way the radio buttons will form a group and will behave as expected (check to see how the keyboard arrows work when some of the radio buttons has the focus).

You can bind the set of radio buttons after configuring them as above via DDX_Radio macro. See: http://msdn.microsoft.com/en-US/library/fchz3yh5(v=VS.80).aspx

Title: Radio groups in MFC


问:
Deploy to JBoss Fuse from Nexus using Jenkins
I am looking for some guidance to deploy maven artifacts from nexus to JBoss Fuse 6.2. The few references i got was using fabric, and we are not using fabric in our current project. Jenkins to Nexus was easy. I would like to get some pointers on deploying from nexus to Fuse without using fabric profiles.</p>

答:
The JBoss Fuse documentation should have a section on setting you JBoss Fuse to point to your Nexus repository (maven repo) in the configuration files. Then you can deploy your application from Fuse/Karaf shell where you can then do install via osgi:install mvn:groupId/artifactId:version in the console.

For example
https://access.redhat.com/documentation/en-us/red_hat_jboss_fuse/6.3/html/deploying_into_apache_karaf/esbdeploylocate

https://access.redhat.com/documentation/en-us/red_hat_jboss_fuse/6.3/html/deploying_into_apache_karaf/ESBDeployLocateRunTime#Locate-RunTime-HttpProxy

You can either configure this in your local m2 settings.xml file, or instead configure JBoss Fuse server (karaf) with the url to your own nexus repo. You can find the configuration files in the etc directory.


问:
Regext for the following
I am to get the following results as an extract from google sheets using Regex

If I have the following 2 field items:

S01_123_123_123

S02_1_123_123_123

I want to extract

S01

S02_1

I have tried the following formulas:

=iferror(sort(unique(arrayformula(REGEXEXTRACT(Sheet!A$2:A,"^(.*?)_")))))
This gives:

S01

S02

```<code>=iferror(sort(unique(arrayformula(REGEXEXTRACT(Sheet!A$2:A,"^z.*?_")))))
</code>```

S01_

S02_

Running out of ideas now. I have even tried non grouping (?:_) with and OR "|" but that doesn't seem to do anything.

答:
You may use

```<code>^(.*?)(?:_[^_]+){3}$
</code>```

The part inside the capturing parentheses will be returned by the REGEXEXTRACT function.

Pattern details

^ - start of string

(.*?) - any 0+ chars as few as possible since *? is a lazy quantifier

(?:_[^_]+){3} - exactly three consecutive occurrences of

_ - an underscore

[^_]+ - one or more symbols other than _

$ - end of string.

Title: Regext for the following

Body:
I am to get the following results as an extract from google sheets using Regex

If I have the following 2 field items:

S01_123_123_123

S02_1_123_123_123

I want to extract

S01

S02_1

I have tried the following formulas:

=iferror(sort(unique(arrayformula(REGEXEXTRACT(Sheet!A$2:A,"^(.*?)_")))))
This gives:

S01

S02

=iferror(sort(unique(arrayformula(REGEXEXTRACT(Sheet!A$2:A,"^z.*?_")))))

S01_

S02_

Running out of ideas now. I have even tried non grouping (?:_) with and OR "|" but that doesn't seem to do anything.

Body:
You may use

^(.*?)(?:_[^_]+){3}$

The part inside the capturing parentheses will be returned by the REGEXEXTRACT function.

Pattern details

^ - start of string

(.*?) - any 0+ chars as few as possible since *? is a lazy quantifier

(?:_[^_]+){3} - exactly three consecutive occurrences of

_ - an underscore

[^_]+ - one or more symbols other than _

$ - end of string.


问:
Execute php before redirect in a wordpress template
I have the following code thrown into a wordpress template page, which works, but how can I execute this link (with its loaded PHP paramaters) on page load instead of on click?</p>

```<code><?php
$current_user = wp_get_current_user();

echo ('<a href=https://portal.pension-resources.com/sso?u='.
$current_user->user_email .'>PRI LINK</a>');

?>
</code>```

答:
Use wp_redirect()

```<code>wp_redirect( $url );
exit;
</code>```

Body:
I have the following code thrown into a wordpress template page, which works, but how can I execute this link (with its loaded PHP paramaters) on page load instead of on click?

<?php
$current_user = wp_get_current_user();

echo ('user_email .'>PRI LINK');

?>

Body:
Use wp_redirect()

wp_redirect( $url );
exit;


答:
Just use set_device_list = deviceList, this is the vba equivalent to the return expression of most c like languages.

To assign it to a string array, do this:

```<code>Dim myArray() As String
Dim device_list() as Variant

device_list = set_device_list(yourNumber)

For i = 1 To UBound(device_list)
  myArray(i) = CStr(device_list(i))
Next
</code>```

Title: Can't Return String Array in VBA

Body:
Just use set_device_list = deviceList, this is the vba equivalent to the return expression of most c like languages.

To assign it to a string array, do this:

Dim myArray() As String
Dim device_list() as Variant

device_list = set_device_list(yourNumber)

For i = 1 To UBound(device_list)
  myArray(i) = CStr(device_list(i))
Next


问:
Microsoft Edge: How to handle placeholder with text-align bug
There is a bug in Edge where empty input fields with a placeholder attribute ignore the text-align property.

https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/4468563/

https://connect.microsoft.com/IE/feedback/details/1743283/microsoft-edge-placeholder-with-text-align-right-bug

Live demo: http://jsfiddle.net/z4fkev4v/

```<code><h3>text-align: right</h3>
<input class="right" type="text" />
<input class="right" type="text" placeholder="wrong cursor alignment" />

.right {
text-align: right;
}
</code>```

Is there any solution to fix this issue?

答:
You can use JS to remove the placeholder on focus:

```<code>   $(function () {
        $("#TextBox1").focusin(function () {
            $(this).attr("placeholder", "");
        });

        $("#TextBox1").focusout(function () {
            var txtval = $(this).val();
            if (txtval == "") {
                $(this).attr("placeholder", "please input any words");
            }
        });
    })
</code>```

source : https://forums.asp.net/t/2065367.aspx?Microsoft+Edge+center+align+input+cursor+on+focus

Body:
There is a bug in Edge where empty input fields with a placeholder attribute ignore the text-align property.

https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/4468563/

https://connect.microsoft.com/IE/feedback/details/1743283/microsoft-edge-placeholder-with-text-align-right-bug

Live demo: http://jsfiddle.net/z4fkev4v/

text-align: right

<input class="right" type="text" />
<input class="right" type="text" placeholder="wrong cursor alignment" />

.right {
text-align: right;
}

Is there any solution to fix this issue?

Body:
You can use JS to remove the placeholder on focus:

   $(function () {
        $("#TextBox1").focusin(function () {
            $(this).attr("placeholder", "");
        });

        $("#TextBox1").focusout(function () {
            var txtval = $(this).val();
            if (txtval == "") {
                $(this).attr("placeholder", "please input any words");
            }
        });
    })

source : https://forums.asp.net/t/2065367.aspx?Microsoft+Edge+center+align+input+cursor+on+focus


答:
```<code><?php

if (!isset($_GET["u"])) {
    $current_user = wp_get_current_user();

    //check to see if u is the same as current user's email
    if ($current_user->user_email !== $_GET['u']) {
        wp_redirect("https://portal.pension-resources.com/sso?u=".$current_user->user_email);
        exit;
    }
}
</code>```

ideally, you will need to wrap this header redirect function inside a if condition check to prevent an infinite loop.

Title: Execute php before redirect in a wordpress template

Body:
<?php

if (!isset($_GET["u"])) {
    $current_user = wp_get_current_user();

    //check to see if u is the same as current user's email
    if ($current_user->user_email !== $_GET['u']) {
        wp_redirect("https://portal.pension-resources.com/sso?u=".$current_user->user_email);
        exit;
    }
}

ideally, you will need to wrap this header redirect function inside a if condition check to prevent an infinite loop.


问:
How to add a transition for a slide show?
I wanted to add a transition for the slide show which i am making for one of my page..

Here is the code,

        var index= 1;

        var toggle=0;

        function plusIndex(n){
         index = index + n;
         showImage(n);
        }
        showImage(1);

        function showImage(n){
        var i;
        var x = document.getElementsByClassName("placestovisit");
        if (index > x.length) {index=1};
        if (index < 1) {index= x.length};
        for (i=0; i<x.length; i++)
        {
          x[i].style.display="none";
        }
            x[index-1].style.display= "block";
        }

        autoSlide();
        function autoSlide(){
        if (toggle) {return};
        var i;
        var x = document.getElementsByClassName("placestovisit");
        for (i=0; i<x.length; i++)
        {
          x[i].style.display="none";
        }
        if (index > x.length) {index = 1};
            x[index-1].style.display= "block";
        index++;
        setTimeout(autoSlide, 4000);
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <body style="height:100%;">

<div id="placescontainer">
<div class="placestovisit fade">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/Hanumangundi_Falls.jpg/1200px-Hanumangundi_Falls.jpg" alt="" />
      <h1>Hanumanagundi Falls</h1>
      <h2 > Suthanabbe Falls or Hanumanagundi Falls is located in the hilly surroundings of the Kudremukh National Park in the Chikkamagaluru district of Karnataka, India.
Suthanabbe Falls is located between Karkala and Lakya dam in the Kudremukh national park. The water falls from a height of 22 meters creating a scenic surroundings around it.</h2>
</div>

<div class="placestovisit fade">
      <img src="https://upload.wikimedia.org/wikipedia/commons/4/4b/Hampi_virupaksha_temple.jpg" alt="" />
      <h1> Hambi(Hambe) </h1>
          <h2> Hampi (Hampe) is a village and temple town recognised as a UNESCO World Heritage Site, listed as the Group of Monuments at Hampi. in northern Karnataka, India. It was one of the richest and largest cities in the world during its prime. It is located within the ruins of the city of Vijayanagara, the former capital of the Vijayanagara Empire. Predating the city of Vijayanagara, Hampi continues to be an important religious centre, housing the Virupaksha Temple and several other monuments belonging to the old city. According to statistics of 2014, Hampi is the most searched historical place in Karnataka on Google.</h2>
</div>
<div class="placestovisit w3-animate-fading">
      <img src="http://www.thebetterindia.com/wp-content/uploads/2012/09/IMG_0750-Com-800x533.jpg" alt="" />
      <h1> Agumbe </h1>
          <h2> Agumbe is a hill station which can be reached by bikes or cars. The way to this place is a diversion from Parkala (The diversion is just a few kms from DT). The best part of the trip to Agumbe is the ride. Beautiful sceneries on both sides will keep company all along the way. This place is abount 45 km from Manipal. Agumbe is one of the highest peaks of the Western Ghats located about 60kms from Udupi. Situated at a height of 830 metres from sea level, it overlooks the Arabian Sea. Agumbe is part of the Shimoga district which is a neighboring district of Udupi. </h2>
</div>

<div class="placestovisit fade">
      <img src="https://d28dwf34zswvrl.cloudfront.net/wp-content/uploads/2017/01/kerala-carbon-neutral-panchayat.jpg" alt="" />
      <h1> Kerala </h1>
          <h2> The border of Kerala is just 75 km from Manipal. The 300-year-old Bekal Fort, shaped like a giant key-hole, is one of the largest and best-preserved forts in Kerala. Surrounded by a splendid beach, the historic Bekal Fort offers a superb view of the Arabian Sea from its tall observation towers, where a few centuries ago huge cannons used to be placed. Today, it is one of the favourite spots for film-makers because the Bekal Fort and its surroundings with backwaters and hilly destinations make fascinating locales. This fort was made by Tipu Sultan and is built right next to the sea. The popular song 'Tu Hi Re' was picturised with this fort in the backdrop.</h2>
</div>

<div class="placestovisit fade">
      <img src="http://udupitoday.com/udtoday/images/uploads/January/images/jan1431attur1.jpg" alt="" />
      <h1> Attur church </h1>
          <h2> Attur Church situated in the outskirts of Karkala town in Karnataka state — India. It is situated 58 km from Mangalore.
Placed amidst placid greenery, the Attur-Karkala parish has a rich history with its origin tracing back to 1759. Moreover it is known for its miraculous history. Miracle, history, beauty, social activities, all bundled into one.
Unlike others, the church is a place of worship and belief for all, irrespective of caste and creed. An vidence for universal peace and brotherhood. People from all walks of the society come here to offer their prayers to St Lawrence</h2>
</div>
<button class="btn" onclick="plusIndex(-1)" id="btn1"> ❮</button>
<button class="btn"  onclick="plusIndex(1)" id="btn2"> ❯</button>

<button class="play"  onclick="toggle=1-toggle; autoSlide()" id="btn3">  Play/Pause </button>

</div>

    </body></code>```

Fiddle Demo

I am newbie to javascript as well as css.

The above works properly, which out transition offline, I dont know what is the problem in fiddle. I think that there is some small misunderstanding, with that..

Could any one help me in adding a slide transition.

I need something like the link http://www.devtrix.net/sliderman/examples.html

答:
The problem is that you are swapping the css display property to display: none, which is instantly making the div invisible, not waiting for any fades.

Instead of turning the display on/off at once, try fadeOut:

```<code>fadeOut("slow", function () {
$(this).css({display:"none"});
});
</code>```

The difference is that the second parameter of fadeOut is a callback function which runs after the fadeout is completed.

Body:
I wanted to add a transition for the slide show which i am making for one of my page..

Here is the code,

        var index= 1;

        var toggle=0;

        function plusIndex(n){
         index = index + n;
         showImage(n);
        }
        showImage(1);

        function showImage(n){
        var i;
        var x = document.getElementsByClassName("placestovisit");
        if (index > x.length) {index=1};
        if (index < 1) {index= x.length};
        for (i=0; i<x.length; i++)
        {
          x[i].style.display="none";
        }
            x[index-1].style.display= "block";
        }

        autoSlide();
        function autoSlide(){
        if (toggle) {return};
        var i;
        var x = document.getElementsByClassName("placestovisit");
        for (i=0; i<x.length; i++)
        {
          x[i].style.display="none";
        }
        if (index > x.length) {index = 1};
            x[index-1].style.display= "block";
        index++;
        setTimeout(autoSlide, 4000);
        }

Hanumanagundi Falls

 Suthanabbe Falls or Hanumanagundi Falls is located in the hilly surroundings of the Kudremukh National Park in the Chikkamagaluru district of Karnataka, India.
Suthanabbe Falls is located between Karkala and Lakya dam in the Kudremukh national park. The water falls from a height of 22 meters creating a scenic surroundings around it.

 Hambi(Hambe)

 Hampi (Hampe) is a village and temple town recognised as a UNESCO World Heritage Site, listed as the Group of Monuments at Hampi. in northern Karnataka, India. It was one of the richest and largest cities in the world during its prime. It is located within the ruins of the city of Vijayanagara, the former capital of the Vijayanagara Empire. Predating the city of Vijayanagara, Hampi continues to be an important religious centre, housing the Virupaksha Temple and several other monuments belonging to the old city. According to statistics of 2014, Hampi is the most searched historical place in Karnataka on Google.

 Agumbe

 Agumbe is a hill station which can be reached by bikes or cars. The way to this place is a diversion from Parkala (The diversion is just a few kms from DT). The best part of the trip to Agumbe is the ride. Beautiful sceneries on both sides will keep company all along the way. This place is abount 45 km from Manipal. Agumbe is one of the highest peaks of the Western Ghats located about 60kms from Udupi. Situated at a height of 830 metres from sea level, it overlooks the Arabian Sea. Agumbe is part of the Shimoga district which is a neighboring district of Udupi.

 Kerala

 The border of Kerala is just 75 km from Manipal. The 300-year-old Bekal Fort, shaped like a giant key-hole, is one of the largest and best-preserved forts in Kerala. Surrounded by a splendid beach, the historic Bekal Fort offers a superb view of the Arabian Sea from its tall observation towers, where a few centuries ago huge cannons used to be placed. Today, it is one of the favourite spots for film-makers because the Bekal Fort and its surroundings with backwaters and hilly destinations make fascinating locales. This fort was made by Tipu Sultan and is built right next to the sea. The popular song 'Tu Hi Re' was picturised with this fort in the backdrop.

 Attur church

 Attur Church situated in the outskirts of Karkala town in Karnataka state — India. It is situated 58 km from Mangalore.
Placed amidst placid greenery, the Attur-Karkala parish has a rich history with its origin tracing back to 1759. Moreover it is known for its miraculous history. Miracle, history, beauty, social activities, all bundled into one.
Unlike others, the church is a place of worship and belief for all, irrespective of caste and creed. An vidence for universal peace and brotherhood. People from all walks of the society come here to offer their prayers to St Lawrence

<button class="btn" onclick="plusIndex(-1)" id="btn1"> ❮</button>
<button class="btn"  onclick="plusIndex(1)" id="btn2"> ❯</button>

<button class="play"  onclick="toggle=1-toggle; autoSlide()" id="btn3">  Play/Pause </button>

Fiddle Demo

I am newbie to javascript as well as css.

The above works properly, which out transition offline, I dont know what is the problem in fiddle. I think that there is some small misunderstanding, with that..

Could any one help me in adding a slide transition.

I need something like the link http://www.devtrix.net/sliderman/examples.html

Body:
The problem is that you are swapping the css display property to display: none, which is instantly making the div invisible, not waiting for any fades.

Instead of turning the display on/off at once, try fadeOut:

fadeOut("slow", function () {
$(this).css({display:"none"});
});

The difference is that the second parameter of fadeOut is a callback function which runs after the fadeout is completed.


问:
Why do all elements of a python dictionary change in the same way when only one element is given a value?
Can anyone explain this?  Why are all elements of yeartonametolist affected when I just change one?

```<code>yeartonametolist = dict.fromkeys(range(2007,2017),{})
yeartonametolist[2007]["a"] = 1
yeartonametolist[2008]["b"] = 2
print yeartonametolist
</code>```

Output:

```<code>{
  2016: {'a': 1, 'b': 2},
  2007: {'a': 1, 'b': 2},
  2008: {'a': 1, 'b': 2},
  2009: {'a': 1, 'b': 2},
  2010: {'a': 1, 'b': 2},
  2011: {'a': 1, 'b': 2},
  2012: {'a': 1, 'b': 2},
  2013: {'a': 1, 'b': 2},
  2014: {'a': 1, 'b': 2},
  2015: {'a': 1, 'b': 2}
}
</code>```

答:
It looks like they have same memory address, so modifying one modifies them all, and this is because they are a only reference.

Here is a better explanation:

Your first line creates your object with integers keys and empty object as a value for all of them.

```<code>yeartonametolist = dict.fromkeys(range(2007,2017),{})
</code>```

Now at this point, if you use the id() function like this

```<code>id(yeartonametolist[2016]) #4294024972L
id(yeartonametolist[2015]) #4294024972L
</code>```

It is the same id, so if you do

```<code>yeartonametolist[2007]["a"] = 1
yeartonametolist[2008]["b"] = 2
</code>```

you are changing the same object.

You can see it as well if you change the {} to object()

```<code>test = dict.fromkeys(range(2007,2017), object() )
print test
</code>```

Output:

```<code>{
 2016: <object object at 0xfff964d8>,
 2007: <object object at 0xfff964d8>,
 2008: <object object at 0xfff964d8>,
 2009: <object object at 0xfff964d8>,
 2010: <object object at 0xfff964d8>,
 2011: <object object at 0xfff964d8>,
 2012: <object object at 0xfff964d8>,
 2013: <object object at 0xfff964d8>,
 2014: <object object at 0xfff964d8>,
 2015: <object object at 0xfff964d8>
}
</code>```

The value for each key points to the same memory address.

Body:
Can anyone explain this?  Why are all elements of yeartonametolist affected when I just change one?

yeartonametolist = dict.fromkeys(range(2007,2017),{})
yeartonametolist[2007]["a"] = 1
yeartonametolist[2008]["b"] = 2
print yeartonametolist

Output:

{
  2016: {'a': 1, 'b': 2},
  2007: {'a': 1, 'b': 2},
  2008: {'a': 1, 'b': 2},
  2009: {'a': 1, 'b': 2},
  2010: {'a': 1, 'b': 2},
  2011: {'a': 1, 'b': 2},
  2012: {'a': 1, 'b': 2},
  2013: {'a': 1, 'b': 2},
  2014: {'a': 1, 'b': 2},
  2015: {'a': 1, 'b': 2}
}

Body:
It looks like they have same memory address, so modifying one modifies them all, and this is because they are a only reference.

Here is a better explanation:

Your first line creates your object with integers keys and empty object as a value for all of them.

yeartonametolist = dict.fromkeys(range(2007,2017),{})

Now at this point, if you use the id() function like this

id(yeartonametolist[2016]) #4294024972L
id(yeartonametolist[2015]) #4294024972L

It is the same id, so if you do

yeartonametolist[2007]["a"] = 1
yeartonametolist[2008]["b"] = 2

you are changing the same object.

You can see it as well if you change the {} to object()

test = dict.fromkeys(range(2007,2017), object() )
print test

Output:

{
 2016: <object object at 0xfff964d8>,
 2007: <object object at 0xfff964d8>,
 2008: <object object at 0xfff964d8>,
 2009: <object object at 0xfff964d8>,
 2010: <object object at 0xfff964d8>,
 2011: <object object at 0xfff964d8>,
 2012: <object object at 0xfff964d8>,
 2013: <object object at 0xfff964d8>,
 2014: <object object at 0xfff964d8>,
 2015: <object object at 0xfff964d8>
}

The value for each key points to the same memory address.


问:
send data from ajax to controller codeigniter
I'm trying to send data from javascript to function in controller with ajax. But ajax wont send. I post my code below:

In javascript function

```<code>var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    url: base_url + "Front_end_controller/eventi",
    method: 'POST',
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    }
});
</code>```

In controller

```<code>public function eventi()
{
    $day = $this->input->post('date');
    var_dump($day);
}
</code>```

答:
I suspect that you miss something. Add the error callback in the ajax function:

```<code>var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    url: base_url + "Front_end_controller/eventi",
    method: 'POST',
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    },
    error:function(result) {
        console.log(result);
    }
});
</code>```

Now, check your console for the error.
It could be an error on the route too (check the /application/config/routes.php too).

Body:
I'm trying to send data from javascript to function in controller with ajax. But ajax wont send. I post my code below:

In javascript function

var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    url: base_url + "Front_end_controller/eventi",
    method: 'POST',
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    }
});

In controller

public function eventi()
{
    $day = $this->input->post('date');
    var_dump($day);
}

Body:
I suspect that you miss something. Add the error callback in the ajax function:

var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    url: base_url + "Front_end_controller/eventi",
    method: 'POST',
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    },
    error:function(result) {
        console.log(result);
    }
});

Now, check your console for the error.
It could be an error on the route too (check the /application/config/routes.php too).


问:
Cassandra tombstones can't be cleared
We have a Cassandra cluster in production that can't stop loging WARN and ERRORS like this :

```<code>WARN [ReadStage:290753] 2016-04-22 17:00:06,461 SliceQueryFilter.java (line 231) Read 101 live and 33528 tombstone cells in keyspace.tablespace.Events_event_type_idx (see tombstone_warn_threshold). 100 columns was requested, slices=[5347432d45504a2d3535373639333936:2016/04/22 16\:46\:24.186-COMMANDE-ORDER-201655769396001-]

ERROR [ReadStage:290744] 2016-04-22 17:00:07,556 SliceQueryFilter.java (line 206) Scanned over 100000 tombstones in crm.Events.Events_event_type_idx; query aborted (see tombstone_failure_threshold)

ERROR [ReadStage:290729] 2016-04-22 17:00:18,708 SliceQueryFilter.java (line 206) Scanned over 100000 tombstones in crm.Events.Events_event_type_idx; query aborted (see tombstone_failure_threshold)

ERROR [ReadStage:290729] 2016-04-22 17:00:18,709 CassandraDaemon.java (line 258) Exception in thread Thread[ReadStage:290729,5,main]
java.lang.RuntimeException: org.apache.cassandra.db.filter.TombstoneOverwhelmingException
at org.apache.cassandra.service.StorageProxy$DroppableRunnable.run(StorageProxy.java:2016)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.cassandra.db.filter.TombstoneOverwhelmingException
at    org.apache.cassandra.db.filter.SliceQueryFilter.collectReducedColumns(SliceQueryFilter.java:208)
at org.apache.cassandra.db.filter.QueryFilter.collateColumns(QueryFilter.java:122)
at org.apache.cassandra.db.filter.QueryFilter.collateOnDiskAtom(QueryFilter.java:80)
.
.
.

ERROR [ReadStage:290751] 2016-04-22 17:00:30,771 SliceQueryFilter.java (line 206) Scanned over 100000 tombstones in crm.Events.Events_event_type_idx; query aborted (see tombstone_failure_threshold)
</code>```

The setup is : Cassandra 2.0.15, 4 Nodes, Replication 3.
There is no TTL on the data inside this tablespace and de gc_grace was set to 0.

We actually do 'maintenance' every weeks which consist of :

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

logfile="/var/log/cassandra/maintenance.log"
echo "----------------------------------------" >> $logfile
echo "$(date) Cassandra cluster maintenance started." >> $logfile
echo "----------------------------------------" >> $logfile

nodetool -h localhost setcompactionthroughput 999
echo "$(date)  Cassandra scrub started." >> $logfile
nodetool -h localhost scrub
echo "$(date)  Cassandra scrub completed." >> $logfile
echo "$(date)  Cassandra repair started." >> $logfile
nodetool -h localhost repair --partitioner-range
echo "$(date)  Cassandra repair completed." >> $logfile
echo "$(date)  Cassandra compaction started." >> $logfile
nodetool -h localhost compact
echo "$(date)  Cassandra compaction completed." >> $logfile
echo "$(date)  Cassandra cleanup started." >> $logfile
nodetool -h localhost cleanup
echo "$(date)  Cassandra cleanup completed." >> $logfile

nodetool -h localhost setcompactionthroughput 16

dt=$SECONDS
ds=$((dt % 60))
dm=$(((dt / 60) % 60))
dh=$((dt / 3600))
printf 'Total Run Time : %d:%02d:%02d' $dh $dm $ds >> $logfile
</code>```

This 'maintenance' does not solve the problem, we tried to do specific actions on the particular Tablespace but it ain't done much.

We tried to set the gc_grace to a higher value then lunch the maintenance script but we had the same result.
I know this is nor really an error but a protection to keep good performances on Cassandra but we are kind in the blur for this one.

Our next step is to dump the entiere tablespace, drop it and then recreate but it seems to be a bit radical for a cluster in production.

Does anyone know what could go wrong for the tombstones cleanup ?

Thanks,

Regards

答:
It has been a long time but ..
After facing the same problem on different cluster there can be multiple source for this type of problem.

It can be because :
- You are deleting / modifying rows at a higher rate than your actual gc_grace and repair combos.
- Compaction can't get thought and your tombstones are never cleared.

Usually this error don't show up if your data model is well structured, most of the time people use Cassandra the same way they'll do with a typical relational database.

Like @JeffJirsa said earlier there is no need to do manual compaction because it will stop the compaction automatically made by Cassandra. TO make them happen again you'll have to restart your node.

The solution here was to lower gc_grace and to do repair more often (should occurs more often that the gc_grace value to avoid problem with resiliency)
Unfortunately, this is not the best solutions which will be to totally remodel the data.

Title: Cassandra tombstones can't be cleared

Body:
We have a Cassandra cluster in production that can't stop loging WARN and ERRORS like this :

WARN [ReadStage:290753] 2016-04-22 17:00:06,461 SliceQueryFilter.java (line 231) Read 101 live and 33528 tombstone cells in keyspace.tablespace.Events_event_type_idx (see tombstone_warn_threshold). 100 columns was requested, slices=[5347432d45504a2d3535373639333936:2016/04/22 16\:46\:24.186-COMMANDE-ORDER-201655769396001-]

ERROR [ReadStage:290744] 2016-04-22 17:00:07,556 SliceQueryFilter.java (line 206) Scanned over 100000 tombstones in crm.Events.Events_event_type_idx; query aborted (see tombstone_failure_threshold)

ERROR [ReadStage:290729] 2016-04-22 17:00:18,708 SliceQueryFilter.java (line 206) Scanned over 100000 tombstones in crm.Events.Events_event_type_idx; query aborted (see tombstone_failure_threshold)

ERROR [ReadStage:290729] 2016-04-22 17:00:18,709 CassandraDaemon.java (line 258) Exception in thread Thread[ReadStage:290729,5,main]
java.lang.RuntimeException: org.apache.cassandra.db.filter.TombstoneOverwhelmingException
at org.apache.cassandra.service.StorageProxy$DroppableRunnable.run(StorageProxy.java:2016)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.cassandra.db.filter.TombstoneOverwhelmingException
at    org.apache.cassandra.db.filter.SliceQueryFilter.collectReducedColumns(SliceQueryFilter.java:208)
at org.apache.cassandra.db.filter.QueryFilter.collateColumns(QueryFilter.java:122)
at org.apache.cassandra.db.filter.QueryFilter.collateOnDiskAtom(QueryFilter.java:80)
.
.
.

ERROR [ReadStage:290751] 2016-04-22 17:00:30,771 SliceQueryFilter.java (line 206) Scanned over 100000 tombstones in crm.Events.Events_event_type_idx; query aborted (see tombstone_failure_threshold)

The setup is : Cassandra 2.0.15, 4 Nodes, Replication 3.
There is no TTL on the data inside this tablespace and de gc_grace was set to 0.

We actually do 'maintenance' every weeks which consist of :

#!/bin/bash

logfile="/var/log/cassandra/maintenance.log"
echo "----------------------------------------" >> $logfile
echo "$(date) Cassandra cluster maintenance started." >> $logfile
echo "----------------------------------------" >> $logfile

nodetool -h localhost setcompactionthroughput 999
echo "$(date)  Cassandra scrub started." >> $logfile
nodetool -h localhost scrub
echo "$(date)  Cassandra scrub completed." >> $logfile
echo "$(date)  Cassandra repair started." >> $logfile
nodetool -h localhost repair --partitioner-range
echo "$(date)  Cassandra repair completed." >> $logfile
echo "$(date)  Cassandra compaction started." >> $logfile
nodetool -h localhost compact
echo "$(date)  Cassandra compaction completed." >> $logfile
echo "$(date)  Cassandra cleanup started." >> $logfile
nodetool -h localhost cleanup
echo "$(date)  Cassandra cleanup completed." >> $logfile

nodetool -h localhost setcompactionthroughput 16

dt=$SECONDS
ds=$((dt % 60))
dm=$(((dt / 60) % 60))
dh=$((dt / 3600))
printf 'Total Run Time : %d:%02d:%02d' $dh $dm $ds >> $logfile

This 'maintenance' does not solve the problem, we tried to do specific actions on the particular Tablespace but it ain't done much.

We tried to set the gc_grace to a higher value then lunch the maintenance script but we had the same result.
I know this is nor really an error but a protection to keep good performances on Cassandra but we are kind in the blur for this one.

Our next step is to dump the entiere tablespace, drop it and then recreate but it seems to be a bit radical for a cluster in production.

Does anyone know what could go wrong for the tombstones cleanup ?

Thanks,

Regards


问:
BAT file: Open new cmd window and execute a command in there
I'm trying to open a new command window in a BAT file:

```<code>start %windir%\system32\cmd.exe
</code>```

After it opens, I'd like to execute a BAT command in the new window:

```<code>echo "test in new window"
</code>```

How can I do this?

答:
The above answers helped me. But still required some figuring out. Here is an example script I use to start 3 processes for web development. It results in 3 windows staying open, as they need to run continously.

Mongo is globally added to my path, so I don't need to cd like I do for the other two programs. Of course the path to your files will vary, but hopefully this will help.

```<code>:: Start MongoDB
start cmd.exe /k "mongod"

:: cd app directory, and start it
cd my-app
start cmd.exe /k "npm run dev"

:: cd to api server, and start that
cd ../my-app-api
start cmd.exe /k "npm run dev"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to open a new command window in a BAT file:

start %windir%\system32\cmd.exe

After it opens, I'd like to execute a BAT command in the new window:

echo "test in new window"

How can I do this?

Body:
The above answers helped me. But still required some figuring out. Here is an example script I use to start 3 processes for web development. It results in 3 windows staying open, as they need to run continously.

Mongo is globally added to my path, so I don't need to cd like I do for the other two programs. Of course the path to your files will vary, but hopefully this will help.

:: Start MongoDB
start cmd.exe /k "mongod"

:: cd app directory, and start it
cd my-app
start cmd.exe /k "npm run dev"

:: cd to api server, and start that
cd ../my-app-api
start cmd.exe /k "npm run dev"


问:
ASP.Net Core doesn't recognize Request.MapPath in Razor segment
Working with ASP.Net Core is still a little new to me. I'm trying to follow a tutorial on PluralSight that details how Image Composition in .NET works.

That said, the code I'm trying to convert from ASP.Net MVC to ASP.Net Core is showing an error on Request in my Index.cshtml:

```<code><img src="@Url.Action("ImageFromPath", new { path = Request.MapPath("~/img/1.jpg") })" />
</code>```

The error is simply:

The name 'Request' does not exist in the current context.

My HomeController.cs:

```<code>public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public ActionResult ImageFromPath(string path)
    {
        var ms = new MemoryStream();
        using (Bitmap bitmap = new Bitmap(path))
        {
            bitmap.Save(ms, ImageFormat.Jpeg);
        }

        ms.Position = 0;
        return File(ms, "image/jpg");
    }
}
</code>```

In MVC, I can look up definition of Request that goes all the way back to WebPageRenderingBase [from metadata], yet this does not exist in .NET Core, can anyone offer a way to get this to work?

EDIT - I later plan on using the backend ImageFromPath method to return an image from an API call, not the file system.

答:
You could just serve the image straight from file system, unless I'm missing something.

```<code><img src="@Url.Content("~/img/1.jpg")" alt="Some Text" />
</code>```

Update

I later plan on using the backend ImageFromPath method to return an
  image from an API call, not the file system.

You just pass the image filename only, and resolve the full path at server-side.

```<code><img src="@Url.Action("ImageFromPath", new { filename = "1.jpg" })" />

public class HomeController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public HomeController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    public ActionResult ImageFromPath(string filename)
    {
        string path = _hostingEnvironment.WebRootPath + "/img/" + filename;
        ...
    }
}
</code>```

Body:
Working with ASP.Net Core is still a little new to me. I'm trying to follow a tutorial on PluralSight that details how Image Composition in .NET works.

That said, the code I'm trying to convert from ASP.Net MVC to ASP.Net Core is showing an error on Request in my Index.cshtml:

The error is simply:

The name 'Request' does not exist in the current context.

My HomeController.cs:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public ActionResult ImageFromPath(string path)
    {
        var ms = new MemoryStream();
        using (Bitmap bitmap = new Bitmap(path))
        {
            bitmap.Save(ms, ImageFormat.Jpeg);
        }

        ms.Position = 0;
        return File(ms, "image/jpg");
    }
}

In MVC, I can look up definition of Request that goes all the way back to WebPageRenderingBase [from metadata], yet this does not exist in .NET Core, can anyone offer a way to get this to work?

EDIT - I later plan on using the backend ImageFromPath method to return an image from an API call, not the file system.

Body:
You could just serve the image straight from file system, unless I'm missing something.

<img src="@Url.Content("~/img/1.jpg")" alt="Some Text" />

Update

I later plan on using the backend ImageFromPath method to return an
  image from an API call, not the file system.

You just pass the image filename only, and resolve the full path at server-side.

<img src="@Url.Action("ImageFromPath", new { filename = "1.jpg" })" />

public class HomeController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public HomeController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    public ActionResult ImageFromPath(string filename)
    {
        string path = _hostingEnvironment.WebRootPath + "/img/" + filename;
        ...
    }
}


问:
Explain db tag storage method
from this post What is the most efficient way to store tags in a database?

It was recommended to store tag tables like this.

```<code>Table: Item
Columns: ItemID, Title, Content

Table: Tag
Columns: TagID, Title

Table: ItemTag
Columns: ItemID, TagID
</code>```

And another SO post said the same thing. Can anyone explain why tags should be stored like this?
I am guessing ItemID is some internal val, title is the tag name (c++, sql, noob, etc)
content is whatever else data i want to store with my item.
why not something like

```<code>Table: Item
Columns: ItemID, Title, <more data i want>

Table: TagList
Columns: ItemID, Title
</code>```

title in item being "item name" and tag title being "c++" "sql" "noob" "etc"

答:
Why?  It's normalized.  ItemID will be the primary key (perhaps a surrogate or identity), TagID will almost certainly be a surrogate/identity and for constraints/performance you'll have a unique constraint and/or index (perhaps even clustered on the tag.title).

In your example, TagList will not have a primary key (unless perhaps both columns will be the primary key), and it cannot be normalized to remove tag title redundancy (two items with the same tag will have separate entries).  In addition, because tags aren't entities in their own right in the second model, they can't be linked to a different type of entity with another ItemTag table.

LastEditorDisplayName: Cade Roux

Title: Explain db tag storage method

Body:
from this post What is the most efficient way to store tags in a database?

It was recommended to store tag tables like this.

Table: Item
Columns: ItemID, Title, Content

Table: Tag
Columns: TagID, Title

Table: ItemTag
Columns: ItemID, TagID

And another SO post said the same thing. Can anyone explain why tags should be stored like this?
I am guessing ItemID is some internal val, title is the tag name (c++, sql, noob, etc)
content is whatever else data i want to store with my item.
why not something like

Table: Item
Columns: ItemID, Title, <more data i want>

Table: TagList
Columns: ItemID, Title

title in item being "item name" and tag title being "c++" "sql" "noob" "etc"

OwnerDisplayName: Cade Roux


问:
Change Enter from submission to Tab?
Users don't like the fact that the Enter key submits the page.  So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.

I have tried many javascript snippets found on the net but none have worked so far.  The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.

```<code>e.returnValue = false;
e.cancel = true;
</code>```

Page still submits with the above in the keydown event handler.  Same effect with return false in the keydown event handler.  The handler is firing, tested by putting a breakpoint in it with firebug.

This needs to work with both IE and Firefox.

Don't say "don't do this".

1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.

2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.

答:
```<code>$("input").bind("keydown", function(event) {

    if (event.which === 13 && this.type !== 'submit') {
        event.preventDefault();
        $(this).next("input").focus();
    }
});
</code>```

Title: Change Enter from submission to Tab?

Body:
Users don't like the fact that the Enter key submits the page.  So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.

I have tried many javascript snippets found on the net but none have worked so far.  The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.

e.returnValue = false;
e.cancel = true;

Page still submits with the above in the keydown event handler.  Same effect with return false in the keydown event handler.  The handler is firing, tested by putting a breakpoint in it with firebug.

This needs to work with both IE and Firefox.

Don't say "don't do this".

1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.

2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.


问:
program wont sort array after one previous sorting
This is what i have so far:

```<code>import java.util.*;
public class ProcessArray {

    public static void main(String[] args) {

        int[] arr = {3, 8, 1, 9, 2};
        System.out.println(Arrays.toString(arr));
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.oddArray(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.evenArray(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int index = 0;
            for (int k = 0; k < arr.length - i; k++) {
                if (arr[k] > arr[index]) {
                    index = k;
                }
            }
            //swap
            int tmp = arr[index];
            arr[index] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = tmp;
        }
    }

    public static int[] oddArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

    public static int[] evenArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

}
</code>```

For some reason when i go to run it, this is what im outputted with:

```<code>[3, 8, 1, 9, 2]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]
</code>```

How do i make odd Array and even Array work? Because the logic make sense, at least to me it does, but the program still just prints the output it got from selectionSort. Im sorry if this basic computer science knowledge, we just recently started learning about sorting.

答: You are trying to sort the array after it has already been sorted. Pass in a copy of the original array to the sorting methods instead of the original array reference. </p>

Body:
This is what i have so far:

import java.util.*;
public class ProcessArray {

    public static void main(String[] args) {

        int[] arr = {3, 8, 1, 9, 2};
        System.out.println(Arrays.toString(arr));
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.oddArray(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.evenArray(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int index = 0;
            for (int k = 0; k < arr.length - i; k++) {
                if (arr[k] > arr[index]) {
                    index = k;
                }
            }
            //swap
            int tmp = arr[index];
            arr[index] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = tmp;
        }
    }

    public static int[] oddArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

    public static int[] evenArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

}

For some reason when i go to run it, this is what im outputted with:

[3, 8, 1, 9, 2]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]

How do i make odd Array and even Array work? Because the logic make sense, at least to me it does, but the program still just prints the output it got from selectionSort. Im sorry if this basic computer science knowledge, we just recently started learning about sorting.


问:
how to get several rows out of my model
This is again an understanding issue, any explanation is appreciated:

I before had the issue to show a foreignkey table in my view, that now works, it looks like follows:

That's quite what I wanted, but:
I only get the first row, but there are of course several in the second collection (it is the row with filename).

It is because of my method in my model, which looks like follows:

```<code>    public function getImportU($unitid)
{
    $unitid = (int) $unitid;
    $rowset = $this->tableGateway->select(['UnitID' => $unitid]);
    $row = $rowset->current();
    if (! $row) {
        return null;
    }
    else{
        return $row;
    }
}
</code>```

Of course I have a row object and it returns the current row. So I thought, ok I will try with a rowset, after that it looked like this:

```<code>public function getImportU($unitid)
{
    $unitid = (int) $unitid;
    $rowset = $this->tableGateway->select(['UnitID' => $unitid]);
    //$row = $rowset->current();
    if (! $rowset) {
        return null;
    }
    else{
        return $rowset;
    }
}
</code>```

I got some errors which said:

Notice: Undefined property: Zend\Db\ResultSet\ResultSet::$Importdate in
  Blockquote

So how to get a recordcollection, all records there are in the table with the same unitid? And how to call them in the view. It is probably not a big deal, but I couldn't find anything usable in the documentation.
EDIT1: Adding related code.

Here I pass the ViewModel within my Controller indexAction:

```<code>return new ViewModel([
                'projects' => $this->projectTable->fetchAll(),
                'dcls' => $this->table,
                    //'id' =>$this->authService,
                ]);
</code>```

And here a snippet of my index.phtml:

```<code> foreach ($projects as $project) :
//var_dump(get_object_vars($project));
?>
    <tr>
    <td><?= $project['Projectname']?></td>
    <td><?= $project['ProjectShortcut']?></td>
    <td><?= $project['ProjectCiNumber']?></td>
    <td><?= $project['Unitname']?></td>
    <td><?= $project['UnitShortcut']?></td>
    <td><?= $project['UnitCiNumber']?></td>
    <td><?= $project['UnitID']?></td>
     </tr>
     <?php
     $dclsx=$dcls->getImportU($project['UnitID']);
    // var_dump($dclss);
     if ( empty ($dclsx)==false){ ?>
        <tr>
        <th></th>
        <th>filename</th>
        <th>importdate</th>
        <th>importuser</th>
        <th>importok</th>
        </tr>
    <?php
        $dclss=array($dclsx);
    //    var_dump($dclss);
         foreach ( $dclss as $dcl) :
         ?>
         <tr>
            <td>   </td>
            <td><?= $dcl->filename?></td>
            <td><?= $dcl->Importdate?></td>
            <td><?= $dcl->Importuser?></td>
        </tr>
       ?php
    endforeach;
       }
   endforeach; ?>
</code>```

答:
I believe you are pretty close to the solution.
"getImportU" returning a rowset is the correct solution as I see it:

```<code>public function getImportU($unitid)
{
    $unitid = (int) $unitid;
    $rowset = $this->tableGateway->select(['UnitID' => $unitid]);
    if (! $rowset) {
        return null;
    }
    else{
        return $rowset;
    }
}
</code>```

Your view should be changed from:

```<code><?php
    $dclss=array($dclsx);
//    var_dump($dclss);
     foreach ( $dclss as $dcl) :
</code>```

to:

```<code><?php
     foreach ( $dclsx as $dcl) :
</code>```

$dclsx is a resultset and can be iterated, it does not make sense to put it in an array.

Your error also suggests that "Importdate" cannot be found in the blockquote table.
Please check if the column exists at the table(also check the name is case sensitive, is it "Importdate", "importdate" or "importDate"?)

Title: how to get several rows out of my model

Body:
This is again an understanding issue, any explanation is appreciated:

I before had the issue to show a foreignkey table in my view, that now works, it looks like follows:

That's quite what I wanted, but:
I only get the first row, but there are of course several in the second collection (it is the row with filename).

It is because of my method in my model, which looks like follows:

    public function getImportU($unitid)
{
    $unitid = (int) $unitid;
    $rowset = $this->tableGateway->select(['UnitID' => $unitid]);
    $row = $rowset->current();
    if (! $row) {
        return null;
    }
    else{
        return $row;
    }
}

Of course I have a row object and it returns the current row. So I thought, ok I will try with a rowset, after that it looked like this:

public function getImportU($unitid)
{
    $unitid = (int) $unitid;
    $rowset = $this->tableGateway->select(['UnitID' => $unitid]);
    //$row = $rowset->current();
    if (! $rowset) {
        return null;
    }
    else{
        return $rowset;
    }
}

I got some errors which said:

Notice: Undefined property: Zend\Db\ResultSet\ResultSet::$Importdate in
  Blockquote

So how to get a recordcollection, all records there are in the table with the same unitid? And how to call them in the view. It is probably not a big deal, but I couldn't find anything usable in the documentation.
EDIT1: Adding related code.

Here I pass the ViewModel within my Controller indexAction:

return new ViewModel([
                'projects' => $this->projectTable->fetchAll(),
                'dcls' => $this->table,
                    //'id' =>$this->authService,
                ]);

And here a snippet of my index.phtml:

 foreach ($projects as $project) :
//var_dump(get_object_vars($project));
?>

    <?= $project['Projectname']?>
    <?= $project['ProjectShortcut']?>
    <?= $project['ProjectCiNumber']?>
    <?= $project['Unitname']?>
    <?= $project['UnitShortcut']?>
    <?= $project['UnitCiNumber']?>
    <?= $project['UnitID']?>

     <?php
     $dclsx=$dcls->getImportU($project['UnitID']);
    // var_dump($dclss);
     if ( empty ($dclsx)==false){ ?>

        filename
        importdate
        importuser
        importok

    <?php
        $dclss=array($dclsx);
    //    var_dump($dclss);
         foreach ( $dclss as $dcl) :
         ?>

            <?= $dcl->filename?>
            <?= $dcl->Importdate?>
            <?= $dcl->Importuser?>

       ?php
    endforeach;
       }
   endforeach; ?>

Body:
I believe you are pretty close to the solution.
"getImportU" returning a rowset is the correct solution as I see it:

public function getImportU($unitid)
{
    $unitid = (int) $unitid;
    $rowset = $this->tableGateway->select(['UnitID' => $unitid]);
    if (! $rowset) {
        return null;
    }
    else{
        return $rowset;
    }
}

Your view should be changed from:

<?php
    $dclss=array($dclsx);
//    var_dump($dclss);
     foreach ( $dclss as $dcl) :

to:

<?php
     foreach ( $dclsx as $dcl) :

$dclsx is a resultset and can be iterated, it does not make sense to put it in an array.

Your error also suggests that "Importdate" cannot be found in the blockquote table.
Please check if the column exists at the table(also check the name is case sensitive, is it "Importdate", "importdate" or "importDate"?)


问:
Keras/TensorFlow: How do I transform text to use as input?
I've been reading tutorials for the last few days, but they all seem to start at the step of "I have my data from this pre-prepared data set, let's go".

What I'm trying to do is take a set of emails I've tokenized, and figure out how to get them into a model as the training and evaluation data.

Example email:

```<code>0 0 0 0 0 0 0 0 0 0 0 0 32192 6675 16943 1380 433 8767 2254 8869 8155
</code>```

I have a folder of emails (one file per email) for each spam and not spam:

```<code>/spam/
    93451.txt
    ...
/not-spam/
    112.txt
    ...
</code>```

How can I get Keras to read this data?

Alternatively, how can I generate a CSV or some other format that it wants to use to input it?

答:
As I understood from your task description (please guide me if I'm wrong), you need to classify texts into either spam or not spam category.

Basically, if you want to create the universal text data classification input solution, your
data input stage code should contain 3 steps:
1. Reading list of folders ("spam", "not spam" in your case) and iterating each folder to the list of files.

At the end you should have:

a) a dictionary containing (label_id -> label_name).

So in your case, you should stay with (0-> spam, 1->not_spam).

b) A pair of (file_content, label).

As you understand, this is out of scope of both keras and tensorflow. It is typical python' code.

2. For each part (file_content, label) you should process the first element, and that's the most interesting part usually.
In your example I can see 0 0 0 0 0 0 0 0 0 0 0 0 32192 6675 16943 1380 433 8767 2254 8869 8155.
 So you already have the indexes of the words, but they are in the text form. All you need is to transform the string to the array having the 300 items (words in your message).

For the further text machine learning projects, I suggest to use raw text data as a source and transform it to the word indexes using tf.contrib.learn.preprocessing.VocabularyProcessor.

3. Transform labels(categories) to the one-hot vector.
So at the end of these step you have a pair of (word_indexes_as_array, label_as_one_hot).
Then you can use these data as input data for training.

Naturally, you would divide this tuple into two, treating the first 80% of data as training set and 20% as testing set (please do not focus on 80/20, numbers it is just a sample).

You may look at at the text classification with keras examples. They are rather straightforward and may be helpful for you as they are starting from the data input step.

Also, please, look at the load_data_and_labels() method in the data input step example. It is a very similar case to yours (positive/negative).

Body:
I've been reading tutorials for the last few days, but they all seem to start at the step of "I have my data from this pre-prepared data set, let's go".

What I'm trying to do is take a set of emails I've tokenized, and figure out how to get them into a model as the training and evaluation data.

Example email:

0 0 0 0 0 0 0 0 0 0 0 0 32192 6675 16943 1380 433 8767 2254 8869 8155

I have a folder of emails (one file per email) for each spam and not spam:

/spam/
    93451.txt
    ...
/not-spam/
    112.txt
    ...

How can I get Keras to read this data?

Alternatively, how can I generate a CSV or some other format that it wants to use to input it?


问:
How to reset value of Child componenet when filter is used in Vue2
I have this fiddle where if you use the inputSpinner and then use filter at the top the value of the input spiner stays the same

JsFiddle

My problem is like this

Code

```<code><script type="text/x-template" id="grid-template">
<div class="container" style="margin-top:10px;">
  <ul class="list-group">
    <li  v-for="entry in filteredData" class="list-group-item" >{{entry.name}} <div><numberinputspinner
                        :min="0"
                        :max="2"
                        :step="0.0001"
                        :card="entry"
                        @newNumber="updateTable"
                      /></div></li>
  </ul>
  </div>
</script> ....
</code>```

答:
When you filter the data, Vue destroys/recreate the unused components (for example if looking for Bruce Lee, would destroy Chuck Norris), as components get destroyed you will lose the data, as is not persistent.

You need to keep that data sync with the parent so when recreated again it would reassign its previous value.

Here's the updated jsFiddle: https://jsfiddle.net/myeu0sL3/9/

What I just did was pass the data to the parent in the newNumber event, and assign it to the collection, like this:

```<code>updateTable:function(card, data){
    card.value = data;
}
</code>```

and then in the component just assign it whenever is passed:

```<code>data: function () {
    const vm = this;
    return {
        numericValue: vm.card.value,
    };
},
</code>```

and emit the card in the newNumber event:

```<code>this.$emit('newNumber', this.card, parseFloat(val).toFixed(4), parseFloat(oldVal).toFixed(4) );
</code>```

Oh and finally there was a mistake in your props declaration, you had it twice, so I merged to include the cards:

```<code>    card: {
        type: Object,
      required: true
    },
</code>```

That's it :)

Body:
I have this fiddle where if you use the inputSpinner and then use filter at the top the value of the input spiner stays the same

JsFiddle

My problem is like this

Code

 ....

Body:
When you filter the data, Vue destroys/recreate the unused components (for example if looking for Bruce Lee, would destroy Chuck Norris), as components get destroyed you will lose the data, as is not persistent.

You need to keep that data sync with the parent so when recreated again it would reassign its previous value.

Here's the updated jsFiddle: https://jsfiddle.net/myeu0sL3/9/

What I just did was pass the data to the parent in the newNumber event, and assign it to the collection, like this:

updateTable:function(card, data){
    card.value = data;
}

and then in the component just assign it whenever is passed:

data: function () {
    const vm = this;
    return {
        numericValue: vm.card.value,
    };
},

and emit the card in the newNumber event:

this.$emit('newNumber', this.card, parseFloat(val).toFixed(4), parseFloat(oldVal).toFixed(4) );

Oh and finally there was a mistake in your props declaration, you had it twice, so I merged to include the cards:

    card: {
        type: Object,
      required: true
    },

That's it :)