问:
tsqlt ways to test stored procedures producing files as output
I have a stored procedure which created a file using BCP. I need to validate the data in the file with a predefined expected resultset. Is there a way this can be tested using TSQLT?</p>

答:
Using tSQLt Tests to confirm bcp.exe reading in data is usually possible.

Using tSQLt Tests to confirm bcp.exe writing out data, on the other hand, is generally quite problematic.

The reason is that tSQLt Tests are run inside SQL Transactions so that they can clean up any modifications you've made at the end of each test. This basically rules out any tSQLt Tests involving external processes (bcp.exe, isql.exe, osql.exe, sqlcmd.exe, etc.) accessing any tables that your tSQLt Tests (or Setup procedures) modify because those tables will have ROW/PAGE/TABLE locks held on them for the duration of the current tSQLt Test. External processes will be connecting back into the database using a different SQL Connection and so will be blocked by the ROW/PAGE/TABLE locks that the tSQLt Transaction holds. bcp.exe, in particular, will essentially wait forever for the locks to be released which will never happen because the tSQLt Test is waiting forever for bcp.exe to return.

So, there are three possibilities here:

Only use bcp.exe to export pre-existing data in tables that you do not modify at all during the tSQLt Test. (This includes ##Temp Tables.)

Don't use bcp.exe (, isql.exe, osql.exe, sqlcmd.exe, etc.) to export data at all. Prefer to use SQL CLR Procedures. Written properly (as in, given @table parameters) these will run in the current SQL connection and so will not be obstructed by current ROW/PAGE/TABLE locks.

Alternatively to 2, if you don't like writing SQL CLR Assemblies, try using OLE Automation Procedures to export your data. Again these will run in the current SQL Connection so, written properly, will not be obstructed by current ROW/PAGE/TABLE locks. Be aware that this opens up more security holes on your SQL Server as you need to enable OLE Automation Procedures via sp_configure... but if you're using bcp.exe from SQL then you've already enabled xp_cmdshell on your SQL Server.

To enable OLE Automation Procedures execute the following:

```<code>sp_configure 'Show Advanced Options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
sp_configure 'Show Advanced Options', 0;
GO
RECONFIGURE;
GO
</code>```

An SQL stored procedure to write an XML variable out to a file might look like this:

```<code>create procedure [dbo].[sp_ExportXmlDataToFile]
    @XmlData xml,
    @XmlFilename nvarchar(255)
as begin
    declare @OleAutomationObjectHandle int, @FileHandle int;
    declare @HResult int, @Source nvarchar(255), @Description nvarchar(255);

    --REF: OpenTextFile Method, https://msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx
    declare @IOMode_ForReading int = 1, @IOMode_ForWriting int = 2, @IOMode_ForAppending int = 8;
    declare @Create_OpenExisting int = 0, @Create_CreateNew int = 1;
    declare @FileFormat_ASCII int = 0, @FileFormat_Unicode int = -1, @FileFormat_Default int = -2; --<<--NOTE: Negative numbers

    execute @HResult = sys.sp_OACreate N'Scripting.FileSystemObject', @OleAutomationObjectHandle out
    if (@HResult <> 0)
    begin
        exec sys.sp_OAGetErrorInfo @OleAutomationObjectHandle, @Source out, @Description out
        raiserror(N'Error Creating COM Component (Scripting.FileSystemObject) 0x%x, %s, %s', 16, 1, @HResult, @Source, @Description)
    end
    else
    begin
        execute @HResult = sys.sp_OAMethod @OleAutomationObjectHandle, N'OpenTextFile', @FileHandle out, @XmlFilename, @IOMode_ForWriting, @Create_CreateNew, @FileFormat_Default
        if (@HResult <> 0)
        begin
            exec sys.sp_OAGetErrorInfo @OleAutomationObjectHandle, @Source out, @Description out
            raiserror(N'Error calling COM Component (Scripting.FileSystemObject.OpenTextFile) 0x%x, %s, %s', 16, 1, @HResult, @Source, @Description)
        end
        else
        begin
            declare @Text nvarchar(max) = cast(@XmlData as nvarchar(max))
            execute sys.sp_OAMethod @FileHandle, N'Write', null, @Text
            execute sys.sp_OADestroy @FileHandle
        end
        execute sys.sp_OADestroy @OleAutomationObjectHandle
    end
end
go
</code>```

Then, a tSQLt Test that uses it might look something like this:

```<code>create procedure [SomethingOrOther_Tests].[Test That sp_LoadXmlFile Inserts Data]
as begin
    -- Assemble
    declare @Expected uniqueidentifier = newid();
    declare @XmlFilename nvarchar(255) = N'C:\Temp\SomethingOrOther_Tests.Test That sp_LoadXmlFile Inserts Data.xml';
    declare @XmlData xml =
N'<S11:Envelope xmlns:S11="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <S11:Header/>
    <S11:Body/>
</S11:Envelope>';
    exec [dbo].[sp_ExportXmlDataToFile] @XmlData=@XmlData, @XmlFilename=@XmlFilename

    -- Act
    exec [dbo].[sp_LoadXmlFile] @ImportGUID=@Expected, @XmlFilename=@XmlFilename

    -- Assert
    declare @Actual uniqueidentifier = (select ImportGUID from dbo.tImportTable where ImportGUID=@Expected)
    exec [tSQLt].[AssertEquals] @Expected, @Actual, 'Did not find expected ImportGUID'
end
go
</code>```

Body:
Using tSQLt Tests to confirm bcp.exe reading in data is usually possible.

Using tSQLt Tests to confirm bcp.exe writing out data, on the other hand, is generally quite problematic.

The reason is that tSQLt Tests are run inside SQL Transactions so that they can clean up any modifications you've made at the end of each test. This basically rules out any tSQLt Tests involving external processes (bcp.exe, isql.exe, osql.exe, sqlcmd.exe, etc.) accessing any tables that your tSQLt Tests (or Setup procedures) modify because those tables will have ROW/PAGE/TABLE locks held on them for the duration of the current tSQLt Test. External processes will be connecting back into the database using a different SQL Connection and so will be blocked by the ROW/PAGE/TABLE locks that the tSQLt Transaction holds. bcp.exe, in particular, will essentially wait forever for the locks to be released which will never happen because the tSQLt Test is waiting forever for bcp.exe to return.

So, there are three possibilities here:

Only use bcp.exe to export pre-existing data in tables that you do not modify at all during the tSQLt Test. (This includes ##Temp Tables.)

Don't use bcp.exe (, isql.exe, osql.exe, sqlcmd.exe, etc.) to export data at all. Prefer to use SQL CLR Procedures. Written properly (as in, given @table parameters) these will run in the current SQL connection and so will not be obstructed by current ROW/PAGE/TABLE locks.

Alternatively to 2, if you don't like writing SQL CLR Assemblies, try using OLE Automation Procedures to export your data. Again these will run in the current SQL Connection so, written properly, will not be obstructed by current ROW/PAGE/TABLE locks. Be aware that this opens up more security holes on your SQL Server as you need to enable OLE Automation Procedures via sp_configure... but if you're using bcp.exe from SQL then you've already enabled xp_cmdshell on your SQL Server.

To enable OLE Automation Procedures execute the following:

sp_configure 'Show Advanced Options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
sp_configure 'Show Advanced Options', 0;
GO
RECONFIGURE;
GO

An SQL stored procedure to write an XML variable out to a file might look like this:

create procedure [dbo].[sp_ExportXmlDataToFile]
    @XmlData xml,
    @XmlFilename nvarchar(255)
as begin
    declare @OleAutomationObjectHandle int, @FileHandle int;
    declare @HResult int, @Source nvarchar(255), @Description nvarchar(255);

    --REF: OpenTextFile Method, https://msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx
    declare @IOMode_ForReading int = 1, @IOMode_ForWriting int = 2, @IOMode_ForAppending int = 8;
    declare @Create_OpenExisting int = 0, @Create_CreateNew int = 1;
    declare @FileFormat_ASCII int = 0, @FileFormat_Unicode int = -1, @FileFormat_Default int = -2; --<<--NOTE: Negative numbers

    execute @HResult = sys.sp_OACreate N'Scripting.FileSystemObject', @OleAutomationObjectHandle out
    if (@HResult <> 0)
    begin
        exec sys.sp_OAGetErrorInfo @OleAutomationObjectHandle, @Source out, @Description out
        raiserror(N'Error Creating COM Component (Scripting.FileSystemObject) 0x%x, %s, %s', 16, 1, @HResult, @Source, @Description)
    end
    else
    begin
        execute @HResult = sys.sp_OAMethod @OleAutomationObjectHandle, N'OpenTextFile', @FileHandle out, @XmlFilename, @IOMode_ForWriting, @Create_CreateNew, @FileFormat_Default
        if (@HResult <> 0)
        begin
            exec sys.sp_OAGetErrorInfo @OleAutomationObjectHandle, @Source out, @Description out
            raiserror(N'Error calling COM Component (Scripting.FileSystemObject.OpenTextFile) 0x%x, %s, %s', 16, 1, @HResult, @Source, @Description)
        end
        else
        begin
            declare @Text nvarchar(max) = cast(@XmlData as nvarchar(max))
            execute sys.sp_OAMethod @FileHandle, N'Write', null, @Text
            execute sys.sp_OADestroy @FileHandle
        end
        execute sys.sp_OADestroy @OleAutomationObjectHandle
    end
end
go

Then, a tSQLt Test that uses it might look something like this:

create procedure [SomethingOrOther_Tests].[Test That sp_LoadXmlFile Inserts Data]
as begin
    -- Assemble
    declare @Expected uniqueidentifier = newid();
    declare @XmlFilename nvarchar(255) = N'C:\Temp\SomethingOrOther_Tests.Test That sp_LoadXmlFile Inserts Data.xml';
    declare @XmlData xml =
N'<S11:Envelope xmlns:S11="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <S11:Header/>
    <S11:Body/>
</S11:Envelope>';
    exec [dbo].[sp_ExportXmlDataToFile] @XmlData=@XmlData, @XmlFilename=@XmlFilename

    -- Act
    exec [dbo].[sp_LoadXmlFile] @ImportGUID=@Expected, @XmlFilename=@XmlFilename

    -- Assert
    declare @Actual uniqueidentifier = (select ImportGUID from dbo.tImportTable where ImportGUID=@Expected)
    exec [tSQLt].[AssertEquals] @Expected, @Actual, 'Did not find expected ImportGUID'
end
go


来源: stackexchange

问:
What are all of the generic collections/types in the 4.0 .NET Framework?
Is there an exhaustive list of all of the "base" (not used in an object-oriented sense but more in a common sense) generic types in the 4.0 .NET Framework? I have found this list that I often send newer/mid-level devs to so they can understand how non-generic types map to generic types, but this is by no means exhaustive. I'm looking for something that also includes things such as KeyValuePair<>, Tuple<>, and other basic generics that may not be very-well known. Interfaces such as IObservable<> would be nice but not necessarily required.

答:
Here's a powershell fragment to list all the generic types in the system assemblies

```<code>[AppDomain]::CurrentDomain.GetAssemblies() |
    ? { $_.FullName -match "^System" -or $_.FullName -match "mscorlib"} |
        % { $_.GetTypes() | ? { $_.ContainsGenericParameters } }
</code>```

This could be adapted to give a more comprehensive list. If you load powershell w/ a .Net 4 config, you'll get the 4.0 list.

```<code>Count Name
----- ----
    1 System.Xml
   12 System.Data
   67 System
  187 mscorlib
  325 System.Core
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here's a powershell fragment to list all the generic types in the system assemblies

[AppDomain]::CurrentDomain.GetAssemblies() |
    ? { $_.FullName -match "^System" -or $_.FullName -match "mscorlib"} |
        % { $_.GetTypes() | ? { $_.ContainsGenericParameters } }

This could be adapted to give a more comprehensive list. If you load powershell w/ a .Net 4 config, you'll get the 4.0 list.

Count Name
----- ----
    1 System.Xml
   12 System.Data
   67 System
  187 mscorlib
  325 System.Core


问:
Remove extra spaces but not space between two words
I want to remove extra spaces present in my string. I have tried trim,ltrim,rtrim and others but non of them are working and even tried the below stuffs.

```<code>//This removes all the spaces even the space between the words
// which i want to be kept
$new_string = preg_replace('/\s/u', '', $old_string);
</code>```

Is there any solution for this ?

Updated:-

Input String:-

```<code>"
Hello Welcome
                             to India    "
</code>```

Output String:-

```<code>"Hello Welcome to India"
</code>```

答:
Try this, this will also remove all &nbsp</p>

```<code>$node3 = htmlentities($node3, null, 'utf-8');
$node3 = str_replace(" ", "", $node3);
$node3 = html_entity_decode($node3);

$node3 = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $node3);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to remove extra spaces present in my string. I have tried trim,ltrim,rtrim and others but non of them are working and even tried the below stuffs.

//This removes all the spaces even the space between the words
// which i want to be kept
$new_string = preg_replace('/\s/u', '', $old_string);

Is there any solution for this ?

Updated:-

Input String:-

"
Hello Welcome
                             to India    "

Output String:-

"Hello Welcome to India"

Body:
Try this, this will also remove all &nbsp

$node3 = htmlentities($node3, null, 'utf-8');
$node3 = str_replace("&nbsp;", "", $node3);
$node3 = html_entity_decode($node3);

$node3 = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $node3);


