问:
how to make a cookie last a year PHP
I attempted to make a cookie-based theme switcher using PHP, and to make the cookie I use this:

```<code>$t = $_GET["t"];
if($t == "dark" || "light" || "mixed") {
    setcookie("theme", $t, time() + 31556926, "/");
} elseif(!isset($t) and !isset($_COOKIE["theme"])) {
    setcookie("theme", "dark", time() + 31556926 , "/");
}
if(isset($_COOKIE["theme"])) {
    echo "<body style=\"background:url(/imgs/" . $_COOKIE['theme'] . ".gif) top left repeat\">";
} else {
    echo "<body style=\"background:url(/imgs/dark.gif) top left repeat\">";
}
</code>```

But this doesn't seem to work, it reloads the page and sets the cookie, but has a strange property of needing to reload the page again in order for it to change the background, and only lasting for the session. As well as this, when you return to the index.php without ?t=light it stays, but then when you reload it disappears. I couldn't figure out any reason that it should be acting this way.

答:
I think you have syntax errors..Just try it..</p>

```<code>$t = $_GET["t"];
if($t == "dark" || $t ==  "light" || $t == "mixed") {
     setcookie("theme", $t, time() + 31556926, "/");
 } elseif(!isset($t) && !isset($_COOKIE["theme"])) {
     setcookie("theme", "dark", time() + 31556926 , "/");
 }
if(isset($_COOKIE["theme"])) {
 echo "<body style=\"background:url(/imgs/" . $_COOKIE['theme'] . ".gif) top  left repeat\">";
} else {
echo "<body style=\"background:url(/imgs/dark.gif) top left repeat\">";
}
</code>```

Title: how to make a cookie last a year PHP

Body:
I attempted to make a cookie-based theme switcher using PHP, and to make the cookie I use this:

$t = $_GET["t"];
if($t == "dark" || "light" || "mixed") {
    setcookie("theme", $t, time() + 31556926, "/");
} elseif(!isset($t) and !isset($_COOKIE["theme"])) {
    setcookie("theme", "dark", time() + 31556926 , "/");
}
if(isset($_COOKIE["theme"])) {
    echo "";
} else {
    echo "";
}

But this doesn't seem to work, it reloads the page and sets the cookie, but has a strange property of needing to reload the page again in order for it to change the background, and only lasting for the session. As well as this, when you return to the index.php without ?t=light it stays, but then when you reload it disappears. I couldn't figure out any reason that it should be acting this way.

Body:
I think you have syntax errors..Just try it..

$t = $_GET["t"];
if($t == "dark" || $t ==  "light" || $t == "mixed") {
     setcookie("theme", $t, time() + 31556926, "/");
 } elseif(!isset($t) && !isset($_COOKIE["theme"])) {
     setcookie("theme", "dark", time() + 31556926 , "/");
 }
if(isset($_COOKIE["theme"])) {
 echo "<body style=\"background:url(/imgs/" . $_COOKIE['theme'] . ".gif) top  left repeat\">";
} else {
echo "<body style=\"background:url(/imgs/dark.gif) top left repeat\">";
}


来源: stackexchange

问:
SQL complex query- ORDER BY and GROUP BY in the same query did not work properly
I have a table like that,

Now, I want to find out the winner, who gave the correct answer most in early. I tried something like that,

```<code>SELECT COUNT(is_correct), msisdn
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1 group by msisdn
</code>```

And output is-

Now, When I try to ORDER BY creation_time , it did not give expected out but error. What should be the query to find out the winner.

