问:
Extracting a selected item in a ListBox c#
I have a list box that displays members of a List<Student> where Student is a class that has some properties like name etc.. I also have a list box that displays members of a 'ListwherePaperis similar toStudent`.

How do I get the selected Student and Paper and add them to a dict {Paper.Name:Student.Name} when a button is clicked ?

I have tried
Form2

selectedStudent_Form2 = studentListBox_Form2.SelectedItem;

But I get an error saying

Cannot implicitly convert type 'object' to 'TestProjectForProject5.Student'.

答:
Place a SelectionChanged event on your first listbox

```<code>LB1.SelectionChanged += LB1_SelectionChanged;
</code>```

Then implement the SelectionChanged method like so:

```<code>   oid LB1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    LB2.SelectedItems.Clear();
    foreach(var selected in LB1.SelectedItems)
    {
        LB2.SelectedItems.Add(selected);
    }
}
</code>```

Note: LB = Listbox

Body:
Place a SelectionChanged event on your first listbox

LB1.SelectionChanged += LB1_SelectionChanged;

Then implement the SelectionChanged method like so:

   oid LB1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    LB2.SelectedItems.Clear();
    foreach(var selected in LB1.SelectedItems)
    {
        LB2.SelectedItems.Add(selected);
    }
}

Note: LB = Listbox


来源: stackexchange

问:
Testing a PHP script on a local computer
New to PHP and web development in general. I am trying to get information from an HTML form to appear in a table on another web page after clicking submit. So I installed Apache and then PHP on my local PC and expected to be able to test a PHP script locally however it does not return the information I was expecting.
The following is the code for the form:

```<code><form method="post" action="showform.php">

Please fill out the following form if you would like to be contacted: <br/>
    Name:<input type="text" name="name" /> <br/><br/>
    Company: <input type="text" name="company"/> <br/><br/>
    Phone: <input type="text" name="phone" /> <br/><br/>
    Email: <input type="text" name="email" /> <br/><br/>

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

The following is the code for the php script:

```<code><table>
<tr><th>Field Name</th><th>Value(s)</th></tr>

<?php
if (empty($_POST)) {
print "<p>No data was submitted.</p>";
 } else {

foreach ($_POST as $key => $value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
if ($key=='extras') {

if (is_array($_POST['extras']) ){
    print "<tr><td><code>$key</code></td><td>";
    foreach ($_POST['extras'] as $value) {
            print "<i>$value</i><br />";
            }
            print "</td></tr>";
    } else {
    print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";
    }
} else {

print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";
}
 }
}
?>
</table>
</body>
</html>
</code>```

I know it works when used on the internet but how come it doesn't work locally. I have checked that apache and php are installed correctly. What could be the issue?
The current result is a table with $key and $value in the places where the correct values should be, in other words in the table cells.
Thanks for your help.

UPDATE: Now working though WAMPSERVER- thanks to all who helped!

答:
You could also try WampServer.

It's a package containing: Apache, MySQL, PHP (Preconfigured for use in Windows).

OwnerDisplayName: Andrew

LastEditorDisplayName: Andrew

ContentLicense: CC BY-SA 2.5

Body:
New to PHP and web development in general. I am trying to get information from an HTML form to appear in a table on another web page after clicking submit. So I installed Apache and then PHP on my local PC and expected to be able to test a PHP script locally however it does not return the information I was expecting.
The following is the code for the form:

<form method="post" action="showform.php">

Please fill out the following form if you would like to be contacted:

    Name:<input type="text" name="name" />

    Company: <input type="text" name="company"/>

    Phone: <input type="text" name="phone" />

    Email: <input type="text" name="email" />

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

The following is the code for the php script:

Field Name	Value(s)

<?php
if (empty($_POST)) {
print "
No data was submitted.
";
 } else {

foreach ($_POST as $key => $value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
if ($key=='extras') {

if (is_array($_POST['extras']) ){
    print "
$key	";
    foreach ($_POST['extras'] as $value) {
            print "$value
";
            }
            print "
";
    } else {
    print "
$key	$value
\n";
    }
} else {

print "
$key	$value
\n";
}
 }
}
?>

I know it works when used on the internet but how come it doesn't work locally. I have checked that apache and php are installed correctly. What could be the issue?
The current result is a table with $key and $value in the places where the correct values should be, in other words in the table cells.
Thanks for your help.

UPDATE: Now working though WAMPSERVER- thanks to all who helped!

OwnerDisplayName: xgmz


答:
Call this method

```<code>RawPrinterHelper.SendStringToPrinter("WindowsPrinterName", Trim("ZplCode"))
</code>```

which belongs to this class

```<code>Imports System.IO
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices

Public Class RawPrinterHelper
    ' Structure and API declarions:
    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Structure DOCINFOW
        <MarshalAs(UnmanagedType.LPWStr)> Public pDocName As String
        <MarshalAs(UnmanagedType.LPWStr)> Public pOutputFile As String
        <MarshalAs(UnmanagedType.LPWStr)> Public pDataType As String
    End Structure

    <DllImport("winspool.Drv", EntryPoint:="OpenPrinterW", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function OpenPrinter(ByVal src As String, ByRef hPrinter As IntPtr, ByVal pd As Long) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="ClosePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="StartDocPrinterW", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function StartDocPrinter(ByVal hPrinter As IntPtr, ByVal level As Int32, ByRef pDI As DOCINFOW) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="EndDocPrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function EndDocPrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="StartPagePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function StartPagePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="EndPagePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function EndPagePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="WritePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function WritePrinter(ByVal hPrinter As IntPtr, ByVal pBytes As IntPtr, ByVal dwCount As Int32, ByRef dwWritten As Int32) As Boolean
    End Function

    ' SendBytesToPrinter()
    ' When the function is given a printer name and an unmanaged array of
    ' bytes, the function sends those bytes to the print queue.
    ' Returns True on success or False on failure.
    Public Shared Function SendBytesToPrinter(ByVal szPrinterName As String, ByVal pBytes As IntPtr, ByVal dwCount As Int32) As Boolean
        Dim hPrinter As IntPtr      ' The printer handle.
        Dim dwError As Int32        ' Last error - in case there was trouble.
        Dim di As DOCINFOW          ' Describes your document (name, port, data type).
        Dim dwWritten As Int32      ' The number of bytes written by WritePrinter().
        Dim bSuccess As Boolean     ' Your success code.

        ' Set up the DOCINFO structure.
        With di
            .pDocName = "My Visual Basic .NET RAW Document"
            .pDataType = "RAW"
        End With
        ' Assume failure unless you specifically succeed.
        bSuccess = False
        If OpenPrinter(szPrinterName, hPrinter, 0) Then
            If StartDocPrinter(hPrinter, 1, di) Then
                If StartPagePrinter(hPrinter) Then
                    ' Write your printer-specific bytes to the printer.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, dwWritten)
                    EndPagePrinter(hPrinter)
                End If
                EndDocPrinter(hPrinter)
            End If
            ClosePrinter(hPrinter)
        End If
        ' If you did not succeed, GetLastError may give more information
        ' about why not.
        If bSuccess = False Then
            dwError = Marshal.GetLastWin32Error()
        End If
        Return bSuccess
    End Function ' SendBytesToPrinter()

    ' SendFileToPrinter()
    ' When the function is given a file name and a printer name,
    ' the function reads the contents of the file and sends the
    ' contents to the printer.
    ' Presumes that the file contains printer-ready data.
    ' Shows how to use the SendBytesToPrinter function.
    ' Returns True on success or False on failure.
    Public Shared Function SendFileToPrinter(ByVal szPrinterName As String, ByVal szFileName As String) As Boolean
        ' Open the file.
        Dim fs As New FileStream(szFileName, FileMode.Open)
        ' Create a BinaryReader on the file.
        Dim br As New BinaryReader(fs)
        ' Dim an array of bytes large enough to hold the file's contents.
        Dim bytes(fs.Length) As Byte
        Dim bSuccess As Boolean
        ' Your unmanaged pointer.
        Dim pUnmanagedBytes As IntPtr

        ' Read the contents of the file into the array.
        bytes = br.ReadBytes(fs.Length)
        ' Allocate some unmanaged memory for those bytes.
        pUnmanagedBytes = Marshal.AllocCoTaskMem(fs.Length)
        ' Copy the managed byte array into the unmanaged array.
        Marshal.Copy(bytes, 0, pUnmanagedBytes, fs.Length)
        ' Send the unmanaged bytes to the printer.
        bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, fs.Length)
        ' Free the unmanaged memory that you allocated earlier.
        Marshal.FreeCoTaskMem(pUnmanagedBytes)
        Return bSuccess
    End Function ' SendFileToPrinter()

    ' When the function is given a string and a printer name,
    ' the function sends the string to the printer as raw bytes.
    Public Shared Function SendStringToPrinter(ByVal szPrinterName As String, ByVal szString As String)
        Dim pBytes As IntPtr
        Dim dwCount As Int32
        ' How many characters are in the string?
        dwCount = szString.Length()
        ' Assume that the printer is expecting ANSI text, and then convert
        ' the string to ANSI text.
        pBytes = Marshal.StringToCoTaskMemAnsi(szString)
        ' Send the converted ANSI string to the printer.
        SendBytesToPrinter(szPrinterName, pBytes, dwCount)
        Marshal.FreeCoTaskMem(pBytes)
    End Function