问:
php in_array - can't verify presence of an item
I'm trying to check whether an item exists in an array that is populated from a file, which consists of filenames, one on each line, like this:

GG.jpg

2J.jpg

WWWW.jpg

I have the following so far:

```<code>$UsedAvatars = array();

$UsedAvatars = file('UsedAvatars.txt',  FILE_IGNORE_NEW_LINES );

// This next part is to check that the array has been populated, and
// it works.

for($counter=0; $counter<count($UsedAvatars); $counter++)
{
    echo $counter . "\t" . $UsedAvatars[$counter] . "<br>";
}

echo "<br>";

    // This is hardwired in because I know that it is in the text file
    // used to populate the array and so should return TRUE
    $filename="GG.jpg";

if( in_array( $filename, $UsedAvatars ) )
{
  echo "found";
}
</code>```

However, the test does not work and "found" is not outputted. I cannot see what is wrong, can anyone help please?

答:
try to replace

```<code>if( in_array( $filename, $UsedAvatars ) )
{
  echo "found";
}
</code>```

to

```<code>$tmp = array_flip ($UsedAvatars);
if ($tmp[$filename] != "")
    echo "found";
</code>```

Body:
I'm trying to check whether an item exists in an array that is populated from a file, which consists of filenames, one on each line, like this:

GG.jpg

2J.jpg

WWWW.jpg

I have the following so far:

$UsedAvatars = array();

$UsedAvatars = file('UsedAvatars.txt',  FILE_IGNORE_NEW_LINES );

// This next part is to check that the array has been populated, and
// it works.

for($counter=0; $counter<count($UsedAvatars); $counter++)
{
    echo $counter . "\t" . $UsedAvatars[$counter] . "
";
}

echo "
";

    // This is hardwired in because I know that it is in the text file
    // used to populate the array and so should return TRUE
    $filename="GG.jpg";

if( in_array( $filename, $UsedAvatars ) )
{
  echo "found";
}

However, the test does not work and "found" is not outputted. I cannot see what is wrong, can anyone help please?

Body:
try to replace

if( in_array( $filename, $UsedAvatars ) )
{
  echo "found";
}

to

$tmp = array_flip ($UsedAvatars);
if ($tmp[$filename] != "")
    echo "found";


问:
How do I set a universal tab size in Bluefish text editor?
I've started using the Bluefish text editor a little while ago, and it has some pretty good merits, but one of the biggest annoyances it has is it's default tab size.

In Bluefish, 'tab width' is the number of space characters a tab is set equal to. This isn't what I'm talking about. 'Tab size' is the actual width on the screen the tab is displayed as. By default, whenever I open a file, the tab size is such that a tab appears approximately the same as a space character (actually ~1.5 space chars), which I just can't deal with. So, I change it, by Documents->Tab Size->Increase, until it's big enough for me. That's all fine, but it only changes the look of this one file, while it's open.

If I open another file, or close the one I just changed and open another, it's back to the default of looking the same as a single space character.

Is there some way I can set Bluefish's default tab size to something bigger, so I don't have to keep changing it all the time? A variable in a config file maybe, or menu option I haven't found?

答:
Additional: If your project, like mine, doesn't accept the changes then you can edit the .bfproject file and change the line:

```<code>editor_tab_width: <new tab size>
</code>```

That works.

Body:
Additional: If your project, like mine, doesn't accept the changes then you can edit the .bfproject file and change the line:

editor_tab_width: <new tab size>

That works.


问:
How to Unicode String Convert to another type of Unicode String
I want to replace a Unicode string with a different type when it comes to a specific type of Unicode string in the string.

EX) 1.

```<code>//Hexadecimal 4characters
string base="U+1234FFFF040001041234";
//I want to replace this type----> ሴЀĄሴ
</code>```

EX) 2.

```<code>//Hexadecimal 4characters
string base="U+1234 U+FFFF U+0400 U+0104 U+1234";
//----> ሴ  Ѐ Ą ሴ
</code>```

I am wondering how to do pattern matching with regular expressions.
And I wonder how I can replace it in such a way.

答:
```<code>Regex regexUnicode = new Regex(@"U\+([0-9A-F]{4})+");

        MatchCollection resultCollection = regexUnicode.Matches(str);
        foreach (Match matched in resultCollection) {

            int length = matched.Groups[0].Length;
            string matchedStr = matched.Groups[0].ToString();
            int startIndex = str.IndexOf(matchedStr);
            string temp = matchedStr;
            string ret = "";
            string buffer = "";
            int bufCount = 0;
            for (int i = 0; i < matchedStr.Length; ++i) {
                if (matchedStr[i] == 'U' || matchedStr[i] == '+') {
                    continue;
                } else if (bufCount != 4) {
                    buffer += matchedStr[i];
                    bufCount++;
                } else if (bufCount == 4) {
                    ret += "&#x" + buffer + ";";
                    buffer = "";
                    buffer += matchedStr[i];
                    bufCount = 1;
                }
            }
            ret += "&#x" + buffer + ";";
            str = str.Remove(startIndex, matchedStr.Length);
            str = str.Insert(startIndex, ret);
        }
</code>```

Body:
I want to replace a Unicode string with a different type when it comes to a specific type of Unicode string in the string.

EX) 1.

//Hexadecimal 4characters
string base="U+1234FFFF040001041234";
//I want to replace this type----> ሴЀĄሴ

EX) 2.

//Hexadecimal 4characters
string base="U+1234 U+FFFF U+0400 U+0104 U+1234";
//----> ሴ  Ѐ Ą ሴ

I am wondering how to do pattern matching with regular expressions.
And I wonder how I can replace it in such a way.


问:
What’s the best way to calculate the size of a directory in VB .NET?
I need to calculate the directory size in VB .Net

I know the following 2 methods

Method 1: from MSDN http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

' The following example calculates the size of a directory
' and its subdirectories, if any, and displays the total size
' in bytes.

```<code>Imports System
Imports System.IO

Public Class ShowDirSize

Public Shared Function DirSize(ByVal d As DirectoryInfo) As Long
    Dim Size As Long = 0
    ' Add file sizes.
    Dim fis As FileInfo() = d.GetFiles()
    Dim fi As FileInfo
    For Each fi In fis
        Size += fi.Length
    Next fi
    ' Add subdirectory sizes.
    Dim dis As DirectoryInfo() = d.GetDirectories()
    Dim di As DirectoryInfo
    For Each di In dis
        Size += DirSize(di)
    Next di
    Return Size
End Function 'DirSize

Public Shared Sub Main(ByVal args() As String)
    If args.Length <> 1 Then
        Console.WriteLine("You must provide a directory argument at the command line.")
    Else
        Dim d As New DirectoryInfo(args(0))
        Dim dsize As Long = DirSize(d)
        Console.WriteLine("The size of {0} and its subdirectories is {1} bytes.", d, dsize)
    End If
End Sub 'Main
End Class 'ShowDirSize
</code>```

Method 2: from What's the best way to calculate the size of a directory in .NET?

```<code>Dim size As Int64 = (From strFile In My.Computer.FileSystem.GetFiles(strFolder, _
              FileIO.SearchOption.SearchAllSubDirectories) _
              Select New System.IO.FileInfo(strFile).Length).Sum()
</code>```

Both these methods work fine. However they take lot of time to calculate the directory size if there are lot of sub-folders. e.g i have a directory with 150,000 sub-folders. The above methods took around 1 hr 30 mins to calculate the size of the directory. However, if I check the size from windows it takes less than a minute.

Please suggest better and faster ways to calculate the size of the directory.

答:
Here this as short as I can get it.

It will display the size of the selected in a message box.
You're going to need a FolderBrowserDialog in the form for this to work.