答:
```<code>SELECT COUNT(is_correct), msisdn
FROM (SELECT * FROM tbl_quiz_reply WHERE is_correct = 1 ORDER BY creation_time DESC) as test
group by msisdn
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table like that,

Now, I want to find out the winner, who gave the correct answer most in early. I tried something like that,

SELECT COUNT(is_correct), msisdn
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1 group by msisdn

And output is-

Now, When I try to ORDER BY creation_time , it did not give expected out but error. What should be the query to find out the winner.


答:
Try this:

```<code>SELECT COUNT(is_correct), msisdn , min(creation_time) as min_creation
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1 group by msisdn
order by min_creation
</code>```

The problem is that you were not returning the column as part of the group. Applying a min() to the column allows you to order by the first occurence by isdn.

Title: SQL complex query- ORDER BY and GROUP BY in the same query did not work properly

Body:
Try this:

SELECT COUNT(is_correct), msisdn , min(creation_time) as min_creation
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1 group by msisdn
order by min_creation

The problem is that you were not returning the column as part of the group. Applying a min() to the column allows you to order by the first occurence by isdn.


问:
How to store multi byte characters in SQL Server database using CodeIgniter
I'm using MS SQL Server and CodeIgniter 2 with Active Record for a project I'm working on, and I just stumbled upon this issue:

When I submit a form that contains Chinese or Hindi characters, I store it in a table, and when I view it all I get are question marks. If I try English or Greek characters, everything seems to work fine.

The reason I believe this is something to do with the PHP I'm writing, is because if I copy-paste the chinese text directly in SQL Server Management Studio, all values are stored and displayed perfectly, both on the SQL Studio, and the web application.

These are the db settings I'm using:

```<code>$db['local']['dbdriver'] = 'sqlsrv';
$db['local']['dbprefix'] = '';
$db['local']['pconnect'] = FALSE;
$db['local']['db_debug'] = TRUE;
$db['local']['cache_on'] = FALSE;
$db['local']['cachedir'] = '';
$db['local']['char_set'] = 'utf8';
$db['local']['dbcollat'] = 'utf8_general_ci';
$db['local']['swap_pre'] = '';
$db['local']['autoinit'] = TRUE;
$db['local']['stricton'] = FALSE;
</code>```

This is the structure of the table I'm testing on right now:

```<code>CREATE TABLE [dbo].[languages](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [language] [nvarchar](1024) NULL,
    [language_local] [nvarchar](1024) NULL,
    [lang_code] [nvarchar](100) NULL,
    [core] [bit] NULL,
 CONSTRAINT [PK_languages] PRIMARY KEY CLUSTERED
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,         ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
</code>```

And this is my charset encoding in config.php

```<code>$config['charset'] = 'utf-8';
</code>```

New troubleshooting data

I tried to save the following string through my form: Iñtërnâtiônàlizætiøn

CodeIgniter replied with this error:

```<code>An error occurred translating the query string to UTF-16: No mapping for the Unicode character exists in the target multi-byte code page. .
</code>```

This doesn't appear when I try to store Chinese characters
Thank you in advance :)

答:
I had same problem but only htmlspecialchars() worked for me.</p>

```<code>$value = htmlspecialchars($input)
</code>```

Body:
I'm using MS SQL Server and CodeIgniter 2 with Active Record for a project I'm working on, and I just stumbled upon this issue:

When I submit a form that contains Chinese or Hindi characters, I store it in a table, and when I view it all I get are question marks. If I try English or Greek characters, everything seems to work fine.

The reason I believe this is something to do with the PHP I'm writing, is because if I copy-paste the chinese text directly in SQL Server Management Studio, all values are stored and displayed perfectly, both on the SQL Studio, and the web application.

These are the db settings I'm using:

$db['local']['dbdriver'] = 'sqlsrv';
$db['local']['dbprefix'] = '';
$db['local']['pconnect'] = FALSE;
$db['local']['db_debug'] = TRUE;
$db['local']['cache_on'] = FALSE;
$db['local']['cachedir'] = '';
$db['local']['char_set'] = 'utf8';
$db['local']['dbcollat'] = 'utf8_general_ci';
$db['local']['swap_pre'] = '';
$db['local']['autoinit'] = TRUE;
$db['local']['stricton'] = FALSE;

This is the structure of the table I'm testing on right now:

CREATE TABLE [dbo].[languages](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [language] [nvarchar](1024) NULL,
    [language_local] [nvarchar](1024) NULL,
    [lang_code] [nvarchar](100) NULL,
    [core] [bit] NULL,
 CONSTRAINT [PK_languages] PRIMARY KEY CLUSTERED
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,         ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

And this is my charset encoding in config.php

$config['charset'] = 'utf-8';

New troubleshooting data

I tried to save the following string through my form: Iñtërnâtiônàlizætiøn

CodeIgniter replied with this error:

An error occurred translating the query string to UTF-16: No mapping for the Unicode character exists in the target multi-byte code page. .

This doesn't appear when I try to store Chinese characters
Thank you in advance :)

Body:
I had same problem but only htmlspecialchars() worked for me.

$value = htmlspecialchars($input)


问:
how to look for column heading in excels in single folder and return in summary sheet
the below code simply return what is in range ("Q33:AS33"), how can i modify it to look for key words(column heading) and return the text below the column heading (1 cell) to the summary sheet? many thanks</p>

```<code>Sub MergeAllWorkbooks()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, FNum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long
    Dim FindString As String
    Dim FindCell As Range

    ' Change this to the path\folder location of your files.
    MyPath = "path name"

    ' Add a slash at the end of the path if needed.
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    ' If there are no Excel files in the folder, exit.
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    ' Fill the myFiles array with the list of Excel files
    ' in the search folder.
    FNum = 0
    Do While FilesInPath <> ""
        FNum = FNum + 1
        ReDim Preserve MyFiles(1 To FNum)
        MyFiles(FNum) = FilesInPath
        FilesInPath = Dir()
    Loop

    ' Set various application properties.
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    ' Add a new workbook with one sheet.
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    ' Loop through all files in the myFiles array.
    If FNum > 0 Then
        For FNum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
            On Error GoTo 0

            If Not mybook Is Nothing Then
                On Error Resume Next

                ' Change this range to fit your own needs.
                With mybook.Worksheets("worksheet name")
                    Set sourceRange = .Range("Q33:AS33")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    ' If source range uses all columns then
                    ' skip this file.
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "There are not enough rows in the target worksheet."
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        ' Copy the file name in column A.
                        With sourceRange
                            BaseWks.Cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(FNum)
                        End With

                        ' Set the destination range.
                        Set destrange = BaseWks.Range("B" & rnum)

                        ' Copy the values from the source range
                        ' to the destination range.
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next FNum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    ' Restore the application properties.
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub
</code>```

答:
A common way to work with a cell relative to another cell is to use the Offset property. In the following example, the contents of the cell that's one row down and three columns over from the active cell on the active worksheet are formatted as double-underlined.

```<code>ActiveCell.Offset(1, 3).Font.Underline = xlDouble
</code>```

Say the cell contain String=”Control Process” is A1, you can find A1 by

Set ControlProcessCell = Cells.Find(what:=”Control Process”………)

Then offset the cell to find the actual value

Set WantedCell = ControlProcessCell.Offset(1,0)

You may need to select the ControlProcessCell first which should be something like

ControlProcessCell.select

ContentLicense: CC BY-SA 2.5

Body:
the below code simply return what is in range ("Q33:AS33"), how can i modify it to look for key words(column heading) and return the text below the column heading (1 cell) to the summary sheet? many thanks

Sub MergeAllWorkbooks()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, FNum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long
    Dim FindString As String
    Dim FindCell As Range

    ' Change this to the path\folder location of your files.
    MyPath = "path name"

    ' Add a slash at the end of the path if needed.
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    ' If there are no Excel files in the folder, exit.
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    ' Fill the myFiles array with the list of Excel files
    ' in the search folder.
    FNum = 0
    Do While FilesInPath <> ""
        FNum = FNum + 1
        ReDim Preserve MyFiles(1 To FNum)
        MyFiles(FNum) = FilesInPath
        FilesInPath = Dir()
    Loop

    ' Set various application properties.
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    ' Add a new workbook with one sheet.
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    ' Loop through all files in the myFiles array.
    If FNum > 0 Then
        For FNum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
            On Error GoTo 0

            If Not mybook Is Nothing Then
                On Error Resume Next

                ' Change this range to fit your own needs.
                With mybook.Worksheets("worksheet name")
                    Set sourceRange = .Range("Q33:AS33")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    ' If source range uses all columns then
                    ' skip this file.
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "There are not enough rows in the target worksheet."
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        ' Copy the file name in column A.
                        With sourceRange
                            BaseWks.Cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(FNum)
                        End With

                        ' Set the destination range.
                        Set destrange = BaseWks.Range("B" & rnum)

                        ' Copy the values from the source range
                        ' to the destination range.
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next FNum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    ' Restore the application properties.
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

Body:
A common way to work with a cell relative to another cell is to use the Offset property. In the following example, the contents of the cell that's one row down and three columns over from the active cell on the active worksheet are formatted as double-underlined.

ActiveCell.Offset(1, 3).Font.Underline = xlDouble

Say the cell contain String=”Control Process” is A1, you can find A1 by

Set ControlProcessCell = Cells.Find(what:=”Control Process”………)

Then offset the cell to find the actual value

Set WantedCell = ControlProcessCell.Offset(1,0)

You may need to select the ControlProcessCell first which should be something like

ControlProcessCell.select


问:
No source code is available for type com.google.gwt.ajaxloader.client.AjaxLoader;
I am migrating an project someone else built to newer packages and I have traced the root of my errors to this
 No source code is available for type com.google.gwt.ajaxloader.client.AjaxLoader; did you forget to inherit a required module?
I am new to GWT and not really sure how it works 100% under the hood so I am having trouble applying solutions to similar posts to solve this error.

答:
go to Maven Repository and get gwt-ajaxloader.jar - it contains both .java and .class files

save the jar to war/WEB-INF/lib folder in your project

right-click on the file in Project Explorer (I assume you use Eclipse), select Build Path -> Add to Build Path

enjoy ;)


问:
How to use an id to load sprite sheets and img files in Corona SDK?
The title sounds confusing, but what I am looking for is something like this: https://www.youtube.com/watch?v=GhI98-HJk6o

Just watch the first minute, notice when the player taps the bottom squares the appropriate unit is spawned. I am trying to achieve this in Corona SDK, but I have been getting stuck a lot recently and I hope you guys can help.

What I tried to do was this:

```<code>local m = {} -- characters.lua

m.units = {
   {img = "sprites/girl.png", timeBetweenAtk = 2350, name = girl, cost = 75, respawnTime = 3750, state = active}
}

m.girl = {}
m.girl.walking = {}
local data = {width = 309, height = 494, numFrames = 10, sheetContentWidth = 1545, sheetContentHeight = 988}
m.girl.walking.sheet = graphics.newImageSheet("sprites/walking-girl.png", data )
m.girl.walking.seq = {name = "walking", start = 1, count = 10, loopCount = 0, loopDirection = "forward"}

m.girl.primaryAtk = {}
local data = {width = 385, height = 477, numFrames = 10, sheetContentWidth = 1925, sheetContentHeight = 954}
m.girl.primaryAtk.sheet = graphics.newImageSheet("sprites/melee-girl.png", data)
m.girl.primaryAtk.seq = {name = "melee", start = 1, count = 10, loopCount = 0, loopDirection = "forward"}

m.girl.idle = {}
local data = {width = 271, height = 473, numFrames = 10, sheetContentWidth = 813, sheetContentHeight = 1892}
m.girl.idle.sheet = graphics.newImageSheet("sprites/idle-girl.png", data)
m.girl.idle.seq = {name = "idle", start = 1, count = 10, loopCount = 0, loopDirection = "forward"}

return m
</code>```

And then I made a function in main.lua, to call the correct sprite:

```<code>local characters = require "characters"

for k = 1, #imgSet do
  local function spawnCharacter(event)
     local identifier = characters.units[k].name
     if event.phase == "began" then
       if moneyCount < characters.units[k].cost then
          print("insufficient funds")
       else
          moneyCount = moneyCount - characters.units[k].cost
          moneyText.text = moneyCount .. " / " .. moneyWallet
          local unit = display.newSprite(characters.identifier.walking.sheet, characters.identifier.walking.seq)
       end
     end
     return true
  end
  imgSet[k]:addEventListener("touch", spawnCharacter)
end
</code>```

But now I know that it is not possible to concatenate display objects, so does anyone know if there is another way to do this.

答:
I think you want to use string as identifier. In your setup:

```<code>m.units = {
 {
   img = "sprites/girl.png",
   timeBetweenAtk = 2350,
   name = "girl", --seems like girl variable not declared so in your code you got nil
   cost = 75,
   respawnTime = 3750,
   state = active -- probably same issue - use string here or some pre-defined variable
  }
}
</code>```

So with my code you got m.units[1].name == "girl"

Now you can use it in spawn function:

```<code>local function spawnCharacter(event)
  local charToSpawn = characters.units[k]
  local identifier = charToSpawn.name
  if event.phase == "began" then
    if moneyCount < charToSpawn.cost then
      print("insufficient funds")
    else
      moneyCount = moneyCount - charToSpawn.cost
      moneyText.text = moneyCount .. " / " .. moneyWallet

      local charWalkingData = characters[identifier].walking -- proper use of string identifier here
      local unit = display.newSprite(charWalkingData.sheet, charWalkingData.seq)
    end
  end
  return true
end
</code>```

Put attention on this line: characters[identifier]
If your identifier variable contains string, i.e. "girl" this calls are simular:

```<code>characters[identifier]
characters["girl"] -- assuming identifier = "girl" in this example
characters.girl
</code>```

Body:
The title sounds confusing, but what I am looking for is something like this: https://www.youtube.com/watch?v=GhI98-HJk6o

Just watch the first minute, notice when the player taps the bottom squares the appropriate unit is spawned. I am trying to achieve this in Corona SDK, but I have been getting stuck a lot recently and I hope you guys can help.

What I tried to do was this:

local m = {} -- characters.lua

m.units = {
   {img = "sprites/girl.png", timeBetweenAtk = 2350, name = girl, cost = 75, respawnTime = 3750, state = active}
}

m.girl = {}
m.girl.walking = {}
local data = {width = 309, height = 494, numFrames = 10, sheetContentWidth = 1545, sheetContentHeight = 988}
m.girl.walking.sheet = graphics.newImageSheet("sprites/walking-girl.png", data )
m.girl.walking.seq = {name = "walking", start = 1, count = 10, loopCount = 0, loopDirection = "forward"}

m.girl.primaryAtk = {}
local data = {width = 385, height = 477, numFrames = 10, sheetContentWidth = 1925, sheetContentHeight = 954}
m.girl.primaryAtk.sheet = graphics.newImageSheet("sprites/melee-girl.png", data)
m.girl.primaryAtk.seq = {name = "melee", start = 1, count = 10, loopCount = 0, loopDirection = "forward"}

m.girl.idle = {}
local data = {width = 271, height = 473, numFrames = 10, sheetContentWidth = 813, sheetContentHeight = 1892}
m.girl.idle.sheet = graphics.newImageSheet("sprites/idle-girl.png", data)
m.girl.idle.seq = {name = "idle", start = 1, count = 10, loopCount = 0, loopDirection = "forward"}

return m

And then I made a function in main.lua, to call the correct sprite:

local characters = require "characters"

for k = 1, #imgSet do
  local function spawnCharacter(event)
     local identifier = characters.units[k].name
     if event.phase == "began" then
       if moneyCount < characters.units[k].cost then
          print("insufficient funds")
       else
          moneyCount = moneyCount - characters.units[k].cost
          moneyText.text = moneyCount .. " / " .. moneyWallet
          local unit = display.newSprite(characters.identifier.walking.sheet, characters.identifier.walking.seq)
       end
     end
     return true
  end
  imgSet[k]:addEventListener("touch", spawnCharacter)
end

But now I know that it is not possible to concatenate display objects, so does anyone know if there is another way to do this.

Body:
I think you want to use string as identifier. In your setup:

m.units = {
 {
   img = "sprites/girl.png",
   timeBetweenAtk = 2350,
   name = "girl", --seems like girl variable not declared so in your code you got nil
   cost = 75,
   respawnTime = 3750,
   state = active -- probably same issue - use string here or some pre-defined variable
  }
}

So with my code you got m.units[1].name == "girl"

Now you can use it in spawn function:

local function spawnCharacter(event)
  local charToSpawn = characters.units[k]
  local identifier = charToSpawn.name
  if event.phase == "began" then
    if moneyCount < charToSpawn.cost then
      print("insufficient funds")
    else
      moneyCount = moneyCount - charToSpawn.cost
      moneyText.text = moneyCount .. " / " .. moneyWallet

      local charWalkingData = characters[identifier].walking -- proper use of string identifier here
      local unit = display.newSprite(charWalkingData.sheet, charWalkingData.seq)
    end
  end
  return true
end

Put attention on this line: characters[identifier]
If your identifier variable contains string, i.e. "girl" this calls are simular:

characters[identifier]
characters["girl"] -- assuming identifier = "girl" in this example
characters.girl


问:
Android project broken after Blue Screen on Windows 10
I re-opened my Android Project after blue screen on my machine running Windows 10, all classes and components are unfound. Anybody any idea? I tried re-build and re-start my machines n times.</p>

答:
In addition to CmosBattery's comment:

File -> Invalidate Caches / Restart ... -> Invalidate and Restart.

This lets Android Studio basically forget everything it knows about your project and forces it to reinitalize everything.
I suspect, that the bluescreen prevented Android Studio from writing a file and so the project state got corrupt.

If this still fails, I recommend to check out a fresh copy and if you do not use source control yet (do it now :)) backup your files, create a new project and copy them back into the newly created project.


问:
Can't get value from web form for double value in .net core
Have this class:

```<code>public class ClientViewModel
{
    public long PKID { get; set; }
    [Required]
    public string Name { get; set; }
    public string Unit { get; set; }
    public string StreetNumber { get; set; }
    public string Street { get; set; }
    public string Suburb { get; set; }
    public string State { get; set; }
    public string PostCode { get; set; }
    public string Country { get; set; }
    public string DT_RowId { get; set; }
    public double Longitude { get; set; }
    public double Latitude { get; set; }
    public bool IsActive { get; set; }
}
</code>```

And this code for razor view:

```<code><form method="post" asp-controller="Clients" asp-action="Edit">
    <input asp-for="PKID" type="hidden" />

    <div class="portlet-body">
        <div class="row">
            <div class="form-group col-md-2">
                <label asp-for="Name">Name:</label>
                <input class="form-control input-sm" type="text" placeholder="Name" asp-for="Name">
                <span class="help-block has-error" asp-validation-for="Name"></span>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="row physical-row default-row">
                    <div class="col-md-2">
                        <label class="control-label">Unit</label>
                        @Html.TextBoxFor(model => model.Unit, new {placeholder = "Unit", id = "physicalLocationUnit", @class = "form-control input-sm"})
                    </div>
                    <div class="col-md-4">
                        <label class="control-label">Street</label>
                        @Html.TextBoxFor(model => model.Street, new {placeholder = "PhysicalAddress", id = "physicalLocation", onfocus = "physicalinitialize()", @class = "form-control input-sm"})
                    </div>
                    <div class="col-md-2 postcode-box">
                        <label class="control-label">Post Code</label>
                        <div>
                            <input type="text"
                                   tabindex="-1"
                                   class="form-control input-sm" />
                        </div>
                    </div>
                    <div class="col-md-2 lattitude-box">
                        <label class="control-label" asp-for="Latitude">Latitude</label>
                        <div>
                            <input type="text"
                                   tabindex="-1"
                                   class="form-control input-sm" asp-for="Latitude" />
                        </div>
                    </div>
                    <div class="col-md-2 longitude-box">
                        <label class="control-label" asp-for="Longitude">Longitude</label>
                        <div>
                            <input type="text"
                                   tabindex="-1"
                                   class="form-control input-sm" asp-for="Longitude" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-actions">
                    <div class="col-md-offset-6 col-md-6">
                        <button type="submit" class="btn green">Save</button>
                        <a asp-controller="Clients" asp-action="WorkManage" asp-route-id="@Model.PKID" class="btn green">Add Work</a>
                    </div>
            </div>
        </div>
    </div>
</form>
</code>```

In Longitude and Latitude has value for example 1.3 and 2.45 but when i try to call controller method i have just 0 value in this variables. Where i was wrong?
Cheers!

答:
The reason it is not working with a period, is that the default CultureInfo on your server accepts only commas as decimal separators.

You might want to try setting the default culture to one that expects periods as decimal separators.

You could do that in your startup.cs, like this :

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, FinOsDbContext context)
{
    app.UseRequestLocalization();

    CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("*insert culture*");
    CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("*insert culture*");
}
</code>```

If you always intend to use a period as decimal separator, regardless of the culture's default, you could specify which decimal separator the culture should use like so :

```<code>System.Globalization.CultureInfo customCulture = new CultureInfo("*insert culture*");
customCulture.NumberFormat.NumberDecimalSeparator = ".";

CultureInfo.DefaultThreadCurrentCulture = customCulture;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
</code>```

Body:
Have this class:

public class ClientViewModel
{
    public long PKID { get; set; }
    [Required]
    public string Name { get; set; }
    public string Unit { get; set; }
    public string StreetNumber { get; set; }
    public string Street { get; set; }
    public string Suburb { get; set; }
    public string State { get; set; }
    public string PostCode { get; set; }
    public string Country { get; set; }
    public string DT_RowId { get; set; }
    public double Longitude { get; set; }
    public double Latitude { get; set; }
    public bool IsActive { get; set; }
}

And this code for razor view:

<form method="post" asp-controller="Clients" asp-action="Edit">
    <input asp-for="PKID" type="hidden" />

                Name:
                <input class="form-control input-sm" type="text" placeholder="Name" asp-for="Name">

                        Unit
                        @Html.TextBoxFor(model => model.Unit, new {placeholder = "Unit", id = "physicalLocationUnit", @class = "form-control input-sm"})

                        Street
                        @Html.TextBoxFor(model => model.Street, new {placeholder = "PhysicalAddress", id = "physicalLocation", onfocus = "physicalinitialize()", @class = "form-control input-sm"})

                        Post Code

                            <input type="text"
                                   tabindex="-1"
                                   class="form-control input-sm" />

                        Latitude

                            <input type="text"
                                   tabindex="-1"
                                   class="form-control input-sm" asp-for="Latitude" />

                        Longitude

                            <input type="text"
                                   tabindex="-1"
                                   class="form-control input-sm" asp-for="Longitude" />

                        <button type="submit" class="btn green">Save</button>
                        Add Work

</form>

In Longitude and Latitude has value for example 1.3 and 2.45 but when i try to call controller method i have just 0 value in this variables. Where i was wrong?
Cheers!

Body:
The reason it is not working with a period, is that the default CultureInfo on your server accepts only commas as decimal separators.

You might want to try setting the default culture to one that expects periods as decimal separators.

You could do that in your startup.cs, like this :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, FinOsDbContext context)
{
    app.UseRequestLocalization();

    CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("*insert culture*");
    CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("*insert culture*");
}