End Class
</code>```

Change ZplCode in your call to SendStringToPrinter to the contents of the file.

See also:
http://support.microsoft.com/kb/322091

Title: How to print batch file in vb.net?

Body:
I have a text file that contains code for printing barcode labels.

code is in Zpl code,I want to print the labels using vb.net.

how to print labels in vb.net?

Update:

zpl textfile has collection of lines,like this

textfile1.txt

    I8,A
    q811
    S2
    OD
    JF
    WN
    D7
    ZB
    Q200,25
    N
    A140,4,0,1,2,2,N,"'X'TREME"
    B116,36,0,1,2,4,52,N,"AB1234"
    A226,90,0,2,1,1,N,"AB1234"
    A14,124,0,2,1,1,N,"Jeans"
    A12,156,0,1,2,2,N,"MRP"
    A86,156,0,1,2,2,N,"Rs.595"
    LO86,166,124,3
    A229,114,0,1,2,2,N,"XRP"
    A229,144,0,2,2,2,N,"Rs.580"
    A14,99,0,2,1,1,N,"32"
    A368,96,3,2,1,1,N,"PCD"
    A540,4,0,1,2,2,N,"'X'TREME"
    B516,36,0,1,2,4,52,N,"AB1234"
    A626,90,0,2,1,1,N,"AB1234"
    A414,124,0,2,1,1,N,"T-Shirt"
    A412,156,0,1,2,2,N,"MRP"
    A486,156,0,1,2,2,N,"Rs.595"
    LO486,166,124,3
    A629,114,0,1,2,2,N,"XRP"
    A629,144,0,2,2,2,N,"Rs.580"
    A414,99,0,2,1,1,N,"XL"
    A768,96,3,2,1,1,N,"PCD"
    P1

How will give the second argument for the below function call?

RawPrinterHelper.SendStringToPrinter("WindowsPrinterName", Trim("ZplCode"))

Body:
Call this method

RawPrinterHelper.SendStringToPrinter("WindowsPrinterName", Trim("ZplCode"))

which belongs to this class

Imports System.IO
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices

Public Class RawPrinterHelper
    ' Structure and API declarions:
    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Structure DOCINFOW
        <MarshalAs(UnmanagedType.LPWStr)> Public pDocName As String
        <MarshalAs(UnmanagedType.LPWStr)> Public pOutputFile As String
        <MarshalAs(UnmanagedType.LPWStr)> Public pDataType As String
    End Structure

    <DllImport("winspool.Drv", EntryPoint:="OpenPrinterW", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function OpenPrinter(ByVal src As String, ByRef hPrinter As IntPtr, ByVal pd As Long) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="ClosePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="StartDocPrinterW", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function StartDocPrinter(ByVal hPrinter As IntPtr, ByVal level As Int32, ByRef pDI As DOCINFOW) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="EndDocPrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function EndDocPrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="StartPagePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function StartPagePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="EndPagePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function EndPagePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="WritePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function WritePrinter(ByVal hPrinter As IntPtr, ByVal pBytes As IntPtr, ByVal dwCount As Int32, ByRef dwWritten As Int32) As Boolean
    End Function

    ' SendBytesToPrinter()
    ' When the function is given a printer name and an unmanaged array of
    ' bytes, the function sends those bytes to the print queue.
    ' Returns True on success or False on failure.
    Public Shared Function SendBytesToPrinter(ByVal szPrinterName As String, ByVal pBytes As IntPtr, ByVal dwCount As Int32) As Boolean
        Dim hPrinter As IntPtr      ' The printer handle.
        Dim dwError As Int32        ' Last error - in case there was trouble.
        Dim di As DOCINFOW          ' Describes your document (name, port, data type).
        Dim dwWritten As Int32      ' The number of bytes written by WritePrinter().
        Dim bSuccess As Boolean     ' Your success code.

        ' Set up the DOCINFO structure.
        With di
            .pDocName = "My Visual Basic .NET RAW Document"
            .pDataType = "RAW"
        End With
        ' Assume failure unless you specifically succeed.
        bSuccess = False
        If OpenPrinter(szPrinterName, hPrinter, 0) Then
            If StartDocPrinter(hPrinter, 1, di) Then
                If StartPagePrinter(hPrinter) Then
                    ' Write your printer-specific bytes to the printer.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, dwWritten)
                    EndPagePrinter(hPrinter)
                End If
                EndDocPrinter(hPrinter)
            End If
            ClosePrinter(hPrinter)
        End If
        ' If you did not succeed, GetLastError may give more information
        ' about why not.
        If bSuccess = False Then
            dwError = Marshal.GetLastWin32Error()
        End If
        Return bSuccess
    End Function ' SendBytesToPrinter()

    ' SendFileToPrinter()
    ' When the function is given a file name and a printer name,
    ' the function reads the contents of the file and sends the
    ' contents to the printer.
    ' Presumes that the file contains printer-ready data.
    ' Shows how to use the SendBytesToPrinter function.
    ' Returns True on success or False on failure.
    Public Shared Function SendFileToPrinter(ByVal szPrinterName As String, ByVal szFileName As String) As Boolean
        ' Open the file.
        Dim fs As New FileStream(szFileName, FileMode.Open)
        ' Create a BinaryReader on the file.
        Dim br As New BinaryReader(fs)
        ' Dim an array of bytes large enough to hold the file's contents.
        Dim bytes(fs.Length) As Byte
        Dim bSuccess As Boolean
        ' Your unmanaged pointer.
        Dim pUnmanagedBytes As IntPtr

        ' Read the contents of the file into the array.
        bytes = br.ReadBytes(fs.Length)
        ' Allocate some unmanaged memory for those bytes.
        pUnmanagedBytes = Marshal.AllocCoTaskMem(fs.Length)
        ' Copy the managed byte array into the unmanaged array.
        Marshal.Copy(bytes, 0, pUnmanagedBytes, fs.Length)
        ' Send the unmanaged bytes to the printer.
        bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, fs.Length)
        ' Free the unmanaged memory that you allocated earlier.
        Marshal.FreeCoTaskMem(pUnmanagedBytes)
        Return bSuccess
    End Function ' SendFileToPrinter()

    ' When the function is given a string and a printer name,
    ' the function sends the string to the printer as raw bytes.
    Public Shared Function SendStringToPrinter(ByVal szPrinterName As String, ByVal szString As String)
        Dim pBytes As IntPtr
        Dim dwCount As Int32
        ' How many characters are in the string?
        dwCount = szString.Length()
        ' Assume that the printer is expecting ANSI text, and then convert
        ' the string to ANSI text.
        pBytes = Marshal.StringToCoTaskMemAnsi(szString)
        ' Send the converted ANSI string to the printer.
        SendBytesToPrinter(szPrinterName, pBytes, dwCount)
        Marshal.FreeCoTaskMem(pBytes)
    End Function
End Class

Change ZplCode in your call to SendStringToPrinter to the contents of the file.

See also:
http://support.microsoft.com/kb/322091


问:
Trying to assign names to dictionary, python thinks I'm indexing a string
This may be a stupid error on my part, and I did actually check the suggested answers before posting, but I am having trouble with the following code:

```<code>label_dict = {}
labels_list = [('name', 'Enter the name of the Item:'), ('price', 'Enter Price:'), ('quantity', 'Enter Quantity:'), ('date_incoming', 'Enter Date Incoming:'),
               ('date_sold', 'Enter Date Sold:'), ('location', 'Enter Location:'), ('returnable', 'Enter whether Returnable:')]

x = 0
for label_name, label_text in labels_list:
    label_dict[label_name] = Label(root, text=label_text)
    label_text[label_name].grid(row=x, column=0)
    x += 1
</code>```

I was under the impression that I was able to create an empty dictionary and then assign values to it at a later date. But python keeps telling me that 'string indices must be integers'.

What am I doing wrong? Any help much appreciated!

答:
Python is absolutely correct. You just have a typo and use string instead of dictionary. Instead of

```<code>#     vvvv
label_text[label_name].grid(row=x, column=0)
#     ^^^^
</code>```

Use label_dict[label_name].grid(row=x, column=0)

ContentLicense: CC BY-SA 3.0

Body:
This may be a stupid error on my part, and I did actually check the suggested answers before posting, but I am having trouble with the following code:

label_dict = {}
labels_list = [('name', 'Enter the name of the Item:'), ('price', 'Enter Price:'), ('quantity', 'Enter Quantity:'), ('date_incoming', 'Enter Date Incoming:'),
               ('date_sold', 'Enter Date Sold:'), ('location', 'Enter Location:'), ('returnable', 'Enter whether Returnable:')]

x = 0
for label_name, label_text in labels_list:
    label_dict[label_name] = Label(root, text=label_text)
    label_text[label_name].grid(row=x, column=0)
    x += 1

I was under the impression that I was able to create an empty dictionary and then assign values to it at a later date. But python keeps telling me that 'string indices must be integers'.

What am I doing wrong? Any help much appreciated!

Body:
Python is absolutely correct. You just have a typo and use string instead of dictionary. Instead of

#     vvvv
label_text[label_name].grid(row=x, column=0)
#     ^^^^

Use label_dict[label_name].grid(row=x, column=0)


问:
Google analytics not showing any data of android studio project
I followed https://developers.google.com/analytics/devguides/collection/android/v4/ to implement google analytics in my android app. But it is not showing any data.
Can anyone help?
Manifest file:

```<code> <application
        android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:name=".AnalyticsApplication">
        <activity android:name="com.xxx.xxxx.SplashScreen"
       android:screenOrientation="portrait">
       <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <activity android:name="com.xxx.xxxx.LoginScreen"
    android:screenOrientation="portrait"/>
        <activity android:name="com.xxx.xxxx.ForgotPasswordScreen"
    android:screenOrientation="portrait"/>
        <activity android:name="com.xx.xxx.SignupScreen"
    android:screenOrientation="portrait"/>
        <activity android:name="com.xxx.xxx.HomeScreen"
    android:screenOrientation="portrait">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.xxx.xxxx.SplashScreen" />
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version"/>

            <meta-data

    android:name="com.google.android.gms.analytics.globalConfigResource"
                android:resource="@xml/global_tracker"/>
        </activity>

    </application>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

AnalyticsApplication

```<code>    public class AnalyticsApplication  extends Application {

    private static GoogleAnalytics sAnalytics;
    private static Tracker mTracker;

    @Override
    public void onCreate() {
        super.onCreate();

        sAnalytics = GoogleAnalytics.getInstance(this);
    }

    synchronized public Tracker getDefaultTracker() {
        // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
        if (mTracker == null) {
            mTracker = sAnalytics.newTracker(R.xml.global_tracker);
        }

        return mTracker;
    }
    }
</code>```

HomeScreen

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.home_screen);
        Helper.printLog(tag, "onCreate");

        AnalyticsApplication application = (AnalyticsApplication)
        getApplication();
        mTracker = application.getDefaultTracker();

        mTracker.setScreenName("home screen");
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
     }
     onclick(){
     mTracker.send(new HitBuilders.EventBuilder()
                    .setCategory("Action account")
                    .setAction("account clicked")
                    .build());
           changeFragment(new AccountFragment());
    }
</code>```

app-gradle

```<code> dependencies{
     compile 'com.google.android.gms:play-services-analytics:10.2.4'}