```<code>Class Form1

Private Sub form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
        Else : End
        End If
        Dim dInfo As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
        Dim sizeOfDir As Long = DirectorySize(dInfo, True)
        MsgBox("Showing Directory size of " & FolderBrowserDialog1.SelectedPath _
               & vbNewLine & "Directory size in Bytes : " & "Bytes " & sizeOfDir _
               & vbNewLine & "Directory size in KB : " & "KB " & Math.Round(sizeOfDir / 1024, 3) _
               & vbNewLine & "Directory size in MB : " & "MB " & Math.Round(sizeOfDir / (1024 * 1024), 3) _
               & vbNewLine & "Directory size in GB : " & "GB " & Math.Round(sizeOfDir / (1024 * 1024 * 1024), 3))
    Catch ex As Exception
    End Try
End Sub

Private Function DirectorySize(ByVal dInfo As IO.DirectoryInfo, ByVal includeSubDir As Boolean) As Long
    Dim totalSize As Long = dInfo.EnumerateFiles().Sum(Function(file) file.Length)
    If includeSubDir Then totalSize += dInfo.EnumerateDirectories().Sum(Function(dir) DirectorySize(dir, True))
    Return totalSize
End Function

End Class
</code>```

Body:
I need to calculate the directory size in VB .Net

I know the following 2 methods

Method 1: from MSDN http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

' The following example calculates the size of a directory
' and its subdirectories, if any, and displays the total size
' in bytes.

Imports System
Imports System.IO

Public Class ShowDirSize

Public Shared Function DirSize(ByVal d As DirectoryInfo) As Long
    Dim Size As Long = 0
    ' Add file sizes.
    Dim fis As FileInfo() = d.GetFiles()
    Dim fi As FileInfo
    For Each fi In fis
        Size += fi.Length
    Next fi
    ' Add subdirectory sizes.
    Dim dis As DirectoryInfo() = d.GetDirectories()
    Dim di As DirectoryInfo
    For Each di In dis
        Size += DirSize(di)
    Next di
    Return Size
End Function 'DirSize

Public Shared Sub Main(ByVal args() As String)
    If args.Length <> 1 Then
        Console.WriteLine("You must provide a directory argument at the command line.")
    Else
        Dim d As New DirectoryInfo(args(0))
        Dim dsize As Long = DirSize(d)
        Console.WriteLine("The size of {0} and its subdirectories is {1} bytes.", d, dsize)
    End If
End Sub 'Main
End Class 'ShowDirSize

Method 2: from What's the best way to calculate the size of a directory in .NET?

Dim size As Int64 = (From strFile In My.Computer.FileSystem.GetFiles(strFolder, _
              FileIO.SearchOption.SearchAllSubDirectories) _
              Select New System.IO.FileInfo(strFile).Length).Sum()

Both these methods work fine. However they take lot of time to calculate the directory size if there are lot of sub-folders. e.g i have a directory with 150,000 sub-folders. The above methods took around 1 hr 30 mins to calculate the size of the directory. However, if I check the size from windows it takes less than a minute.

Please suggest better and faster ways to calculate the size of the directory.

Body:
Here this as short as I can get it.

It will display the size of the selected in a message box.
You're going to need a FolderBrowserDialog in the form for this to work.

Class Form1

Private Sub form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
        Else : End
        End If
        Dim dInfo As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
        Dim sizeOfDir As Long = DirectorySize(dInfo, True)
        MsgBox("Showing Directory size of " & FolderBrowserDialog1.SelectedPath _
               & vbNewLine & "Directory size in Bytes : " & "Bytes " & sizeOfDir _
               & vbNewLine & "Directory size in KB : " & "KB " & Math.Round(sizeOfDir / 1024, 3) _
               & vbNewLine & "Directory size in MB : " & "MB " & Math.Round(sizeOfDir / (1024 * 1024), 3) _
               & vbNewLine & "Directory size in GB : " & "GB " & Math.Round(sizeOfDir / (1024 * 1024 * 1024), 3))
    Catch ex As Exception
    End Try
End Sub

Private Function DirectorySize(ByVal dInfo As IO.DirectoryInfo, ByVal includeSubDir As Boolean) As Long
    Dim totalSize As Long = dInfo.EnumerateFiles().Sum(Function(file) file.Length)
    If includeSubDir Then totalSize += dInfo.EnumerateDirectories().Sum(Function(dir) DirectorySize(dir, True))
    Return totalSize
End Function

End Class


问:
Thymeleaf - Parsing external CSS file? Expressions, variables etc
There does not seem to be any concrete answers from what I could find, although I'm more inclined to say this is not possible.

However, is it possible to use Thmymeleaf expressions within an external CSS file? For example, if I have main.css and it contains:

```<code>body {
    font-size: [[${fooBean.isLarge ? '22px;' : '16px;' }]];
}

.header {
    margin-top:
    background: url{[[${fooBean.isMain ? '/img/blue.jpg' : '/img/red.jpg' }]]}
                    no-repeat center center fixed;
}
</code>```

Is this possible at all using Thymeleaf?

答: Thymeleaf 3 introduced new template modes.  One of them is CSS,  you can see an example of one here.  You'd have to set up all the spring stuff/controllers, but you should be able to use them like normal (adding your fooBean to the model).</p>

Body:
There does not seem to be any concrete answers from what I could find, although I'm more inclined to say this is not possible.

However, is it possible to use Thmymeleaf expressions within an external CSS file? For example, if I have main.css and it contains:

body {
    font-size: [[${fooBean.isLarge ? '22px;' : '16px;' }]];
}

.header {
    margin-top:
    background: url{[[${fooBean.isMain ? '/img/blue.jpg' : '/img/red.jpg' }]]}
                    no-repeat center center fixed;
}

Is this possible at all using Thymeleaf?


问:
EF 4 Dynamic Where Clause not working
I am trying to create a query with a Dynamic where clause in EF version 4 and the only where clause that is being generated is the "c.clientid == Clientid" from the initial statement. looking at the SQL Profiler the result.where statements are not being appended to the result variable. Can you tell me what I am doing wrong?

```<code>var result = (from c in cxt.Customer
                              where c.clientid == Clientid
                              select c);

                string employeenumber = formdata["employeenumber"].ToString();
                if (!string.IsNullOrWhiteSpace(employeenumber))
                {
                    result.Where(t => t.EmployeeNumber.ToLower() == employeenumber);
                }

                string FirstName = formdata["FirstName"].ToString();
                if (!string.IsNullOrWhiteSpace(FirstName))
                {
                    result.Where(t => t.FirstName.ToLower().Contains(FirstName));
                }

               return result.ToList();
</code>```

答:
You don't assign the result of result.Where(...) to your result variable.

In your if statements insert: result = result.Where(...);

Title: EF 4 Dynamic Where Clause not working

Body:
I am trying to create a query with a Dynamic where clause in EF version 4 and the only where clause that is being generated is the "c.clientid == Clientid" from the initial statement. looking at the SQL Profiler the result.where statements are not being appended to the result variable. Can you tell me what I am doing wrong?

var result = (from c in cxt.Customer
                              where c.clientid == Clientid
                              select c);

                string employeenumber = formdata["employeenumber"].ToString();
                if (!string.IsNullOrWhiteSpace(employeenumber))
                {
                    result.Where(t => t.EmployeeNumber.ToLower() == employeenumber);
                }

                string FirstName = formdata["FirstName"].ToString();
                if (!string.IsNullOrWhiteSpace(FirstName))
                {
                    result.Where(t => t.FirstName.ToLower().Contains(FirstName));
                }

               return result.ToList();


问:
Render JSON response using Django's render()
I am working my way through Django's tutorial but failing to display an API response using Django's render() function.

models.py

```<code>...
class MF_Version():
    def get_MF_Version(self):
        url = 'https://www.mediafire.com/api/1.5/system/get_version.php?response_format=json'
        r = requests.get(url)
        return r
...
</code>```

views.py

```<code>...
def view_Version(request):
    hr = HttpResponse(MF_Version().get_MF_Version())
    return render(request, 'mediafire/version.html', {'hr': hr})
    # return hr
...
</code>```

version.html

```<code>{% if 1 %}
    {{ hr }}
{% endif %}
</code>```

Browser output:

```<code><HttpResponse status_code=200, "text/html; charset=utf-8">
</code>```

MefiaFire response:

```<code>{"response":{"action":"system\/get_version","current_api_version":"1.5","result":"Success"}}
</code>```

If I comment out return render(...) in the view.py file and replace it with return hr, I do see the JSON response from MediaFire, but I cannot figure out how to access action, current_api_version and result in the HTML template.

Any help is appreciated.

答:
MF_Version().get_MF_Version() get a json,

you can try this:

```<code>def view_Version(request):
    hr = MF_Version().get_MF_Version().json()
    return render(request, 'mediafire/version.html', {'hr': hr}
</code>```

Body:
I am working my way through Django's tutorial but failing to display an API response using Django's render() function.

models.py

...
class MF_Version():
    def get_MF_Version(self):
        url = 'https://www.mediafire.com/api/1.5/system/get_version.php?response_format=json'
        r = requests.get(url)
        return r
...

views.py

...
def view_Version(request):
    hr = HttpResponse(MF_Version().get_MF_Version())
    return render(request, 'mediafire/version.html', {'hr': hr})
    # return hr
...

version.html

{% if 1 %}
    {{ hr }}
{% endif %}

Browser output:

<HttpResponse status_code=200, "text/html; charset=utf-8">

MefiaFire response:

{"response":{"action":"system\/get_version","current_api_version":"1.5","result":"Success"}}

If I comment out return render(...) in the view.py file and replace it with return hr, I do see the JSON response from MediaFire, but I cannot figure out how to access action, current_api_version and result in the HTML template.

Any help is appreciated.

Body:
MF_Version().get_MF_Version() get a json,

you can try this:

def view_Version(request):
    hr = MF_Version().get_MF_Version().json()
    return render(request, 'mediafire/version.html', {'hr': hr}


问:
Update a column with the result-dataset-count of a stored procedure
I have a table #data which has the columns Id and Count. In addition I have a stored procedure MyProc which accepts a parameter @id (equals the Id column) and returns a dataset (the count equals the Count column).

My goal is to assign the Count column from Id with MyProc without a cursor.

I know, something like this does not work:

```<code>UPDATE d
SET Count = (SELECT COUNT(*) FROM (EXEC MyProc d.Id))
FROM #data AS d
</code>```

Is there a syntax I do not know or is a cursor the only option to achieve this?

PS: It is a code quality and performance problem for me. Calling the stored procedure would be the easiest way without repeating 50 lines of SQL but a cursor slows it down.

答:
I don't fully understand what you're trying to do but I think your solution will involve @@ROWCOUNT; Observe:

```<code>-- Sample data and proc...
----------------------------------------------------------------------
IF OBJECT_ID('tempdb..#data') IS NOT NULL DROP TABLE #data;
IF OBJECT_ID('dbo.MyProc') IS NOT NULL DROP PROC dbo.MyProc;
GO

CREATE TABLE #data
(
  id      int,
  [Count] int
);

INSERT #data VALUES (1,5), (1,10), (2,3), (4,6);
GO

CREATE PROC dbo.MyProc(@id int)
AS
BEGIN
  SELECT 'some value'
  FROM #data
  WHERE @id = id;
END;
GO
</code>```

Data BEFORE:

```<code>id          Count
----------- -----------
1           5
1           10
2           3
4           6
</code>```

A routine that uses @@ROWCOUNT

```<code>DECLARE @someid int = 1; -- the value you're passing to your proc

EXEC dbo.MyProc 1;
DECLARE @rows int = @@ROWCOUNT; -- this is what you need.

UPDATE #data
SET [Count] = @rows
WHERE id = @someid;
</code>```

Data AFTER

```<code>id          Count
----------- -----------
1           2
1           2
2           3
4           6
</code>```

Body:
I have a table #data which has the columns Id and Count. In addition I have a stored procedure MyProc which accepts a parameter @id (equals the Id column) and returns a dataset (the count equals the Count column).

My goal is to assign the Count column from Id with MyProc without a cursor.

I know, something like this does not work:

UPDATE d
SET Count = (SELECT COUNT(*) FROM (EXEC MyProc d.Id))
FROM #data AS d

Is there a syntax I do not know or is a cursor the only option to achieve this?

PS: It is a code quality and performance problem for me. Calling the stored procedure would be the easiest way without repeating 50 lines of SQL but a cursor slows it down.

Body:
I don't fully understand what you're trying to do but I think your solution will involve @@ROWCOUNT; Observe:

-- Sample data and proc...
----------------------------------------------------------------------
IF OBJECT_ID('tempdb..#data') IS NOT NULL DROP TABLE #data;
IF OBJECT_ID('dbo.MyProc') IS NOT NULL DROP PROC dbo.MyProc;
GO

CREATE TABLE #data
(
  id      int,
  [Count] int
);

INSERT #data VALUES (1,5), (1,10), (2,3), (4,6);
GO

CREATE PROC dbo.MyProc(@id int)
AS
BEGIN
  SELECT 'some value'
  FROM #data
  WHERE @id = id;
END;
GO

Data BEFORE:

id          Count
----------- -----------
1           5
1           10
2           3
4           6

A routine that uses @@ROWCOUNT

DECLARE @someid int = 1; -- the value you're passing to your proc

EXEC dbo.MyProc 1;
DECLARE @rows int = @@ROWCOUNT; -- this is what you need.

UPDATE #data
SET [Count] = @rows
WHERE id = @someid;

Data AFTER

id          Count
----------- -----------
1           2
1           2
2           3
4           6


问:
asp.net C# Rdlc Report Sum #Error in column
Dear all coder please help me with this, I am having a column of student marks in my report and the row of the columns contains both Number as mark and Text as Grade. So when I sum the total of the column it throws an error #Error, where as when I replaced the Text or grade from the row as a number then it gives the correct result. But I want it to give the sum even when it contains the Text in the row, it should only calculate the Number and avoid Text.
Please Help Me!!

enter image description here

答:
Posting as an answer from my above comment. It may be helpful to someone. SSRS IIF evaluates both true and false expression no matter what IIf condition evaluates to so casting needs to be done after IIF evaluates.</p>

```<code>   =Sum(CInt(IIF(IsNumeric(Fields!FirstSecond.Value), Fields!FirstSecond.Value, 0)))
</code>```

Body:
Posting as an answer from my above comment. It may be helpful to someone. SSRS IIF evaluates both true and false expression no matter what IIf condition evaluates to so casting needs to be done after IIF evaluates.

   =Sum(CInt(IIF(IsNumeric(Fields!FirstSecond.Value), Fields!FirstSecond.Value, 0)))


问:
Calculate value based on amount of green against blue and red
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

```<code>var red:int = 53;
var green:int = 150;
var blue:int = 28;
</code>```

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

```<code>var red:int = 0;
var green:int = 255;
var blue:int = 0;
</code>```

Would receive the highest score(10) and:

```<code>var red:int = 255;
var green:int = 0;
var blue:int = 255;
</code>```

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

答:
This is a bit tricky, because there are 3 components, but if I understand correctly, only one of the components determines your ranking.

You could ignore the red and blue components entirely and rank just on 0-255 green level; the result will be that two colors of green=64 but swapped values of red and blue, e.g., rgb[100, 64, 50] and rgb[50, 64, 100] will be scored equally since both have the same amount of green. This result implies that the green-score is a projection of the 3D RGB coordinate onto the 'green axis'.

Body:
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

var red:int = 53;
var green:int = 150;
var blue:int = 28;

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

var red:int = 0;
var green:int = 255;
var blue:int = 0;

Would receive the highest score(10) and:

var red:int = 255;
var green:int = 0;
var blue:int = 255;

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.


问:
Project access denied using Eclipse
I have a Maven project (made of 5 subprojects) I cloned from a Git Repository.

When I compile (mvn clean install) them I get no errors, but, when I import them in Eclipse and try to Right Click > Maven > Update Project on the main one, I get error messages with (Access Denied) on every subproject (not on the main, which, btw is the parent folder with the subprojects' folders in it).

I already checked the folder properties and gave full access on every directory and file for every user, I am actually modifying the files and developing the application, but I still get these error messages when I try to update the project.

Is there an obvious solution I am not seeing?

On a side note: Also my coworker is having the same issue.

答:
I fix it by un-hiding the whole folder on \.eclipse.

Select all folders, right click > Properties > Attributes - uncheck Hidden

Title: Project access denied using Eclipse


问:
Switch timezone base on array value
I'm getting an array with about 200 records, each record has a datetime and timezone, my question is, how do I display each date-time accordingly to the city/country that the information is display.

```<code>array(
   'date'=>'2017-04-02T01:00:00',
   'timezone'=>'Europe/London'
)
</code>```

Say that you are in NYC, how do you display date value in America/New_York time zone?

I'd like to display the date value as Sun 2 of April at 1:00:00PM

答:
You can set the desired output format with date_default_timezone_set() and use strtotime() and date() together to ensure that your output will be based on the correct timezone from your array:

```<code> date_default_timezone_set("America/New_York");
 echo date("r",strtotime($array['date']." ".$array['timezone']));
</code>```

Using your example data the output would be "Sat, 01 Apr 2017 20:00:00 -0400". Hope this helps

Title: Switch timezone base on array value

Body:
I'm getting an array with about 200 records, each record has a datetime and timezone, my question is, how do I display each date-time accordingly to the city/country that the information is display.

array(
   'date'=>'2017-04-02T01:00:00',
   'timezone'=>'Europe/London'
)

Say that you are in NYC, how do you display date value in America/New_York time zone?

I'd like to display the date value as Sun 2 of April at 1:00:00PM

Body:
You can set the desired output format with date_default_timezone_set() and use strtotime() and date() together to ensure that your output will be based on the correct timezone from your array:

 date_default_timezone_set("America/New_York");
 echo date("r",strtotime($array['date']." ".$array['timezone']));

Using your example data the output would be "Sat, 01 Apr 2017 20:00:00 -0400". Hope this helps


问:
Using jQuery object of elements and :contains
I want to find if a link containing the word 'gathered'.

I am aware of the logic to get it but I am struggling to have a jQuery sintax for the selector:

```<code>if (index === 3) {

    var $link = $('#rest').find('.trigger');

    var $currentLinkPage = $link.eq(index - 1);

    $($currentLinkPage + ":contains('gathered')").......

}
</code>```

The console returns: 'Syntax error, unrecognized expression: [object Object]:contains('gathered')'

Is there a way of using :contains in this case?

答:
```<code>$currentLinkPage.filter(':contains("gathered")')
</code>```

Your $currentLinkPage is a jQuery object of .trigger elements

You only need to filter for the ones that contain the text you seek

Note: eq may not be what you need, update your question for what you're trying to get at

Body:
I want to find if a link containing the word 'gathered'.

I am aware of the logic to get it but I am struggling to have a jQuery sintax for the selector:

if (index === 3) {

    var $link = $('#rest').find('.trigger');

    var $currentLinkPage = $link.eq(index - 1);

    $($currentLinkPage + ":contains('gathered')").......

}

The console returns: 'Syntax error, unrecognized expression: [object Object]:contains('gathered')'

Is there a way of using :contains in this case?

Body:
$currentLinkPage.filter(':contains("gathered")')

Your $currentLinkPage is a jQuery object of .trigger elements

You only need to filter for the ones that contain the text you seek

Note: eq may not be what you need, update your question for what you're trying to get at


问:
Set cookie in express.js appear j: prefix
I'm trying to set cookie using res.cookie like below:

```<code>res.cookie('userId',req.user._id); //set cookie here
console.log(req.user._id); //returned correct value, eg abc
</code>```

then I'm seeing j:"abc" in my cookie, why does this happens?

答:
According the the Express 4 docs, res.cookie(name, value [, options]) sets a cookie name to a value. The value parameter may be a string or object converted to JSON.

In this instance, req.user._id is an object so you would set the cookie as res.cookie('userId', JSON.stringify(req.user._id))

Body:
I'm trying to set cookie using res.cookie like below:

res.cookie('userId',req.user._id); //set cookie here
console.log(req.user._id); //returned correct value, eg abc

then I'm seeing j:"abc" in my cookie, why does this happens?


问:
parsing url with regular expressions and KRL's replace method
I want to take the current page's URL (using page:env("caller")) and extract a section of it.

For instance, I want to take

```<code>http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=cats
</code>```

and assign

```<code>cats
</code>```

to a variable.

How would I do this with KRL?

I have tried

```<code>url = page:env("caller");
query = url.replace("http://www\.google\.com/search\?sourceid=chrome&ie=UTF-8&q=", "");
</code>```

but it simply assigns the entire page:env("caller") to the variable query (e.g. http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=cats).

Edit: a jQuery solution would most likely work, as well.

Edit2: @JAM --

The select statement you posted doesn't seem to work. I tested it on http://www.google.com/search?q=cats and it didn't fire. Not sure if the URL doesn't match pageview or what (it looks like it should match to me).

The app I put it in:

```<code>ruleset a835x36 {
  meta {
    name "regex testing2"
    description <<
 >>
author ""
logging on
}

rule get_query {
    select when pageview "http://www.google.com/search.*(?:&|?)q=(\w+)(?:&|$)"    setting(query)
      notify("Query",query) with sticky = true;
   }
}
</code>```

Also, I'm looking for a more robust way to get at the query, since Google has many ways to land on a search results page with URLs that won't look like http://www.google.com/search?q=cats. For example, going to google and searching for cats just gave http://www.google.com/webhp?hl=en#sclient=psy&hl=en&site=webhp&source=hp&q=cats&aq=f&aqi=&aql=&oq=&gs_rfai=&pbx=1&fp=8ac6b4cea9b27ecb for the URL of the results. I guess I could parse anything with a regex, though...

答:
2 Ways to accomplish what you want.

1) In the pre block

```<code>pre {
  queryInURL = page:url("query");
  q = queryInURL.replace(re/.*?q=(.*?)(?:$|&.*)/,"$1");
}
</code>```

page:url("query") grabs the entire string of parameters in a url

do string replace to capture specific query parameter that you want

Full Example App Tested

Tested on url -> http://example.com/?q=cats&wow=cool

```<code>ruleset a60x439 {
  meta {
    name "url query test"
    description <<
      Getting the query from the current page URL
    >>
    author "Mike Grace"
    logging on
  }

  rule get_query {
    select when pageview ".*"
    pre {
      queryInURL = page:url("query");
      q = queryInURL.replace(re/.*?q=(.*?)(?:$|&.*)/,"$1");
    }
    {
      notify("Query",queryInURL) with sticky = true;
      notify("q",q) with sticky = true;
    }
  }

}
</code>```

2) In the rules selection expression the way JAM has shown