If you always intend to use a period as decimal separator, regardless of the culture's default, you could specify which decimal separator the culture should use like so :

System.Globalization.CultureInfo customCulture = new CultureInfo("*insert culture*");
customCulture.NumberFormat.NumberDecimalSeparator = ".";

CultureInfo.DefaultThreadCurrentCulture = customCulture;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;


问:
How to bind a read-only WPF control property (eg ActualWidth) so its value is accessible in the view model?
I want to bind a read-only property of a control to my view model so that the value is available in the view model.

What is the best way of doing this?

For example I'd like to bind ActualWidth to a property in my view model.  The width value is generated by WPF using its layout logic so I can't generate this value in my view model and push it to the control property, as would normally be the case.  Instead I need to have WPF generate the value and push it to the view model.

I would just use Mode=OneWayToSource, but this doesn't work for read-only properties:

```<code>  <Border
      ...
      ActualWidth="{Binding MyDataModelWidth, Mode=OneWayToSource}"
      >
      ... child controls ...
  </Border>
</code>```

The way I am doing it currently is to handle SizeChanged for the border and the code-behind plugs the value into the view model, but this doesn't feel quite right.

Has anyone already solved this problem?

UPDATE:
My question is effectively a duplicate of this one:
Pushing read-only GUI properties back into ViewModel

答:
do you really need a binding for that?</p>

```<code>    class MyVM
    {
        FrameworkElement _context;

        public MyVM(FrameworkElement context)
        {
            _context = context;
        }

        public double Width
        {
            get { return _context.ActualWidth; }
        }
    }
</code>```

Body:
I want to bind a read-only property of a control to my view model so that the value is available in the view model.

What is the best way of doing this?

For example I'd like to bind ActualWidth to a property in my view model.  The width value is generated by WPF using its layout logic so I can't generate this value in my view model and push it to the control property, as would normally be the case.  Instead I need to have WPF generate the value and push it to the view model.

I would just use Mode=OneWayToSource, but this doesn't work for read-only properties:

  <Border
      ...
      ActualWidth="{Binding MyDataModelWidth, Mode=OneWayToSource}"
      >
      ... child controls ...
  </Border>

The way I am doing it currently is to handle SizeChanged for the border and the code-behind plugs the value into the view model, but this doesn't feel quite right.

Has anyone already solved this problem?

UPDATE:
My question is effectively a duplicate of this one:
Pushing read-only GUI properties back into ViewModel

Body:
do you really need a binding for that?

    class MyVM
    {
        FrameworkElement _context;

        public MyVM(FrameworkElement context)
        {
            _context = context;
        }

        public double Width
        {
            get { return _context.ActualWidth; }
        }
    }


答:
Make your life easier using strtotime():

```<code>setcookie('theme', 'dark', strtotime('+1 year'), '/');
</code>```

By the way, cookies should be above everything else - it's part of the header. You should place it above all, else - it may produce errors (if you want to hide the errors you can simply insert @ before setcookie).