</code>```

project-gradle

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'
    classpath 'com.google.gms:google-services:3.0.0'

}
</code>```

答:
Try firebase analytics firebase is a google product to build high quality apps and its uses Google Analytics. Firebase and google analytics are same

Visit - https://firebase.google.com/docs/analytics/
Hope this help

Body:
I followed https://developers.google.com/analytics/devguides/collection/android/v4/ to implement google analytics in my android app. But it is not showing any data.
Can anyone help?
Manifest file:

 <application
        android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:name=".AnalyticsApplication">
        <activity android:name="com.xxx.xxxx.SplashScreen"
       android:screenOrientation="portrait">
       <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <activity android:name="com.xxx.xxxx.LoginScreen"
    android:screenOrientation="portrait"/>
        <activity android:name="com.xxx.xxxx.ForgotPasswordScreen"
    android:screenOrientation="portrait"/>
        <activity android:name="com.xx.xxx.SignupScreen"
    android:screenOrientation="portrait"/>
        <activity android:name="com.xxx.xxx.HomeScreen"
    android:screenOrientation="portrait">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.xxx.xxxx.SplashScreen" />
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version"/>

            <meta-data

    android:name="com.google.android.gms.analytics.globalConfigResource"
                android:resource="@xml/global_tracker"/>
        </activity>

    </application>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

AnalyticsApplication

    public class AnalyticsApplication  extends Application {

    private static GoogleAnalytics sAnalytics;
    private static Tracker mTracker;

    @Override
    public void onCreate() {
        super.onCreate();

        sAnalytics = GoogleAnalytics.getInstance(this);
    }

    synchronized public Tracker getDefaultTracker() {
        // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
        if (mTracker == null) {
            mTracker = sAnalytics.newTracker(R.xml.global_tracker);
        }

        return mTracker;
    }
    }

HomeScreen

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.home_screen);
        Helper.printLog(tag, "onCreate");

        AnalyticsApplication application = (AnalyticsApplication)
        getApplication();
        mTracker = application.getDefaultTracker();

        mTracker.setScreenName("home screen");
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
     }
     onclick(){
     mTracker.send(new HitBuilders.EventBuilder()
                    .setCategory("Action account")
                    .setAction("account clicked")
                    .build());
           changeFragment(new AccountFragment());
    }

app-gradle

 dependencies{
     compile 'com.google.android.gms:play-services-analytics:10.2.4'}

project-gradle

dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'
    classpath 'com.google.gms:google-services:3.0.0'

}


问:
In which branch should I build a docker image?
We have a react project that is based on react-static-boilerplate which will follow git DMZ flow and will make use of docker images.

Does the build in git dmz flow pertains to yarn build?

Since master and hotfix are deployed in production and release branch is where manual testing is done, does it mean that this is where I should trigger a docker build?

答:
This depends on the tradeoffs you want to make. In ideal world, you would want to automate a docker build for every branch for testing. If that takes too much time, then you might want to design a base image to start with.

Still, there is nothing wrong ignoring docker but let build without it. At that point, you would take more responsibility at master branch build.

Docker is simply there for pushing system configuration efforts to the developer but you can make best of the both worlds by providing a good base image and building for every branch. Having said that, Docker's internal caching will save you acceptable amount of time in the same testing environment even you keep a long recipe.


问:
how to deserialize a collection from an alamofire request
this is a pretty basic question of the syntax for deserializing responsejson collection in alamofire and swift

I have a GET service that returns an array of user objects e.g.

```<code>[
  {"uname": "bob"},
  {"uname": "jane"}
]
</code>```

and here is my request

```<code>   Alamofire.request(.GET, url , encoding:.JSON)
     .responseJSON(options: .MutableContainers, completionHandler:{ (request, response, JSON, error) -> Void in
        let result = JSON as? [Dictionary<String,String>]
        if (response!.statusCode == 200 && error == nil){
           //how should I deserialize the result here to return [String]
           callback(success: true, errorMsg: nil, friends:friends)
         }
         else{
           callback(success: false,errorMsg:error?.localizedDescription,friends:nil)
          }
    })
</code>```

My question is how to deserialize the result, and am I correct to assume that the json result is a [Dictionary] and in order for me to change it to a [String] result, should I map it?

If I use the map syntax below I have a few questions

```<code>let friends = result?.map {
                    return $0["uname"] as String?
                }
</code>```

With the optional return value can I get it to return a [String] instead of a [String?] in a graceful way - isn't there a way to let map return only non null values somehow in a concise syntax?

Also is there a better syntax for map that lets me name the parameters instead of using $0?

答:
Updated implementation for Alamofire 4.3

```<code>Alamofire.request(url, method: .get)
  .responseJSON { response in
      if response.data != nil {
        let json = JSON(data: response.data!)
        let name = json["data"][0]["name"].string
        if name != nil {
          print(name!)
        }
      }
  }
</code>```

That will parse this JSON input:

```<code>{
  data: [
    { name: 'John' },
    { name: 'Dave' }
  ]
}
</code>```

Body:
this is a pretty basic question of the syntax for deserializing responsejson collection in alamofire and swift

I have a GET service that returns an array of user objects e.g.

[
  {"uname": "bob"},
  {"uname": "jane"}
]

and here is my request

   Alamofire.request(.GET, url , encoding:.JSON)
     .responseJSON(options: .MutableContainers, completionHandler:{ (request, response, JSON, error) -> Void in
        let result = JSON as? [Dictionary<String,String>]
        if (response!.statusCode == 200 && error == nil){
           //how should I deserialize the result here to return [String]
           callback(success: true, errorMsg: nil, friends:friends)
         }
         else{
           callback(success: false,errorMsg:error?.localizedDescription,friends:nil)
          }
    })

My question is how to deserialize the result, and am I correct to assume that the json result is a [Dictionary] and in order for me to change it to a [String] result, should I map it?

If I use the map syntax below I have a few questions

let friends = result?.map {
                    return $0["uname"] as String?
                }

With the optional return value can I get it to return a [String] instead of a [String?] in a graceful way - isn't there a way to let map return only non null values somehow in a concise syntax?

Also is there a better syntax for map that lets me name the parameters instead of using $0?

Body:
Updated implementation for Alamofire 4.3

Alamofire.request(url, method: .get)
  .responseJSON { response in
      if response.data != nil {
        let json = JSON(data: response.data!)
        let name = json["data"][0]["name"].string
        if name != nil {
          print(name!)
        }
      }
  }

That will parse this JSON input:

{
  data: [
    { name: 'John' },
    { name: 'Dave' }
  ]
}


问:
Idiomatic Python: Propagating yields or flattening sequences?
I'm writing a breadth depth-first tree traversal function, and what I want to do is this:

```<code>def traverse(node):
    yield node
    for n in node.children:
        yield_all traverse(n) # << if Python had a yield_all statement
</code>```

The idea is to end up with a (flat) sequence of nodes in the tree.

Approach #1: (propagating yields)

```<code>def traverse(node):
    yield node
    for n in node.children:
        for m in traverse(n):
            yield m
</code>```

Approach #2: (flattening sequences)

```<code>def traverse(node):
    return itertools.chain([node],*(traverse(n) for n in node.children))
</code>```

The first approach seems more clean, but I feel weird explicitly yielding each node in the subtree at each level.

The second approach is terse and slightly dirty, but it matches what I would write in Haskell:

```<code>traverse node = node : concatMap traverse (children node)
</code>```

So my question is: Which is better? Or am I missing a best 3rd option?

答:
[UPDATE] See PEP-380, this yield all syntax is available starting from Python 3.3 as yield from:

```<code>def traverse(node):
    yield node
    for n in node.children:
        yield from traverse(n)
</code>```

Body:
I'm writing a breadth depth-first tree traversal function, and what I want to do is this:

def traverse(node):
    yield node
    for n in node.children:
        yield_all traverse(n) # << if Python had a yield_all statement

The idea is to end up with a (flat) sequence of nodes in the tree.

Approach #1: (propagating yields)

def traverse(node):
    yield node
    for n in node.children:
        for m in traverse(n):
            yield m

Approach #2: (flattening sequences)

def traverse(node):
    return itertools.chain([node],*(traverse(n) for n in node.children))

The first approach seems more clean, but I feel weird explicitly yielding each node in the subtree at each level.

The second approach is terse and slightly dirty, but it matches what I would write in Haskell:

traverse node = node : concatMap traverse (children node)

So my question is: Which is better? Or am I missing a best 3rd option?

Body:
[UPDATE] See PEP-380, this yield all syntax is available starting from Python 3.3 as yield from:

def traverse(node):
    yield node
    for n in node.children:
        yield from traverse(n)


问:
can we retrieve and set PHP cookies using javascriopt
I've set a cookie using PHP,

```<code>setcookie("redirect", $this->currentPage(), time() + 31536000);
</code>```

but I want to retrieve the value of this cookie using javascript when a certain link is clicked. How can I do that?

答: Wrong concept. Cookies are stored in browsers. PHP gets/sets browser cookies through HTTP requests and responses. So both PHP and browser JS can manipulate the same cookies.</p>

Body:
I've set a cookie using PHP,

setcookie("redirect", $this->currentPage(), time() + 31536000);

but I want to retrieve the value of this cookie using javascript when a certain link is clicked. How can I do that?


问:
php not getting key and value from generated url
I am trying to create a forgot password and password reset module using PHP.

Users upon entering the email id, I am fetching the record from MySQL that matches with the email id. I am able to fetch the record.

My reset_password form:

```<code><html>
  <body>
    <form method="post" action="sendlink.php">
      <p>Enter Email Address To Send Password Link</p>
      <input type="text" name="email">
      <input type="submit" name="submit_email">
    </form>
  </body>
</html>
</code>```

I am creating a link with the email id and password and send it as a mail to the user.  I am able to send the email.  I am providing a part of the code that enables me to send the email with the link.

```<code><?php
if(isset($_POST['submit_email']) && $_POST['email'])
{
  require 'connect.php';
  $email = $_POST['email'];
  $select=mysqli_query($connection, "select * from users where email='$email'");
  if(mysqli_num_rows($select)==1)
  {
    while($row=mysqli_fetch_array($select))
    {
      $email=$row['email'];
      $pass=$row['pass'];
    }
    $link="<a href='www.mywebsite.com/reset_pass.php?key=".$email."&?reset=".$pass."'>Click to reset password.</a>";
    require_once "phpmailer/class.phpmailer.php";
    $mail = new PHPMailer(true);
    $mail->CharSet =  "utf-8";
</code>```