Body:
I want to take the current page's URL (using page:env("caller")) and extract a section of it.

For instance, I want to take

http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=cats

and assign

cats

to a variable.

How would I do this with KRL?

I have tried

url = page:env("caller");
query = url.replace("http://www\.google\.com/search\?sourceid=chrome&ie=UTF-8&q=", "");

but it simply assigns the entire page:env("caller") to the variable query (e.g. http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=cats).

Edit: a jQuery solution would most likely work, as well.

Edit2: @JAM --

The select statement you posted doesn't seem to work. I tested it on http://www.google.com/search?q=cats and it didn't fire. Not sure if the URL doesn't match pageview or what (it looks like it should match to me).

The app I put it in:

ruleset a835x36 {
  meta {
    name "regex testing2"
    description <<
 >>
author ""
logging on
}

rule get_query {
    select when pageview "http://www.google.com/search.*(?:&|?)q=(\w+)(?:&|$)"    setting(query)
      notify("Query",query) with sticky = true;
   }
}

Also, I'm looking for a more robust way to get at the query, since Google has many ways to land on a search results page with URLs that won't look like http://www.google.com/search?q=cats. For example, going to google and searching for cats just gave http://www.google.com/webhp?hl=en#sclient=psy&hl=en&site=webhp&source=hp&q=cats&aq=f&aqi=&aql=&oq=&gs_rfai=&pbx=1&fp=8ac6b4cea9b27ecb for the URL of the results. I guess I could parse anything with a regex, though...

Body:
2 Ways to accomplish what you want.

1) In the pre block

pre {
  queryInURL = page:url("query");
  q = queryInURL.replace(re/.*?q=(.*?)(?:$|&.*)/,"$1");
}

page:url("query") grabs the entire string of parameters in a url

do string replace to capture specific query parameter that you want

Full Example App Tested

Tested on url -> http://example.com/?q=cats&wow=cool

ruleset a60x439 {
  meta {
    name "url query test"
    description <<
      Getting the query from the current page URL
    >>
    author "Mike Grace"
    logging on
  }

  rule get_query {
    select when pageview ".*"
    pre {
      queryInURL = page:url("query");
      q = queryInURL.replace(re/.*?q=(.*?)(?:$|&.*)/,"$1");
    }
    {
      notify("Query",queryInURL) with sticky = true;
      notify("q",q) with sticky = true;
    }
  }

}

2) In the rules selection expression the way JAM has shown


问:
iOS how to start image off screen and animate it onto the screen
I am trying to slide an image from off the screen onto the screen from the left and stopping at the center point in the view.  I would like to keep it contrained at the y position if possible (IE image is set in story board).

I am reading this tutorial, but it is in swift and I cannot make the same assignments in objective-c.

http://www.raywenderlich.com/95910/uiview-animation-swift-tutorial

It says to set the view off the screen (in swift):

```<code>heading.center.x  -= view.bounds.width
</code>```

Then animate (in swift):

```<code>UIView.animateWithDuration(0.5, animations: {
    self.heading.center.x += self.view.bounds.width
})
</code>```

However I cannot manipulate center.x in objective c like they are doing in swift.

I have tried adjusting the initial position of the image in viewWillAppear by changing the bounds with no luck.

EDIT:

Here is what I am trying to get it positioned off the screen:

```<code>self.heading.center = CGPointMake(-200, self.heading.center.y);
</code>```

No matter how negative I set the x position the view will still appears on the screen.  Actually no matter what I set x position to the view does not move in the x direction at all.  I have also tried to set the frame

答:
Try to use CGAffineTransformMakeTranslation:</p>

```<code>      [UIView animateKeyframesWithDuration:5
                               delay:0
                               options:UIViewKeyframeAnimationOptionCalculationModeLinear
                               animations:^{

                               view.transform = CGAffineTransformMakeTranslation(550, -40);
                               }];
</code>```

Body:
I am trying to slide an image from off the screen onto the screen from the left and stopping at the center point in the view.  I would like to keep it contrained at the y position if possible (IE image is set in story board).

I am reading this tutorial, but it is in swift and I cannot make the same assignments in objective-c.

http://www.raywenderlich.com/95910/uiview-animation-swift-tutorial

It says to set the view off the screen (in swift):

heading.center.x  -= view.bounds.width

Then animate (in swift):

UIView.animateWithDuration(0.5, animations: {
    self.heading.center.x += self.view.bounds.width
})

However I cannot manipulate center.x in objective c like they are doing in swift.

I have tried adjusting the initial position of the image in viewWillAppear by changing the bounds with no luck.

EDIT:

Here is what I am trying to get it positioned off the screen:

self.heading.center = CGPointMake(-200, self.heading.center.y);

No matter how negative I set the x position the view will still appears on the screen.  Actually no matter what I set x position to the view does not move in the x direction at all.  I have also tried to set the frame

Body:
Try to use CGAffineTransformMakeTranslation:

      [UIView animateKeyframesWithDuration:5
                               delay:0
                               options:UIViewKeyframeAnimationOptionCalculationModeLinear
                               animations:^{

                               view.transform = CGAffineTransformMakeTranslation(550, -40);
                               }];


问:
How do I create a CSV file from database in Python?
I have a Sqlite 3 and/or MySQL table named "clients"..

Using python 2.6, How do I create a csv file named Clients100914.csv with headers?
excel dialect...

The Sql execute: select * only gives table data, but I would like complete table with headers.

How do I create a record set to get table headers. The table headers should come directly from sql not written in python.

```<code>w = csv.writer(open(Fn,'wb'),dialect='excel')
#w.writelines("header_row")
#Fetch into sqld
w.writerows(sqld)
</code>```

This code leaves me with file open and no headers. Also cant get figure out how to use file as log.

答:
This is simple and works fine for me.

Lets say you have already connected to your database table and also got a cursor object. So following on on from that point.

```<code>import csv
curs = conn.cursor()
curs.execute("select * from oders")
m_dict = list(curs.fetchall())

with open("mycsvfile.csv", "wb") as f:
    w = csv.DictWriter(f, m_dict[0].keys())
    w.writerow(dict((fn,fn) for fn in m_dict[0].keys()))
    w.writerows(m_dict)
</code>```

Body:
I have a Sqlite 3 and/or MySQL table named "clients"..

Using python 2.6, How do I create a csv file named Clients100914.csv with headers?
excel dialect...

The Sql execute: select * only gives table data, but I would like complete table with headers.

How do I create a record set to get table headers. The table headers should come directly from sql not written in python.

w = csv.writer(open(Fn,'wb'),dialect='excel')
#w.writelines("header_row")
#Fetch into sqld
w.writerows(sqld)

This code leaves me with file open and no headers. Also cant get figure out how to use file as log.

Body:
This is simple and works fine for me.

Lets say you have already connected to your database table and also got a cursor object. So following on on from that point.

import csv
curs = conn.cursor()
curs.execute("select * from oders")
m_dict = list(curs.fetchall())

with open("mycsvfile.csv", "wb") as f:
    w = csv.DictWriter(f, m_dict[0].keys())
    w.writerow(dict((fn,fn) for fn in m_dict[0].keys()))
    w.writerows(m_dict)


问:
Wagtail streamtext paragraph unedtiable in demo blog causing django app to crash
I am attempting to follow the demo blog project, to get up to speed with wagtail. I've installed wagtail into an existing django app.

http://wagtail-nesting-box.readthedocs.io/en/latest/tutorial_blog/

I installed nesting box:

```<code>pip install wagtail-nesting-box
</code>```

I added the following into my settings.py

```<code>INSTALLED_APPS = [
    'wagtail_box',
    'wagtail_box.blog',
    'wagtail.contrib.settings',
]
</code>```

I migrated the changes within my virtualenv using:

```<code>python manage.py migrate
</code>```

I created a blog page as per the instructions, then a child item blog post.

The blog post editor loads, and I see the various fields, including the body... However when I click the paragraph element , a blue box appears, but I am unable to edit it.

If I click the H2 element, I can edit this. But the Paragraph element, is locked and I can not add any text to it.

If I attempt to save the page with nothing in the paragraph element I receive the following error:

```<code>ValueError at /cms/pages/7/edit/

invalid literal for int() with base 10: ''
</code>```

Which i've traced back to this code, in stream_block.py

```<code> int(data['%s-%d-order' % (prefix, i)]),
</code>```

How can I unlock the paragraph element so that it's editable?

How can I generate a more user friendly error? So the django app doesn't crash if it has an empty paragraph field.

Thanks

答:
It turns out there is Javascript that makes certain regions editable, that needs to be placed in your static folder.

Locate each of the following folders: -

```<code>wagtailadmin
wagtaildocs
wagtailembeds
wagtailimages
wagtailsnippets
wagtailusers
</code>```

Each of these folders, contains a static directory.
Copy the contents of each static directory, into your public web static folder.

It's specifically the wagtailembeds static javascript that makes the body editable.

Body:
I am attempting to follow the demo blog project, to get up to speed with wagtail. I've installed wagtail into an existing django app.

http://wagtail-nesting-box.readthedocs.io/en/latest/tutorial_blog/