Title: how to make a cookie last a year PHP

Body:
Make your life easier using strtotime():

setcookie('theme', 'dark', strtotime('+1 year'), '/');

By the way, cookies should be above everything else - it's part of the header. You should place it above all, else - it may produce errors (if you want to hide the errors you can simply insert @ before setcookie).


问:
Get all Cities of Country from DBpedia using SPARQL
I would like to get all Cities of India from DBpedia database.

I tried many stackoverflow solutions but till now i have not got my required output.

How to fetch all Cities of Country using SPARQL.

答:
Might be (for sure) incomplete since data in DBpedia is based on mappings from Wikipedia (here only the infoboxes):

PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbr: <http://dbpedia.org/resource/>
SELECT ?s WHERE {
 ?s a dbo:City ;
    dbo:country dbr:India
}
```

<p>Or you can try to use the Wikipedia categories:</p>

<pre class="lang-sql prettyprint-override"><code>PREFIX dbc: <http://dbpedia.org/resource/Category:>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX dct: <http://purl.org/dc/terms/>
SELECT DISTINCT ?s WHERE {
 ?s dct:subject/skos:broader* dbc:Cities_and_towns_in_India
}
</code>```

Body:
Might be (for sure) incomplete since data in DBpedia is based on mappings from Wikipedia (here only the infoboxes):

PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbr: <http://dbpedia.org/resource/>
SELECT ?s WHERE {
 ?s a dbo:City ;
    dbo:country dbr:India
}

Or you can try to use the Wikipedia categories:

PREFIX dbc: <http://dbpedia.org/resource/Category:>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX dct: <http://purl.org/dc/terms/>
SELECT DISTINCT ?s WHERE {
 ?s dct:subject/skos:broader* dbc:Cities_and_towns_in_India
}


问:
How to interpret this result in machine learning? What's going wrong in model?
I am trying to train my model. I have tried so many parameters and I also increased the number of samples. But I'm unable to predict what's going wrong in my model and what should I do to improve accuracy? Here is the detail of my code. I'm collecting 50 thousand samples for a single class and I'm using 95 percent data for training.

```<code>def conv2d(input, filter):
    return tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME')
def max_pool(conv_out1):
    return tf.nn.max_pool(conv_out1, ksize=[1,2,2,1], strides= 1,2,2,1], padding='SAME')
input = tf.reshape(x, [-1, 16, 16,1])
filter = weight_variable([3, 3, 1,5])
conv_out1 = tf.nn.relu(conv2d(input,filter))
pooling_out1 = max_pool(conv_out1)
print pooling_out1.get_shape()
pool_list = pooling_out1.get_shape().as_list()
z = pool_list[1]*pool_list[2]*pool_list[3]
W_fc_input = tf.reshape(pooling_out2,[-1,z])
W_fc = weight_variable([z, 25])
entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y_)
loss = tf.reduce_mean(entropy)
run_optimizer = tf.train.AdamOptimizer(1e-4).minimize(loss)
for i in range(total_train_step):
    batch = Input.train.next_batch(batch_size)
    run_optimizer.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    if i % FLAGS.step_interval == 0:
       train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
       test_accuracy = accuracy.eval(feed_dict={x: Input_test.Samples, y_: InputData.test.labels, keep_prob: 1.0})
</code>```

答: I suppose you should change loss function from reduce_mean to something differ. Your loss value is not changed during training. As first attempt you can try reduce_sum.</p>

Body:
I am trying to train my model. I have tried so many parameters and I also increased the number of samples. But I'm unable to predict what's going wrong in my model and what should I do to improve accuracy? Here is the detail of my code. I'm collecting 50 thousand samples for a single class and I'm using 95 percent data for training.

def conv2d(input, filter):
    return tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME')
def max_pool(conv_out1):
    return tf.nn.max_pool(conv_out1, ksize=[1,2,2,1], strides= 1,2,2,1], padding='SAME')
input = tf.reshape(x, [-1, 16, 16,1])
filter = weight_variable([3, 3, 1,5])
conv_out1 = tf.nn.relu(conv2d(input,filter))
pooling_out1 = max_pool(conv_out1)
print pooling_out1.get_shape()
pool_list = pooling_out1.get_shape().as_list()
z = pool_list[1]*pool_list[2]*pool_list[3]
W_fc_input = tf.reshape(pooling_out2,[-1,z])
W_fc = weight_variable([z, 25])
entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y_)
loss = tf.reduce_mean(entropy)
run_optimizer = tf.train.AdamOptimizer(1e-4).minimize(loss)
for i in range(total_train_step):
    batch = Input.train.next_batch(batch_size)
    run_optimizer.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    if i % FLAGS.step_interval == 0:
       train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
       test_accuracy = accuracy.eval(feed_dict={x: Input_test.Samples, y_: InputData.test.labels, keep_prob: 1.0})


问:
why it returns empty value but of boolean type when no match is found
I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?</p>

```<code>$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('546',array_column($arr, 'uid'));

echo gettype($match);
</code>```

答:
your code is working , when array_search not found then return false and if  gettype($match); then show boolean and if found then return index so in this case return integer

this is code which return

```<code><?php
$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('5465',array_column($arr, 'uid'));

echo gettype($match);
</code>```

and output is: integer

this is normal example

```<code><?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>
</code>```

for more information

http://php.net/manual/ro/function.array-search.php

Body:
I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?

$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('546',array_column($arr, 'uid'));

echo gettype($match);

Body:
your code is working , when array_search not found then return false and if  gettype($match); then show boolean and if found then return index so in this case return integer

this is code which return

<?php
$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('5465',array_column($arr, 'uid'));

echo gettype($match);

and output is: integer

this is normal example

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

for more information

http://php.net/manual/ro/function.array-search.php


问:
how to send form data in orchard CMS
I'm using a form in my orchard website. How i can sent the form data to an email
     address?

     My form is like

```<code>   <form>
       <input type="text" name="name">
       <input type="submit"name="submit" value="submit">
     </form>
</code>```

答:
Orchard has built-in ways to do this. If you enable the Dynamic Forms, Email Messaging and Email Workflows Activities modules you can build forms and send emails with the submitted values, without writing a single line of code.

When you enable the Email Messaging module you will be prompted to configure the email settings. The only mandatory settings are Sender email address and host name. You can enter any email address here and use localhost for testing purposes.

If you want to show the form on every page, you don't need to edit the Layout.cshtml file. In fact there's rarely a reason to do so. Instead, go to the Widgets menu in the dashboard and add a new Form Widget to the default layer. Which zone you place it in is entirely up to you. In the editor of the widget you can build a form by dragging Dynamic Form elements to the layout.

Once you have your form set up, you can create a new workflow through the Workflows menu that sends an email every time your form is submitted. Simply start off with a Dynamic Form Submitted trigger to begin the workflow and link it to a Send Email activity. You can reference the form values in any of the email fields by using tokens, e.g.:

```<code><div>Name: {FormSubmission.Field:Name}</div>
</code>```

You can find step by step guides on dynamic forms and workflows in the official documentation:
http://docs.orchardproject.net/en/latest/Documentation/Creating-Dynamic-Forms/
http://docs.orchardproject.net/en/latest/Documentation/Workflows/

Just ignore the part on Custom Forms when you get to Workflows, since those are outdated.

Title: how to send form data in orchard CMS

Body:
I'm using a form in my orchard website. How i can sent the form data to an email
     address?

     My form is like

   <form>
       <input type="text" name="name">
       <input type="submit"name="submit" value="submit">
     </form>

Body:
Orchard has built-in ways to do this. If you enable the Dynamic Forms, Email Messaging and Email Workflows Activities modules you can build forms and send emails with the submitted values, without writing a single line of code.

When you enable the Email Messaging module you will be prompted to configure the email settings. The only mandatory settings are Sender email address and host name. You can enter any email address here and use localhost for testing purposes.

If you want to show the form on every page, you don't need to edit the Layout.cshtml file. In fact there's rarely a reason to do so. Instead, go to the Widgets menu in the dashboard and add a new Form Widget to the default layer. Which zone you place it in is entirely up to you. In the editor of the widget you can build a form by dragging Dynamic Form elements to the layout.

Once you have your form set up, you can create a new workflow through the Workflows menu that sends an email every time your form is submitted. Simply start off with a Dynamic Form Submitted trigger to begin the workflow and link it to a Send Email activity. You can reference the form values in any of the email fields by using tokens, e.g.:

<div>Name: {FormSubmission.Field:Name}</div>

You can find step by step guides on dynamic forms and workflows in the official documentation:
http://docs.orchardproject.net/en/latest/Documentation/Creating-Dynamic-Forms/
http://docs.orchardproject.net/en/latest/Documentation/Workflows/

Just ignore the part on Custom Forms when you get to Workflows, since those are outdated.


问:
QListView displays different sized items depending on sort order of model
Im trying to sort a QFileSystemModel by name, date of creation and date of last access (all ascending and descending). Im using QSortFilterProxyModel for sorting. Somehow there is a strange effect when changing sort order: The number of characters displayed until the name gets elided varies very strong. Depending on the sort order, some items have only three letters (Pro...) while others have up to ten (Programms). I already set the views grid size big enough (100x100), changing the icon size doesnt affect the view.

If I sort the QFileSystemModel directly everything works fine, but I cant sort by other aspects than filename then.