This is continued by other codes to send the mail.  This part is working correctly and I am receiving the mail.

When I click on the link received in the mail, I intend to open up a form to reset the password using reset_pass.php given in the link.

The following is the link that gets generated:

```<code>http://www.mywebsite.com/reset_pass.php?key=user@theshoecompany.com&?reset=39eb0152f5a43c08169716dbf158f08e
</code>```

Code to open the form to accept new password:

```<code><?php
if($_GET['key'] && $_GET['reset'])
{
  $email=$_GET['key'];
  $pass=$_GET['reset'];
  require('connect.php');
  $query = "SELECT * FROM `users` WHERE email='$email' and pass='$pass'";
  $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
  $count = mysqli_num_rows($result);

//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1)
  {
    ?>
    <form method="post" action="submit_new.php">
    <input type="hidden" name="emailnew" value="<?php echo $email;?>">
    <p>Enter New password</p>
    <input type="password" name='passwordnew'>
    <input type="submit" name="Submit">
    </form>
    <?php
  }
}
else {
  echo "<script>
                alert('could not get email or password');
                </script>";
}
?>
</code>```

With the above code I wanted to open a form for the user to type in a new password.  But the values of email and password are not getting posted from the link.  The browser opens blank page, loads it and just remains blank without opening the form to accept the password.

How do i rectify this?

答:
In the example you've provided, the query string parameters are key and ?reset because you have ? twice in the generated reset_pass URL:

```<code>$link="<a href='www.mywebsite.com/reset_pass.php?key=".$email."&?reset=".$pass."'>Click to reset password.</a>";
                                                ^               ^
</code>```

Based on your conditional in the reset_pass.php page, the page that loads should contain the  payload (because 'reset' != '?reset'). If you "View Source" on the reset_pass.php page when it loads, you should see this as well - if you're not already seeing the alert.

If you update the link generation to contain only 1 ?, it may work:

```<code>$link="<a href='www.mywebsite.com/reset_pass.php?key=".$email."&reset=".$pass."'>Click to reset password.</a>";
</code>```

Body:
I am trying to create a forgot password and password reset module using PHP.

Users upon entering the email id, I am fetching the record from MySQL that matches with the email id. I am able to fetch the record.

My reset_password form:

    <form method="post" action="sendlink.php">

Enter Email Address To Send Password Link

      <input type="text" name="email">
      <input type="submit" name="submit_email">
    </form>

I am creating a link with the email id and password and send it as a mail to the user.  I am able to send the email.  I am providing a part of the code that enables me to send the email with the link.

<?php
if(isset($_POST['submit_email']) && $_POST['email'])
{
  require 'connect.php';
  $email = $_POST['email'];
  $select=mysqli_query($connection, "select * from users where email='$email'");
  if(mysqli_num_rows($select)==1)
  {
    while($row=mysqli_fetch_array($select))
    {
      $email=$row['email'];
      $pass=$row['pass'];
    }
    $link="Click to reset password.";
    require_once "phpmailer/class.phpmailer.php";
    $mail = new PHPMailer(true);
    $mail->CharSet =  "utf-8";

This is continued by other codes to send the mail.  This part is working correctly and I am receiving the mail.

When I click on the link received in the mail, I intend to open up a form to reset the password using reset_pass.php given in the link.

The following is the link that gets generated:

http://www.mywebsite.com/reset_pass.php?key=user@theshoecompany.com&?reset=39eb0152f5a43c08169716dbf158f08e

Code to open the form to accept new password:

<?php
if($_GET['key'] && $_GET['reset'])
{
  $email=$_GET['key'];
  $pass=$_GET['reset'];
  require('connect.php');
  $query = "SELECT * FROM `users` WHERE email='$email' and pass='$pass'";
  $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
  $count = mysqli_num_rows($result);

//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1)
  {
    ?>
    <form method="post" action="submit_new.php">
    <input type="hidden" name="emailnew" value="<?php echo $email;?>">

Enter New password

    <input type="password" name='passwordnew'>
    <input type="submit" name="Submit">
    </form>
    <?php
  }
}
else {
  echo "";
}
?>

With the above code I wanted to open a form for the user to type in a new password.  But the values of email and password are not getting posted from the link.  The browser opens blank page, loads it and just remains blank without opening the form to accept the password.

How do i rectify this?

Body:
In the example you've provided, the query string parameters are key and ?reset because you have ? twice in the generated reset_pass URL:

$link="<a href='www.mywebsite.com/reset_pass.php?key=".$email."&?reset=".$pass."'>Click to reset password.</a>";
                                                ^               ^

Based on your conditional in the reset_pass.php page, the page that loads should contain the <script>alert(...)</script> payload (because 'reset' != '?reset'). If you "View Source" on the reset_pass.php page when it loads, you should see this as well - if you're not already seeing the alert.

If you update the link generation to contain only 1 ?, it may work:

$link="<a href='www.mywebsite.com/reset_pass.php?key=".$email."&reset=".$pass."'>Click to reset password.</a>";


问:
bash script: how to insert text between two specific characters
For example, I have a file containing a line as below:

```<code>"abc":"def"
</code>```

I need to insert 123 between "abc":" and def" so that the line will become: "abc":"123def".

As "abc" appears only once so I think I can just search it and do the insertion.

How to do this with bash script such as sed or awk?

答:
```<code>AMD$ sed 's/"abc":"/&123/' File
"abc":"123def"
</code>```

Match "abc":", then append this match with 123 (& will contain the matched string "abc":")

If you want to take care of space before and after :, you can use:

```<code>sed 's/"abc" *: *"/&123/'
</code>```

For replacing all such patterns, use g with sed.

```<code>sed 's/"abc" *: *"/&123/g' File
</code>```

Body:
For example, I have a file containing a line as below:

"abc":"def"

I need to insert 123 between "abc":" and def" so that the line will become: "abc":"123def".

As "abc" appears only once so I think I can just search it and do the insertion.

How to do this with bash script such as sed or awk?

Body:
AMD$ sed 's/"abc":"/&123/' File
"abc":"123def"

Match "abc":", then append this match with 123 (& will contain the matched string "abc":")

If you want to take care of space before and after :, you can use:

sed 's/"abc" *: *"/&123/'

For replacing all such patterns, use g with sed.

sed 's/"abc" *: *"/&123/g' File


问:
How can I append a string to a line when certain conditions are met?
I'm handling large .txt files and we are trying to identify which ones do not comply with the correct amount of characters in a line (80 characters top).

For the sake of this example let's say that we need 10 characters for every line, I need to append "(+Number of extra characters)" and "(-Number of missing characters)" for each line that does not have exactly 10 characters.

Here is what I have so far:

```<code>while IFS='' read -r line || [[ -n "$line" ]]; do
  if [[ "${#line}" -gt 10 ]]; then
    echo "Mo dan 10 D: ${#line}"
  elif [[ "${#line}" -lt 10 ]]; then
    echo "Less dan 10 D: ${#line}"
  fi

done < "$1"
</code>```

I'm stuck in finding a way to append those two strings I'm echoing in the corresponding line so we can identify them.

I researched about awk and sed but haven't been able to properly loop through the entire .txt file, count the amount of characters in every line and append a string with the appropriate message.

Would appreciate some assistance in either shell scripting or as an awk or sed solution.
Thank You.

Edit: This is an example input file (note white spaces also count as characters)

```<code>Line 1****
Line 2*****
Line 3*
Line 4****
Line 5****
Line 6**
Line 7****
Line 8********
Line 9****
</code>```

This is the desired output

```<code>Line 1****
Line 2*****(+1)
Line 3*(-3)
Line 4****
Line 5****
Line 6**(-2)
Line 7****
Line 8********(+4)
Line 9****
</code>```

答:
For performance reasons, using a shell loop to process the lines of a file is the wrong approach (unless the file is very small).

A text-processing utility such as awk is the much better choice:

```<code>awk -v targetLen=10 '
  diff = length($0) - targetLen { # input line ($0) does not have the expected length
    $0 = $0 "(" (diff > 0 ? "+" : "") diff ")" # append diff (with +, if positive)
  }
  1  # Print the (possibly modified) line.
' <<'EOF'  # sample input as a here-document
1234567890
123456789
123456789012
EOF
</code>```

This yields:

1234567890
123456789(-1)
123456789012(+2)
```

Caveat: The BSD/macOS awk implementation is not locale-aware, so its length function counts bytes, which will only work as intended with ASCII-range characters.

Body:
I'm handling large .txt files and we are trying to identify which ones do not comply with the correct amount of characters in a line (80 characters top).

For the sake of this example let's say that we need 10 characters for every line, I need to append "(+Number of extra characters)" and "(-Number of missing characters)" for each line that does not have exactly 10 characters.

Here is what I have so far:

while IFS='' read -r line || [[ -n "$line" ]]; do
  if [[ "${#line}" -gt 10 ]]; then
    echo "Mo dan 10 D: ${#line}"
  elif [[ "${#line}" -lt 10 ]]; then
    echo "Less dan 10 D: ${#line}"
  fi

done < "$1"

I'm stuck in finding a way to append those two strings I'm echoing in the corresponding line so we can identify them.

I researched about awk and sed but haven't been able to properly loop through the entire .txt file, count the amount of characters in every line and append a string with the appropriate message.

Would appreciate some assistance in either shell scripting or as an awk or sed solution.
Thank You.

Edit: This is an example input file (note white spaces also count as characters)

Line 1****
Line 2*****
Line 3*
Line 4****
Line 5****
Line 6**
Line 7****
Line 8********
Line 9****

This is the desired output

Line 1****
Line 2*****(+1)
Line 3*(-3)
Line 4****
Line 5****
Line 6**(-2)
Line 7****
Line 8********(+4)
Line 9****

Body:
For performance reasons, using a shell loop to process the lines of a file is the wrong approach (unless the file is very small).

A text-processing utility such as awk is the much better choice:

awk -v targetLen=10 '
  diff = length($0) - targetLen { # input line ($0) does not have the expected length
    $0 = $0 "(" (diff > 0 ? "+" : "") diff ")" # append diff (with +, if positive)
  }
  1  # Print the (possibly modified) line.
' <<'EOF'  # sample input as a here-document
1234567890
123456789
123456789012
EOF

This yields:

1234567890
123456789(-1)
123456789012(+2)

Caveat: The BSD/macOS awk implementation is not locale-aware, so its length function counts bytes, which will only work as intended with ASCII-range characters.


答:
```<code>$ cat lines.in
Line 1****
Line 2*****
Line 3*
Line 4****
Line 5****
Line 6**
Line 7****
Line 8********
Line 9****

