问:
How do I make this Macro repeat in vba
The following macro is designed to take an input string from the user and search through a directory (constant) for that input string. It then copies the corresponding information in the same row of the input string and the headers as well. After it is done copying and pasting that info, the macro ends. I would like to make it so that, after the macro is done copying and pasting info it asks for another string and does the search again, but copies the info on the next line.
Please let me know if I can provide any more information, I've been working on this for 2 weeks now and can't figure it out. The code is below.</p>

```<code>'Author: Michael Majdalani
Public WS As Worksheet
Sub SearchWKBooksSubFolders(Optional Folderpath As Variant, Optional Str As Variant)

Dim myfolder As String
Dim a As Single
Dim sht As Worksheet
Dim Lrow As Single
Dim Folders() As String
Dim Folder As Variant
Dim p As Integer
ReDim Folders(0)

'This is where the folder path is chosen, for the current application
'It is constant, If you would like to choose a different folderpath
'Uncomment the commented lines and comment the declaration of myfolder

If IsMissing(Folderpath) Then
    Set WS = Sheet1
    'With Application.FileDialog(msoFileDialogFolderPicker)
        '.Show
        myfolder = "O:QUALITY\INSPECTION REPORTS\"
    'End With

'This is where the user is prompted to enter the string, if no string is entered
'A message will appear. If a string is entered, It will enter the headers
'"Search String" and "links" and the correlated information
'Value here keeps track of the directory and which subfolders/folders
'it is searching through

    Str = Application.InputBox(prompt:="Search string:", Title:="Search all workbooks in a folder", Type:=2)
    If Str = "" Then MsgBox "No string entered, Please try again"
    WS.Range("A1") = "Search string:"
    WS.Range("A2") = Str
    WS.Range("B1") = "Links"
    Folderpath = myfolder
    Value = Dir(myfolder, &H1F)
Else
    If Right(Folderpath, 2) = "\\" Then
        Exit Sub
    End If
    Value = Dir(Folderpath, &H1F)
End If

'The first part of this do Until loop has a lot to do with how the maneuvering is completed
'within the folder path and directory for excel to search through every folder/subfolder
'needed.

Do Until Value = ""
    If Value = "." Or Value = ".." Then
    Else
        If GetAttr(Folderpath & Value) = 16 Then
            Folders(UBound(Folders)) = Value
            ReDim Preserve Folders(UBound(Folders) + 1)
        ElseIf (Right(Value, 3) = "xls" Or Right(Value, 4) = "xlsx" Or Right(Value, 4) = "xlsm") And Left(Value, 1) <> "~" Then
            On Error Resume Next
            Dim wb As Workbook
            Set wb = Workbooks.Open(Filename:=Folderpath & Value, Password:="zzzzzzzzzzzz")
            On Error GoTo 0
            'If there is an error on Workbooks.Open, then wb Is Nothing:
            If wb Is Nothing Then
                Lrow = WS.Range("A" & Rows.Count).End(xlUp).Row + 1
                WS.Range("A" & Lrow).Value = Value
                WS.Range("B" & Lrow).Value = "Password protected"
            Else
                'For each sheet in the workbooks, the next loop will search through the first
                'column of every sheet in every workbook found in the directory chosen.
                'It then creates the link, as well as updating value to end the loop.

                For Each sht In wb.Worksheets
                    'Expand all groups in sheet and Unprotect
                    sht.Unprotect

                    sht.Outline.ShowLevels RowLevels:=8, ColumnLevels:=8

                    'c here is used to search for the user input string
                    Set c = sht.Columns(1).Find(Str, After:=sht.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
                    If Not c Is Nothing Then
                        firstAddress = c.Address
                        Do
                            Lrow = WS.Range("A" & Rows.Count).End(xlUp).Row
                            WS.Range("B" & Lrow).Value = Value
                            WS.Hyperlinks.Add Anchor:=WS.Range("B" & Lrow), Address:=Folderpath & Value, SubAddress:= _
                            "'" & sht.Name & "'" & "!" & c.Address, TextToDisplay:="Link"
                            Set c = sht.Cells.FindNext(After:=c)
                            Cells.EntireColumn.AutoFit

                        Loop While Not c Is Nothing And c.Address <> firstAddress
                    End If

                    'if c is nothing, continue
                    If c Is Nothing Then GoTo Cont Else

                    'if c is equal to our searched string then it will loop through the
                    'adjacent thirty cells copying and pasting all the information
                    'to the main workbook
                    If Str = c.Formula Then
                       Dim i As Integer

                       For i = 1 To 30

                    If IsEmpty(wb.Sheets(sht.Name).Range(firstAddress).Offset(0, i)) Then GoTo Done

                        Dim cnt As Long

                        'cnt is the amount of cells between the searched string and the top
                        'of that workbook, used to copy the headers to the main workbook
                        cnt = ((Range(firstAddress, "A1").Cells.Count) - 1) * -1

                        'Copy and paste info
                        wb.Sheets(sht.Name).Range(firstAddress).Offset(0, i).Select
                        Selection.Copy

                        WS.Range("B2").Offset(0, i).PasteSpecial

                        'Copy and paste header info
                        wb.Sheets(sht.Name).Range(firstAddress).Offset(cnt, i).Select
                        Selection.Copy

                        WS.Range("B1").Offset(0, i).PasteSpecial

                        Next i

                    'When done, close the workbook and autofit the cells on the main
                    'workbook
Done:                   wb.Close False
                        Cells.EntireColumn.AutoFit
                        End
                    End If
              'Continues the loop if the string is not found
Cont:             Next sht
                wb.Close False
                End If
            End If
        End If
    'Increments value to the next directory
    Value = Dir
Loop

'Recursive loop
For Each Folder In Folders
    Call SearchWKBooksSubFolders(Folderpath & Folder & "\", Str)
Next Folder

Cells.EntireColumn.AutoFit
End Sub
</code>```

答:
Apply some recursion as follows:

This sub will msgbox the inputstring, ask if you want to do it again, gets a new input string and calls itself. This way it will just keep going with different strings (in your case folderpath) until the user exits.

Edit: Added an incrementer that allows for the recursion to take the next row each time.

```<code>Public SomeIncrementer as Integer

Sub DoStuff(str As String)
Dim repeat As Integer
Dim nextstring As String
    Worksheets(1).Range("A" & SomeIncremeter).value = str
    repeat = MsgBox("Again?", vbYesNo)
    If repeat = vbYes Then
        SomeIncrementer = SomeIncrementer + 1
        nextstring = InputBox("Next string?")
        DoStuff (nextstring)
    End If
End Sub

'And start from here:
Sub Test()
    SomeIncrementer = 1
    DoStuff "Hello"
End Sub
</code>```

Title: How do I make this Macro repeat in vba

Body:
The following macro is designed to take an input string from the user and search through a directory (constant) for that input string. It then copies the corresponding information in the same row of the input string and the headers as well. After it is done copying and pasting that info, the macro ends. I would like to make it so that, after the macro is done copying and pasting info it asks for another string and does the search again, but copies the info on the next line.
Please let me know if I can provide any more information, I've been working on this for 2 weeks now and can't figure it out. The code is below.

'Author: Michael Majdalani
Public WS As Worksheet
Sub SearchWKBooksSubFolders(Optional Folderpath As Variant, Optional Str As Variant)

Dim myfolder As String
Dim a As Single
Dim sht As Worksheet
Dim Lrow As Single
Dim Folders() As String
Dim Folder As Variant
Dim p As Integer
ReDim Folders(0)

'This is where the folder path is chosen, for the current application
'It is constant, If you would like to choose a different folderpath
'Uncomment the commented lines and comment the declaration of myfolder

If IsMissing(Folderpath) Then
    Set WS = Sheet1
    'With Application.FileDialog(msoFileDialogFolderPicker)
        '.Show
        myfolder = "O:QUALITY\INSPECTION REPORTS\"
    'End With

'This is where the user is prompted to enter the string, if no string is entered
'A message will appear. If a string is entered, It will enter the headers
'"Search String" and "links" and the correlated information
'Value here keeps track of the directory and which subfolders/folders
'it is searching through

    Str = Application.InputBox(prompt:="Search string:", Title:="Search all workbooks in a folder", Type:=2)
    If Str = "" Then MsgBox "No string entered, Please try again"
    WS.Range("A1") = "Search string:"
    WS.Range("A2") = Str
    WS.Range("B1") = "Links"
    Folderpath = myfolder
    Value = Dir(myfolder, &H1F)
Else
    If Right(Folderpath, 2) = "\\" Then
        Exit Sub
    End If
    Value = Dir(Folderpath, &H1F)
End If

'The first part of this do Until loop has a lot to do with how the maneuvering is completed
'within the folder path and directory for excel to search through every folder/subfolder
'needed.