Where can I change the behavior how QSortFilterProxyModel elides text? Why does my proxy affect the view at all? Where can I find any further information about the QFileSystemModel at all? I still dont know what data is stored in the other columns (#1 is filename).

Screenshot:

As you can see, depending on the sortorder, filenames get elided or they don't. If im sorting descending, its "twai...", if im sorting ascending its "twain.dll".

Thats the code which gets executed when I click the sort arrow:

```<code>// initialization
fileNameSortModel = new QSortFilterProxyModel(parent);
fileNameSortModel.sourceModel(originalModel); // originalModel is type of QFileSystemModel

// ...

void PFileListWithHeader::onNameSort(Qt::SortOrder order)
{
    currentModel = fileNameSortModel;
    view->setModel(currentModel);
    view->setRootIndex(translateOriginalIndexToProxy(originalModel->index(path)));
    currentModel->sort(0, order);
}
</code>```

Thanks in advance!

答: The problem lies somewhere in the ItemDelegate which paints the icons onto the QListView. I subclassed it, handled eliding and painting myself and now everything works as it should. I will investigate this furter and post a detailled description as soon as (and if) I can.

Body:
Im trying to sort a QFileSystemModel by name, date of creation and date of last access (all ascending and descending). Im using QSortFilterProxyModel for sorting. Somehow there is a strange effect when changing sort order: The number of characters displayed until the name gets elided varies very strong. Depending on the sort order, some items have only three letters (Pro...) while others have up to ten (Programms). I already set the views grid size big enough (100x100), changing the icon size doesnt affect the view.

If I sort the QFileSystemModel directly everything works fine, but I cant sort by other aspects than filename then.

Where can I change the behavior how QSortFilterProxyModel elides text? Why does my proxy affect the view at all? Where can I find any further information about the QFileSystemModel at all? I still dont know what data is stored in the other columns (#1 is filename).

Screenshot:

As you can see, depending on the sortorder, filenames get elided or they don't. If im sorting descending, its "twai...", if im sorting ascending its "twain.dll".

Thats the code which gets executed when I click the sort arrow:

// initialization
fileNameSortModel = new QSortFilterProxyModel(parent);
fileNameSortModel.sourceModel(originalModel); // originalModel is type of QFileSystemModel

// ...

void PFileListWithHeader::onNameSort(Qt::SortOrder order)
{
    currentModel = fileNameSortModel;
    view->setModel(currentModel);
    view->setRootIndex(translateOriginalIndexToProxy(originalModel->index(path)));
    currentModel->sort(0, order);
}

Thanks in advance!


问:
Why agg() in PySpark is only able to summarize one column of a DataFrame at a time?
For the below dataframe

```<code>df = spark.createDataFrame(data=[('Alice',4.300),('Bob',7.677)], schema=['name','High'])
</code>```

When I try to find min & max I am only getting min value in output.

```<code>df.agg({'High':'max','High':'min'}).show()
</code>```

+-----------+
|min(High)  |
+-----------+
|    2094900|
+-----------+
```

Why can't agg() give both max & min like in Pandas?

答:
As you can see here:

agg(*exprs)

Compute aggregates and returns the result as a DataFrame.

The available aggregate functions are avg, max, min, sum, count.

If exprs is a single dict mapping from string to string, then the key is the column to perform aggregation on, and the value is the aggregate function.

Alternatively, exprs can also be a list of aggregate Column expressions.

Parameters:    exprs – a dict mapping from column name (string) to aggregate functions (string), or a list of Column.

You can use a list of column and apply the function that you need on every column, like this:

```<code>>>> from pyspark.sql import functions as F

>>> df.agg(F.min(df.High),F.max(df.High),F.avg(df.High),F.sum(df.High)).show()
+---------+---------+---------+---------+
|min(High)|max(High)|avg(High)|sum(High)|
+---------+---------+---------+---------+
|      4.3|    7.677|   5.9885|   11.977|
+---------+---------+---------+---------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For the below dataframe

df = spark.createDataFrame(data=[('Alice',4.300),('Bob',7.677)], schema=['name','High'])

When I try to find min & max I am only getting min value in output.

df.agg({'High':'max','High':'min'}).show()

+-----------+
|min(High)  |
+-----------+
|    2094900|
+-----------+

Why can't agg() give both max & min like in Pandas?

Body:
As you can see here:

agg(*exprs)

Compute aggregates and returns the result as a DataFrame.

The available aggregate functions are avg, max, min, sum, count.

If exprs is a single dict mapping from string to string, then the key is the column to perform aggregation on, and the value is the aggregate function.

Alternatively, exprs can also be a list of aggregate Column expressions.

Parameters:    exprs – a dict mapping from column name (string) to aggregate functions (string), or a list of Column.

You can use a list of column and apply the function that you need on every column, like this:

>>> from pyspark.sql import functions as F

>>> df.agg(F.min(df.High),F.max(df.High),F.avg(df.High),F.sum(df.High)).show()
+---------+---------+---------+---------+
|min(High)|max(High)|avg(High)|sum(High)|
+---------+---------+---------+---------+
|      4.3|    7.677|   5.9885|   11.977|
+---------+---------+---------+---------+


问:
How to redirect to another page after form action?
I am using Simple Form (getsimpleform.com) to email the HTML form contents to my email. The problem I am facing is that the HTML Form action is handled by getsimpleform so when the user clicks on submit button of the form, they are redirected to https://getsimpleform.com/ but I want them to stay be redirected to another page (i.e. contact.html).

So I want the form action to be performed but at the same time, I want the user to be redirected to another web page.

Thanks.

答:
First of all you need to change the action url of the form to your domain name

From

```<code>action="https://getsimpleform.com/"
</code>```

To

```<code>action="https://YourDomain.com/"
</code>```

and then on your php or whatever server side language you are using you can redirect e.g. I will use php example.

```<code>header('Location: http://www.YourDomain.com/OtherPage');
</code>```

Body:
First of all you need to change the action url of the form to your domain name

From

action="https://getsimpleform.com/"

To

action="https://YourDomain.com/"

and then on your php or whatever server side language you are using you can redirect e.g. I will use php example.

header('Location: http://www.YourDomain.com/OtherPage');


问:
Selenium finding xPath ID element that changes in Java
I have this xPath: //*[@id="searchpopupSCH_USER_1496689382343"]

but on the backend, the 13 digits are actually a timestamp so it changes everytime you re-test/re-click.

For example,

1st tab, //*[@id="searchpopupSCH_USER_1496689382343"]
2nt tab, //*[@id="searchpopupSCH_USER_1496694868441"]

Is there to target that ID that keeps changing?

I was thinking of using Reg Exp but somehow I am bit block.

```<code>    String frameID = "//*[@id=\"searchpopupSCH_USER_";
    String regExp = "\\d{13}";

    Pattern p = Pattern.compile(frameID + regExp);

    WebElement xPathUserList;
    xPathUserList.findElement(By.xpath(p));  //param of xpath only take String
</code>```

My concern is the WebElement.

How can you target By.Path("//*[@id=\"searchpopupSCH_USER_xxxxxxxxxxxx"

thanks for your inputs.

答:
Declare a variable like below:

```<code>public static final String TIME_STAMP = new SimpleDateFormat("ddMMyyHHmmss").format(Calendar.getInstance().getTime());
</code>```

Then in xpath:

```<code>driver.findElement(By.xapth("//htmltag[@id="searchpopupSCH_USER_".concat(TIME_STAMP + "]"));
</code>```

As per your requirement, you may change date format.

Body:
I have this xPath: //*[@id="searchpopupSCH_USER_1496689382343"]

but on the backend, the 13 digits are actually a timestamp so it changes everytime you re-test/re-click.

For example,

1st tab, //*[@id="searchpopupSCH_USER_1496689382343"]
2nt tab, //*[@id="searchpopupSCH_USER_1496694868441"]

Is there to target that ID that keeps changing?

I was thinking of using Reg Exp but somehow I am bit block.

    String frameID = "//*[@id=\"searchpopupSCH_USER_";
    String regExp = "\\d{13}";

    Pattern p = Pattern.compile(frameID + regExp);

    WebElement xPathUserList;
    xPathUserList.findElement(By.xpath(p));  //param of xpath only take String

My concern is the WebElement.

How can you target By.Path("//*[@id=\"searchpopupSCH_USER_xxxxxxxxxxxx"

thanks for your inputs.

Body:
Declare a variable like below:

public static final String TIME_STAMP = new SimpleDateFormat("ddMMyyHHmmss").format(Calendar.getInstance().getTime());

Then in xpath:

driver.findElement(By.xapth("//htmltag[@id="searchpopupSCH_USER_".concat(TIME_STAMP + "]"));

As per your requirement, you may change date format.


答:
You can add an action calback on your button, for example :

in yout HTML

```<code><form>
...
<input type="submit" onclick="redirect()">
</form>
</code>```

and in your javascript :

```<code>var redirect = function(){
   document.location.href="contact.html"
}
</code>```

Title: How to redirect to another page after form action?

Body:
I am using Simple Form (getsimpleform.com) to email the HTML form contents to my email. The problem I am facing is that the HTML Form action is handled by getsimpleform so when the user clicks on submit button of the form, they are redirected to https://getsimpleform.com/ but I want them to stay be redirected to another page (i.e. contact.html).

So I want the form action to be performed but at the same time, I want the user to be redirected to another web page.

Thanks.

Body:
You can add an action calback on your button, for example :

in yout HTML

<form>
...
<input type="submit" onclick="redirect()">
</form>

and in your javascript :

var redirect = function(){
   document.location.href="contact.html"
}


问:
What happens when one of the Kafka replicas is down
I have a cluster of 2 Kafka brokers and a topic with replication factor 2. If one of the brokers dies, will my producers be able to continue sending new messages to this degraded cluster of 1 node? Or replication factor 2 requires 2 alive nodes and messaged will be refused?</p>

答:
replication-factor 2 doesn't require 2 live brokers, it publish message while one broker is down depends on those configurations
- acks
- min.insync.replicas

Check those configurations as mentioned above @Javier


问:
Running external tools in Eclipse on Mac OS X
I'm using Flash Builder 4 on a mac. I've created a JSFL file for building a few fla's and then testing my main SWF file. I'm trying to run this JSFL file as an external tool from Flash Builder 4 but when I select Adobe Flash CS4.app as the file to run the JSFL Eclipse warns "External tool location specified is not a file."

I have Parallels installed and if I point at a .exe file this warning goes away. Is this a bug? Why can't I use a .app as an external tool in Eclipse?

答:
Try this:

Location: /usr/bin/open

Working Directory: empty

Arguments: -a /Applications/YourApp.app --args "arguments"


答:
Based on their official page recommendation on redirect

```<code>  <input type='hidden' name='redirect_to' value='https://yourdomain.com/contact.html' />
</code>```

Try to insert it into the form and see whether it solves your problem.

P.S. don't forget to change [yourdomain] to your actual domain.

Body:
Based on their official page recommendation on redirect

  <input type='hidden' name='redirect_to' value='https://yourdomain.com/contact.html' />

Try to insert it into the form and see whether it solves your problem.

P.S. don't forget to change [yourdomain] to your actual domain.


问:
Variable doesn't save the current List size
So I have this piece of code here:

```<code>List<String> s1 = new ArrayList<String>();
int size = s1.size();

s1.add("A");
s1.add("B");
System.out.println(size);
s1.add("C");
s1.add("D");
System.out.println(size);
</code>```

And that's the output:

```<code>0
0
</code>```

But it should be:

```<code>2
4
</code>```

What it the problem? Why doesn't the variable size get the current List size when I call her?

Thanks for helping me!

答:
At the time you did this  int size = s1.size(); the list was empty. so size is a primitive value that is not going to be updated automatically according to the list's sizes!

You need to refresh that value every time the list changes its size!

```<code>s1.add("A");
s1.add("B");
size = s1.size();   // update size
System.out.println(size);
s1.add("C");
s1.add("D");
size = s1.size();   // update size
System.out.println(size);
</code>```

Body:
So I have this piece of code here:

List<String> s1 = new ArrayList<String>();
int size = s1.size();

s1.add("A");
s1.add("B");
System.out.println(size);
s1.add("C");
s1.add("D");
System.out.println(size);

And that's the output:

0
0

But it should be:

2
4

What it the problem? Why doesn't the variable size get the current List size when I call her?

Thanks for helping me!

Body:
At the time you did this  int size = s1.size(); the list was empty. so size is a primitive value that is not going to be updated automatically according to the list's sizes!

You need to refresh that value every time the list changes its size!

s1.add("A");
s1.add("B");
size = s1.size();   // update size
System.out.println(size);
s1.add("C");
s1.add("D");
size = s1.size();   // update size
System.out.println(size);


问:
Laravel site works in directory, but isn't opened when move to subdirectory in Ubuntu 16.04
I am using Ubuntu 16.04. Here is my virtual host configuration. I edited my root folder from

/var/www/example.com/public_html/mysite/public

to

/var/www/example.com/public_html

Then I configured my vitualhost for sub directory, as below. Site shows only white screen. Error log, nginx error log is empty.

```<code>server {
        listen 80;
        #listen [::]:80 default_server ipv6only=on;

    root /var/www/example.com/public_html;
    index index.php index.html index.htm;

    server_name example.com www.example.com;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    error_log /var/www/logs/error.log;

   location = /50x.html {
            root /usr/share/nginx/html;
    }

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;

    }

    location ^~ /mysite {

            alias /var/www/example.com/public_html/mysite/public;
            try_files $uri $uri/ @mysite;

            location ~* \.php {
                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
                fastcgi_split_path_info ^(.+\.php)(.*)$;
                include /etc/nginx/fastcgi_params;
            }
    }

    location @mysite {
            rewrite ^/mysite/(.*)$ /mysite/index.php?/$1 last;
    }
</code>```

}

I can't figure out what is a problem.

1) File permissions, laravel configuration had been done correctly.

2) I assume that the problem is with php fpm. But it works, opening the website without subdirectory

I had done same thing before in Ubuntu 14.04. It seems, in Ubuntu 16.04 there is some difference. Also, I checked my public/index.php, added there die() function with message. But, again was white screen. Maybe, I miss something while configuring Nginx ?

答: /public is sub-directory of laravel, when you move your project to another directory root should be   your_project_path/public

Body:
I am using Ubuntu 16.04. Here is my virtual host configuration. I edited my root folder from

/var/www/example.com/public_html/mysite/public

to

/var/www/example.com/public_html

Then I configured my vitualhost for sub directory, as below. Site shows only white screen. Error log, nginx error log is empty.

server {
        listen 80;
        #listen [::]:80 default_server ipv6only=on;

    root /var/www/example.com/public_html;
    index index.php index.html index.htm;

    server_name example.com www.example.com;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    error_log /var/www/logs/error.log;

   location = /50x.html {
            root /usr/share/nginx/html;
    }

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;

    }

    location ^~ /mysite {

            alias /var/www/example.com/public_html/mysite/public;
            try_files $uri $uri/ @mysite;

            location ~* \.php {
                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
                fastcgi_split_path_info ^(.+\.php)(.*)$;
                include /etc/nginx/fastcgi_params;
            }
    }

    location @mysite {
            rewrite ^/mysite/(.*)$ /mysite/index.php?/$1 last;
    }

}

I can't figure out what is a problem.

1) File permissions, laravel configuration had been done correctly.