I installed nesting box:

pip install wagtail-nesting-box

I added the following into my settings.py

INSTALLED_APPS = [
    'wagtail_box',
    'wagtail_box.blog',
    'wagtail.contrib.settings',
]

I migrated the changes within my virtualenv using:

python manage.py migrate

I created a blog page as per the instructions, then a child item blog post.

The blog post editor loads, and I see the various fields, including the body... However when I click the paragraph element , a blue box appears, but I am unable to edit it.

If I click the H2 element, I can edit this. But the Paragraph element, is locked and I can not add any text to it.

If I attempt to save the page with nothing in the paragraph element I receive the following error:

ValueError at /cms/pages/7/edit/

invalid literal for int() with base 10: ''

Which i've traced back to this code, in stream_block.py

 int(data['%s-%d-order' % (prefix, i)]),

How can I unlock the paragraph element so that it's editable?

How can I generate a more user friendly error? So the django app doesn't crash if it has an empty paragraph field.

Thanks

Body:
It turns out there is Javascript that makes certain regions editable, that needs to be placed in your static folder.

Locate each of the following folders: -

wagtailadmin
wagtaildocs
wagtailembeds
wagtailimages
wagtailsnippets
wagtailusers

Each of these folders, contains a static directory.
Copy the contents of each static directory, into your public web static folder.

It's specifically the wagtailembeds static javascript that makes the body editable.


问:
Deciphering Heroku 'git push' output from regluar 'git push' output errors
Currently I parse STDERR output from  git push -q to present any git push errors to the user. This works wonderfully most of the time. However when pushing to Heroku, their pre-receive hook outputs the status of the server and application status to STDERR as well.

I am basically just looking for an easy way to differentiate whether the output is actually errors from git vs extraneous Heroku data. I've tried checking for the presence of a "---->" prefix, but not all Heroku output has it. I also thought of checking for "fatal:" and "ssh:" in the STDERR string, but that seems very brittle. And I couldn't find any documentation that every git error is prefixed with ***:

Actual Git Error sent to STDERR:

```<code>ssh: Could not resolve hostname heroku.com: nodename nor servname provided, or not known
fatal: The remote end hung up unexpectedly
</code>```

Typical Heroku Status:

```<code>-----> Heroku receiving push
-----> Rack app detected
-----> Gemfile detected, running Bundler version 1.0.3
       All dependencies are satisfied
       Compiled slug size is 8.4MB
-----> Launching.... done
       http://XXXXXXX.com deployed to Heroku
</code>```

Does anyone have any ideas of a better way to accomplish identifying only the real git errors?

答:
According to Heroku: as of right now, there is no bullet-proof way to differentiate Heroku output from Git output. But they are working on standardizing their output format.

So it's mostly a matter of looking for the most common elements.

Body:
Currently I parse STDERR output from  git push -q to present any git push errors to the user. This works wonderfully most of the time. However when pushing to Heroku, their pre-receive hook outputs the status of the server and application status to STDERR as well.

I am basically just looking for an easy way to differentiate whether the output is actually errors from git vs extraneous Heroku data. I've tried checking for the presence of a "---->" prefix, but not all Heroku output has it. I also thought of checking for "fatal:" and "ssh:" in the STDERR string, but that seems very brittle. And I couldn't find any documentation that every git error is prefixed with ***:

Actual Git Error sent to STDERR:

ssh: Could not resolve hostname heroku.com: nodename nor servname provided, or not known
fatal: The remote end hung up unexpectedly

Typical Heroku Status:

-----> Heroku receiving push
-----> Rack app detected
-----> Gemfile detected, running Bundler version 1.0.3
       All dependencies are satisfied
       Compiled slug size is 8.4MB
-----> Launching.... done
       http://XXXXXXX.com deployed to Heroku

Does anyone have any ideas of a better way to accomplish identifying only the real git errors?


问:
I'm trying to only get one row from a LEFT JOIN
Temp ordering table

```<code>temp_id     series_id   news_ticket_breakdown_id    quantity    expiry_time
58db09bba25b4   2                  2                     2       1490750973
58db09bba25b4   2                  4                     1      1490750973
</code>```

NEWS ITEMS TABLE

```<code>news_id   series_id      news_title
   26          2         GENERIC TICKETING
   27          2         GENERIC TICKETING
</code>```

When I do a left join on series_id I get back 4 rows and I only want 2. I'm not sure how to limit the amount of joined rows to one row.

CURRENT QUERY

```<code>SELECT
    *
FROM
    ticket_ordering_temp
LEFT JOIN
    news_items
on
    ( news_items.series_id = SELECT
                                DISTINCT(event_id)
                             FROM
                                news_items
                             where
                                series_id=ticket_ordering_temp.series_id
    )
where
    temp_id='58db09bba25b4''
</code>```

DESIRED RESULT
I want just 1 row from table 2 and not 2 rows joined as stated above

```<code>temp_id     series_id   news_ticket_breakdown_id    quantity    expiry_time news_title
58db09bba25b4   2                  2                     2       1490750973  GENERIC TICKETING
58db09bba25b4   2                  4                     1      1490750973 GENERIC TICKETING
</code>```

答:
For your sample data and your desired result, you can try following sql to do:

```<code>SELECT
    ticket_ordering_temp.*, t.news_title
FROM
    ticket_ordering_temp
LEFT JOIN(
    SELECT DISTINCT series_id, news_title
    FROM news_items
) t ON ticket_ordering_temp.series_id = t.series_id
WHERE temp_id = '58db09bba25b4'
</code>```

however, I think you should tell us the logic behind these sample data.

Demo in SqlFiddle

Body:
Temp ordering table

temp_id     series_id   news_ticket_breakdown_id    quantity    expiry_time
58db09bba25b4   2                  2                     2       1490750973
58db09bba25b4   2                  4                     1      1490750973

NEWS ITEMS TABLE

news_id   series_id      news_title
   26          2         GENERIC TICKETING
   27          2         GENERIC TICKETING

When I do a left join on series_id I get back 4 rows and I only want 2. I'm not sure how to limit the amount of joined rows to one row.

CURRENT QUERY

SELECT
    *
FROM
    ticket_ordering_temp
LEFT JOIN
    news_items
on
    ( news_items.series_id = SELECT
                                DISTINCT(event_id)
                             FROM
                                news_items
                             where
                                series_id=ticket_ordering_temp.series_id
    )
where
    temp_id='58db09bba25b4''

DESIRED RESULT
I want just 1 row from table 2 and not 2 rows joined as stated above

temp_id     series_id   news_ticket_breakdown_id    quantity    expiry_time news_title
58db09bba25b4   2                  2                     2       1490750973  GENERIC TICKETING
58db09bba25b4   2                  4                     1      1490750973 GENERIC TICKETING

Body:
For your sample data and your desired result, you can try following sql to do:

SELECT
    ticket_ordering_temp.*, t.news_title
FROM
    ticket_ordering_temp
LEFT JOIN(
    SELECT DISTINCT series_id, news_title
    FROM news_items
) t ON ticket_ordering_temp.series_id = t.series_id
WHERE temp_id = '58db09bba25b4'

however, I think you should tell us the logic behind these sample data.

Demo in SqlFiddle


问:
display image choosen in xml and change main_activity on second time launch
i want to learn how to create an android app, and i'm confused at :

1.first time launching my app will display viewpagers img_btn ice, img_btn jelly. and when img_buttons clicked will display which image chosen in profil.xml, is there any solution do it in 1 xml or i must create 2 xml for each button?

2.if user have choosed img_button, main_activity will change to profil.xml, so for the second time launch will show profil.xml. how can i do that?

main_activity.xml

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#000000"
>
<TextView
    android:text="Choose char"
    android:textSize="25dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#1e00ff"/>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_ViewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"/>
</code>```

page1.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Halaman 2"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/textView"
    android:layout_gravity="center_horizontal"
    android:textSize="54dp"
    android:textColor="#0aedff"/>
<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageButton"
    android:background="#00000000"
    android:src="@drawable/btn_info"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_vertical|center"/>
</code>```

page1.java

```<code>import android.support.v4.app.*;
import android.view.*;
import android.os.*;

public class page1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,   Bundle savedInstanceState)
{
    View v=inflater.inflate(R.layout.halaman_1, container,false);
    return v;
}
}
</code>```

page2.xml and page2.java same as page1
English isn’t my first language, so please excuse any mistakes.

答:
I am not sure what Fragment you extended.  import android.support.v4.app.Fragment; or import android.app.Fragment; The below example assume you use support.v4

```<code>public void replaceFragment(Fragment fragment, String title) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame, fragment)
                .addToBackStack(title)
                .commit();
    }

    public void addFragment(Fragment fragment, String title) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.content_frame, fragment, title)
                .addToBackStack(title)
                .commit();
    }
</code>```

you better has 2 xml (eg. page1.xml, page2.xml) and two classes extend Fragment, you may use the above function to first add a fragment, subsequently use replace when you open new fragments. Notice there is a R.id.content_frame in the functions given. That is from your main_activity.xlm, make a linear_layout name it content_frame, which will hold the open fragment. You then put a button on page1.xml,  put an ImageView inside page2.xml, when the button on page1 has been clicked. use replaceFragment to open page2.xml

Body:
i want to learn how to create an android app, and i'm confused at :

1.first time launching my app will display viewpagers img_btn ice, img_btn jelly. and when img_buttons clicked will display which image chosen in profil.xml, is there any solution do it in 1 xml or i must create 2 xml for each button?

2.if user have choosed img_button, main_activity will change to profil.xml, so for the second time launch will show profil.xml. how can i do that?

main_activity.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#000000"
>
<TextView
    android:text="Choose char"
    android:textSize="25dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#1e00ff"/>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_ViewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"/>

page1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Halaman 2"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/textView"
    android:layout_gravity="center_horizontal"
    android:textSize="54dp"
    android:textColor="#0aedff"/>
<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageButton"
    android:background="#00000000"
    android:src="@drawable/btn_info"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_vertical|center"/>

page1.java

import android.support.v4.app.*;
import android.view.*;
import android.os.*;

public class page1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,   Bundle savedInstanceState)
{
    View v=inflater.inflate(R.layout.halaman_1, container,false);
    return v;
}
}

page2.xml and page2.java same as page1
English isn’t my first language, so please excuse any mistakes.

Body:
I am not sure what Fragment you extended.  import android.support.v4.app.Fragment; or import android.app.Fragment; The below example assume you use support.v4

public void replaceFragment(Fragment fragment, String title) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame, fragment)
                .addToBackStack(title)
                .commit();
    }

    public void addFragment(Fragment fragment, String title) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.content_frame, fragment, title)
                .addToBackStack(title)
                .commit();
    }