$ cat lines.sh
#!/bin/bash
mark=10
while IFS='' read -r line || [[ -n "$line" ]]; do
    diff=$(( ${#line} - mark ))
    if [ ${diff} -eq 0 ]; then
        echo "${line}"
    else
        printf "%s (%+d)\n" "${line}" "${diff}"
    fi
done < "$1"

$ ./lines.sh lines.in
Line 1****
Line 2***** (+1)
Line 3* (-3)
Line 4****
Line 5****
Line 6** (-2)
Line 7****
Line 8******** (+4)
Line 9****
</code>```

Title: How can I append a string to a line when certain conditions are met?


答:
Not sure if it's typo. But the problem is in this line:

```<code>label_text[label_name].grid(row=x, column=0)
</code>```

label_text is a string and indeed its indexes can only be integers, but you use another string as an index.

Title: Trying to assign names to dictionary, python thinks I'm indexing a string

Body:
Not sure if it's typo. But the problem is in this line:

label_text[label_name].grid(row=x, column=0)

label_text is a string and indeed its indexes can only be integers, but you use another string as an index.


问:
Semantic-UI - How to clear dropdown cache
How can I clear the cache of Semantic-UI dropdown that is set to fetch its content from remote URL? Here is my code so far. It doesn't send a new request to api.php whenever I click it i.e. it shows old data. However, when I search something, it sends the request. </p>

```<code>$('#dd').dropdown({
        apiSettings: {
            url: '/api.php?q={query}',
            data: {query: ''},
            method: 'POST'
        }
});
</code>```

答:
You may want to add cache: false to prevent caching of dropdown.

```<code>$('#dd').dropdown({
    apiSettings: {
        url: '/api.php?q={query}',
        data: {query: ''},
        method: 'POST',
        cache: false
    }
});
</code>```

And here's on clearing the cache in localStorage

Body:
How can I clear the cache of Semantic-UI dropdown that is set to fetch its content from remote URL? Here is my code so far. It doesn't send a new request to api.php whenever I click it i.e. it shows old data. However, when I search something, it sends the request.

$('#dd').dropdown({
        apiSettings: {
            url: '/api.php?q={query}',
            data: {query: ''},
            method: 'POST'
        }
});

Body:
You may want to add cache: false to prevent caching of dropdown.

$('#dd').dropdown({
    apiSettings: {
        url: '/api.php?q={query}',
        data: {query: ''},
        method: 'POST',
        cache: false
    }
});

And here's on clearing the cache in localStorage


问:
programmatically determine generic type
apologies if this is a duplicate.

Is there any way to determine what generic type a class is?

ie I want to know what T is....

```<code>public void doSomething(SomeClass<T> thing)
{
    Class<T> t = ???;
}
</code>```

thanks, p.

答: Not in Java.  You will have to accept a parameter of Class<T> too, which the caller will have to supply.  (You can do this in the constructor if you would like, so that the class reference will be available to all class methods.)  This is a commonly used hack to determine what T refers to at runtime, which is not available otherwise due to the way Java implements generics.

Title: programmatically determine generic type

Body:
apologies if this is a duplicate.

Is there any way to determine what generic type a class is?

ie I want to know what T is....

public void doSomething(SomeClass<T> thing)
{
    Class<T> t = ???;
}

thanks, p.


问:
Detect bad json data in PHP json_decode()?
I'm trying handle bad json data when parsed through json_decode(). I'm using the following script:

```<code>if(!json_decode($_POST)) {
  echo "bad json data!";
  exit;
}
</code>```

If $_POST equals:

```<code>'{ bar: "baz" }'
</code>```

Then json_decode handles the error fine and spits out "bad json data!";
However, if I set $_POST to something like "invalid data", it gives me:

```<code>Warning: json_decode() expects parameter 1 to be string, array given in C:\server\www\myserver.dev\public_html\rivrUI\public_home\index.php  on line 6
bad json data!
</code>```

Do I need to write a custom script to detect valid json data, or is there some other nifty way to detect this?

答:
This is how Guzzle handles json</p>

```<code>    /**
 * Parse the JSON response body and return an array
 *
 * @return array|string|int|bool|float
 * @throws RuntimeException if the response body is not in JSON format
 */
public function json()
{
    $data = json_decode((string) $this->body, true);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new RuntimeException('Unable to parse response body into JSON: ' . json_last_error());
    }

    return $data === null ? array() : $data;
}
</code>```

Body:
I'm trying handle bad json data when parsed through json_decode(). I'm using the following script:

if(!json_decode($_POST)) {
  echo "bad json data!";
  exit;
}

If $_POST equals:

'{ bar: "baz" }'

Then json_decode handles the error fine and spits out "bad json data!";
However, if I set $_POST to something like "invalid data", it gives me:

Warning: json_decode() expects parameter 1 to be string, array given in C:\server\www\myserver.dev\public_html\rivrUI\public_home\index.php  on line 6
bad json data!

Do I need to write a custom script to detect valid json data, or is there some other nifty way to detect this?

Body:
This is how Guzzle handles json

    /**
 * Parse the JSON response body and return an array
 *
 * @return array|string|int|bool|float
 * @throws RuntimeException if the response body is not in JSON format
 */
public function json()
{
    $data = json_decode((string) $this->body, true);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new RuntimeException('Unable to parse response body into JSON: ' . json_last_error());
    }

    return $data === null ? array() : $data;
}


问:
Upload build/ipa for testing in TestFlight
I am using application loader to upload my IPA on TestFlight to make it available for testers to test the app.
Application loader shows a successfully uploaded message but when I log into iTunesConnect in Apple developer account, I don't see the build in TestFlight under that particular app.

This is what application loader shows.

This is what the iTunesConnect shows.

答:
I had the same issue recently and the way to "fix it" was: in ItunesConnect go to the AppStore tab and click on the "Version or Platform" link and select iOS. There create a new version with the exact version number you are uploading.

After this you will be able to see the builds you are uploading and start testing in Testflight.

Hope this helps!


问:
Problems with React-Native v 0.45.0 on building on XCode
I initialized a react native project. It installed with 0.45.0 version of react-native.

XCode isn't able to build it.

There is a problem with config.hpp file.
Error is highlighted in red color, which says "'boost/config/user.hpp' file not found"

答:
delete $APP_DIR/node_modules/react-native/third-party/glog-0.3.4

download glob-0.3.5 from https://github.com/google/glog replace glob-0.3.4


问:
Moving data across the appdomain with good performance?

A little background

I'm working on an .net application that's uses plugins heavily, the application can request data from the plugins that is then sent back and displayed by the application.

First I implemented the plugin framework in MEF but feel that it was a bit limited for my purposes, I wanted to be able to isolate plugins and have some versioning and licensing support (since plugins can be written by thirdparty).

Then started looking at MAF which seems support just those scenarios, however I can see one thing that might be a problem, before I invest too much time changing everything to MAF it would be great knowing if someone has experience with this issue since I havent worked much with MAF.

The problem

Currently when  data is sent back to the application you get the actual objects of the data along with an adapter that says which fields the object contains and you can use the adapter on the object to extract the fields you want. The good thing about this is that you don't have to generate any new results objects but can simply query the results data when you want it from each object.

Now with MAF there's the Appdomain issue, I can't freely send all the objects across the app domain and inheriting from marshalbyref for each object isn't viable.

I could generate a result object with the string fields for each object but from a performance standpoint it doesnt seem such a good idea, the interface might only show 10 of hundreds of objects so it seems smarter to do on demand.

The solution I'm thinking might work is generating a sequence of just object id's and let the interface fetch the fields from the plugin through the appdomain through a proxy. So the application says for instance it wants fieldname x from items [y] in the plugin and those strings is sent across the appdomain.

The Question

So my questions are, is this a good way to do it, is there a better way? I'm obviously going to take a little performance hit moving across the appdomain still but since it's on demand and only for a small number of objects it shouldn't be too bad right? How do I go about setting up a proxy object like that?

It's not the easiest question in the world to answer, sorry. I'll really appreciate any insight, the future of the plugin architecture depends on it :)

答:
As far as I've read, MEF was only designed with a basic set-up, for us all to all build the features that we need on top of it. Have you considered adding the features, or are hard limitations forcing the change?

Admittedly I don't have experience of MEF in very large applications (where MAF is more suited), and I don't know the features you're missing, but with MEF I've yet to find something I couldn't add myself. At least then you have it just how you want/need it!


问:
Can you customize the auth0 login screen in xamarin app
I have a xamarin app that is utilizing auth0 for auth purposes. But I see for web version you can pass different options for theming the login page appearance. Is that also possible in a xamarin app.</p>

```<code> client = new Auth0Client(new Auth0ClientOptions
 {
     Domain = Resources.GetString(Resource.String.auth0_domain),
     ClientId = Resources.GetString(Resource.String.auth0_client_id),
     Activity = this
 });
</code>```

答: Actually I found you can customize it here: manage login page</p>

Body:
I have a xamarin app that is utilizing auth0 for auth purposes. But I see for web version you can pass different options for theming the login page appearance. Is that also possible in a xamarin app.

 client = new Auth0Client(new Auth0ClientOptions
 {
     Domain = Resources.GetString(Resource.String.auth0_domain),
     ClientId = Resources.GetString(Resource.String.auth0_client_id),
     Activity = this
 });


问:
R loop with strings inside a data frame name
I want to generate a dataframe, hminput, with 3 parameters from different smaller dataframes (named frqAFR, frqAMR, .. etc, as you can see below). So, instead of writing separately all the code to extract the three columns of each one and then bind them by column and after that by row, I was wondering if I could optimize it a bit with a for loop with strings from a list.

So, here is my idea so far:

```<code>listpop<-c("frqAFR","frqAMR","frqEUR","frqEAS","frqSAS","frqAFROURU","frqIND")

for (g in listpop) {
  hminput<- rbind(cbind(paste(g)["SNP"],paste(g)["POP"],paste(g)["MAF"]))
              }
</code>```

But it generates a hminput dataframe with three NAs.
Any thoughts? Thanks!

Desired output:

```<code>hminput

snp1 pop1 maf1
snp2 pop2 maf2
snp3 pop3 maf3
...
</code>```

答:
We need to get the value of the dataset objects.  Assuming that the 'listpop' strings are the data.frame object names, get the values in a list using mget, then subset the columns "SNP", "POP", "MAF", and rbind the list elements

```<code>hminput <- do.call(rbind, lapply(mget(listpop), function(x) x[c("SNP", "POP", "MAF")]))
</code>```

If we are using the for loop

```<code>hminput <- c()
for(g in listpop) {
     hminput <- rbind(hminput, get(g)[c("SNP", "POP", "MAF")])
}
</code>```

If we are looking for efficient solution, then rbindlist from data.table can be used

```<code>library(data.table)
rbindlist(lapply(mget(listpop), `[`, c("SNP", "POP", "MAF")))
</code>```

And if we need to use tidyverse

```<code>library(tidyverse)
mget(listpop) %>%
         map(~.[c("SNP", "POP", "MAF")] %>%
         bind_rows()
</code>```

Body:
I want to generate a dataframe, hminput, with 3 parameters from different smaller dataframes (named frqAFR, frqAMR, .. etc, as you can see below). So, instead of writing separately all the code to extract the three columns of each one and then bind them by column and after that by row, I was wondering if I could optimize it a bit with a for loop with strings from a list.

So, here is my idea so far:

listpop<-c("frqAFR","frqAMR","frqEUR","frqEAS","frqSAS","frqAFROURU","frqIND")

for (g in listpop) {
  hminput<- rbind(cbind(paste(g)["SNP"],paste(g)["POP"],paste(g)["MAF"]))
              }

But it generates a hminput dataframe with three NAs.
Any thoughts? Thanks!

Desired output:

hminput

snp1 pop1 maf1
snp2 pop2 maf2
snp3 pop3 maf3
...

Body:
We need to get the value of the dataset objects.  Assuming that the 'listpop' strings are the data.frame object names, get the values in a list using mget, then subset the columns "SNP", "POP", "MAF", and rbind the list elements

hminput <- do.call(rbind, lapply(mget(listpop), function(x) x[c("SNP", "POP", "MAF")]))

If we are using the for loop

hminput <- c()
for(g in listpop) {
     hminput <- rbind(hminput, get(g)[c("SNP", "POP", "MAF")])
}

If we are looking for efficient solution, then rbindlist from data.table can be used

library(data.table)
rbindlist(lapply(mget(listpop), `[`, c("SNP", "POP", "MAF")))

And if we need to use tidyverse

library(tidyverse)
mget(listpop) %>%
         map(~.[c("SNP", "POP", "MAF")] %>%
         bind_rows()


答:
sed:

```<code>$ sed -E 's/(:")(.*)/\1123\2/' <<<'"abc":"def"'
"abc":"123def"
</code>```

(:") gets :" and put in captured group 1

(.*) gets the remaining portion and put in captured group 2

in the replacement, \1123\2 puts 123 between the groups

awk:

```<code>$ awk -F: 'sub(".", "&123", $2)' <<<'"abc":"def"'
"abc" "123def"
</code>```

In the sub() function, the second ($2) field is being operated on, pattern is used as . (which would match "), and in the replacement the matched portion (&) is followed by 123.

Title: bash script: how to insert text between two specific characters

Body:
sed:

$ sed -E 's/(:")(.*)/\1123\2/' <<<'"abc":"def"'
"abc":"123def"

(:") gets :" and put in captured group 1

(.*) gets the remaining portion and put in captured group 2

in the replacement, \1123\2 puts 123 between the groups

awk:

$ awk -F: 'sub(".", "&123", $2)' <<<'"abc":"def"'
"abc" "123def"

In the sub() function, the second ($2) field is being operated on, pattern is used as . (which would match "), and in the replacement the matched portion (&) is followed by 123.


问:
NSString extension method doesn't call String extension method
I have an extension on String that defines test.  I also want to be able to get test's functionality from NSString.  In the real code String.test is more complex.  So rather than re-implementing it for NSString I cast str to String and call test on it.  My understanding here is that now str is of type String and String.test will be invoked, returning String Test.

However, it seems that str.test() winds up calling NSString.test and I wind up with unending recursion until the stack overflows.

```<code>import Foundation

extension NSString {

    func test() -> NSString {
        let str = self as String
        return str.test() as NSString
    }
}

extension String {

    func test() -> String {
        return "String test"
    }
}

let s: NSString = "test"
s.test()
</code>```

答:
Change your first function to:

```<code>func test() -> NSString {
    let str = self as String
    return ("" + str.test()) as NSString
}
</code>```

which should get you going...

then submit a bug report.

HTH

Body:
I have an extension on String that defines test.  I also want to be able to get test's functionality from NSString.  In the real code String.test is more complex.  So rather than re-implementing it for NSString I cast str to String and call test on it.  My understanding here is that now str is of type String and String.test will be invoked, returning String Test.

However, it seems that str.test() winds up calling NSString.test and I wind up with unending recursion until the stack overflows.

import Foundation

extension NSString {

    func test() -> NSString {
        let str = self as String
        return str.test() as NSString
    }
}

extension String {

    func test() -> String {
        return "String test"
    }
}

let s: NSString = "test"
s.test()

Body:
Change your first function to:

func test() -> NSString {
    let str = self as String
    return ("" + str.test()) as NSString
}

which should get you going...

then submit a bug report.

HTH


问:
vue template with v-if base on ajax result
i daymic render template element with ajax function change the data,
but exactly it doesn't update the view immedidately, here is the pseude code：</p>

```<code><template v-if="userInfo.nickName">
  <div class="base-info" v-show="userInfo.nickName">
    <p>欢迎，{{this.userInfo.nickName}} <a href="javascript:;" @click="logout">退出</a></p>
  </div>
</template>
<template v-else>
  <div class="base-crud">
    <el-button @click="toLogin" type="primary">登录</el-button>
    <el-button @click="toRegister" type="primary">注册</el-button>
  </div>
</template>

mounted() {
  // the updateUserInfo is an vuex action fn, the userInfo was come from vuex store data
  ajaxFn().then((data) => this.updateUserInfo(data));
}
</code>```

答:
I found the problem:
just replace Object.assign(state.userInfo, data) to state.userInfo = Object.assign({}, state.userInfo, data) in the store action fn;
It's my fault , sorry!!

Body:
i daymic render template element with ajax function change the data,
but exactly it doesn't update the view immedidately, here is the pseude code：

<template v-if="userInfo.nickName">

欢迎，{{this.userInfo.nickName}} 退出

</template>
<template v-else>

    <el-button @click="toLogin" type="primary">登录</el-button>
    <el-button @click="toRegister" type="primary">注册</el-button>

</template>

mounted() {
  // the updateUserInfo is an vuex action fn, the userInfo was come from vuex store data
  ajaxFn().then((data) => this.updateUserInfo(data));
}


问:
R : How can I combine these two data frames into a data frame by date column?
I'm new practicing R and now getting stuck with problems for many days can't go on.
I chose my recorded data to analyse. The data will be recorded every hour from 2 example devices and there are some little delay problem between recording devices to database server so some hours the data can be recorded at the seconds '0 (+-5 or keep changing a very little unstably)' you can clearly see in example data.

Big problems are

1) There are some rows from Date column are not equal in seconds part.

2) There are some rows from Date are missing rows I found a missing row from df2 'at hour 13' after I had selected example data by head(df1,24)/head(df2,24) and got the results like under here. If there are 10000 selected rows going to be a big problem with many missing values.

```<code>> class(df1$Date)
[1] "POSIXct" "POSIXt"
</code>```

df1

```<code>> df1
                  Date Val   Weekday
1  2017-06-08 13:00:04 520  Thursday
2  2017-06-08 12:00:04 507  Thursday
3  2017-06-08 11:00:04 501  Thursday
4  2017-06-08 10:00:04 472  Thursday
5  2017-06-08 09:00:04 444  Thursday
6  2017-06-08 08:00:04 446  Thursday
7  2017-06-08 07:00:04 444  Thursday
8  2017-06-08 06:00:04 441  Thursday
9  2017-06-08 05:00:04 439  Thursday
10 2017-06-08 04:00:04 442  Thursday
11 2017-06-08 03:00:04 440  Thursday
12 2017-06-08 02:00:04 443  Thursday
13 2017-06-08 01:00:04 445  Thursday
14 2017-06-08 00:00:04 445  Thursday
15 2017-06-07 23:00:04 446 Wednesday
16 2017-06-07 22:00:04 445 Wednesday
17 2017-06-07 21:00:04 447 Wednesday
18 2017-06-07 20:00:04 445 Wednesday
19 2017-06-07 19:00:04 451 Wednesday
20 2017-06-07 18:00:04 469 Wednesday
21 2017-06-07 17:00:04 473 Wednesday
22 2017-06-07 16:00:04 510 Wednesday
23 2017-06-07 15:00:04 517 Wednesday
24 2017-06-07 14:00:04 524 Wednesday
</code>```

df2

```<code>> df2
                  Date df1.Val   Weekday
1  2017-06-08 12:00:04 507  Thursday
2  2017-06-08 11:00:04 501  Thursday
3  2017-06-08 10:00:04 472  Thursday
4  2017-06-08 09:00:04 444  Thursday
5  2017-06-08 08:00:04 446  Thursday
6  2017-06-08 07:00:04 444  Thursday
7  2017-06-08 06:00:04 441  Thursday
8  2017-06-08 05:00:04 439  Thursday
9  2017-06-08 04:00:04 442  Thursday
10 2017-06-08 03:00:04 440  Thursday
11 2017-06-08 02:00:04 443  Thursday
12 2017-06-08 01:00:04 445  Thursday
13 2017-06-08 00:00:04 445  Thursday
14 2017-06-07 23:00:04 446 Wednesday
15 2017-06-07 22:00:04 445 Wednesday
16 2017-06-07 21:00:04 447 Wednesday
17 2017-06-07 20:00:04 445 Wednesday
18 2017-06-07 19:00:04 451 Wednesday
19 2017-06-07 18:00:04 469 Wednesday
20 2017-06-07 17:00:04 473 Wednesday
21 2017-06-07 16:00:03 510 Wednesday
22 2017-06-07 15:00:03 517 Wednesday
23 2017-06-07 14:00:03 524 Wednesday
24 2017-06-07 13:00:03 489 Wednesday
</code>```

So, how to prepare data to be able for combining the data frames?

I want the output to be like this example :

```<code>                  Date df1.Val df2.Val   Weekday
   2017-06-08 13:00:04 520              Thursday
   2017-06-08 12:00:00 507     507      Thursday
   2017-06-08 11:00:00 501     501      Thursday
   2017-06-08 10:00:00 472     472      Thursday
   2017-06-08 09:00:00 444     444      Thursday
   2017-06-08 08:00:00 446     446      Thursday
   2017-06-08 07:00:00 444     444      Thursday
   2017-06-08 06:00:00 441     441      Thursday
   2017-06-08 05:00:00 439     439      Thursday
   2017-06-08 04:00:00 442     442      Thursday
   2017-06-08 03:00:00 440     440      Thursday
   2017-06-08 02:00:00 443     443      Thursday
   2017-06-08 01:00:00 445     445      Thursday
   2017-06-08 00:00:00 445     445     Thursday
   2017-06-07 23:00:00 446     446     Wednesday
   2017-06-07 22:00:00 445     445     Wednesday
   2017-06-07 21:00:00 447     447     Wednesday
   2017-06-07 20:00:00 445     445     Wednesday
   2017-06-07 19:00:00 451     451     Wednesday
   2017-06-07 18:00:00 469     469     Wednesday
   2017-06-07 17:00:00 473     473     Wednesday
   2017-06-07 16:00:00 510     510     Wednesday
   2017-06-07 15:00:00 517     517     Wednesday
   2017-06-07 14:00:00 524     524     Wednesday
   2017-06-07 13:00:00         489     Wednesday
</code>```

but these to Val are the same because the devices get val from the same source if they are from different sources assume it's going to be like this :

```<code>                  Date df1.Val df3.Val   Weekday
   2017-06-08 13:00:04 520     550      Thursday
   2017-06-08 12:00:00 507     515      Thursday
   2017-06-08 11:00:00 501     496      Thursday
</code>```

Please help. Thank you so much.

答:
This should now work. One caveat, the new dataframe is getting sorted automatically.:</p>

```<code>Date = c("2017-06-08 13:00:04", "2017-06-08 12:00:04", "2017-06-08 11:00:04",
         "2017-06-08 10:00:04", "2017-06-08 09:00:04")
Val = c("520", "507", "501", "472", "444")
Weekday = c("Thursday", "Thursday", "Thursday", "Thursday", "Thursday")

df1 = as.data.frame(cbind(Date, Val, Weekday))
df1$Date = as.POSIXct(df1$Date)
df1$Val = as.numeric(as.character(df1$Val))

Date1 = c("2017-06-08 12:00:04", "2017-06-08 11:00:04",
         "2017-06-08 10:00:04", "2017-06-08 09:00:04", "2017-06-08 09:00:03")
Val1 = c("507", "501", "472", "444", "446")
Weekday1 = c("Thursday", "Thursday", "Thursday", "Thursday", "Thursday")

df2 = as.data.frame(cbind(Date1, Val1, Weekday1))
df2$Date1 = as.POSIXct(df2$Date1)
df2$Val1 = as.numeric(as.character(df2$Val1))

colnames(df2)[1] = "Date"
colnames(df2)[2] = "Val"
colnames(df2)[3] = "Weekday"

df1$Date = align.time(df1$Date, n = 60)
df2$Date = align.time(df2$Date, n = 60)

ndf = merge(df1, df2, by = c("Date", "Weekday"), all = TRUE, sort = TRUE)
ndf
</code>```

Body:
I'm new practicing R and now getting stuck with problems for many days can't go on.
I chose my recorded data to analyse. The data will be recorded every hour from 2 example devices and there are some little delay problem between recording devices to database server so some hours the data can be recorded at the seconds '0 (+-5 or keep changing a very little unstably)' you can clearly see in example data.

Big problems are

1) There are some rows from Date column are not equal in seconds part.

2) There are some rows from Date are missing rows I found a missing row from df2 'at hour 13' after I had selected example data by head(df1,24)/head(df2,24) and got the results like under here. If there are 10000 selected rows going to be a big problem with many missing values.

> class(df1$Date)
[1] "POSIXct" "POSIXt"

df1

> df1
                  Date Val   Weekday
1  2017-06-08 13:00:04 520  Thursday
2  2017-06-08 12:00:04 507  Thursday
3  2017-06-08 11:00:04 501  Thursday
4  2017-06-08 10:00:04 472  Thursday
5  2017-06-08 09:00:04 444  Thursday
6  2017-06-08 08:00:04 446  Thursday
7  2017-06-08 07:00:04 444  Thursday
8  2017-06-08 06:00:04 441  Thursday
9  2017-06-08 05:00:04 439  Thursday
10 2017-06-08 04:00:04 442  Thursday
11 2017-06-08 03:00:04 440  Thursday
12 2017-06-08 02:00:04 443  Thursday
13 2017-06-08 01:00:04 445  Thursday
14 2017-06-08 00:00:04 445  Thursday
15 2017-06-07 23:00:04 446 Wednesday
16 2017-06-07 22:00:04 445 Wednesday
17 2017-06-07 21:00:04 447 Wednesday
18 2017-06-07 20:00:04 445 Wednesday
19 2017-06-07 19:00:04 451 Wednesday
20 2017-06-07 18:00:04 469 Wednesday
21 2017-06-07 17:00:04 473 Wednesday
22 2017-06-07 16:00:04 510 Wednesday
23 2017-06-07 15:00:04 517 Wednesday
24 2017-06-07 14:00:04 524 Wednesday

df2

> df2
                  Date df1.Val   Weekday
1  2017-06-08 12:00:04 507  Thursday
2  2017-06-08 11:00:04 501  Thursday
3  2017-06-08 10:00:04 472  Thursday
4  2017-06-08 09:00:04 444  Thursday
5  2017-06-08 08:00:04 446  Thursday
6  2017-06-08 07:00:04 444  Thursday
7  2017-06-08 06:00:04 441  Thursday
8  2017-06-08 05:00:04 439  Thursday
9  2017-06-08 04:00:04 442  Thursday
10 2017-06-08 03:00:04 440  Thursday
11 2017-06-08 02:00:04 443  Thursday
12 2017-06-08 01:00:04 445  Thursday
13 2017-06-08 00:00:04 445  Thursday
14 2017-06-07 23:00:04 446 Wednesday
15 2017-06-07 22:00:04 445 Wednesday
16 2017-06-07 21:00:04 447 Wednesday
17 2017-06-07 20:00:04 445 Wednesday
18 2017-06-07 19:00:04 451 Wednesday
19 2017-06-07 18:00:04 469 Wednesday
20 2017-06-07 17:00:04 473 Wednesday
21 2017-06-07 16:00:03 510 Wednesday
22 2017-06-07 15:00:03 517 Wednesday
23 2017-06-07 14:00:03 524 Wednesday
24 2017-06-07 13:00:03 489 Wednesday

So, how to prepare data to be able for combining the data frames?

I want the output to be like this example :

                  Date df1.Val df2.Val   Weekday
   2017-06-08 13:00:04 520              Thursday
   2017-06-08 12:00:00 507     507      Thursday
   2017-06-08 11:00:00 501     501      Thursday
   2017-06-08 10:00:00 472     472      Thursday
   2017-06-08 09:00:00 444     444      Thursday
   2017-06-08 08:00:00 446     446      Thursday
   2017-06-08 07:00:00 444     444      Thursday
   2017-06-08 06:00:00 441     441      Thursday
   2017-06-08 05:00:00 439     439      Thursday
   2017-06-08 04:00:00 442     442      Thursday
   2017-06-08 03:00:00 440     440      Thursday
   2017-06-08 02:00:00 443     443      Thursday
   2017-06-08 01:00:00 445     445      Thursday
   2017-06-08 00:00:00 445     445     Thursday
   2017-06-07 23:00:00 446     446     Wednesday
   2017-06-07 22:00:00 445     445     Wednesday
   2017-06-07 21:00:00 447     447     Wednesday
   2017-06-07 20:00:00 445     445     Wednesday
   2017-06-07 19:00:00 451     451     Wednesday
   2017-06-07 18:00:00 469     469     Wednesday
   2017-06-07 17:00:00 473     473     Wednesday
   2017-06-07 16:00:00 510     510     Wednesday
   2017-06-07 15:00:00 517     517     Wednesday
   2017-06-07 14:00:00 524     524     Wednesday
   2017-06-07 13:00:00         489     Wednesday

but these to Val are the same because the devices get val from the same source if they are from different sources assume it's going to be like this :

                  Date df1.Val df3.Val   Weekday
   2017-06-08 13:00:04 520     550      Thursday
   2017-06-08 12:00:00 507     515      Thursday
   2017-06-08 11:00:00 501     496      Thursday

Please help. Thank you so much.

Body:
This should now work. One caveat, the new dataframe is getting sorted automatically.:

Date = c("2017-06-08 13:00:04", "2017-06-08 12:00:04", "2017-06-08 11:00:04",
         "2017-06-08 10:00:04", "2017-06-08 09:00:04")
Val = c("520", "507", "501", "472", "444")
Weekday = c("Thursday", "Thursday", "Thursday", "Thursday", "Thursday")

df1 = as.data.frame(cbind(Date, Val, Weekday))
df1$Date = as.POSIXct(df1$Date)
df1$Val = as.numeric(as.character(df1$Val))

Date1 = c("2017-06-08 12:00:04", "2017-06-08 11:00:04",
         "2017-06-08 10:00:04", "2017-06-08 09:00:04", "2017-06-08 09:00:03")
Val1 = c("507", "501", "472", "444", "446")
Weekday1 = c("Thursday", "Thursday", "Thursday", "Thursday", "Thursday")

df2 = as.data.frame(cbind(Date1, Val1, Weekday1))
df2$Date1 = as.POSIXct(df2$Date1)
df2$Val1 = as.numeric(as.character(df2$Val1))

colnames(df2)[1] = "Date"
colnames(df2)[2] = "Val"
colnames(df2)[3] = "Weekday"

df1$Date = align.time(df1$Date, n = 60)
df2$Date = align.time(df2$Date, n = 60)

ndf = merge(df1, df2, by = c("Date", "Weekday"), all = TRUE, sort = TRUE)
ndf


问:
PHP CSV string to array
I'm trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:

Delimiter: ,
Enclosure: "
New line: \r\n
```

<p>Example content:</p>

```"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
```

<p>When I try to parse it like this:</p>

```$url = "http://www.url-to-feed.com";
$csv = file_get_contents($url);
$data = str_getcsv($csv);
var_dump($data);
```

<p>The last and first element are concatenated in one string:</p>

```[0]=> string(5) "12345"
...
[7]=> string(4) "0.04"
[8]=> string(19) "27-05-2013
"12346""
```

How can I fix this? Any help would be appreciated.

答:
You should use fgetcsv.  Since you cannot import a file as a stream because the csv is a variable, then you should spoof the string as a file by using php://temp or php://memory first:

```<code>$fp = fopen("php://temp", 'r+');
fputs($fp, $csvText);
rewind($fp);
</code>```

Then you will have no problem using fgetcsv:

```<code>$csv = [];
while ( ($data = fgetcsv($fp) ) !== FALSE ) {
    $csv[] = $data;
}
fclose($fp)
</code>```

$data will be an array of a single csv line (which may include line breaks or commas, etc), as it should be.

Caveat: The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes. (the default is 2 MB) http://www.php.net/manual/en/wrappers.php.php

Title: PHP CSV string to array

Body:
I'm trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:

Delimiter: ,
Enclosure: "
New line: \r\n

Example content:

"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"

When I try to parse it like this:

$url = "http://www.url-to-feed.com";
$csv = file_get_contents($url);
$data = str_getcsv($csv);
var_dump($data);

The last and first element are concatenated in one string:

[0]=> string(5) "12345"
...
[7]=> string(4) "0.04"
[8]=> string(19) "27-05-2013
"12346""

How can I fix this? Any help would be appreciated.

Body:
You should use fgetcsv.  Since you cannot import a file as a stream because the csv is a variable, then you should spoof the string as a file by using php://temp or php://memory first:

$fp = fopen("php://temp", 'r+');
fputs($fp, $csvText);
rewind($fp);

Then you will have no problem using fgetcsv:

$csv = [];
while ( ($data = fgetcsv($fp) ) !== FALSE ) {
    $csv[] = $data;
}
fclose($fp)

$data will be an array of a single csv line (which may include line breaks or commas, etc), as it should be.

Caveat: The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes. (the default is 2 MB) http://www.php.net/manual/en/wrappers.php.php

ContentLicense: CC BY-SA 4.0


问:
Refresh input text box with new string every 10 seconds
I've searched on here and other places (about 15 other forums...yes I kept count) as well and I can't seem to find any previous posts that match what is below. Either that or I didn't search hard enough....

What I'm trying to do: Everytime someone presses the submit button I want the <input type="text" name="comment_id" id="comment_id" value=""> to have a new random string (new id) so that way each time someone presses submit the id is not a replica of the previous as I'm using such ID (not the automated ID by database) to identify these comments.

What I currently have <input type="text" name="comment_id" id="comment_id" value="<?php $length = 18; $randomString = substr(str_shuffle("0123456789-abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); echo $randomString;?>">

That broken down is basically this

```<code><?php
$length = 18;
$randomString = substr(str_shuffle("0123456789-abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
echo $randomString;
?>
</code>```

Gives me an 18 character string like this (BknmexSFAgP7pjsUIo).

So all in all I just want it so that every single time someone presses submit, the input box gives me a new ID, I've tried using several methods but none seem to do the trick....

Thank you in advance for your help.

答:
Okay so after many many many.....okay after A LOT of searching, I finally found my answer. Now this is my own modified code but I'm going to post it in case anyone else would need help with this.

I have this refreshing every 1 second so that way if someone decided to comment right after they've already posted a comment, the previous comment doesn't have the same id as the current....yea I know that did not make sense, but then again it did. :/

```<code><textarea id="comment_id"></textarea>

var myCommentID = setInterval(generateCommentID, 1000);
function generateCommentID() {
    var comment = "0123456789-abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var result = "", rand;
    for (var i = 0; i < 6; i++) {
        for (var j = 0; j < 4; j++) {
            rand = Math.floor(Math.random() * comment.length);
            result += comment.charAt(rand);
        }
    }
    document.getElementById("comment_id").innerHTML = result;
}
</code>```

Original code is from this sexy fiddle

Body:
I've searched on here and other places (about 15 other forums...yes I kept count) as well and I can't seem to find any previous posts that match what is below. Either that or I didn't search hard enough....

What I'm trying to do: Everytime someone presses the submit button I want the <input type="text" name="comment_id" id="comment_id" value=""> to have a new random string (new id) so that way each time someone presses submit the id is not a replica of the previous as I'm using such ID (not the automated ID by database) to identify these comments.

What I currently have <input type="text" name="comment_id" id="comment_id" value="<?php $length = 18; $randomString = substr(str_shuffle("0123456789-abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); echo $randomString;?>">

That broken down is basically this

<?php
$length = 18;
$randomString = substr(str_shuffle("0123456789-abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
echo $randomString;
?>

Gives me an 18 character string like this (BknmexSFAgP7pjsUIo).

So all in all I just want it so that every single time someone presses submit, the input box gives me a new ID, I've tried using several methods but none seem to do the trick....

Thank you in advance for your help.

Body:
Okay so after many many many.....okay after A LOT of searching, I finally found my answer. Now this is my own modified code but I'm going to post it in case anyone else would need help with this.

I have this refreshing every 1 second so that way if someone decided to comment right after they've already posted a comment, the previous comment doesn't have the same id as the current....yea I know that did not make sense, but then again it did. :/

<textarea id="comment_id"></textarea>

var myCommentID = setInterval(generateCommentID, 1000);
function generateCommentID() {
    var comment = "0123456789-abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var result = "", rand;
    for (var i = 0; i < 6; i++) {
        for (var j = 0; j < 4; j++) {
            rand = Math.floor(Math.random() * comment.length);
            result += comment.charAt(rand);
        }
    }
    document.getElementById("comment_id").innerHTML = result;
}

Original code is from this sexy fiddle


问:
Python : How to use random sample when we don't need duplicates random sample
My Code

```<code>import random

MyList = [[1,2,3,4,5,6,7,8],[a,s,d,f,g,h,h],[q,w,e,r,t,y]]
MyListRandom = []
random_number = 5
i=0
while True:
     random_list = randint(0,len(MyList))
     element_random = random.sample(MyList[random_list], 1)
     if element_random[0] not in MyListRandom:
     i = i+1
     MyListRandom.append(element_random[0])
else:
    continue
if(i>=random_number):
    break
</code>```

if I don't want to use this code to check it

```<code> if element_random[0] not in MyListRandom:
     MyListRandom.append(element_random[0])
</code>```

Is there a better way more than this if i don't want a duplicates sample?

答:
If I understand your question understand correctly, you just want a randomized version of your original list, also eliminating any duplicates in your original list.  If that's correct you can use set and shuffle:

```<code>MyListRandom = list(set(MyList))
random.shuffle(MyListRandom)
</code>```

If you're not worried about duplicates in your original list, just trying to workaround the possible duplicates introduced by sample, then this would work:

```<code>MyListRandom = MyList[:]   # to make a copy
random.shuffle(MyListRandom)
</code>```

Body:
My Code

import random

MyList = [[1,2,3,4,5,6,7,8],[a,s,d,f,g,h,h],[q,w,e,r,t,y]]
MyListRandom = []
random_number = 5
i=0
while True:
     random_list = randint(0,len(MyList))
     element_random = random.sample(MyList[random_list], 1)
     if element_random[0] not in MyListRandom:
     i = i+1
     MyListRandom.append(element_random[0])
else:
    continue
if(i>=random_number):
    break

if I don't want to use this code to check it

 if element_random[0] not in MyListRandom:
     MyListRandom.append(element_random[0])

Is there a better way more than this if i don't want a duplicates sample?

Body:
If I understand your question understand correctly, you just want a randomized version of your original list, also eliminating any duplicates in your original list.  If that's correct you can use set and shuffle:

MyListRandom = list(set(MyList))
random.shuffle(MyListRandom)

If you're not worried about duplicates in your original list, just trying to workaround the possible duplicates introduced by sample, then this would work:

MyListRandom = MyList[:]   # to make a copy
random.shuffle(MyListRandom)


问:
Get/set variable inside if statement
I have a small example to define and assign to arr array.

```<code>var arr;

if (arr = [1]) { // arr is an array here, it contains 1 element
    console.log(arr.length); // 1
}
</code>```

Then, I want to get length of the array

```<code>var arr;

// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
    console.log(arr.length);
}
</code>```

Uncaught TypeError: Cannot read property 'length' of undefined

答:
In this line:

```<code>if (arr = [1] && arr.length)
</code>```

You assigned the array to arr and at the same time tried to check for the length. Since JS does not know yet that arr contains an array at this point it throws an exception when trying to access the length property.

For comparison, this does not throw an exception:

```<code>if (arr = [1]) {
    if (arr.length) {
        console.log(arr.length);
    }
}
</code>```

Because upon reaching the second condition check, JS already knows that arr is an array.

Title: Get/set variable inside if statement

Body:
I have a small example to define and assign to arr array.

var arr;

if (arr = [1]) { // arr is an array here, it contains 1 element
    console.log(arr.length); // 1
}

Then, I want to get length of the array

var arr;

// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
    console.log(arr.length);
}

Uncaught TypeError: Cannot read property 'length' of undefined

Body:
In this line:

if (arr = [1] && arr.length)

You assigned the array to arr and at the same time tried to check for the length. Since JS does not know yet that arr contains an array at this point it throws an exception when trying to access the length property.

For comparison, this does not throw an exception:

if (arr = [1]) {
    if (arr.length) {
        console.log(arr.length);
    }
}

Because upon reaching the second condition check, JS already knows that arr is an array.