2) I assume that the problem is with php fpm. But it works, opening the website without subdirectory

I had done same thing before in Ubuntu 14.04. It seems, in Ubuntu 16.04 there is some difference. Also, I checked my public/index.php, added there die() function with message. But, again was white screen. Maybe, I miss something while configuring Nginx ?


问:
How to use DataFrame Window expressions and withColumn and not to change partition?
For some reason I have to convert RDD to DataFrame, then do something with DataFrame.

My interface is RDD,so I have to convert DataFrame to RDD， and when I use df.withcolumn, the partition change to 1, so I have to repartition and sortBy RDD.

Is there any cleaner solution ?

This is my code :

```<code>val rdd = sc.parallelize(List(1,3,2,4,5,6,7,8),4)
val partition = rdd.getNumPartitions
println(partition + "rdd")

val df=rdd.toDF()
val rdd2=df.rdd

val result = rdd.toDF("col1")
  .withColumn("csum", sum($"col1").over(Window.orderBy($"col1")))
  .withColumn("rownum", row_number().over(Window.orderBy($"col1")))
  .withColumn("avg", $"csum"/$"rownum").rdd

println(result.getNumPartitions + "rdd2")
</code>```

答:
Let's make this as simple as possible, we will generate the same data into 4 partitions

```<code>scala> val df = spark.range(1,9,1,4).toDF
df: org.apache.spark.sql.DataFrame = [id: bigint]

scala> df.show
+---+
| id|
+---+
|  1|
|  2|
|  3|
|  4|
|  5|
|  6|
|  7|
|  8|
+---+

scala> df.rdd.getNumPartitions
res13: Int = 4
</code>```

We don't need 3 window functions to prove this, so let's do it with one :

```<code>scala> import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.expressions.Window

scala> val df2 = df.withColumn("csum", sum($"id").over(Window.orderBy($"id")))
df2: org.apache.spark.sql.DataFrame = [id: bigint, csum: bigint]
</code>```

So what's happening here is that we didn't just add a column but we computed a window of cumulative sum over the data and since you haven't provided an partition column, the window function will move all the data to a single partition and you even get a warning from spark :

```<code>scala> df2.rdd.getNumPartitions
17/06/06 10:05:53 WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.
res14: Int = 1

scala> df2.show
17/06/06 10:05:56 WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.
+---+----+
| id|csum|
+---+----+
|  1|   1|
|  2|   3|
|  3|   6|
|  4|  10|
|  5|  15|
|  6|  21|
|  7|  28|
|  8|  36|
+---+----+
</code>```

So let's add now a column to partition on. We will create a new DataFrame just for the sake of demonstration :

```<code>scala> val df3 = df.withColumn("x", when($"id"<5,lit("a")).otherwise("b"))
df3: org.apache.spark.sql.DataFrame = [id: bigint, x: string]
</code>```

It has indeed the same number of partitions that we defined explicitly on df :

```<code>scala> df3.rdd.getNumPartitions
res18: Int = 4
</code>```

Let's perform our window operation using the column x to partition :

```<code>scala> val df4 = df3.withColumn("csum", sum($"id").over(Window.orderBy($"id").partitionBy($"x")))
df4: org.apache.spark.sql.DataFrame = [id: bigint, x: string ... 1 more field]

scala> df4.show
+---+---+----+
| id|  x|csum|
+---+---+----+
|  5|  b|   5|
|  6|  b|  11|
|  7|  b|  18|
|  8|  b|  26|
|  1|  a|   1|
|  2|  a|   3|
|  3|  a|   6|
|  4|  a|  10|
+---+---+----+
</code>```

The window function will repartition our data using the default number of partitions set in spark configuration.

```<code>scala> df4.rdd.getNumPartitions
res20: Int = 200
</code>```

Body:
For some reason I have to convert RDD to DataFrame, then do something with DataFrame.

My interface is RDD,so I have to convert DataFrame to RDD， and when I use df.withcolumn, the partition change to 1, so I have to repartition and sortBy RDD.

Is there any cleaner solution ?

This is my code :

val rdd = sc.parallelize(List(1,3,2,4,5,6,7,8),4)
val partition = rdd.getNumPartitions
println(partition + "rdd")

val df=rdd.toDF()
val rdd2=df.rdd

val result = rdd.toDF("col1")
  .withColumn("csum", sum($"col1").over(Window.orderBy($"col1")))
  .withColumn("rownum", row_number().over(Window.orderBy($"col1")))
  .withColumn("avg", $"csum"/$"rownum").rdd

println(result.getNumPartitions + "rdd2")

Body:
Let's make this as simple as possible, we will generate the same data into 4 partitions

scala> val df = spark.range(1,9,1,4).toDF
df: org.apache.spark.sql.DataFrame = [id: bigint]

scala> df.show
+---+
| id|
+---+
|  1|
|  2|
|  3|
|  4|
|  5|
|  6|
|  7|
|  8|
+---+

scala> df.rdd.getNumPartitions
res13: Int = 4

We don't need 3 window functions to prove this, so let's do it with one :

scala> import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.expressions.Window