Do Until Value = ""
    If Value = "." Or Value = ".." Then
    Else
        If GetAttr(Folderpath & Value) = 16 Then
            Folders(UBound(Folders)) = Value
            ReDim Preserve Folders(UBound(Folders) + 1)
        ElseIf (Right(Value, 3) = "xls" Or Right(Value, 4) = "xlsx" Or Right(Value, 4) = "xlsm") And Left(Value, 1) <> "~" Then
            On Error Resume Next
            Dim wb As Workbook
            Set wb = Workbooks.Open(Filename:=Folderpath & Value, Password:="zzzzzzzzzzzz")
            On Error GoTo 0
            'If there is an error on Workbooks.Open, then wb Is Nothing:
            If wb Is Nothing Then
                Lrow = WS.Range("A" & Rows.Count).End(xlUp).Row + 1
                WS.Range("A" & Lrow).Value = Value
                WS.Range("B" & Lrow).Value = "Password protected"
            Else
                'For each sheet in the workbooks, the next loop will search through the first
                'column of every sheet in every workbook found in the directory chosen.
                'It then creates the link, as well as updating value to end the loop.

                For Each sht In wb.Worksheets
                    'Expand all groups in sheet and Unprotect
                    sht.Unprotect

                    sht.Outline.ShowLevels RowLevels:=8, ColumnLevels:=8

                    'c here is used to search for the user input string
                    Set c = sht.Columns(1).Find(Str, After:=sht.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
                    If Not c Is Nothing Then
                        firstAddress = c.Address
                        Do
                            Lrow = WS.Range("A" & Rows.Count).End(xlUp).Row
                            WS.Range("B" & Lrow).Value = Value
                            WS.Hyperlinks.Add Anchor:=WS.Range("B" & Lrow), Address:=Folderpath & Value, SubAddress:= _
                            "'" & sht.Name & "'" & "!" & c.Address, TextToDisplay:="Link"
                            Set c = sht.Cells.FindNext(After:=c)
                            Cells.EntireColumn.AutoFit

                        Loop While Not c Is Nothing And c.Address <> firstAddress
                    End If

                    'if c is nothing, continue
                    If c Is Nothing Then GoTo Cont Else

                    'if c is equal to our searched string then it will loop through the
                    'adjacent thirty cells copying and pasting all the information
                    'to the main workbook
                    If Str = c.Formula Then
                       Dim i As Integer

                       For i = 1 To 30

                    If IsEmpty(wb.Sheets(sht.Name).Range(firstAddress).Offset(0, i)) Then GoTo Done

                        Dim cnt As Long

                        'cnt is the amount of cells between the searched string and the top
                        'of that workbook, used to copy the headers to the main workbook
                        cnt = ((Range(firstAddress, "A1").Cells.Count) - 1) * -1

                        'Copy and paste info
                        wb.Sheets(sht.Name).Range(firstAddress).Offset(0, i).Select
                        Selection.Copy

                        WS.Range("B2").Offset(0, i).PasteSpecial

                        'Copy and paste header info
                        wb.Sheets(sht.Name).Range(firstAddress).Offset(cnt, i).Select
                        Selection.Copy

                        WS.Range("B1").Offset(0, i).PasteSpecial

                        Next i

                    'When done, close the workbook and autofit the cells on the main
                    'workbook
Done:                   wb.Close False
                        Cells.EntireColumn.AutoFit
                        End
                    End If
              'Continues the loop if the string is not found
Cont:             Next sht
                wb.Close False
                End If
            End If
        End If
    'Increments value to the next directory
    Value = Dir
Loop

'Recursive loop
For Each Folder In Folders
    Call SearchWKBooksSubFolders(Folderpath & Folder & "\", Str)
Next Folder

Cells.EntireColumn.AutoFit
End Sub

Body:
Apply some recursion as follows:

This sub will msgbox the inputstring, ask if you want to do it again, gets a new input string and calls itself. This way it will just keep going with different strings (in your case folderpath) until the user exits.

Edit: Added an incrementer that allows for the recursion to take the next row each time.

Public SomeIncrementer as Integer

Sub DoStuff(str As String)
Dim repeat As Integer
Dim nextstring As String
    Worksheets(1).Range("A" & SomeIncremeter).value = str
    repeat = MsgBox("Again?", vbYesNo)
    If repeat = vbYes Then
        SomeIncrementer = SomeIncrementer + 1
        nextstring = InputBox("Next string?")
        DoStuff (nextstring)
    End If
End Sub

'And start from here:
Sub Test()
    SomeIncrementer = 1
    DoStuff "Hello"
End Sub


来源: stackexchange

问:
asp.net mvc file upload security breach
ok apart from checking the file type and file size both server side how can i avoid security breach during uploading of file that may compromise my system (basically from the advance hacker) . is this enough? . i am not talking about any special scenario just simple file upload.

Well security is one of the major concern in my application.

答: You could make sure you don't store those files to a folder which is publicly accessible and executable by the web server. Also you could use heuristics by checking the first few bytes of the file for known file formats. For example common image formats have standard beginning headers so you might check for the presence of those headers.</p>

ContentLicense: CC BY-SA 2.5

Title: asp.net mvc file upload security breach


问:
Elasticsearch query with single letters
I've a question to understand the retrieved results of an elasticsearch query.

F.e. I look for "london AND apartment AND in" and I get 8,500 results.

Then I look for "london AND apartment AND i" and I get the same result count but I'm expecting to find more results because I think there will be more words starting with an "i" instead "in"?

答:
Elastic search does not do partial match by default unless you have specified a specific analyzer or filter to it.

It can match only full words by default. Also if you use just the basic match query for querying then AND operator usually does not work.

You got to use query_string for using AND operator. In your case its just matching AND as separate word probably. and i and in  are probbaly not searched because those words are usually stop words and not stored in the index for search

ContentLicense: CC BY-SA 3.0

Title: Elasticsearch query with single letters


问:
Wiznet W5100 unplugged cable detection
How to detect if cable is unplugged on W5100 Ethernet controller?.

In  datasheet I can't find register for cable detection. But chip provides LAN status LED.

答:
W5100 does not support reading register to get status if cable is plugged or not (network available or not). You can only check by doing fake connection and wait for either any response or timeout.

Instead, you should use W5200 which has this feature.

Title: Wiznet W5100 unplugged cable detection


问:
Mapping SQL functions in Entity Framework with constant parameters
I have code that heavily depends on ISO calendar weeks; its persistence layer is done using the Entity Framework 6.

In C#, I have added an extension method to DateTime:

```<code>// From https://stackoverflow.com/a/11155102/112964
public static int IsoWeek(this DateTime self) {
    var day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(self);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        self = self.AddDays(3);
    }

    // Return the week of our adjusted day
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(self, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
</code>```

I would like for this extension method to work in IQueryables as well, and map it to the SQL Server function DATEPART(iso_week, self).

This means that I would like to call DATEPART with a first parameter that is always 'iso_week'. The second parameter should be the DateTime passed into the C# method. From what I understand, DbFunctionAttribute only works if both parameters are parameters of the function.

Is it possible to perform such a mapping or do I need to create a stored procedure that calls DATEPART(iso_week, @param) and call that procedure?

答:
I could not find a way to do what I wanted, so I did the following:

Create a scalar valued function in SQL server

```<code>CREATE FUNCTION IsoWeek(@date DATETIME)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
  RETURN datepart(ISO_WEEK, @date);
END
</code>```

Import the function into the EDMX (simply by calling Update from Database)

```<code><Schema Namespace="Some.Namespace" …>
…
    <Function Name="IsoWeek" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo" ReturnType="int">
      <Parameter Name="date" Type="datetime" Mode="In" />
    </Function>
</code>```

Update the IsoWeek extension function with a DbFunctionAttribute.

```<code>[DbFunction("Some.Namespace", "IsoWeek")]
public static int IsoWeek(this DateTime self) {
    …
}
</code>```

Now I can use dateTime.IsoWeek() in C# code as well as in Entity-Famework-Linq-Queries.

Body:
I have code that heavily depends on ISO calendar weeks; its persistence layer is done using the Entity Framework 6.

In C#, I have added an extension method to DateTime:

// From https://stackoverflow.com/a/11155102/112964
public static int IsoWeek(this DateTime self) {
    var day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(self);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        self = self.AddDays(3);
    }

    // Return the week of our adjusted day
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(self, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

I would like for this extension method to work in IQueryables as well, and map it to the SQL Server function DATEPART(iso_week, self).

This means that I would like to call DATEPART with a first parameter that is always 'iso_week'. The second parameter should be the DateTime passed into the C# method. From what I understand, DbFunctionAttribute only works if both parameters are parameters of the function.

Is it possible to perform such a mapping or do I need to create a stored procedure that calls DATEPART(iso_week, @param) and call that procedure?

Body:
I could not find a way to do what I wanted, so I did the following:

Create a scalar valued function in SQL server

CREATE FUNCTION IsoWeek(@date DATETIME)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
  RETURN datepart(ISO_WEEK, @date);
END

Import the function into the EDMX (simply by calling Update from Database)

<Schema Namespace="Some.Namespace" …>
…
    <Function Name="IsoWeek" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo" ReturnType="int">
      <Parameter Name="date" Type="datetime" Mode="In" />
    </Function>

Update the IsoWeek extension function with a DbFunctionAttribute.

[DbFunction("Some.Namespace", "IsoWeek")]
public static int IsoWeek(this DateTime self) {
    …
}

Now I can use dateTime.IsoWeek() in C# code as well as in Entity-Famework-Linq-Queries.


问:
How do I strip only the string part from a list in Python?
I have a list that looks like:

```<code>{
    'J2EE': 0.0202219636,
    'financial': 0.2439565346,
    'Guru': 0.0202219636,
    'AWS': 0.0202219636,
    'next generation': 0.12072663160000001,
    'Machine Learning': 0.2025762767,
    'technology': 0.066936981
}
</code>```

How do I extract only the text parts and make my list look like:

```<code>['J2EE', 'financial', 'Guru', 'AWS', ...]
</code>```

Should I use Regular expressions?

答: I doubt it, but if you really want it in the form of {'J2EE','financial','Guru','AWS',....} use set(dict)

Body:
I have a list that looks like:

{
    'J2EE': 0.0202219636,
    'financial': 0.2439565346,
    'Guru': 0.0202219636,
    'AWS': 0.0202219636,
    'next generation': 0.12072663160000001,
    'Machine Learning': 0.2025762767,
    'technology': 0.066936981
}

How do I extract only the text parts and make my list look like:

['J2EE', 'financial', 'Guru', 'AWS', ...]

Should I use Regular expressions?


问:
What is the efficient way of doing Date Partitioning in BigQuery of 2 TB data?
Currently i have exported data as sharded to Google cloud, downloaded in server and streaming to the partitioned table, but the problem is that it takes long time. It streams like 1 Gb for 40 Minutes. Please help me to make it faster. My machine is 12 kernel and 20 Gb RAM CPU.</p>

答:
You can directly load data from Google Cloud Storage into your partition using a generated API call or other methods

To update data in a specific partition, append a partition decorator to the name of the partitioned table when loading data into the table. A partition decorator represents a specific date and takes the form:

```<code>$YYYYMMDD
</code>```

For example, the following command replaces the data in the entire partition for the date January 1, 2016 (20160101) in a partitioned table named mydataset.table1 with content loaded from a Cloud Storage bucket:

```<code>bq load  --replace --source_format=NEWLINE_DELIMITED_JSON 'mydataset.table1$20160101' gs://[MY_BUCKET]/replacement_json.json
</code>```

Note: Because partitions in a partitioned table share the table schema, replacing data in a partition will not replace the schema of the table. Instead, the schema of the new data must be compatible with the table schema. To update the schema of the table with the load job, use configuration.load.schemaUpdateOptions.

Read more https://cloud.google.com/bigquery/docs/creating-partitioned-tables

Body:
You can directly load data from Google Cloud Storage into your partition using a generated API call or other methods

To update data in a specific partition, append a partition decorator to the name of the partitioned table when loading data into the table. A partition decorator represents a specific date and takes the form:

$YYYYMMDD

For example, the following command replaces the data in the entire partition for the date January 1, 2016 (20160101) in a partitioned table named mydataset.table1 with content loaded from a Cloud Storage bucket:

bq load  --replace --source_format=NEWLINE_DELIMITED_JSON 'mydataset.table1$20160101' gs://[MY_BUCKET]/replacement_json.json

Note: Because partitions in a partitioned table share the table schema, replacing data in a partition will not replace the schema of the table. Instead, the schema of the new data must be compatible with the table schema. To update the schema of the table with the load job, use configuration.load.schemaUpdateOptions.

Read more https://cloud.google.com/bigquery/docs/creating-partitioned-tables


问:
Declare Attribute in VB.NET
In my VB 6.0 code, I declare have the following line:

```<code>Attribute VB_Name = "MyFile"
</code>```

However, in VB.NET, I get the error "expecting declaration".  Isn't this a declaration statement?  Is there a good reference for finding the differences between VB.NET and VB 6.0?

答:
There's no need for the above code at all in VB.NET.

In VB 6, it specifies the name of the file from within code—this is used for things like the window title, as well as allowing you to explicitly qualify references to the members of that class in your code.

In VB.NET, the name used in the declaration of the class already serves that purpose. You no longer need to provide an explicit name with an Attribute. Consider the following mini-class:

```<code>Public Class MyFile
    Public Sub DoWork()
        'do something here
    End Sub
End Class
</code>```

To call the DoWork method of the class you've named MyFile from another place in your code, you would simply write:

```<code>MyFile.DoWork()
</code>```

just as you could after you specified the VB_Name attribute under previous versions of VB.

Also note that the file name that your class/module is saved as can be something completely different; the name you specify in the class declaration is not dependent on the name you've given the file itself, just like previous versions.

Title: Declare Attribute in VB.NET

Body:
In my VB 6.0 code, I declare have the following line:

Attribute VB_Name = "MyFile"

However, in VB.NET, I get the error "expecting declaration".  Isn't this a declaration statement?  Is there a good reference for finding the differences between VB.NET and VB 6.0?

Body:
There's no need for the above code at all in VB.NET.

In VB 6, it specifies the name of the file from within code—this is used for things like the window title, as well as allowing you to explicitly qualify references to the members of that class in your code.

In VB.NET, the name used in the declaration of the class already serves that purpose. You no longer need to provide an explicit name with an Attribute. Consider the following mini-class:

Public Class MyFile
    Public Sub DoWork()
        'do something here
    End Sub
End Class

To call the DoWork method of the class you've named MyFile from another place in your code, you would simply write:

MyFile.DoWork()

just as you could after you specified the VB_Name attribute under previous versions of VB.

Also note that the file name that your class/module is saved as can be something completely different; the name you specify in the class declaration is not dependent on the name you've given the file itself, just like previous versions.


问:
JSON requests in C using libcurl
I'm defining a PUT request with a JSON request body using libcurl in C.

This how I'm doing it:

```<code>    sprintf(jsonObj, "\"name\" : \"%s\", \"age\" : \"%s\"", name, age);

    struct curl_slist *headers = NULL;
    curl_slist_append(headers, "Accept: application/json");
    curl_slist_append(headers, "Content-Type: application/json");
    curl_slist_append(headers, "charset: utf-8");

    curl_easy_setopt(curl, CURLOPT_URL, url);

    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1");

    res = curl_easy_perform(curl);
</code>```

The request body is arriving like this:

```<code>    { '"name" : "Pedro", "age" : "22"' }
</code>```

With { ' at the start and ' } at the end.

--- MORE INFO -----

if I declare this code

```<code>    char* jsonObj = "{ \"name\" : \"Pedro\" , \"age\" : \"22\" }";

    struct curl_slist *headers = NULL;
    curl_slist_append(headers, "Accept: application/json");
    curl_slist_append(headers, "Content-Type: application/json");
    curl_slist_append(headers, "charset: utf-8");

    curl_easy_setopt(curl, CURLOPT_URL, url);

    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1");

    res = curl_easy_perform(curl);
</code>```

the server receives this as the request body:

```<code>{ '{ "name" : "Pedro" , "age" : "22" }': '' }
</code>```

My question is:

Is the libCurl pre-formatting/encoding automatically the Json request?

By the way, does the libCurl have some way of encoding a JSON object?

Thanks so much!

答:
A key part of understanding whether the system is behaving correctly is seeing what the program is actually sending over the network. So another way to check the byte stream, instead of pointing it at your server (and/or running Wireshark), is to just run a netcat instance in a separate window on the test machine:

```<code>nc -l 8080
</code>```

and point the code (CURLOPT_URL) at "http://localhost:8080".

You'll need to hit Control-D in the nc window to terminate the connection so that curl completes, but you can also type a test return text beforehand, which can be useful if you're expecting some sort of reply to test against.

ContentLicense: CC BY-SA 4.0

Title: JSON requests in C using libcurl

Body:
I'm defining a PUT request with a JSON request body using libcurl in C.

This how I'm doing it:

    sprintf(jsonObj, "\"name\" : \"%s\", \"age\" : \"%s\"", name, age);

    struct curl_slist *headers = NULL;
    curl_slist_append(headers, "Accept: application/json");
    curl_slist_append(headers, "Content-Type: application/json");
    curl_slist_append(headers, "charset: utf-8");

    curl_easy_setopt(curl, CURLOPT_URL, url);

    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1");

    res = curl_easy_perform(curl);

The request body is arriving like this:

    { '"name" : "Pedro", "age" : "22"' }

With { ' at the start and ' } at the end.

--- MORE INFO -----

if I declare this code

    char* jsonObj = "{ \"name\" : \"Pedro\" , \"age\" : \"22\" }";

    struct curl_slist *headers = NULL;
    curl_slist_append(headers, "Accept: application/json");
    curl_slist_append(headers, "Content-Type: application/json");
    curl_slist_append(headers, "charset: utf-8");

    curl_easy_setopt(curl, CURLOPT_URL, url);

    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1");

    res = curl_easy_perform(curl);

the server receives this as the request body:

{ '{ "name" : "Pedro" , "age" : "22" }': '' }

My question is:

Is the libCurl pre-formatting/encoding automatically the Json request?

By the way, does the libCurl have some way of encoding a JSON object?

Thanks so much!

Body:
A key part of understanding whether the system is behaving correctly is seeing what the program is actually sending over the network. So another way to check the byte stream, instead of pointing it at your server (and/or running Wireshark), is to just run a netcat instance in a separate window on the test machine:

nc -l 8080

and point the code (CURLOPT_URL) at "http://localhost:8080".

You'll need to hit Control-D in the nc window to terminate the connection so that curl completes, but you can also type a test return text beforehand, which can be useful if you're expecting some sort of reply to test against.


问:
How complex can an enum get before reading lines of data from a file is better (e.g. .csv)?
I have created part of a platformer game where I have an actor class, representing instances of objects and characters, and a type enum which denotes what data each actor will have (such as speed, attack, defence, etc).
Specifying all the data of each type seems somewhat tedious with hardcoded enum definitions.
E.g.

```<code>PLANE("Plane", 10, 10, 2, 0),
MISSILE("Missile", 1, 0, 0, 4);
</code>```

Would it be best to specify data in a file and read it instead?

答:
Some thoughts here:

instead of giving a "human readable" name string to your enum, you could as well @Override the toString() method to automatically return Plane for PLANE (easy - just lowercase everything except first letter)

such code breaks your ability to add more features later on

There is the old Open/Closed principle. Basically it is saying: your code needs should be open in those areas where change is most likely to happen.

I am pretty sure: today you need 4 values, like 10, 10, 2, 0 for a Plane, as above. But in a few days, you might want to have more attributes. Then you have to turn to all your enum constants and update them.

In that sense, it might be better to give up a bit of compile time safety here; and use a Map instead. Map key could be an enum (just listing the different potential properties some player/item/... has). Map key would be the specific value for that strength.

If you would want to go down that route, you could then specify a type for each enum constant. So that you know that a map value for STRENGTH for example would be a Integer object, or something alike.

In other words: you might turn into the dark realms of reflection here.

Body:
I have created part of a platformer game where I have an actor class, representing instances of objects and characters, and a type enum which denotes what data each actor will have (such as speed, attack, defence, etc).
Specifying all the data of each type seems somewhat tedious with hardcoded enum definitions.
E.g.

PLANE("Plane", 10, 10, 2, 0),
MISSILE("Missile", 1, 0, 0, 4);

Would it be best to specify data in a file and read it instead?


问:
How to transcode a video to custom resolution using Xamarin.MP4Transcoder.Transcoder
I need to transcode a video to 640*480 resolution using Xamarin.MP4Transcoder.Transcoder. Currently there are 2 available resolutions 720pFormat and 960x540Format. There is a method called Transcoder For (IMediaFormatStrategy strategy) available in Transcoder class.

I can create MediaFormat object with MIME Type, Width and Height
by below mentioned code snippet:

MediaFormat obj = MediaFormat.CreateVideoFormat("video/mp4", 480, 640);
```
</div>
</div>
</p>

<p>but the problem is how can assign it to IMediaFormatStrategy or is there any other way to achieve this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Piece of code for Transcoding a video:

Xamarin.MP4Transcoder.Transcoder.For960x540Format().ConvertAsync(inputFile, outputFile, f =>
    {
      onProgress?.Invoke((int)(f * (double)100), 100);

    } );

inputFile: Video file which needs to be transcoded.
outputFile: Resultant file generated after transcoding.</code>```

For more info you can refer https://github.com/neurospeech/xamarin-android-ffmpeg

Any help is appreciated. Thanks in advance!!

答:
I had to do similar, and luckily found how it was made in Java, and then I just had to convert it to C#.

The resulting class (for 640x360) looks like this:

```<code>public class For640x360Format : Java.Lang.Object, IMediaFormatStrategy
{
    public static int AUDIO_BITRATE_AS_IS = -1;
    public static int AUDIO_CHANNELS_AS_IS = -1;
    static String TAG = "640x360FormatStrategy";
    static int LONGER_LENGTH = 640;
    static int SHORTER_LENGTH = 360;
    static int DEFAULT_VIDEO_BITRATE = 8000 * 1000; // From Nexus 4 Camera in 720p
    int mVideoBitrate;
    int mAudioBitrate;
    int mAudioChannels;

    public For640x360Format ()
    {
        mVideoBitrate = DEFAULT_VIDEO_BITRATE;
        mAudioBitrate = AUDIO_BITRATE_AS_IS;
        mAudioChannels = AUDIO_CHANNELS_AS_IS;
    }

    public For640x360Format (int videoBitrate)
    {
        mVideoBitrate = videoBitrate;
        mAudioBitrate = AUDIO_BITRATE_AS_IS;
        mAudioChannels = AUDIO_CHANNELS_AS_IS;
    }

    public For640x360Format (int videoBitrate, int audioBitrate, int audioChannels)
    {
        mVideoBitrate = videoBitrate;
        mAudioBitrate = audioBitrate;
        mAudioChannels = audioChannels;
    }

    public MediaFormat CreateAudioOutputFormat (MediaFormat inputFormat)
    {
        if (mAudioBitrate == AUDIO_BITRATE_AS_IS || mAudioChannels == AUDIO_CHANNELS_AS_IS) return null;

        // Use original sample rate, as resampling is not supported yet.
        MediaFormat format = MediaFormat.CreateAudioFormat (MediaFormatExtraConstants.MimetypeAudioAac,
                                                            inputFormat.GetInteger (MediaFormat.KeySampleRate),
                                                            mAudioChannels);
        // this is obsolete: MediaCodecInfo.CodecProfileLevel.AACObjectLC, so using MediaCodecProfileType.Aacobjectlc instead
        format.SetInteger (MediaFormat.KeyAacProfile, (int)MediaCodecProfileType.Aacobjectlc);
        format.SetInteger (MediaFormat.KeyBitRate, mAudioBitrate);
        return format;
    }

    public MediaFormat CreateVideoOutputFormat (MediaFormat inputFormat)
    {
        int width = inputFormat.GetInteger (MediaFormat.KeyWidth);
        int height = inputFormat.GetInteger (MediaFormat.KeyHeight);
        int longer, shorter, outWidth, outHeight;

        if (width >= height)
        {
            longer = width;
            shorter = height;
            outWidth = LONGER_LENGTH;
            outHeight = SHORTER_LENGTH;
        }
        else
        {
            shorter = width;
            longer = height;
            outWidth = SHORTER_LENGTH;
            outHeight = LONGER_LENGTH;
        }

        if (longer * 9 != shorter * 16)
        {
            throw new OutputFormatUnavailableException ("This video is not 16:9, and is not able to transcode. (" + width + "x" + height + ")");
        }
        if (shorter <= SHORTER_LENGTH)
        {
            #if DEBUG
            Console.WriteLine ("This video is less or equal to 720p, pass-through. (" + width + "x" + height + ")");
            #endif

            return null;
        }

        MediaFormat format = MediaFormat.CreateVideoFormat ("video/avc", outWidth, outHeight);
        format.SetInteger (MediaFormat.KeyBitRate, mVideoBitrate);
        format.SetInteger (MediaFormat.KeyFrameRate, 30);
        format.SetInteger (MediaFormat.KeyIFrameInterval, 3);
        // this is obsolete: MediaCodecInfo.CodecCapabilities.COLORFormatSurface, so using MediaCodecCapabilities.Formatsurface instead
        format.SetInteger (MediaFormat.KeyColorFormat, (int)MediaCodecCapabilities.Formatsurface);

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

Just change LONGER_LENGTH and SHORTER_LENGTH to whatever resolution you need and, obviously, create a new class for it.
Could probably also just make a generic class that takes in the two lengths, but I haven't had a need for it yet.

Link to the Java code

Body:
I need to transcode a video to 640*480 resolution using Xamarin.MP4Transcoder.Transcoder. Currently there are 2 available resolutions 720pFormat and 960x540Format. There is a method called Transcoder For (IMediaFormatStrategy strategy) available in Transcoder class.

I can create MediaFormat object with MIME Type, Width and Height
by below mentioned code snippet:

MediaFormat obj = MediaFormat.CreateVideoFormat("video/mp4", 480, 640);

but the problem is how can assign it to IMediaFormatStrategy or is there any other way to achieve this.

Piece of code for Transcoding a video:

Xamarin.MP4Transcoder.Transcoder.For960x540Format().ConvertAsync(inputFile, outputFile, f =>
    {
      onProgress?.Invoke((int)(f * (double)100), 100);

    } );

inputFile: Video file which needs to be transcoded.
outputFile: Resultant file generated after transcoding.

For more info you can refer https://github.com/neurospeech/xamarin-android-ffmpeg

Any help is appreciated. Thanks in advance!!

Body:
I had to do similar, and luckily found how it was made in Java, and then I just had to convert it to C#.

The resulting class (for 640x360) looks like this:

public class For640x360Format : Java.Lang.Object, IMediaFormatStrategy
{
    public static int AUDIO_BITRATE_AS_IS = -1;
    public static int AUDIO_CHANNELS_AS_IS = -1;
    static String TAG = "640x360FormatStrategy";
    static int LONGER_LENGTH = 640;
    static int SHORTER_LENGTH = 360;
    static int DEFAULT_VIDEO_BITRATE = 8000 * 1000; // From Nexus 4 Camera in 720p
    int mVideoBitrate;
    int mAudioBitrate;
    int mAudioChannels;

    public For640x360Format ()
    {
        mVideoBitrate = DEFAULT_VIDEO_BITRATE;
        mAudioBitrate = AUDIO_BITRATE_AS_IS;
        mAudioChannels = AUDIO_CHANNELS_AS_IS;
    }

    public For640x360Format (int videoBitrate)
    {
        mVideoBitrate = videoBitrate;
        mAudioBitrate = AUDIO_BITRATE_AS_IS;
        mAudioChannels = AUDIO_CHANNELS_AS_IS;
    }

    public For640x360Format (int videoBitrate, int audioBitrate, int audioChannels)
    {
        mVideoBitrate = videoBitrate;
        mAudioBitrate = audioBitrate;
        mAudioChannels = audioChannels;
    }

    public MediaFormat CreateAudioOutputFormat (MediaFormat inputFormat)
    {
        if (mAudioBitrate == AUDIO_BITRATE_AS_IS || mAudioChannels == AUDIO_CHANNELS_AS_IS) return null;

        // Use original sample rate, as resampling is not supported yet.
        MediaFormat format = MediaFormat.CreateAudioFormat (MediaFormatExtraConstants.MimetypeAudioAac,
                                                            inputFormat.GetInteger (MediaFormat.KeySampleRate),
                                                            mAudioChannels);
        // this is obsolete: MediaCodecInfo.CodecProfileLevel.AACObjectLC, so using MediaCodecProfileType.Aacobjectlc instead
        format.SetInteger (MediaFormat.KeyAacProfile, (int)MediaCodecProfileType.Aacobjectlc);
        format.SetInteger (MediaFormat.KeyBitRate, mAudioBitrate);
        return format;
    }

    public MediaFormat CreateVideoOutputFormat (MediaFormat inputFormat)
    {
        int width = inputFormat.GetInteger (MediaFormat.KeyWidth);
        int height = inputFormat.GetInteger (MediaFormat.KeyHeight);
        int longer, shorter, outWidth, outHeight;

        if (width >= height)
        {
            longer = width;
            shorter = height;
            outWidth = LONGER_LENGTH;
            outHeight = SHORTER_LENGTH;
        }
        else
        {
            shorter = width;
            longer = height;
            outWidth = SHORTER_LENGTH;
            outHeight = LONGER_LENGTH;
        }

        if (longer * 9 != shorter * 16)
        {
            throw new OutputFormatUnavailableException ("This video is not 16:9, and is not able to transcode. (" + width + "x" + height + ")");
        }
        if (shorter <= SHORTER_LENGTH)
        {
            #if DEBUG
            Console.WriteLine ("This video is less or equal to 720p, pass-through. (" + width + "x" + height + ")");
            #endif

            return null;
        }

        MediaFormat format = MediaFormat.CreateVideoFormat ("video/avc", outWidth, outHeight);
        format.SetInteger (MediaFormat.KeyBitRate, mVideoBitrate);
        format.SetInteger (MediaFormat.KeyFrameRate, 30);
        format.SetInteger (MediaFormat.KeyIFrameInterval, 3);
        // this is obsolete: MediaCodecInfo.CodecCapabilities.COLORFormatSurface, so using MediaCodecCapabilities.Formatsurface instead
        format.SetInteger (MediaFormat.KeyColorFormat, (int)MediaCodecCapabilities.Formatsurface);

        return format;
    }
}

Just change LONGER_LENGTH and SHORTER_LENGTH to whatever resolution you need and, obviously, create a new class for it.
Could probably also just make a generic class that takes in the two lengths, but I haven't had a need for it yet.

Link to the Java code


问:
PayPal and Sandbox payment credentials : sandbox and production fields
im very new with this API. I want to generate a PayPal PAY button. I've created a SANDBOX Paypal as a vendor and as a buyer. Two accounts.

I don't know how to get 'sandbox' and 'production' fields.

I haven't created an APP, all the time ask me to confirm and email which I've confirmed 10 times.

```<code>         paypal.Button.render({

        env: 'sandbox', // sandbox | production

        // PayPal Client IDs - replace with your own
        // Create a PayPal app: https://developer.paypal.com/developer/applications/create
        client: {
            sandbox:    'AFcWxV21C7fd0v3bYYYRCpSSRl31AULfweezb3a.97AL03QEPQS.cIvX',
            production: 'QGWT5LPKXCYKNMEW'
        },

        // Show the buyer a 'Pay Now' button in the checkout flow
        commit: true,
</code>```

...

i dont know how to get sandbox and production fields, inside 'client' object.

thanks!

答:
To create email confirmed and verified sandbox account, please refer the below steps:

```<code>1. Login to http://developer.paypal.com/ with your LIVE PayPal account
2. Click Dashboard
3. Click sandbox accounts
4. Click Create account button on the top right corner
5. Create a business account for seller and a personal account for buyer
6. Please add bank account and credit card and also populate some amount to your account
7. The email address need not be an real one.
</code>```

Please refer the below link for your reference for creating sandbox:

https://developer.paypal.com/docs/classic/lifecycle/sb_create-accounts/

Refer the following links for PayPal Express checkout client side integrations, where you can find steps to get the client id details:

https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/client-side-REST-integration/

https://developer.paypal.com/demo/checkout/#/pattern/client

Body:
im very new with this API. I want to generate a PayPal PAY button. I've created a SANDBOX Paypal as a vendor and as a buyer. Two accounts.

I don't know how to get 'sandbox' and 'production' fields.

I haven't created an APP, all the time ask me to confirm and email which I've confirmed 10 times.

         paypal.Button.render({

        env: 'sandbox', // sandbox | production

        // PayPal Client IDs - replace with your own
        // Create a PayPal app: https://developer.paypal.com/developer/applications/create
        client: {
            sandbox:    'AFcWxV21C7fd0v3bYYYRCpSSRl31AULfweezb3a.97AL03QEPQS.cIvX',
            production: 'QGWT5LPKXCYKNMEW'
        },

        // Show the buyer a 'Pay Now' button in the checkout flow
        commit: true,

...

i dont know how to get sandbox and production fields, inside 'client' object.

thanks!

Body:
To create email confirmed and verified sandbox account, please refer the below steps:

1. Login to http://developer.paypal.com/ with your LIVE PayPal account
2. Click Dashboard
3. Click sandbox accounts
4. Click Create account button on the top right corner
5. Create a business account for seller and a personal account for buyer
6. Please add bank account and credit card and also populate some amount to your account
7. The email address need not be an real one.

Please refer the below link for your reference for creating sandbox:

https://developer.paypal.com/docs/classic/lifecycle/sb_create-accounts/

Refer the following links for PayPal Express checkout client side integrations, where you can find steps to get the client id details:

https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/client-side-REST-integration/

https://developer.paypal.com/demo/checkout/#/pattern/client


问:
image selection des not work in ionic 2 app
i am trying to open the photolibrary of android to select images using ionic 2.
here is the code of the home.ts in witch the camera plugin is used.

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Camera} from '@ionic-native/camera';
@Component({
   selector: 'page-home',
   templateUrl: 'home.html'
})
export class HomePage {
   image640:any;
   constructor(public navCtrl: NavController,public camera : Camera)
   {

   }

openGallery()
{
    var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
   this.camera.getPicture(
  options
   ).then(
      (imageData)=>
   {
      this.image640 = 'data:image/jpeg;base64,'+imageData;
   },
   (err) =>
   {
      console.log(err);
   }
);
}

}
</code>```

And the code of the home.html is below :

```<code><ion-header>
  <ion-navbar>
   <ion-title align="center">
   Blank
  </ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>

  <img src="image640" *ngIf="image640"/>

<Button align="center" ion-button (click)="openGallery()">Open
Gallery</Button>

</ion-content>
</code>```

but when i click on the opengallery button, the android library is opened but when i select an image, a blank screen appear during about 8 seconds, and after that, the it is the rootpage that is displayed. Then i cannot see the selected image in my page.
can somebody help ?

答:
Set options

```<code>var options = {
  quality: 100,
  sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
  saveToPhotoAlbum: true,
  correctOrientation: true,
};
</code>```

Then select photos like this

```<code> this.camera.getPicture(options).then((imagePath) => {

  // Special handling for Android library
  if (this.platform.is('android') && sourceType ===
 this.camera.PictureSourceType.PHOTOLIBRARY) { //when selecting from library

        //your code goes here
  } else { //when capturing by camera
      //your code goes here
  }
</code>```

Body:
i am trying to open the photolibrary of android to select images using ionic 2.
here is the code of the home.ts in witch the camera plugin is used.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Camera} from '@ionic-native/camera';
@Component({
   selector: 'page-home',
   templateUrl: 'home.html'
})
export class HomePage {
   image640:any;
   constructor(public navCtrl: NavController,public camera : Camera)
   {

   }

openGallery()
{
    var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
   this.camera.getPicture(
  options
   ).then(
      (imageData)=>
   {
      this.image640 = 'data:image/jpeg;base64,'+imageData;
   },
   (err) =>
   {
      console.log(err);
   }
);
}

}

And the code of the home.html is below :

<ion-header>
  <ion-navbar>
   <ion-title align="center">
   Blank
  </ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>

<Button align="center" ion-button (click)="openGallery()">Open
Gallery</Button>

</ion-content>

but when i click on the opengallery button, the android library is opened but when i select an image, a blank screen appear during about 8 seconds, and after that, the it is the rootpage that is displayed. Then i cannot see the selected image in my page.
can somebody help ?

Body:
Set options

var options = {
  quality: 100,
  sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
  saveToPhotoAlbum: true,
  correctOrientation: true,
};

Then select photos like this

 this.camera.getPicture(options).then((imagePath) => {

  // Special handling for Android library
  if (this.platform.is('android') && sourceType ===
 this.camera.PictureSourceType.PHOTOLIBRARY) { //when selecting from library

        //your code goes here
  } else { //when capturing by camera
      //your code goes here
  }


问:
Double-pipe statement with two commands using the `&&` on a `for` loop (batch script)
Based on answers and comments from this question, I cannot understand how to add a double-pipe || statement with two commands using the && on a for loop. Consider the following example taken from here:

```<code>@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
</code>```

If I try

```<code>for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" || echo Error while getting datetime. >> %someoutputfile% && GOTO endthis
</code>```

I get a Unexpected && error. I tried adding parenthesis around the each command after the || but they too give Unexpected ) similar errors.

Can someone explain what I am doing wrong? Should I put the || commands before the do set "dt=%%a" or something?

答:
Here's a working example:</p>

```<code>@ echo off

for /f "tokens=2 delims==" %%a in ('WMIC OS Get LocalDateTime /value') do (
    set dt=%%a && (
        echo Local Data Time: "%dt%"
    ) || (
        echo Error while getting datetime.
        goto ERROR
    )
)

echo Exiting...
goto END

:ERROR
echo Terminating...

:END
</code>```

Body:
Based on answers and comments from this question, I cannot understand how to add a double-pipe || statement with two commands using the && on a for loop. Consider the following example taken from here:

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

If I try

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" || echo Error while getting datetime. >> %someoutputfile% && GOTO endthis

I get a Unexpected && error. I tried adding parenthesis around the each command after the || but they too give Unexpected ) similar errors.

Can someone explain what I am doing wrong? Should I put the || commands before the do set "dt=%%a" or something?

Body:
Here's a working example:

@ echo off

for /f "tokens=2 delims==" %%a in ('WMIC OS Get LocalDateTime /value') do (
    set dt=%%a && (
        echo Local Data Time: "%dt%"
    ) || (
        echo Error while getting datetime.
        goto ERROR
    )
)

echo Exiting...
goto END

:ERROR
echo Terminating...

:END


问:
Dividing a number by instances of my class in Python
I have a class called Time, and I need to implement a Frequency class. How can I implement dividing ints or floats by an instance of Time to get an instance of Frequency ?

I already know about __div__, __truediv__, __floordiv__ and other Python special methods, and I already use them in my code to divide instances of classes by numbers or instances of other classes, but I cannot find a way to divide a number by an instance of my class.

Is it possible to implement dividing a number by an instance of a class in Python ?

答:
you need to implement __rtruediv__ and__rfloordiv__.

from the documentation

```<code>object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rmatmul__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other)
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)
</code>```

These methods are called to implement the binary arithmetic operations
  (+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |) with
  reflected (swapped) operands. These functions are only called if the
  left operand does not support the corresponding operation [3] and the
  operands are of different types. [4] For instance, to evaluate the
  expression x - y, where y is an instance of a class that has an
  __rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns NotImplemented.

Body:
you need to implement __rtruediv__ and__rfloordiv__.

from the documentation

object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rmatmul__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other)
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)

These methods are called to implement the binary arithmetic operations
  (+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |) with
  reflected (swapped) operands. These functions are only called if the
  left operand does not support the corresponding operation [3] and the
  operands are of different types. [4] For instance, to evaluate the
  expression x - y, where y is an instance of a class that has an
  __rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns NotImplemented.


问:
C# Accessing to multiple controls from a thread
I have a code and when you click on start some controls must be disabled for the safety... :

```<code>Thread t = new Thread(() => MyMethod(text));

button1.Enabled = false;
textBox2.Enabled = false;
button2.Enabled = false;

t.Start();
</code>```

This is not a problem.
My problem is where i should turn all of them On again, My mean is when the MyMethod ends , i have to Invoke all the controls i want to enable them.

```<code>MyMethod(string text){
.
.
.
button1.Invoke(new MethodInvoker(delegate{ button1.Enabled=true; }));
textBox2.Invoke(new MethodInvoker(delegate{textBox2.Enabled=true; }));
button2.Invoke(new MethodInvoker(delegate{ button2.Enabled=true; }));
}
</code>```

So if we had a bunch of Controls Set, It would be hard to change the values of they in a thread.

Is there anyway to Access these for an easier or faster way ?

Thanks,

答:
Store the current dispatcher before calling your method in a separate thread.

```<code>var uiDispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
</code>```

Use Dispatcher in your MyMethod such as:

```<code>void MyMethod(Dispatcher uiDispatcher)
{
...

    uiDispatcher.Invoke(() =>
                {
    button1.Enabled = true;
    button2.Enabled = true;
    ...
                });
}
</code>```

Body:
I have a code and when you click on start some controls must be disabled for the safety... :

Thread t = new Thread(() => MyMethod(text));

button1.Enabled = false;
textBox2.Enabled = false;
button2.Enabled = false;

t.Start();

This is not a problem.
My problem is where i should turn all of them On again, My mean is when the MyMethod ends , i have to Invoke all the controls i want to enable them.

MyMethod(string text){
.
.
.
button1.Invoke(new MethodInvoker(delegate{ button1.Enabled=true; }));
textBox2.Invoke(new MethodInvoker(delegate{textBox2.Enabled=true; }));
button2.Invoke(new MethodInvoker(delegate{ button2.Enabled=true; }));
}

So if we had a bunch of Controls Set, It would be hard to change the values of they in a thread.

Is there anyway to Access these for an easier or faster way ?

Thanks,

Body:
Store the current dispatcher before calling your method in a separate thread.

var uiDispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;

Use Dispatcher in your MyMethod such as:

void MyMethod(Dispatcher uiDispatcher)
{
...

    uiDispatcher.Invoke(() =>
                {
    button1.Enabled = true;
    button2.Enabled = true;
    ...
                });
}


答:
As noticed by brittenb in his comment, the data structure in your example is in fact a type we call a dictionary in Python. See https://docs.python.org/3/tutorial/datastructures.html#dictionaries for further details.

Getting the list of keys of a dictionary is done by calling

```<code>list(dict.keys())
</code>```

This is what calling it on your example would look like:

```<code>test = {'J2EE': 0.0202219636, 'financial': 0.2439565346, 'Guru': 0.0202219636, 'AWS': 0.0202219636, 'next generation': 0.12072663160000001, 'Machine Learning': 0.2025762767, 'technology': 0.066936981}
list(test.keys())
>>>['financial', 'next generation', 'Guru', 'technology', 'J2EE', 'Machine Learning', 'AWS']
</code>```

Title: How do I strip only the string part from a list in Python?

Body:
I have a list that looks like:

{
    'J2EE': 0.0202219636,
    'financial': 0.2439565346,
    'Guru': 0.0202219636,
    'AWS': 0.0202219636,
    'next generation': 0.12072663160000001,
    'Machine Learning': 0.2025762767,
    'technology': 0.066936981
}

How do I extract only the text parts and make my list look like:

['J2EE', 'financial', 'Guru', 'AWS', ...]

Should I use Regular expressions?

Body:
As noticed by brittenb in his comment, the data structure in your example is in fact a type we call a dictionary in Python. See https://docs.python.org/3/tutorial/datastructures.html#dictionaries for further details.

Getting the list of keys of a dictionary is done by calling

list(dict.keys())

This is what calling it on your example would look like:

test = {'J2EE': 0.0202219636, 'financial': 0.2439565346, 'Guru': 0.0202219636, 'AWS': 0.0202219636, 'next generation': 0.12072663160000001, 'Machine Learning': 0.2025762767, 'technology': 0.066936981}
list(test.keys())
>>>['financial', 'next generation', 'Guru', 'technology', 'J2EE', 'Machine Learning', 'AWS']


问:
use Adam optimizer TWICE in tensorflow
I am trying to use adam optimizer twice to minimize different tensor in my code, I have tried use GradientDescentOptimizer twice, it's fine, but I get wrong message when using adam optimizer twice, I asked another question at:tensorflowVariable RNNLM/RNNLM/embedding/Adam_2/ does not exist, but that solution doesn't work in here.  I also look up page:https://github.com/tensorflow/tensorflow/issues/6220, But I still don't understand.

 Here is my code, I get Error message:ValueError: Variable NN/NN/W/Adam_2/ does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?

Then I tried the solution at tensorflowVariable RNNLM/RNNLM/embedding/Adam_2/ does not exist, but doesn't work

import tensorflow as tf

def main():
    optimizer = tf.train.GradientDescentOptimizer(0.005)
    # optimizer = tf.train.AdamOptimizer(0.005)

    with tf.variable_scope('NN') as scope:
        W = tf.get_variable(name='W', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        X = tf.get_variable(name='X', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        y_ = tf.get_variable(name='y_', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        y1 = W + X
        loss_1 = tf.reduce_mean(tf.abs(y_ - y1))

        # train_op1 = tf.train.GradientDescentOptimizer(0.005).minimize(loss_1)
        train_op1 = tf.train.AdamOptimizer(0.005).minimize(loss_1)
        # with tf.variable_scope('opt'):
        #     train_op1 = tf.train.AdamOptimizer(0.005).minimize(loss_1)

        ##############################################################################################
        scope.reuse_variables()

        W2 = tf.get_variable(name='W', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        X2 = tf.get_variable(name='X', initializer=tf.random_uniform(dtype=tf.float32, shape=[5, 1]))
        b = tf.Variable(tf.random_normal(shape=[5, 1], dtype=tf.float32))
        y2 = W2 + X2 + b
        loss_2 = tf.reduce_mean(tf.abs(y_ - y2))

        # train_op2 = tf.train.GradientDescentOptimizer(0.005).minimize(loss_2)
        train_op2 = tf.train.AdamOptimizer(0.005).minimize(loss_2)
        # with tf.variable_scope('opt'):
        #     train_op2 = tf.train.AdamOptimizer(0.005).minimize(loss_2)

if __name__ == '__main__':
    main()
```

答: The simplest way to fix this problem is put the second optimizer in a different scope. This way the naming does not cause any confusion. </p>

Title: use Adam optimizer TWICE in tensorflow


问:
How to decrease build times / speed up compile time in Xcode?
What strategies can be used in general to decrease build times for any Xcode project? I'm mostly interested in Xcode specific strategies.

I'm doing iPhone development using Xcode, and my project is slowly getting bigger and bigger. I find the compile / link phases are starting to take more time than I'd like.

Currently, I'm:

Using Static Libraries to make it so
most of my code doesn't need to be
compiled everytime I clean and build
my main project

Have removed most resources from my
application, and test with a hard
coded file system path in the iPhone
simulator whenever possible so my
resources don't have to constantly be
packaged as I make changes to them.

I've noticed that the "Checking Dependencies" phase seems to take longer than I'd like. Any tips to decrease that as well would be appreciated!

答:
I used a script to make use of a RAM drive, together with some "forward declarations" optimizations my project clean build time went from 53 seconds to 20 seconds.

I was tempted to get the Gui on the AppStore, but opted rather to
go for command line. I put the script as part of git repository.

To see the build times, enter this in a terminal:
"defaults write com.apple.dt.Xcode ShowBuildOperationDuration YES"

Restart Xcode to notice the build times in the toolbar.
(this is my non clean build time using objective-c)

Adjust the script to your liking. - Note the script clears
the derived data folder.

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

#2 GIG RAM
GIGA_BYTES=$((2*1024*1024*1024))

# a sector is 512 bytes
NUMSECTORS=$((${GIGA_BYTES}/512))

#ram disk
mydev=`hdiutil attach -nomount ram://$NUMSECTORS`
newfs_hfs $mydev

# make mount point
MOUNT_POINT=/Users/your_user_name/Library/Developer/Xcode/DerivedData

# *******************************************
# ** WARNING - MOUNT POINT WILL BE DELETED **
# *******************************************
rm -rf ${MOUNT_POINT}
mkdir -p ${MOUNT_POINT}

# mount
mount -t hfs $mydev ${MOUNT_POINT}
echo unmount $(MOUNT_POINT)
</code>```

To see the effect and to control the RAM Drive:

```<code>mount                       - see mount points
umount mount_point          - unmount point
diskutil list               - see disks
diskutil eject /dev/diskX   - eject the disk
df -ahl                     - see free space
</code>```

NOTE:
I essentially use the hdiutil provided by macOs.
I tried switching the -kernel option (no swapping to disk) on but failed on my machine, saying it is not implemented.

Maybe the new OS coming soon we will see even more improvements as the new file system copy feature is really fast, and possibly makes this script redundant.

Body:
I used a script to make use of a RAM drive, together with some "forward declarations" optimizations my project clean build time went from 53 seconds to 20 seconds.

I was tempted to get the Gui on the AppStore, but opted rather to
go for command line. I put the script as part of git repository.

To see the build times, enter this in a terminal:
"defaults write com.apple.dt.Xcode ShowBuildOperationDuration YES"

Restart Xcode to notice the build times in the toolbar.
(this is my non clean build time using objective-c)

Adjust the script to your liking. - Note the script clears
the derived data folder.

#!/bin/sh

#2 GIG RAM
GIGA_BYTES=$((2*1024*1024*1024))

# a sector is 512 bytes
NUMSECTORS=$((${GIGA_BYTES}/512))

#ram disk
mydev=`hdiutil attach -nomount ram://$NUMSECTORS`
newfs_hfs $mydev

# make mount point
MOUNT_POINT=/Users/your_user_name/Library/Developer/Xcode/DerivedData

# *******************************************
# ** WARNING - MOUNT POINT WILL BE DELETED **
# *******************************************
rm -rf ${MOUNT_POINT}
mkdir -p ${MOUNT_POINT}

# mount
mount -t hfs $mydev ${MOUNT_POINT}
echo unmount $(MOUNT_POINT)

To see the effect and to control the RAM Drive:

mount                       - see mount points
umount mount_point          - unmount point
diskutil list               - see disks
diskutil eject /dev/diskX   - eject the disk
df -ahl                     - see free space

NOTE:
I essentially use the hdiutil provided by macOs.
I tried switching the -kernel option (no swapping to disk) on but failed on my machine, saying it is not implemented.

Maybe the new OS coming soon we will see even more improvements as the new file system copy feature is really fast, and possibly makes this script redundant.


问:
How to Parse json data having array in IONIC hybrid appliaction
I am beginner in hybrid Ionic App Development. I want to implement RESTful web service in my project.
My json Data is:

```<code>{
    "records": [
        {
            "Name": "Alfreds Futterkiste",
            "City": "Berlin",
            "Country": "Germany"
        },
        {
            "Name": "Ana Trujillo Emparedados y helados",
            "City": "México D.F.",
            "Country": "Mexico"
        },
        {
            "Name": "Antonio Moreno Taquería",
            "City": "México D.F.",
            "Country": "Mexico"
        }]
}
</code>```

Here i want to Parse this Data in Listview in ionic. I don't no how to parse data with array.Please suggest the solution or tutorials to get result.I want to show all Names in Listview.
I am using this api link: http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt
thanks in advance.

答:
Here you no need to parse the JSON data, it is already in object format.

You can use like this

```<code> var myData = {
    "records": [
        {
            "Name": "Alfreds Futterkiste",
            "City": "Berlin",
            "Country": "Germany"
        },
        {
            "Name": "Ana Trujillo Emparedados y helados",
            "City": "México D.F.",
            "Country": "Mexico"
        },
        {
            "Name": "Antonio Moreno Taquería",
            "City": "México D.F.",
            "Country": "Mexico"
        }]
}
var record1 = myData.records[0];
var record2 = myData.records[1];
var record3 = myData.records[2];

console.log(record1)
console.log(record2)
console.log(record3)

console.log("Record 1 Data:")
console.log('\t'+"Name: "+record1.Name)
console.log('\t'+"City: "+record1.City)
console.log('\t'+"Country: "+record1.Country)

console.log("Record 2 Data:")
console.log('\t'+"Name: "+record2.Name)
console.log('\t'+"City: "+record2.City)
console.log('\t'+"Country: "+record2.Country)

console.log("Record 3 Data:")
console.log('\t'+"Name: "+record3.Name)
console.log('\t'+"City: "+record3.City)
console.log('\t'+"Country: "+record3.Country)
</code>```

Body:
I am beginner in hybrid Ionic App Development. I want to implement RESTful web service in my project.
My json Data is:

{
    "records": [
        {
            "Name": "Alfreds Futterkiste",
            "City": "Berlin",
            "Country": "Germany"
        },
        {
            "Name": "Ana Trujillo Emparedados y helados",
            "City": "México D.F.",
            "Country": "Mexico"
        },
        {
            "Name": "Antonio Moreno Taquería",
            "City": "México D.F.",
            "Country": "Mexico"
        }]
}

Here i want to Parse this Data in Listview in ionic. I don't no how to parse data with array.Please suggest the solution or tutorials to get result.I want to show all Names in Listview.
I am using this api link: http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt
thanks in advance.

Body:
Here you no need to parse the JSON data, it is already in object format.

You can use like this

 var myData = {
    "records": [
        {
            "Name": "Alfreds Futterkiste",
            "City": "Berlin",
            "Country": "Germany"
        },
        {
            "Name": "Ana Trujillo Emparedados y helados",
            "City": "México D.F.",
            "Country": "Mexico"
        },
        {
            "Name": "Antonio Moreno Taquería",
            "City": "México D.F.",
            "Country": "Mexico"
        }]
}
var record1 = myData.records[0];
var record2 = myData.records[1];
var record3 = myData.records[2];

console.log(record1)
console.log(record2)
console.log(record3)

console.log("Record 1 Data:")
console.log('\t'+"Name: "+record1.Name)
console.log('\t'+"City: "+record1.City)
console.log('\t'+"Country: "+record1.Country)

console.log("Record 2 Data:")
console.log('\t'+"Name: "+record2.Name)
console.log('\t'+"City: "+record2.City)
console.log('\t'+"Country: "+record2.Country)

console.log("Record 3 Data:")
console.log('\t'+"Name: "+record3.Name)
console.log('\t'+"City: "+record3.City)
console.log('\t'+"Country: "+record3.Country)


问:
Using REST Assured library for testing SOAP webservices
Is there a possibility of using REST Assured library for testing SOAP webservices?
I have a bunch of Test Suites in SOAP UI and I need to check if there is possibility of using REST Assured.
Can anyone suggest if this is possible?
Many thanks for any comments.</p>

答:
REST-assured does not have direct support for testing SOAP services, but it is possible by manually setting the SOAPAction and Content-Type headers and doing an HTTP POST etc. Then you can run XPath assertions on the response like you do for normal REST services in REST-assured.

I suggest you also evaluate Karate as it has built-in support for SOAP, and also makes XML manipulation a lot easier.


问:
RFID Reader to connect with Beagle Board
Can someone tell me about RFID reader that is compatible with Beagle Board??</p>

答:
Well if you are looking for a PICC's UID reading with a low-cost solution you should look here. It is a lightweight library written in C for BeagleBone Black.

You could use this library with RC522 Module. Communication protocol is SPI(SPI0) between BBB and RC522 Module.


问:
Bulk insert in rails
I cannot solve the following problem
Any help or suggestion is appreciated

Agent collects orders for Product on a paper going from one Shop to another in his Region.

At the end of the day, he inserts the quantity of each Product to each Shop.

Each Shop orders more than 4 types of products.

I need to design to be able to bulk insert.

```<code><table>
  <tr>
    <td>Shop1</td>
    <td>Product1</td>
    <td>Product2</td>
    <td>Product3</td>
    <td>Product4</td>
    etc...
  </tr>
  <tr>
    <td>Shop2</td>
    <td>Product1</td>
    <td>Product2</td>
    <td>Product3</td>
    <td>Product4</td>
    etc...
  </tr>
  etc...
</table>
</code>```

In the browser it needs to look as below

答:
One approach could be to use a custom form model. This is a pretty good guide on the subject. This may not be perfect, but should get you on the right track at least. All credit to the following (slightly modified for your question) code goes to Sam Slotsky from the blog linked above. Read the post for more detail about each piece.

Here's the custom form model:

```<code>class ProductForm
  include ActiveModel::Model

  attr_accessor :products

  def products_attributes=(attributes)
    @products ||= []
    attributes.each do |i, product_params|
      @products.push(Product.new(product_params))
    end
  end
end
</code>```

Here's the controller:

```<code>class ProductsController < ApplicationController
  def new
    @product_Form = ProductForm.new(products: [Product.new])
  end

  def create
    @product_form = ProductForm.new(params[:product_form])

    if @product_form.save
      flash[:notice] = "Created products"
      redirect_to root_path
    else
      flash[:notice] = "There were errors"
      render :new
    end
  end
end
</code>```

Here's the view:

```<code><div>
  <%= form_for @product_form, url: products_path, method: :post do |f| %>
    <%= f.fields_for :products do |c| %>
      <%= c.text_field :attr_1 %>
      <%= c.text_field :attr_2
      <%- # ... etc ... %>
    <% end %>

    <p>
      <%= f.submit "Submit" %>
    </p>
  <% end %>
</div>
</code>```

Title: Bulk insert in rails

Body:
I cannot solve the following problem
Any help or suggestion is appreciated

Agent collects orders for Product on a paper going from one Shop to another in his Region.

At the end of the day, he inserts the quantity of each Product to each Shop.

Each Shop orders more than 4 types of products.

I need to design to be able to bulk insert.

    Shop1
    Product1
    Product2
    Product3
    Product4
    etc...

    Shop2
    Product1
    Product2
    Product3
    Product4
    etc...

  etc...

In the browser it needs to look as below

Body:
One approach could be to use a custom form model. This is a pretty good guide on the subject. This may not be perfect, but should get you on the right track at least. All credit to the following (slightly modified for your question) code goes to Sam Slotsky from the blog linked above. Read the post for more detail about each piece.

Here's the custom form model:

class ProductForm
  include ActiveModel::Model

  attr_accessor :products

  def products_attributes=(attributes)
    @products ||= []
    attributes.each do |i, product_params|
      @products.push(Product.new(product_params))
    end
  end
end

Here's the controller:

class ProductsController < ApplicationController
  def new
    @product_Form = ProductForm.new(products: [Product.new])
  end

  def create
    @product_form = ProductForm.new(params[:product_form])

    if @product_form.save
      flash[:notice] = "Created products"
      redirect_to root_path
    else
      flash[:notice] = "There were errors"
      render :new
    end
  end
end

Here's the view:

<div>
  <%= form_for @product_form, url: products_path, method: :post do |f| %>
    <%= f.fields_for :products do |c| %>
      <%= c.text_field :attr_1 %>
      <%= c.text_field :attr_2
      <%- # ... etc ... %>
    <% end %>

    <p>
      <%= f.submit "Submit" %>
    </p>
  <% end %>
</div>


问:
How to disable a button dynamically
I want to gray out a button dynamically. How to do that?</p>

答:
in xaml

```<code><Button Name="myButton">Click Me</Button>
</code>```

in code behind

```<code>myButton.IsEnabled = false;
</code>```

Title: How to disable a button dynamically

Body:
in xaml

<Button Name="myButton">Click Me</Button>

in code behind

myButton.IsEnabled = false;


问:
How to perform this query in oracle sql?
Lets say I have the TABLE shown below. Could you please help me find the persons that have the Attribute1 but not the Attribute3?

Thanks,

Christina

答:
Many different ways of solving this. Here's one</p>

```<code>Select person_id from your_table
Where attribute_id = 'Attribute1'
Minus
Select person_id from your_table
Where attribute_id = 'Attribute3'
/
</code>```

Body:
Many different ways of solving this. Here's one

Select person_id from your_table
Where attribute_id = 'Attribute1'
Minus
Select person_id from your_table
Where attribute_id = 'Attribute3'
/


问:
How do I set the SCSS of a single page's tags to transparent in Ionic 2?
I built out a simple, single page application that uses the Cordova CameraPreview plugin to show the Android camera with Ionic components on top. The tutorial I followed used the below code segment to make the background transparent so that you can see the camera. Now I am trying to build on that tutorial and have a single page that is transparent, but the rest of the pages should not be.

```<code>html, body, ion-app, ion-content, ion-page, .nav-decor {
    background-color: transparent !important;
}
</code>```

The simple question is: How do I a make the HTML background for one page transparent, but not the others?

This is probably simple, but I am new to Ionic.

答:
In your scss page(lets assume your page name is login),

```<code>page-login{
    background: transparent !important;
}
</code>```

This will work. However, you will not see any difference if you wrapped some content inside . In such case, you need to give define transparent to

```<code>.content-md{
    background: transparent !imporant;
}
</code>```

Body:
I built out a simple, single page application that uses the Cordova CameraPreview plugin to show the Android camera with Ionic components on top. The tutorial I followed used the below code segment to make the background transparent so that you can see the camera. Now I am trying to build on that tutorial and have a single page that is transparent, but the rest of the pages should not be.

html, body, ion-app, ion-content, ion-page, .nav-decor {
    background-color: transparent !important;
}

The simple question is: How do I a make the HTML background for one page transparent, but not the others?

This is probably simple, but I am new to Ionic.

Body:
In your scss page(lets assume your page name is login),

page-login{
    background: transparent !important;
}

This will work. However, you will not see any difference if you wrapped some content inside . In such case, you need to give define transparent to

.content-md{
    background: transparent !imporant;
}


问:
Image not shown in TextBlock
I have a TextBlock I'm adding inlines to, some of which are images. This is for a Twitter application, so the images are emojis.

I have now encountered a strange issue where an emoji image is not displayed, but another emoji right next to the missing one works just fine. In the attached screenshot I'm using Snoop to look at the WPF structure, and as far as I can tell everything is identical for all the inline images. (I would be surprised if they weren't, though, because they are all put into the TextBlock in the same way).

The image source points to an image that actually does exist, so why isn't it displayed when the other emoji is displayed just fine?

Does anybody have any idea as to what can cause this strange issue?

For completion, this is the somewhat pseudo code that returns text with emojis as a list of Inline's:

```<code>List<Inline> inlines =  new List<Inline>();

foreach (Match match in Regex.Matches(text, emojiPattern)) {
    Uri src = new Uri("URL_TO_EMOJI");
    InlineUIContainer cont = new InlineUIContainer(new Image {
        Source = new BitmapImage(src)
    });
    inlines.Add(cont);
}

return inlines;
</code>```

Update

It seems this is a problem with many connections. My Twitter application displays various lists. If I put the user in the screenshot in a separate list, then I display only that list, the emojis are all displayed. If I display many other lists, and users, at the same time, the emoji problems reappears.

There is no difference if I use Twitters own emojis, or the CDN for Twemoji.

So apparently there seems to be some sort of limit as to how many separate images can be used. So how can this limit be extended, or even ignored?

答:
I never did find out about the connection limit, so I ended up downloading the images myself, and caching them so that I never download the same emoji more than once:

```<code>private readonly Dictionary<string, BitmapImage> EmojiCache = new Dictionary<string, BitmapImage>();

private BitmapImage GetEmoji(string emojiCode) {
    if (EmojiCache.ContainsKey(emojiCode)) {
        return EmojiCache[emojiCode];
    }

    WebClient client = new WebClient();
    byte[] emojiBytes = client.DownloadData($"https://twemoji.maxcdn.com/2/72x72/{emojiCode}.png");
    BitmapImage emojiImg = new BitmapImage();
    using (MemoryStream ms = new MemoryStream(emojiBytes)) {
        ms.Position = 0;
        emojiImg.BeginInit();
        emojiImg.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        emojiImg.CacheOption = BitmapCacheOption.OnLoad;
        emojiImg.UriSource = null;
        emojiImg.StreamSource = ms;
        emojiImg.EndInit();
    }

    EmojiCache.Add(emojiCode, emojiImg);

    return emojiImg;
}
</code>```

If anybody knows more about any connection limits in WPF that could cause the main issue, feel free to leave a comment or an answer on how to extend it.

Title: Image not shown in TextBlock

Body:
I have a TextBlock I'm adding inlines to, some of which are images. This is for a Twitter application, so the images are emojis.

I have now encountered a strange issue where an emoji image is not displayed, but another emoji right next to the missing one works just fine. In the attached screenshot I'm using Snoop to look at the WPF structure, and as far as I can tell everything is identical for all the inline images. (I would be surprised if they weren't, though, because they are all put into the TextBlock in the same way).

The image source points to an image that actually does exist, so why isn't it displayed when the other emoji is displayed just fine?

Does anybody have any idea as to what can cause this strange issue?

For completion, this is the somewhat pseudo code that returns text with emojis as a list of Inline's:

List<Inline> inlines =  new List<Inline>();

foreach (Match match in Regex.Matches(text, emojiPattern)) {
    Uri src = new Uri("URL_TO_EMOJI");
    InlineUIContainer cont = new InlineUIContainer(new Image {
        Source = new BitmapImage(src)
    });
    inlines.Add(cont);
}

return inlines;

Update

It seems this is a problem with many connections. My Twitter application displays various lists. If I put the user in the screenshot in a separate list, then I display only that list, the emojis are all displayed. If I display many other lists, and users, at the same time, the emoji problems reappears.

There is no difference if I use Twitters own emojis, or the CDN for Twemoji.

So apparently there seems to be some sort of limit as to how many separate images can be used. So how can this limit be extended, or even ignored?

Body:
I never did find out about the connection limit, so I ended up downloading the images myself, and caching them so that I never download the same emoji more than once:

private readonly Dictionary<string, BitmapImage> EmojiCache = new Dictionary<string, BitmapImage>();

private BitmapImage GetEmoji(string emojiCode) {
    if (EmojiCache.ContainsKey(emojiCode)) {
        return EmojiCache[emojiCode];
    }

    WebClient client = new WebClient();
    byte[] emojiBytes = client.DownloadData($"https://twemoji.maxcdn.com/2/72x72/{emojiCode}.png");
    BitmapImage emojiImg = new BitmapImage();
    using (MemoryStream ms = new MemoryStream(emojiBytes)) {
        ms.Position = 0;
        emojiImg.BeginInit();
        emojiImg.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        emojiImg.CacheOption = BitmapCacheOption.OnLoad;
        emojiImg.UriSource = null;
        emojiImg.StreamSource = ms;
        emojiImg.EndInit();
    }

    EmojiCache.Add(emojiCode, emojiImg);

    return emojiImg;
}

If anybody knows more about any connection limits in WPF that could cause the main issue, feel free to leave a comment or an answer on how to extend it.


问:
WebForm Data Binding to SQL Database
I'm learning the basics of WebForms by following this tutorial:

https://learn.microsoft.com/en-us/aspnet/web-forms/overview/presenting-and-managing-data/model-binding/updating-deleting-and-creating-data

I've been able to insert the data from the website directly into a database. I'm facing now another issue. After the button of the form is pressed, I'd like to get the inserted data in my code so I can perform some calculations and then insert the data into the database.

Is it possible to achieve this with the method suggested in the tutorial?

答:
You should make use of the addStudentForm_InsertItem() method as shown below.

```<code>public void addStudentForm_InsertItem()
{
    var item = new Student();

    TryUpdateModel(item);
    if (ModelState.IsValid)
    {
</code>```

//Do your modifications, calculations here, and set the updated properties on item.

```<code>        using (SchoolContext db = new SchoolContext())
        {
            db.Students.Add(item);
            db.SaveChanges();
        }
    }
}
</code>```

Title: WebForm Data Binding to SQL Database

Body:
You should make use of the addStudentForm_InsertItem() method as shown below.

public void addStudentForm_InsertItem()
{
    var item = new Student();

    TryUpdateModel(item);
    if (ModelState.IsValid)
    {

//Do your modifications, calculations here, and set the updated properties on item.

        using (SchoolContext db = new SchoolContext())
        {
            db.Students.Add(item);
            db.SaveChanges();
        }
    }
}


问:
How complex can an enum get before reading lines of data from a file is better (e.g. .csv)?
I have created part of a platformer game where I have an actor class, representing instances of objects and characters, and a type enum which denotes what data each actor will have (such as speed, attack, defence, etc).
Specifying all the data of each type seems somewhat tedious with hardcoded enum definitions.
E.g.

```<code>PLANE("Plane", 10, 10, 2, 0),
MISSILE("Missile", 1, 0, 0, 4);
</code>```

Would it be best to specify data in a file and read it instead?

答:
My answer to that question would now be: Take a DSL for it, for instance using Kotlin (similar things are possible in Groovy).

Without going into any detail, the following can be valid Kotlin (actually working code copied from a production system):

```<code>buildTreats {
    category(BEVERAGE) {
        treat(id = 2, key = "bonusfood.treat.appleJuice") {
            47.kcal
            0.5 of GLASS
        }
    …
    }
    …
}
</code>```

The advantage is that you have full code completion and compile-time checks that you just cannot have with a CSV file.

Body:
I have created part of a platformer game where I have an actor class, representing instances of objects and characters, and a type enum which denotes what data each actor will have (such as speed, attack, defence, etc).
Specifying all the data of each type seems somewhat tedious with hardcoded enum definitions.
E.g.

PLANE("Plane", 10, 10, 2, 0),
MISSILE("Missile", 1, 0, 0, 4);

Would it be best to specify data in a file and read it instead?

Body:
My answer to that question would now be: Take a DSL for it, for instance using Kotlin (similar things are possible in Groovy).

Without going into any detail, the following can be valid Kotlin (actually working code copied from a production system):

buildTreats {
    category(BEVERAGE) {
        treat(id = 2, key = "bonusfood.treat.appleJuice") {
            47.kcal
            0.5 of GLASS
        }
    …
    }
    …
}

The advantage is that you have full code completion and compile-time checks that you just cannot have with a CSV file.


问:
Adobe Granite HTML Library Manager
In Adobe Granite HTML library Manager, How "max data uri size" works?
I tried an image with a lot of data size in the configuration.But there is no
change.
Can someone tell me how this configuration works in AEM?

答:
The minification of css-files can auto-inline small resources (e.g. icons). The config-parameter htmllibmanager.maxDataUriSize steers maximum size for resources to be auto-inlined.

Here is an example css:

```<code>#tiny-icon {
    height: 32px;
    width: 32px;
    background-image: url("tiny-icon.gif");
}
</code>```

My sample-icon has a size of 360 bytes. With maxDataUriSize <= 360, the minified css file will look:

```<code>#tiny-icon{height:32px;width:32px;background-image:url("test-alex/tiny-icon.gif")}
</code>```

With maxDataUriSize > 360, the icon will be auto-inlined as data-url:

```<code>#tiny-icon{height:32px;width:32px;background-image:url("data:image/gif;base64,R0lGODlhIAAgAIQQAEeczSqmzligoGmarl6khnCdy3CpaBjo9Gbuk4HxcbLf1Gb35tnhhtna19T2NO/w7////////////////////////////////////////////////////////////////yH5BAEKABAALAAAAAAgACAAAAXlYCGOZCkOhBGsgOm+I6qycF3Ka9DaPErkO17NBxSSHshHY8lwOA6LhWJJpdaS1OYzOq1Wr0qmEyr1Vh/XrCNB7pobyJqazX0vk/JGk162J9EwemttdnB/NXuEfn+ALgKDdYuMLwIGfG5mjHgjAiKVBIpvmpsFlaUGBACRoqNKnqifAAF9rJpWsaiyAZherVWxAQK6BYW+WbksKyKSjFVNqcrKy5mjzmvDBTojvcZibNIm3LZzUAGBd92CCGR5rWFi61xy7tbxC0tGLwOVwuD5JvsM9DP3z0XAgQUN8sOWkMRBhjBCAAA7")}
</code>```

If you want to test it by yourself, please be aware that client-libs are cached. Either delete the cache in /var/clientlibs, or update the css file. Otherwise the configuration changes will have no effect, as you will still see the cached version of the clientlib.

Title: Adobe Granite HTML Library Manager

Body:
The minification of css-files can auto-inline small resources (e.g. icons). The config-parameter htmllibmanager.maxDataUriSize steers maximum size for resources to be auto-inlined.

Here is an example css:

#tiny-icon {
    height: 32px;
    width: 32px;
    background-image: url("tiny-icon.gif");
}

My sample-icon has a size of 360 bytes. With maxDataUriSize <= 360, the minified css file will look:

#tiny-icon{height:32px;width:32px;background-image:url("test-alex/tiny-icon.gif")}

With maxDataUriSize > 360, the icon will be auto-inlined as data-url:

#tiny-icon{height:32px;width:32px;background-image:url("data:image/gif;base64,R0lGODlhIAAgAIQQAEeczSqmzligoGmarl6khnCdy3CpaBjo9Gbuk4HxcbLf1Gb35tnhhtna19T2NO/w7////////////////////////////////////////////////////////////////yH5BAEKABAALAAAAAAgACAAAAXlYCGOZCkOhBGsgOm+I6qycF3Ka9DaPErkO17NBxSSHshHY8lwOA6LhWJJpdaS1OYzOq1Wr0qmEyr1Vh/XrCNB7pobyJqazX0vk/JGk162J9EwemttdnB/NXuEfn+ALgKDdYuMLwIGfG5mjHgjAiKVBIpvmpsFlaUGBACRoqNKnqifAAF9rJpWsaiyAZherVWxAQK6BYW+WbksKyKSjFVNqcrKy5mjzmvDBTojvcZibNIm3LZzUAGBd92CCGR5rWFi61xy7tbxC0tGLwOVwuD5JvsM9DP3z0XAgQUN8sOWkMRBhjBCAAA7")}

If you want to test it by yourself, please be aware that client-libs are cached. Either delete the cache in /var/clientlibs, or update the css file. Otherwise the configuration changes will have no effect, as you will still see the cached version of the clientlib.


问:
java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex
I am not sure what this error means.

```<code>Execution failed for task ':excelSior:packageAllDebugClassesForMultiDex'.
> java.util.zip.ZipException: duplicate entry: android/support/v4/util/TimeUtils.class
</code>```

I am currently using android-support-v4.jar for my libraries

```<code>dependencies {
    compile project(':addThisSDK')
    compile project(':centeredContentButton')
    compile project(':googleplayservices_lib')
    compile files('libs/adxtag2.4.6.jar')
    compile files('libs/android-support-v4.jar')
    compile files('libs/aws-android-sdk-1.7.1.1-debug.jar')
    compile files('libs/commons-lang-2.6.jar')
    compile files('libs/crittercism_v4_4_0_sdkonly.jar')
    compile files('libs/dd-plist.jar')
    compile files('libs/FiksuAndroidSDK_4.1.1.jar')
    compile files('libs/iqengines-sdk-barcode.jar')
    compile files('libs/irEventTracker-1.2.jar')
    compile files('libs/jolt-core-0.0.7.jar')
    compile files('libs/json-utils-0.0.7.jar')
    compile files('libs/jsoup-1.7.2.jar')
    compile files('libs/kooaba-api-v4-java.jar')
    compile 'com.android.support:multidex:1.0.0'
}
</code>```

Error does not show up during gradle sync. Just when I try to run the application

What could be the problem?

答:
This is because you have added a library and given its dependency on a module more than once.

In my case, I had added a library as a module and as a gradle dependency both.

Removing one source of adding library (I removed gradle dependency) solved my problem.

Body:
I am not sure what this error means.

Execution failed for task ':excelSior:packageAllDebugClassesForMultiDex'.
> java.util.zip.ZipException: duplicate entry: android/support/v4/util/TimeUtils.class

I am currently using android-support-v4.jar for my libraries

dependencies {
    compile project(':addThisSDK')
    compile project(':centeredContentButton')
    compile project(':googleplayservices_lib')
    compile files('libs/adxtag2.4.6.jar')
    compile files('libs/android-support-v4.jar')
    compile files('libs/aws-android-sdk-1.7.1.1-debug.jar')
    compile files('libs/commons-lang-2.6.jar')
    compile files('libs/crittercism_v4_4_0_sdkonly.jar')
    compile files('libs/dd-plist.jar')
    compile files('libs/FiksuAndroidSDK_4.1.1.jar')
    compile files('libs/iqengines-sdk-barcode.jar')
    compile files('libs/irEventTracker-1.2.jar')
    compile files('libs/jolt-core-0.0.7.jar')
    compile files('libs/json-utils-0.0.7.jar')
    compile files('libs/jsoup-1.7.2.jar')
    compile files('libs/kooaba-api-v4-java.jar')
    compile 'com.android.support:multidex:1.0.0'
}

Error does not show up during gradle sync. Just when I try to run the application

What could be the problem?