you better has 2 xml (eg. page1.xml, page2.xml) and two classes extend Fragment, you may use the above function to first add a fragment, subsequently use replace when you open new fragments. Notice there is a R.id.content_frame in the functions given. That is from your main_activity.xlm, make a linear_layout name it content_frame, which will hold the open fragment. You then put a button on page1.xml,  put an ImageView inside page2.xml, when the button on page1 has been clicked. use replaceFragment to open page2.xml


问:
Convert CVS/SVN to a Programming Snippets Site
I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public web- server also, I was thinking that I should convert the cvs automatically to a programming snippets website.

cvsweb is not what I mean.

doxygen is for a complete project and to browse the self-referencing codes online.I think doxygen is more like web based ctags.

I tried with rest2web, it is requires that I write /restweb headers and files to be .txt files and it will interfere with the programming language syntax.

An approach I have thought is:
1) run source-hightlight and create .html pages for all the scripts.
2) now write a script to index those script .htmls and create webpage.
3) Create the website of those pages.

before proceeding, I thought I shall discuss here, if the members have any suggestion.
What do do, when you want to maintain your snippets and notes in cvs and also auto generate it into a good website. I like rest2web for converting notes to html.

答:
I finally settled for rest2web. I had to do the following.

Use a separate python script to recursively copy the files in the CVS to a separate directory.

Added extra files index.txt and template.txt to all the directories which I wanted to be in the webpage.

The best thing about rest2web is that it supports python scripting within the template.txt, so I just ran a loop of the contents and indexed them in the page.

There is still lot more to go to automate the entire process. For eg. Inline viewing of programs and colorization, which I think can be done with some more trials.

I have the completed website here, It is called uthcode.

OwnerDisplayName: Senthil


问:
UIButton's background color progressively getting darker on touch down drag
I've been encountering this bug where the UIButton progressively gets darker when the UIButton is being dragged down (See animated gif below for demonstration). The UIButton was created using the interface builder and only the background color was changed.

What is the issue causing this behavior?

EDIT:

Button is initialized with this method (Title color was changed too).

```<code>- (void)initUserButton{
    [self.userButton setBackgroundColor:[UIColor colorWithHexString:ATTENDANCE_HEADER_ACCENT]];
    [self.userButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
</code>```

答:
The problem was in the embedded frameworks all along. There was a category overriding the setHighlighted method for UIButton and it is affecting the whole project with it.

I have fixed the bug in the category and made it to only override on custom buttons that the framework will use.

Body:
I've been encountering this bug where the UIButton progressively gets darker when the UIButton is being dragged down (See animated gif below for demonstration). The UIButton was created using the interface builder and only the background color was changed.

What is the issue causing this behavior?

EDIT:

Button is initialized with this method (Title color was changed too).

- (void)initUserButton{
    [self.userButton setBackgroundColor:[UIColor colorWithHexString:ATTENDANCE_HEADER_ACCENT]];
    [self.userButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}


问:
Xamrin forms carousel view missing reference
I am using carousel view in xamarin forms to navigate through pages. After adding packages to my project's xamarin forms folder, I got an error "Cannot load file or assemble xamarin.forms.carouselview or one of its dependencies" I tried loading the assembly in appdelegate.cs. Now am getting a build error "Reference to type xamarin.forms.IItemViewController claims it is defined assembly xamarin.forms.core, version=1.5.0.0, culture=neutral, publickeytoken=null, but could be found" this error is pointing to the code of appdelegate that i have written.
I will be grateful if i get any suggetions

PS: this works perfect in a sample app. i am getting such error only when i am integrating this in my official project.

答:
Xamarin Forms CarouselView has a dependency of Xamarin.Forms (>= 2.3.0.42-pre3)

You must upgrade to at least that version or higher. Your Xamarin.Forms.Core dll should then be version=2.0.0 instead of v1.5.0.


问:
Is there any Visual Studio extension to switch to related files?
Suppose an architecture where a certain functionality - a "component" - is scattered across many related files. For example there is a HTML template, a JavaScript file, a CSS file etc. belonging together. Should be common in any non-trivial project.

The more technical layers are used, the more you need to switch between related files. In a current project I have 6 layers that need to be edited for one functionality. Since the files are grouped by technical layers, they are not near each other. Which makes the trivial task of switching files time-consuming.

Is there any known Visual Studio extension which does help with that situation?

For designers (WinForms/WPF/...) a similiar feature always existed (go to designer, go to code).

Just an idea how it could look like:

Having it in the context menu would be OK as well.
Maybe I am lucky and it already exists?

答: You can switch between related files with my (commercial) Tabs Studio extension if they have a common part in the file name. On how to create custom title and path rules see Tab Grouping documentation.</p>


问:
How does one send data from a dictionary over an mqtt broker
Basically I have two raspberry pi's and I want one to publish data obtained from a dictionary in a python file and the the other to subscribe to this dictionary data.  Apologies if this is a very bland question but I can't find any info on the internet regarding this.</p>

答:
If you want to send a dictionary directly from a python script on Host A to a python script on Host B there is a way.

Convert your dictionary into a string.

Send the string as a payload from Host A to the broker.

Subscribe to the broker with Host B and receive the payload.

Evaluate the string with ast.literal_eval() which will convert it back into a dictionary.

If that explanation is unclear I could post some example code.

I would probably use JSON or multiple topics instead but the above procedure will work.


问:
How do you make multiple radio buttons over an image responsive?
I have a picture of Hawaiian islands and I've placed 8 radio buttons with absolute position. But when I use the Chrome inspector to see if the image with the radio buttons are responsive, I see that they are not and the buttons don't stay on the spot on the image that were on full screen. Any suggestions?

CSS:

```<code>#radio1{
    position:absolute;
    top:58.9%;
    left:24.4%;
}

#radio2{
    position:absolute;
    top:57.5%;
    left:27.1%;
}

#radio3{
    position:absolute;
    top:63.2%;
    left:34.05%;
}

#radio4{
    position:absolute;
    top:66.8%;
    left:38%;
}

#radio5{
    position:absolute;
    top:68.9%;
    left:40.4%;
}

#radio6{
    position:absolute;
    top:69.7%;
    left:38.8%;
}

#radio7{
    position:absolute;
    top:73.1%;
    left:40.5%;
}

#radio8{
    position:absolute;
    top:78.8%;
    left:45.5%;
}

#third.form img{
    display:block;
    max-width: 100%;
    height: auto;
</code>```

HTML:

```<code><img src="map.png">
<label for="radio1"></label><input type="radio" name="radio" id="radio1" required><br>
<label for="radio2"></label><input type="radio" name="radio" id="radio2"><br>
<label for="radio3"></label><input type="radio" name="radio" id="radio3"><br>
<label for="radio4"></label><input type="radio" name="radio" id="radio4"><br>
<label for="radio5"></label><input type="radio" name="radio" id="radio5"><br>
<label for="radio6"></label><input type="radio" name="radio" id="radio6"><br>
<label for="radio7"></label><input type="radio" name="radio" id="radio7"><br>
<label for="radio8"></label><input type="radio" name="radio" id="radio8"><br>
</code>```

答: Okay so the the dots position changes because the left and top positions are with respect to the entire container and not the containing div itself. </p>

Body:
I have a picture of Hawaiian islands and I've placed 8 radio buttons with absolute position. But when I use the Chrome inspector to see if the image with the radio buttons are responsive, I see that they are not and the buttons don't stay on the spot on the image that were on full screen. Any suggestions?

CSS:

#radio1{
    position:absolute;
    top:58.9%;
    left:24.4%;
}

#radio2{
    position:absolute;
    top:57.5%;
    left:27.1%;
}

#radio3{
    position:absolute;
    top:63.2%;
    left:34.05%;
}

#radio4{
    position:absolute;
    top:66.8%;
    left:38%;
}

#radio5{
    position:absolute;
    top:68.9%;
    left:40.4%;
}

#radio6{
    position:absolute;
    top:69.7%;
    left:38.8%;
}

#radio7{
    position:absolute;
    top:73.1%;
    left:40.5%;
}

#radio8{
    position:absolute;
    top:78.8%;
    left:45.5%;
}

#third.form img{
    display:block;
    max-width: 100%;
    height: auto;

HTML:

<input type="radio" name="radio" id="radio1" required>

<input type="radio" name="radio" id="radio2">

<input type="radio" name="radio" id="radio3">

<input type="radio" name="radio" id="radio4">

<input type="radio" name="radio" id="radio5">

<input type="radio" name="radio" id="radio6">

<input type="radio" name="radio" id="radio7">

<input type="radio" name="radio" id="radio8">


问:
Slow SQL in MariaDB
MariaDB. Server version: 5.5.5-10.1.18-MariaDB MariaDB Server

There are 3 tables:

```<code>1. City: 4,000 rows (has foreign key country_id to Country.id and index)
2. Street: 40,000 rows  (has foreign key city_id to City.id and index)
3. House: 4,000,000,000 rows (has foreign key to Street.id and index)
</code>```

Following SQL never finished:

```<code>select count(*) from House , Street  WHERE Street.city_id IN
(SELECT id FROM City WHERE country_id=177)
and Street.id=House.street_id;
</code>```

But if in the nested SELECT instead the original code:

(SELECT id FROM City WHERE country_id=177)

I put

SELECT id FROM City WHERE id IN (4617,4618)

when it runs < 0.5 sec

Below is Explain plan for slow query

```
+------+-------------+-------+--------+----------------------------+------------------------+---------+------------------+------------+-------------+
| id   | select_type | table | type   | possible_keys               | key                   | key_len | ref              | rows       | Extra       |
+------+-------------+-------+--------+-----------------------------+-----------------------+---------+------------------+------------+-------------+
|    1 | PRIMARY     | House | index  | IDX_House_streetIndex       | IDX_House_streetIndex | 11      | NULL             | 4,000,000,000 | Using index |
|    1 | PRIMARY     | Street| eq_ref | PRIMARY,IDX_DF9A1AD51E5D0459| PRIMARY               | 4       | House.street_id  |          1 |             |
|    1 | PRIMARY     | City  | eq_ref | PRIMARY,IDX_784DD132166D1F9C| PRIMARY               | 4       | Street.city_id   |          1 | Using where |
+------+-------------+-------+--------+------------------------------------------+------------------------------------------+---------+———————
```

答:
Don't use IN ( SELECT ... ); it usually performs poorly.  Instead, use the equivalent JOIN.

```<code>select  count(*)
    FROM  City
    JOIN  Street  ON Street.city_id = City.id
    JOIN  House   ON House.street_id = Street.id
    WHERE  City.country_id=177
</code>```