scala> val df2 = df.withColumn("csum", sum($"id").over(Window.orderBy($"id")))
df2: org.apache.spark.sql.DataFrame = [id: bigint, csum: bigint]

So what's happening here is that we didn't just add a column but we computed a window of cumulative sum over the data and since you haven't provided an partition column, the window function will move all the data to a single partition and you even get a warning from spark :

scala> df2.rdd.getNumPartitions
17/06/06 10:05:53 WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.
res14: Int = 1

scala> df2.show
17/06/06 10:05:56 WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.
+---+----+
| id|csum|
+---+----+
|  1|   1|
|  2|   3|
|  3|   6|
|  4|  10|
|  5|  15|
|  6|  21|
|  7|  28|
|  8|  36|
+---+----+

So let's add now a column to partition on. We will create a new DataFrame just for the sake of demonstration :

scala> val df3 = df.withColumn("x", when($"id"<5,lit("a")).otherwise("b"))
df3: org.apache.spark.sql.DataFrame = [id: bigint, x: string]

It has indeed the same number of partitions that we defined explicitly on df :

scala> df3.rdd.getNumPartitions
res18: Int = 4

Let's perform our window operation using the column x to partition :

scala> val df4 = df3.withColumn("csum", sum($"id").over(Window.orderBy($"id").partitionBy($"x")))
df4: org.apache.spark.sql.DataFrame = [id: bigint, x: string ... 1 more field]

scala> df4.show
+---+---+----+
| id|  x|csum|
+---+---+----+
|  5|  b|   5|
|  6|  b|  11|
|  7|  b|  18|
|  8|  b|  26|
|  1|  a|   1|
|  2|  a|   3|
|  3|  a|   6|
|  4|  a|  10|
+---+---+----+

The window function will repartition our data using the default number of partitions set in spark configuration.

scala> df4.rdd.getNumPartitions
res20: Int = 200


问:
jQuery UI : My resize function is not working properly
I want to know that my resize function is not working properly as I aspected means the problem is when I resize the div ( increase the padding ) and leave it and when I again try to resize it padding shrinks.

Note : I am Increasing the padding not the height.

```<code>$( function() {
    $( "#resizable" ).resizable({
      resize: function( event, ui ) {
        var originalHeight = ui.originalSize.height;
        var newHeight = ui.size.height;
        var pad = 5;
        if (originalHeight < newHeight) {
          pad = newHeight - originalHeight;
        }
        $(this).css({'padding': pad, 'height': 200, 'width': 400});
      }
    });
 });
</code>```

My fiddle link

答:
Yeah @Botimoo seems correct. You should probably consider positioning with something other than padding. But something like this probably is close to what you want if you want to stick with padding

https://jsfiddle.net/6rh7emog/5/

```<code><div id="resizable" class="ui-widget-content">
  <div id="wrapper">
    <h3 class="ui-widget-header">Resizable</h3>
  </div>
</code>```

```<code>$( function() {
    $( "#resizable" ).resizable({
      aspectRatio: true,
      resize: function( event, ui ) {
        var originalHeight = ui.originalSize.height;
        var newHeight = ui.size.height;
        $('#wrapper').css({
              'padding': newHeight - 200
        });
      }
    });
 });
</code>```

Body:
I want to know that my resize function is not working properly as I aspected means the problem is when I resize the div ( increase the padding ) and leave it and when I again try to resize it padding shrinks.

Note : I am Increasing the padding not the height.

$( function() {
    $( "#resizable" ).resizable({
      resize: function( event, ui ) {
        var originalHeight = ui.originalSize.height;
        var newHeight = ui.size.height;
        var pad = 5;
        if (originalHeight < newHeight) {
          pad = newHeight - originalHeight;
        }
        $(this).css({'padding': pad, 'height': 200, 'width': 400});
      }
    });
 });

My fiddle link

Body:
Yeah @Botimoo seems correct. You should probably consider positioning with something other than padding. But something like this probably is close to what you want if you want to stick with padding

https://jsfiddle.net/6rh7emog/5/

<div id="resizable" class="ui-widget-content">
  <div id="wrapper">
    <h3 class="ui-widget-header">Resizable</h3>
  </div>

$( function() {
    $( "#resizable" ).resizable({
      aspectRatio: true,
      resize: function( event, ui ) {
        var originalHeight = ui.originalSize.height;
        var newHeight = ui.size.height;
        $('#wrapper').css({
              'padding': newHeight - 200
        });
      }
    });
 });


问:
Ocaml - How can I convert value of int variable to string?
I want to make string "t1", "t2","t3", ...so on.

so I did like this
let i =0;...
(something) -> let z = "t" ^ string_of_int (i+1)

my intention is every time that program enters (something), i increases.
because I have to make new string when program enters (something).

but it had syntax error
What should I do?

答:
If you want to embed an integer as part of a string, use Printf.sprintf:

```<code>let make_string i =
  Printf.sprintf "t%d" i
</code>```

You'll have to take care of tht part that generates increasing numbers with something else, like a for loop.

Body:
If you want to embed an integer as part of a string, use Printf.sprintf:

let make_string i =
  Printf.sprintf "t%d" i

You'll have to take care of tht part that generates increasing numbers with something else, like a for loop.


答:
To print correct size you should always use s1.size(); in your case. as list is modifiable, hence storing it in a local variable will not help unless you have unmodifiable list. As local variable is not updated every-time new entry is added/removed in the list.

You should call s1.size(); after adding data to the list.

Title: Variable doesn't save the current List size


问:
Is it possible to see where a .DLL is searching for a file?
I get a "File not found." message from a .DLL I am using, but I am not sure which path it tries to find the file in. It might as well be hard-coded, and I would like to find out.

Is there any method or tool I could use?

Thank you in advance

答:
Try using Process Explorer. From the page:

Ever wondered which program has a particular file or directory open?
  Now you can find out. Process Explorer shows you information about
  which handles and DLLs processes have opened or loaded.

If you hit Ctrl + D (show DLL view - can also be done from View menu) and then select your process, it will show all of the DLLs loaded by that process and their locations.

You may also get useful answers asking in Software Recommendations.


问:
How to render 3d object to silhouette image in python?
I am trying to render an obj (a human body model) to its corresponding silhouette image given camera intrinsic&&extrinsic parameters and I want to know which renderer is suitable for the task. I don't want real time display of the rendered images because efficiency is my top concern. I have 100000 3d objects and i need to write a script to render the silhouette images of those objects in one go. </p>

答:
Here is a small example rendering with OpenGL to an image using ModernGL and Pillow

pillow docs

ModernGL docs

Sample code:

```<code>import struct

import ModernGL
from PIL import Image

ctx = ModernGL.create_standalone_context()

prog = ctx.program([
    ctx.vertex_shader('''
        #version 330
        in vec2 vert;
        void main() {
            gl_Position = vec4(vert, 0.0, 1.0);
        }
    '''),
    ctx.fragment_shader('''
        #version 330
        out vec4 color;
        void main() {
            color = vec4(0.3, 0.5, 1.0, 1.0);
        }
    '''),
])

vbo = ctx.buffer(struct.pack('6f', 0.0, 0.8, -0.6, -0.8, 0.6, -0.8))
vao = ctx.simple_vertex_array(prog, vbo, ['vert'])

fbo = ctx.framebuffer(ctx.renderbuffer((512, 512)))

fbo.use()
ctx.viewport = (0, 0, 512, 512)
ctx.clear(0.9, 0.9, 0.9)
vao.render()

pixels = fbo.read(components=3, alignment=1)
img = Image.frombytes('RGB', fbo.size, pixels).transpose(Image.FLIP_TOP_BOTTOM)
img.show()
</code>```

Body:
Here is a small example rendering with OpenGL to an image using ModernGL and Pillow

pillow docs

ModernGL docs

Sample code:

import struct

import ModernGL
from PIL import Image

ctx = ModernGL.create_standalone_context()

prog = ctx.program([
    ctx.vertex_shader('''
        #version 330
        in vec2 vert;
        void main() {
            gl_Position = vec4(vert, 0.0, 1.0);
        }
    '''),
    ctx.fragment_shader('''
        #version 330
        out vec4 color;
        void main() {
            color = vec4(0.3, 0.5, 1.0, 1.0);
        }
    '''),
])

vbo = ctx.buffer(struct.pack('6f', 0.0, 0.8, -0.6, -0.8, 0.6, -0.8))
vao = ctx.simple_vertex_array(prog, vbo, ['vert'])

fbo = ctx.framebuffer(ctx.renderbuffer((512, 512)))

fbo.use()
ctx.viewport = (0, 0, 512, 512)
ctx.clear(0.9, 0.9, 0.9)
vao.render()

pixels = fbo.read(components=3, alignment=1)
img = Image.frombytes('RGB', fbo.size, pixels).transpose(Image.FLIP_TOP_BOTTOM)
img.show()


问:
Add hyperlink to Apple Passbook front page
I tried to find solution for this across lot of resources on the internet including the Passbook documentation but I didn't have any success.

I know it's possible to add hyperlink on the back of the Passbook but that's not something I can use.

I'm trying to create a Passbook with the logo, date and title on the top, two hyperlinks (buttons) in the middle and the barcode in the bottom of the Passbook.

Thanks in advance!

答:
No, it's not possible to add hyperlinks to the fields on the front of a pass. The data detector behaviour of Wallet only applies to back fields.

https://developer.apple.com/library/content/documentation/UserExperience/Reference/PassKit_Bundle/Chapters/FieldDictionary.html#//apple_ref/doc/uid/TP40012026-CH4-SW5

Under the Standard Field section, you'll see mention of dataDetectorTypes. It's stated there.


问:
jquery validate check at least one checkbox with dynamicly id's
I want to validate that atleast one checkbox is selected. The checkboxes are added dynamicly so the exact ID's are unknown. All i know is that they start with the same ID name e.g.  "Sameid_xxx", "Sameid_xx1"
,"Sameid_xx2" etc..

here is what i have:

```<code>$cbx_group = $('input[Id^="Sameid"]');

$cbx_group.prop('required', true);
if ($cbx_group.is(":checked")) {
  $cbx_group.prop('required', false);
}
</code>```

the problem here is that this makes all checkboxes required. I also dont have form validator

答:
You can try this:

Use attribute contains selector.
Link: http://api.jquery.com/attribute-contains-selector/

function test() {
$cbx_group = $('input[Id*="Sameid"]');

$cbx_group.prop('required', true);
if ($cbx_group.is(":checked")) {
  $cbx_group.prop('required', false);
  console.log('checked');
} else {
console.log('not checked');
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="Sameid1">
<input type="checkbox" id="Sameid2">

<button id="one" onclick="test()">Click</button></code>```

Body:
I want to validate that atleast one checkbox is selected. The checkboxes are added dynamicly so the exact ID's are unknown. All i know is that they start with the same ID name e.g.  "Sameid_xxx", "Sameid_xx1"
,"Sameid_xx2" etc..

here is what i have:

$cbx_group = $('input[Id^="Sameid"]');

$cbx_group.prop('required', true);
if ($cbx_group.is(":checked")) {
  $cbx_group.prop('required', false);
}

the problem here is that this makes all checkboxes required. I also dont have form validator

Body:
You can try this:

Use attribute contains selector.
Link: http://api.jquery.com/attribute-contains-selector/

function test() {
$cbx_group = $('input[Id*="Sameid"]');

$cbx_group.prop('required', true);
if ($cbx_group.is(":checked")) {
  $cbx_group.prop('required', false);
  console.log('checked');
} else {
console.log('not checked');
}

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="Sameid1">
<input type="checkbox" id="Sameid2">

<button id="one" onclick="test()">Click</button>


问:
how to make a cookie last a year PHP
I attempted to make a cookie-based theme switcher using PHP, and to make the cookie I use this:

```<code>$t = $_GET["t"];
if($t == "dark" || "light" || "mixed") {
    setcookie("theme", $t, time() + 31556926, "/");
} elseif(!isset($t) and !isset($_COOKIE["theme"])) {
    setcookie("theme", "dark", time() + 31556926 , "/");
}
if(isset($_COOKIE["theme"])) {
    echo "<body style=\"background:url(/imgs/" . $_COOKIE['theme'] . ".gif) top left repeat\">";
} else {
    echo "<body style=\"background:url(/imgs/dark.gif) top left repeat\">";
}
</code>```

But this doesn't seem to work, it reloads the page and sets the cookie, but has a strange property of needing to reload the page again in order for it to change the background, and only lasting for the session. As well as this, when you return to the index.php without ?t=light it stays, but then when you reload it disappears. I couldn't figure out any reason that it should be acting this way.

答:
Not sure if there is a maximum, however I found a couple of people who suggest it is limited by the unixtime, ie nothing past 2038.  However, as others have pointed out, there is no point making it more than 10 years as browsers / computers will expire within 10 years and be reloading or replaced etc.  My reference:
https://www.quora.com/What-is-the-limit-to-a-persistent-cookies-expiry-date

In the meantime I found this regarding the size and number limits:
http://browsercookielimits.iain.guru/

Title: how to make a cookie last a year PHP

Body:
I attempted to make a cookie-based theme switcher using PHP, and to make the cookie I use this:

$t = $_GET["t"];
if($t == "dark" || "light" || "mixed") {
    setcookie("theme", $t, time() + 31556926, "/");
} elseif(!isset($t) and !isset($_COOKIE["theme"])) {
    setcookie("theme", "dark", time() + 31556926 , "/");
}
if(isset($_COOKIE["theme"])) {
    echo "";
} else {
    echo "";
}

But this doesn't seem to work, it reloads the page and sets the cookie, but has a strange property of needing to reload the page again in order for it to change the background, and only lasting for the session. As well as this, when you return to the index.php without ?t=light it stays, but then when you reload it disappears. I couldn't figure out any reason that it should be acting this way.


问:
xsl template is overriding with xsl include
I am trying to create some reusable templates while developing a html page for xml with xsl. But when I include the other xsl's, the main xsl template is getting overridden instead of adding it to it. please suggest.

Here is my xml,

```<code><employee>
<address>
    <street>street1</street>
    <city>city1</city>
    <doornumber>1-23</doornumber>
    <pincode>123456</pincode>
</address>
<personalinfo>
    <name>testname1</name>
    <phone>999999999</phone>
    <dob>23-09-34</dob>
</personalinfo>
<remarks>
    <education>
        <name>testname2</name>
        <college>college1</college>
        <gpa>7.5</gpa>
    </education>
</remarks>

<data>
    <name>data1</name>
</data>
<data>
    <name>data2</name>
</data>
<data>
    <name>data3</name>
</data>
<data>
    <name>data4</name>
</data>
<data>
    <name>data5</name>
</data>
</employee>
</code>```

Here is my main xsl,

```<code> <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:template match="/">
    <html>
        <body>
            <table>
                <tr>
                    <th>Name</th>
                    <th>College</th>
                    <th>City</th>
                </tr>
                <xsl:apply-templates/>
            </table>
        </body>
    </html>
</xsl:template>

<xsl:template match="employee">
    <tr>
        <td>
            <xsl:value-of select="personalinfo/name"/>
        </td>
        <td>
            <xsl:value-of select="remarks/education/college"/>
        </td>
        <td>
            <xsl:value-of select="address/city"/>
        </td>
    </tr>
</xsl:template>
<!-- <xsl:include href="test_include1.xsl" /> -->
<!-- <xsl:include href="test_include2.xsl" /> -->
</xsl:stylesheet>
</code>```

Here is my test_include1.xsl,

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:template match="employee">

<table><tr>
    <th>data names</th></tr>
<xsl:for-each select="data">
<tr>
    <td>
        <xsl:value-of select="name"/>
    </td>
</tr>

</xsl:for-each>
</table>
</xsl:template>

</xsl:stylesheet>
</code>```

Here is my test_include2.xsl,

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:template match="employee">

<table><tr>
                <th>Name</th>
                <th>College</th></tr>
<tr>
    <td>
        <xsl:value-of select="personalinfo/name"/>
    </td>
    <td>
        <xsl:value-of select="remarks/education/college"/>
    </td>
    </tr>
</table>
</xsl:template>
</xsl:stylesheet>
</code>```

I am trying to modularize the same xml data in different templates so that I can reuse the same templates in other stylesheets. Please suggest how I can acheive this. Thank you.
Here is the expected result,

```<code>     <html><body>
   <table>
        <tr>
        <th>Name</th>
        <th>College</th>
        <th>City</th>
        </tr>
        <tr>
        <td>testname1</td>
        <td>college1</td>
        <td>city1</td>
        </tr>
    </table>
    <table>
        <tr><th>data names</th></tr>
        <tr><td>data1</td></tr>
        <tr><td>data2</td></tr>
        <tr><td>data3</td></tr>
        <tr><td>data4</td></tr>
        <tr><td>data5</td></tr>
     </table>
     <table>
        <tr>
        <th>Name</th>
        <th>College</th>
        </tr>
        <tr>
        <td>testname1</td>
        <td>college1</td>
        </tr>
    </table>
    </body></html>
</code>```

答:
Firstly, I don't see any xsl:include declarations in any of these stylesheets, so I'm not quite sure what you are doing. [Sorry - missed the pale grey commented out code - poor contrast on my monitor.]

Secondly, with XSLT 1.0 the behaviour when you have two templates matching the same node, with the same precedence and priority, is not very well defined. Technically it's an error, but the processor is allowed to recover by choosing the rule that comes "last in the stylesheet" - which itself is not particularly well defined when there are multiple modules involved.

Thirdly, you say "the main xsl template is getting overridden instead of adding it to it". This suggests you have some particular expectation of how you want it to behave, but I can't really work out what this expectation is. You haven't given any expected results, so I don't know what you are trying to achieve. But it will always be the case, if you have more than one rule that matches a node, that you either get an error, or exactly one of the rules is executed - they are never combined in any way.

Body:
I am trying to create some reusable templates while developing a html page for xml with xsl. But when I include the other xsl's, the main xsl template is getting overridden instead of adding it to it. please suggest.

Here is my xml,

<employee>
<address>
    <street>street1</street>
    <city>city1</city>
    <doornumber>1-23</doornumber>
    <pincode>123456</pincode>
</address>
<personalinfo>
    <name>testname1</name>
    <phone>999999999</phone>
    <dob>23-09-34</dob>
</personalinfo>
<remarks>
    <education>
        <name>testname2</name>
        <college>college1</college>
        <gpa>7.5</gpa>
    </education>
</remarks>

<data>
    <name>data1</name>
</data>
<data>
    <name>data2</name>
</data>
<data>
    <name>data3</name>
</data>
<data>
    <name>data4</name>
</data>
<data>
    <name>data5</name>
</data>
</employee>

Here is my main xsl,

 <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:template match="/">

                    Name
                    College
                    City

                <xsl:apply-templates/>

</xsl:template>

<xsl:template match="employee">

            <xsl:value-of select="personalinfo/name"/>

            <xsl:value-of select="remarks/education/college"/>

            <xsl:value-of select="address/city"/>

</xsl:template>

</xsl:stylesheet>

Here is my test_include1.xsl,

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:template match="employee">

    data names

<xsl:for-each select="data">

        <xsl:value-of select="name"/>

</xsl:for-each>

</xsl:template>

</xsl:stylesheet>

Here is my test_include2.xsl,

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:template match="employee">

                Name
                College

        <xsl:value-of select="personalinfo/name"/>

        <xsl:value-of select="remarks/education/college"/>

</xsl:template>
</xsl:stylesheet>

I am trying to modularize the same xml data in different templates so that I can reuse the same templates in other stylesheets. Please suggest how I can acheive this. Thank you.
Here is the expected result,

        Name
        College
        City

        testname1
        college1
        city1

data names

data1

data2

data3

data4

data5

        Name
        College

        testname1
        college1