Then, you need these indexes:

```<code>City:    INDEX(country_id, id)
Street:  INDEX(city_id, id)
House:   INDEX(street_id)
</code>```

Please, when asking this kind of question, provide SHOW CREATE TABLE.

4 billion houses?  I doubt if there are that many in the world!

If theses suggestions are not sufficient, the reconsider whether the tables are "over-normalized".

Title: Slow SQL in MariaDB

Body:
MariaDB. Server version: 5.5.5-10.1.18-MariaDB MariaDB Server

There are 3 tables:

1. City: 4,000 rows (has foreign key country_id to Country.id and index)
2. Street: 40,000 rows  (has foreign key city_id to City.id and index)
3. House: 4,000,000,000 rows (has foreign key to Street.id and index)

Following SQL never finished:

select count(*) from House , Street  WHERE Street.city_id IN
(SELECT id FROM City WHERE country_id=177)
and Street.id=House.street_id;

But if in the nested SELECT instead the original code:

(SELECT id FROM City WHERE country_id=177)

I put

SELECT id FROM City WHERE id IN (4617,4618)

when it runs < 0.5 sec

Below is Explain plan for slow query

+------+-------------+-------+--------+----------------------------+------------------------+---------+------------------+------------+-------------+
| id   | select_type | table | type   | possible_keys               | key                   | key_len | ref              | rows       | Extra       |
+------+-------------+-------+--------+-----------------------------+-----------------------+---------+------------------+------------+-------------+
|    1 | PRIMARY     | House | index  | IDX_House_streetIndex       | IDX_House_streetIndex | 11      | NULL             | 4,000,000,000 | Using index |
|    1 | PRIMARY     | Street| eq_ref | PRIMARY,IDX_DF9A1AD51E5D0459| PRIMARY               | 4       | House.street_id  |          1 |             |
|    1 | PRIMARY     | City  | eq_ref | PRIMARY,IDX_784DD132166D1F9C| PRIMARY               | 4       | Street.city_id   |          1 | Using where |
+------+-------------+-------+--------+------------------------------------------+------------------------------------------+---------+———————

Body:
Don't use IN ( SELECT ... ); it usually performs poorly.  Instead, use the equivalent JOIN.

select  count(*)
    FROM  City
    JOIN  Street  ON Street.city_id = City.id
    JOIN  House   ON House.street_id = Street.id
    WHERE  City.country_id=177

Then, you need these indexes:

City:    INDEX(country_id, id)
Street:  INDEX(city_id, id)
House:   INDEX(street_id)

Please, when asking this kind of question, provide SHOW CREATE TABLE.

4 billion houses?  I doubt if there are that many in the world!

If theses suggestions are not sufficient, the reconsider whether the tables are "over-normalized".


问:
jQuery add # to all internal links
Can someone tell me how to add hashes to all the internal links on a page?

For example:

```<code>page.html > page.html#
</code>```

Thank you,
d

答:
If you're saying you only want to add # to links that are to pages within the same domain, you can compare the hostname of window.location to that of the link:

```<code>$("a").attr("href", function(i, href) {
    if( window.location.hostname === this.hostname ) {
        return href + "#";
    }
});
</code>```

Title: jQuery add # to all internal links

Body:
Can someone tell me how to add hashes to all the internal links on a page?

For example:

page.html > page.html#

Thank you,
d

Body:
If you're saying you only want to add # to links that are to pages within the same domain, you can compare the hostname of window.location to that of the link:

$("a").attr("href", function(i, href) {
    if( window.location.hostname === this.hostname ) {
        return href + "#";
    }
});


问:
Button with 3 states using React
I've got a need for a button with 3 states.

Each state, would need to handle click and send a value.

The use-case is:

Non-favourite

Favourite

Uber-favourite

I tried using this.state.count + 1 to indicated the levels, but had no success. I am unsure this is the best way either.

I am using the const fill as the CSS value (colour) I will pass into the svg element.

Here is my attempt, but it is limited as checked only has 2 states (on/off) and I need 3. It is also in this codepen.

```<code>class Switch extends React.Component {
  constructor ( props ) {
    super( props );
    this.state = {
      checked: !!props.checked
    };
  }
  handleClick(e) {
        this.setState({
      checked: !this.state.checked
    });
  }

  render () {
    const fill = this.state.checked ? "#E1E0DD" : "#999999";
    return (
        <button className="switch" onClick={this.handleClick.bind(this)} >
      <svg width="100" height="100">
        <g>
          <path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
        </g>
      </svg>
            </button>
    );
  }
}

const App = () => (
    <div>
        <Switch checked={ true } />
    </div>
)

React.render( <App />, document.getElementById( "page" ) );
</code>```

答:
There are several issues with your code.

Firstly, don't derive a component's state from its props - this is an anti-pattern.

Secondly, because setState calls can be batched by React, you should use the function(prevState, nextProps) argument to setState rather than an object when you are basing new state on previous state.

Thirdly, as mentioned in the comment above, you are never going to be able to get three states by using a boolean.

I would implement this something like this:

```<code>class TripleSwitch extends React.Component {
  constructor() {
    super();
    this.state = {
       favourite: 0
    }
  }

  handleClick() {
    this.setState((prevState) => ({
       favourite: (prevState.favourite + 1) % 3
    }));
  }

  render () {
    const { favourite } = this.state;
    const fill = favourite === 0 ? "#E1E0DD" :
                 favourite === 1 ? "#000444" :
                 "#999999";
    return (
        <button className="switch" onClick={this.handleClick.bind(this)} >
      <svg width="100" height="100">
        <g>
          <path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
        </g>
      </svg>
            </button>
    );
  }
}
</code>```

Title: Button with 3 states using React

Body:
I've got a need for a button with 3 states.

Each state, would need to handle click and send a value.

The use-case is:

Non-favourite

Favourite

Uber-favourite

I tried using this.state.count + 1 to indicated the levels, but had no success. I am unsure this is the best way either.

I am using the const fill as the CSS value (colour) I will pass into the svg element.

Here is my attempt, but it is limited as checked only has 2 states (on/off) and I need 3. It is also in this codepen.

class Switch extends React.Component {
  constructor ( props ) {
    super( props );
    this.state = {
      checked: !!props.checked
    };
  }
  handleClick(e) {
        this.setState({
      checked: !this.state.checked
    });
  }

  render () {
    const fill = this.state.checked ? "#E1E0DD" : "#999999";
    return (
        <button className="switch" onClick={this.handleClick.bind(this)} >
      <svg width="100" height="100">
        <g>
          <path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
        </g>
      </svg>
            </button>
    );
  }
}

const App = () => (

        <Switch checked={ true } />

)

React.render( <App />, document.getElementById( "page" ) );

Body:
There are several issues with your code.

Firstly, don't derive a component's state from its props - this is an anti-pattern.

Secondly, because setState calls can be batched by React, you should use the function(prevState, nextProps) argument to setState rather than an object when you are basing new state on previous state.

Thirdly, as mentioned in the comment above, you are never going to be able to get three states by using a boolean.

I would implement this something like this:

class TripleSwitch extends React.Component {
  constructor() {
    super();
    this.state = {
       favourite: 0
    }
  }

  handleClick() {
    this.setState((prevState) => ({
       favourite: (prevState.favourite + 1) % 3
    }));
  }

  render () {
    const { favourite } = this.state;
    const fill = favourite === 0 ? "#E1E0DD" :
                 favourite === 1 ? "#000444" :
                 "#999999";
    return (
        <button className="switch" onClick={this.handleClick.bind(this)} >
      <svg width="100" height="100">
        <g>
          <path id="svg_2" d="m0,38l37,0l11,-38l11,38l37,0l-30,23l11,38l-30,-23l-30,23l11,-38l-30,-23l0,0z" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" fill={fill} />
        </g>
      </svg>
            </button>
    );
  }
}


问:
Using a table made from input file Lua
I have a text file with contents like this

```<code>Jack 17
Will 16
Jordan 15
Elsie 16
</code>```

You get the idea, it's a list of people's names with their ages.

I have a program that reads the file in. Like so:

```<code>file = io.open("ages.txt")
for line in file:lines()
    do
        local name, age = line:match("(%a+) (%d+)")
        print(age) --Not exactly what I want
    end
file:close()
</code>```

print(age) gives me the ages of all people, without names. It runs for everyone, as expected as it's within the loop (as an aside, why does it not work outside the loop? It gives me nil there)

What I want to do is load it into a table. This way, if I want to know Jack's age, I can go print(Jack.age) and it will give me 17. How can this be program be constructed to support this functionality?

答:
Perhaps you are looking for something like this to build a table in the loop:

```<code>file = io.open("ages.txt")
names = {}

for line in file:lines()
    do
        local n, a = line:match("(%a+) (%d+)")
        names[n] = {age = a}
    end
file:close()
</code>```

Here is a sample interaction:

```<code>> print(names.Will.age)
16
> print(names.Jordan.age)
15
> print(names.Elsie.age)
16
</code>```

Title: Using a table made from input file Lua

Body:
I have a text file with contents like this

Jack 17
Will 16
Jordan 15
Elsie 16

You get the idea, it's a list of people's names with their ages.

I have a program that reads the file in. Like so:

file = io.open("ages.txt")
for line in file:lines()
    do
        local name, age = line:match("(%a+) (%d+)")
        print(age) --Not exactly what I want
    end
file:close()

print(age) gives me the ages of all people, without names. It runs for everyone, as expected as it's within the loop (as an aside, why does it not work outside the loop? It gives me nil there)

What I want to do is load it into a table. This way, if I want to know Jack's age, I can go print(Jack.age) and it will give me 17. How can this be program be constructed to support this functionality?

Body:
Perhaps you are looking for something like this to build a table in the loop:

file = io.open("ages.txt")
names = {}

for line in file:lines()
    do
        local n, a = line:match("(%a+) (%d+)")
        names[n] = {age = a}
    end
file:close()

Here is a sample interaction:

> print(names.Will.age)
16
> print(names.Jordan.age)
15
> print(names.Elsie.age)
16


问:
How to save Atom editor config and list of packages installed
I have recently started using Atom editor. Its pretty great so far. I am planning to install it on several other machines.

How can I replicate the config and list of packages installed on my current machine to other machines. Is there a config that I can use to export and import them on other machines.

答:
atom-package-sync is a package that I created a couple weeks ago. It works a little bit like the synchronization of Google Chrome, you just login and it syncs your packages and settings automatically across all your Atom instances.

I plan to release the source code for the server side in the coming weeks and add an export feature for alternative backups.