问:
JavaScript regular expression to validate input such as 2.4**6-0
I am trying to validate a line of input. it should be one or more integers. The integers can be separated by a single full stop or one or more asterisks. 0 is not valid, but -0 is. A full stop is not valid at the end of the line, but one or more asterisks are. So "2.4*-2.-0**" is valid.

I have tried using:

```<code>/^(?:(?:-0)|(?:-?[1-9]\d*)\.|\*+)*(?:(?:-0)|(?:-?[1-9]\d*))\**$/.test(myline)
</code>```

but this rejects input that has a mix of full stops and asterisks in it.

I do subsequently successfully parse out all the components of the string using:

```<code>var regEx = new RegExp("((?:-0)|(?:-?[1-9]\\d*))(\\.|\\*+|$)", "g"), result;
while((result = regEx.exec(myline)) !== null)
</code>```

I could concatenate the values of result[0] and result[1] from each pass of the while loop and at the end compare that with the original string. I was just hoping for a single test at the start before entering the loop with all its logic.

答:
The answer may be to test for invalid things rather than a completely valid string, such as:

```<code>if (/(?:[^-.*0-9])|(?:^[.*0])|(?:\d-)|(?:\.[.*])|(?:\*\.)|(?:[.*]-?0\d)|(?:[-.]$)|(?:-00)|(?:-[^0-9])|(?:[.*]0)|^$/.test(mydata))
</code>```

I have run a comprehensive set of test cases through this and have not found any problems.

Body:
I am trying to validate a line of input. it should be one or more integers. The integers can be separated by a single full stop or one or more asterisks. 0 is not valid, but -0 is. A full stop is not valid at the end of the line, but one or more asterisks are. So "2.4*-2.-0**" is valid.

I have tried using:

/^(?:(?:-0)|(?:-?[1-9]\d*)\.|\*+)*(?:(?:-0)|(?:-?[1-9]\d*))\**$/.test(myline)

but this rejects input that has a mix of full stops and asterisks in it.

I do subsequently successfully parse out all the components of the string using:

var regEx = new RegExp("((?:-0)|(?:-?[1-9]\\d*))(\\.|\\*+|$)", "g"), result;
while((result = regEx.exec(myline)) !== null)

I could concatenate the values of result[0] and result[1] from each pass of the while loop and at the end compare that with the original string. I was just hoping for a single test at the start before entering the loop with all its logic.

Body:
The answer may be to test for invalid things rather than a completely valid string, such as:

if (/(?:[^-.*0-9])|(?:^[.*0])|(?:\d-)|(?:\.[.*])|(?:\*\.)|(?:[.*]-?0\d)|(?:[-.]$)|(?:-00)|(?:-[^0-9])|(?:[.*]0)|^$/.test(mydata))

I have run a comprehensive set of test cases through this and have not found any problems.


来源: stackexchange

问:
Rearrange Methods in IntelliJ: visibility first, dependencies 2nd
I want to configure IntelliJ IDE (v2017.1, Ultimate Edition) so that it re-arranges my methods in the following order (using Settings / Editor / Code Style / Java) when I do "Rearrange":

According to visibility: public methods first, private methods last (in practice, I only have public and private methods)

According to dependencies, i.e. to the call order, as implemented with the option "Keep dependent methods together / depth-first order".

However, the 2nd rule is always prioritized so that public and private methods are mixed once I enable the "Keep dependent methods together" option. Is there a way to change the order of these different types of rules?

答: Please vote for the related request in YouTrack: https://youtrack.jetbrains.com/issue/IDEA-148129</p>

ContentLicense: CC BY-SA 3.0


问:
How to show a UITableViewCell as selected and still receive didDeselectRowAtIndexPath
I have a UITableView which when isEditing=YES shows the cells with standard iOS selection circular 'checkbox' (see picture below). Some of these are 'bookmarked' via CoreData.

tableView:willDisplayCell reads from CoreData and sets
cell.selected = YES;  for the bookmarked cells.

Trouble is that these 'bookmarked' cells do not respond to

```<code>tableView:didDeselectRowAtIndexPath
</code>```

or

```<code>tableView:didSelectRowAtIndexPath
</code>```

Whereas the same callbacks work fine on cells with cell.selected=NO;

The image shows a selected cell above a non selected cell.

This is executed inside

```<code>- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

 if (tableView.isEditing)
    { [cell setSelected:[self isCellFave:indexPath]];  }
</code>```

Where isCellFave does

```<code>- (BOOL) isCellFave:(NSIndexPath *) indexPathIn
{
    BOOL isSelected = NO;
     // Check if this cell is a favourite
    NSError *error;

    NSString * id = [self getIDFromIndexPath:IndexPathIn];

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
    request.predicate = [NSPredicate predicateWithFormat:@"( id = %@ )", id];
    request.sortDescriptors = @[[[NSSortDescriptor alloc] initWithKey:@"sort1" ascending:YES selector:@selector(caseInsensitiveCompare:)]];

    NSArray *fetchedObjects = [ManagedContext executeFetchRequest:request error:&error];

    if ([fetchedObjects count] !=0) //if a result then it is a fave
    {
        // When we set a cell as selected, all gestures stop working - so we can't deselect it.
        isSelected=YES;
    }
    return isSelected;
}
</code>```

答:
Try to use these codes.

```<code>   - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
     if (tableView.isEditing) {
          [cell setSelected:[self isCellFave:indexPath]];
          [cell  addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(unselectRow:)]];
          }
      }
    }
</code>```

Then add a tap gesture handler

```<code>- (void)unselectRow:(UITapGestureRecognizer *)sender {
    UITableViewCell *cell  = (UITableViewCell *)     sender.view;
    cell.selected = NO;
}
</code>```

Body:
I have a UITableView which when isEditing=YES shows the cells with standard iOS selection circular 'checkbox' (see picture below). Some of these are 'bookmarked' via CoreData.

tableView:willDisplayCell reads from CoreData and sets
cell.selected = YES;  for the bookmarked cells.

Trouble is that these 'bookmarked' cells do not respond to

tableView:didDeselectRowAtIndexPath

or

tableView:didSelectRowAtIndexPath

Whereas the same callbacks work fine on cells with cell.selected=NO;

The image shows a selected cell above a non selected cell.

This is executed inside

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

 if (tableView.isEditing)
    { [cell setSelected:[self isCellFave:indexPath]];  }

Where isCellFave does

- (BOOL) isCellFave:(NSIndexPath *) indexPathIn
{
    BOOL isSelected = NO;
     // Check if this cell is a favourite
    NSError *error;

    NSString * id = [self getIDFromIndexPath:IndexPathIn];

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
    request.predicate = [NSPredicate predicateWithFormat:@"( id = %@ )", id];
    request.sortDescriptors = @[[[NSSortDescriptor alloc] initWithKey:@"sort1" ascending:YES selector:@selector(caseInsensitiveCompare:)]];

    NSArray *fetchedObjects = [ManagedContext executeFetchRequest:request error:&error];

    if ([fetchedObjects count] !=0) //if a result then it is a fave
    {
        // When we set a cell as selected, all gestures stop working - so we can't deselect it.
        isSelected=YES;
    }
    return isSelected;
}

Body:
Try to use these codes.

   - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
     if (tableView.isEditing) {
          [cell setSelected:[self isCellFave:indexPath]];
          [cell  addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(unselectRow:)]];
          }
      }
    }

Then add a tap gesture handler

- (void)unselectRow:(UITapGestureRecognizer *)sender {
    UITableViewCell *cell  = (UITableViewCell *)     sender.view;
    cell.selected = NO;
}


问:
Core data with GCD
I was exploring GCD with core data. I know that managed object context is not thread safe.

I created private context with option "NSPrivateQueueConcurrencyType". As per document I have to use performBlock or performBlockAndWait to do any operation with context, it will do that operation in its own private thread. My questions are,

What are the operation I have to do inside perform block? Is it only accessing the context object or using managed object as well?

Even if I insert a new object to database within "DispatchQueue.global().async"(without using perform block), it works fine. Why? (It is a different thread)

Is that ok doing database operation in different thread, if we create context with "NSPrivateQueueConcurrencyType"?

I can use perform block for every database operation, but our project already has lots of code which are running in private queue. Please help me to understand this better.

答:
This answer is conclusion of answer given by Sandeep Bhandari. Here I assume everyone is clear with Thread and Queue concepts.

Always managed object context should be accessed from single thread at any point of time, because it is not thread safe. If we are using context in multiple thread, we should make sure that it is serialised, so that no two threads are accessing same context at same time. If it does it will crash.

iOS 5 and later, Apple has provided 3 ways to create the context.

confinementConcurrencyType(Deprecated in iOS 10): If you create context with this option, it is your duty to make sure that you are doing all database operation in a thread which created this context.

privateQueueConcurrencyType: If we are using this option to create context,  it will create its own internal queue to crate this context and to make sure that all database operation happens in same thread. It will use internal queue only if you perform all your task with this context inside performBlock or performBlockAndWait. If you are using any other queue to do any database operation with this context it will work, if no two thread is accessing at same time. If two threads are accessing it, this will crash. It is very hard to manage this, since that task execution happens at run time depending on resource availability. This type of issues cannot be reproduce that easily. So use those performBlock API to do any database operation with this context.

mainQueueConcurrencyType: If you are using this option to create the context, it will create managed object context in main thread. You need to do any database operation with this context in main thread. You can use performBlock here as well to make sure all task happens in main thread. Even doing any operation with this context will work fine in other thread, if no two thread is accessing at same time.

Title: Core data with GCD


问:
Java overloading methods with generic and a collection of a generic
Having an interface with these two methods:

```<code>void add(T result);
void add(List<T> result);
</code>```

I was expecting Java on runtime will call the appropriated method:

```<code>final U result = getResult();
myInterface.add(result);
</code>```

If U is a list I thought second method would be called, but always the first one is called.
Why this behavior? What should be the correct way to achieve that?

答:
It depends on the compile-time type of U. If U is unbounded, the compiler can't determine whether it's a List or a String or your aunt Hilda.
So the "ungenericized" code becomes:

```<code>final Object result = getResult();
myInterface.add(result);
</code>```

However, if U is actually <U extends List<?>>, the compiler can narrow down the possibilities (with your help) and the "ungenericized" code becomes:

```<code>final List result = getResult();
myInterface.add(result);
</code>```

giving you the expected overloaded method call.

Body:
Having an interface with these two methods:

void add(T result);
void add(List<T> result);

I was expecting Java on runtime will call the appropriated method:

final U result = getResult();
myInterface.add(result);

If U is a list I thought second method would be called, but always the first one is called.
Why this behavior? What should be the correct way to achieve that?

Body:
It depends on the compile-time type of U. If U is unbounded, the compiler can't determine whether it's a List or a String or your aunt Hilda.
So the "ungenericized" code becomes:

final Object result = getResult();
myInterface.add(result);

However, if U is actually <U extends List<?>>, the compiler can narrow down the possibilities (with your help) and the "ungenericized" code becomes:

final List result = getResult();
myInterface.add(result);

giving you the expected overloaded method call.


问:
How to send file name to my gmail with PHP and HTML form?
I would like if someone upload a file gets the name of the file to my gmail.For example, I would like you to email arrives "FileName: background.jpg"

PHP code:

```<code><?php
   if(isset($_FILES['file_array'])){
      $name_array = $_FILES['file_array']['name'];
      $tmp_name_array = $_FILES['file_array']['tmp_name'];
      $type_array = $_FILES['file_array']['type'];
      $size_array = $_FILES['file_array']['size'];
      $error_array = $_FILES['file_array']['error'];
      for($i = 0; $i < count($tmp_name_array); $i++){
         if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
            header("Location:");
         }
      }
   }
?>
</code>```

I've tried to like this:

```<code><?php
   if(isset($_FILES['file_array'])){
      $name_array = $_FILES['file_array']['name'];
      $tmp_name_array = $_FILES['file_array']['tmp_name'];
      $type_array = $_FILES['file_array']['type'];
      $size_array = $_FILES['file_array']['size'];
      $error_array = $_FILES['file_array']['error'];
      $za = "mygmail@gmail.com";
      $od  = "Od: " . $Email . "\r\n";
      $info .= "FileName:" .$name_array. "\r\n";
         for($i = 0; $i < count($tmp_name_array); $i++){
           if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
              header("Location:");
              mail($za, $od, $info);
           }
        }
    }
?>
</code>```

But I just received in the mail "FileName: array".

HTML code:

```<code><form class="contact_form" action="../assets/php/postavi_oglas.php" method="post" enctype="multipart/form-data">
    <label>Izaberite fotografije:</label>
    <input class="contact_area" type="file" name="file_array[]">
    <input class="contact_area" type="file" name="file_array[]">
    <input class="contact_area" type="file" name="file_array[]">
    <input class="contact_area" type="file" name="file_array[]">
    <input class="contact_area" type="file" name="file_array[]">
    <input class="btn btn-theme" type="submit" value="Posalji Fotografije">
</form>
</code>```

答:
it says array because it is array and need to be in the loop</p>

```<code>for($i = 0; $i < count($tmp_name_array); $i++){
    if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
    // a array
     $fname=$name_array[$i];
     $info= "FileName:" .$fname. "\r\n";
     header("Location:");
     mail($za, $od, $info);
       }
</code>```

Body:
I would like if someone upload a file gets the name of the file to my gmail.For example, I would like you to email arrives "FileName: background.jpg"

PHP code:

<?php
   if(isset($_FILES['file_array'])){
      $name_array = $_FILES['file_array']['name'];
      $tmp_name_array = $_FILES['file_array']['tmp_name'];
      $type_array = $_FILES['file_array']['type'];
      $size_array = $_FILES['file_array']['size'];
      $error_array = $_FILES['file_array']['error'];
      for($i = 0; $i < count($tmp_name_array); $i++){
         if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
            header("Location:");
         }
      }
   }
?>

I've tried to like this:

<?php
   if(isset($_FILES['file_array'])){
      $name_array = $_FILES['file_array']['name'];
      $tmp_name_array = $_FILES['file_array']['tmp_name'];
      $type_array = $_FILES['file_array']['type'];
      $size_array = $_FILES['file_array']['size'];
      $error_array = $_FILES['file_array']['error'];
      $za = "mygmail@gmail.com";
      $od  = "Od: " . $Email . "\r\n";
      $info .= "FileName:" .$name_array. "\r\n";
         for($i = 0; $i < count($tmp_name_array); $i++){
           if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
              header("Location:");
              mail($za, $od, $info);
           }
        }
    }
?>

But I just received in the mail "FileName: array".

HTML code:

<form class="contact_form" action="../assets/php/postavi_oglas.php" method="post" enctype="multipart/form-data">
    Izaberite fotografije:
    <input class="contact_area" type="file" name="file_array[]">
    <input class="contact_area" type="file" name="file_array[]">
    <input class="contact_area" type="file" name="file_array[]">
    <input class="contact_area" type="file" name="file_array[]">
    <input class="contact_area" type="file" name="file_array[]">
    <input class="btn btn-theme" type="submit" value="Posalji Fotografije">
</form>

Body:
it says array because it is array and need to be in the loop

for($i = 0; $i < count($tmp_name_array); $i++){
    if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
    // a array
     $fname=$name_array[$i];
     $info= "FileName:" .$fname. "\r\n";
     header("Location:");
     mail($za, $od, $info);
       }


问:
How to change browser from IE to Chrome on Hyperlink click
I have one application which default open in IE browser. On the home page, there is link. if we click that link, application open in another tab of IE but I want to change the browser also.

```<code><!DOCTYPE html>
<html>
<body>

<p>Open link in a chrome browser <a href="https://www.dotnet-tutorial.com" target="_blank">Visit Dotnet Tutorial</a></p>

</body>
</html>
</code>```

If I click on Visit Dotnet Tutorial, it should open in chrome. How to setup browser also in Hyperlink.

Please help on this.
thanks

答:
This is not possible from the HTML.

Browser is chosen based on the Operating System settings.

Yours is obviously IE.

If you own the dotnet-tutorial page, you can set up a browser check there
and add a notification like:
"This page works best in Google Chrome"

This question explains how to detect browser:
How to detect Safari, Chrome, IE, Firefox and Opera browser?

Body:
I have one application which default open in IE browser. On the home page, there is link. if we click that link, application open in another tab of IE but I want to change the browser also.

<!DOCTYPE html>

Open link in a chrome browser Visit Dotnet Tutorial

If I click on Visit Dotnet Tutorial, it should open in chrome. How to setup browser also in Hyperlink.

Please help on this.
thanks

ContentLicense: CC BY-SA 4.0


问:
I want to merge all txt files to 1 txt files, but i get an error if a file is empty
If i run it 1 time it works,the second time i runit the 2nd txt file is empty so the script stops running on this line:

```<code>strTxt = strTxt & txt.ReadAll
</code>```

How can I solve it, that it doesn't stop if a file is empty?

```<code>Sub MergeTxtFiles()
    Dim fso As Object, txt As Object, strTxt As String
    Dim strParentFldr As String, strFile As String
    Dim iFreeFile As Integer, strOutPutFile As String

    KillProperly "D:\users\gf05856\Documents\TEst\RVA002ALL.txt"
    Call DeleteLine1
    Call DeleteLine2

    strOutPutFile = "D:\users\gf05856\Documents\TEst\RVA002ALL.txt"
    strParentFldr = "D:\users\gf05856\Documents\TEst"

    Set fso = CreateObject("Scripting.FileSystemObject")

    strFile = Dir(strParentFldr & "\Register van aankomst 002*.txt")

    If Len(strFile) > 0 Then
        Do
            Set txt = fso.OpenTextFile(strParentFldr & "\" & strFile)
            strTxt = strTxt & txt.ReadAll
            strFile = Dir
        Loop Until Len(strFile) = 0
        If Left(strTxt, 2) = vbCrLf Then strTxt = Mid(strTxt, 2)
    End If

    iFreeFile = FreeFile

    Open strOutPutFile For Output As #iFreeFile
    Print #iFreeFile, strTxt
    Close #iFreeFile

    Set txt = Nothing
    Set fso = Nothing
End Sub

Public Sub KillProperly(Killfile As String)
    If Len(Dir$(Killfile)) > 0 Then
        SetAttr Killfile, vbNormal
        Kill Killfile
    End If
End Sub

Sub DeleteLine1()
    Const ForReading = 1
    Const ForWriting = 2

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D (Histo).txt", ForReading)

    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        If InStr(strLine, "CLIFOUPAYCODE") = 0 Then
            strNewContents = strNewContents & strLine & vbCrLf
        End If
    Loop

    objFile.Close
    Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D (Histo).txt", ForWriting)

    objFile.Write strNewContents
    objFile.Close
End Sub

Sub DeleteLine2()
    Const ForReading = 1
    Const ForWriting = 2

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D.txt", ForReading)

    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        If InStr(strLine, "CLIFOUPAYCODE") = 0 Then
            strNewContents = strNewContents & strLine & vbCrLf
        End If
    Loop

    objFile.Close
    Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D.txt", ForWriting)

    objFile.Write strNewContents
    objFile.Close
End Sub
</code>```

答:
.ReadAll() fails on empty/zero length/size files:

```<code>>> WScript.Echo oFS.GetFile("x").Size
>> Set f = oFS.OpenTextFile("x")
>> s = f.ReadAll()
>>
0
Error Number:       62
Error Description:  Eingabe hinter Dateiende.
>>
</code>```

So you should check the .Size to determine whether the file should be opened at all.

(BTW: What's the real world problem you try to solve?)

Body:
If i run it 1 time it works,the second time i runit the 2nd txt file is empty so the script stops running on this line:

strTxt = strTxt & txt.ReadAll

How can I solve it, that it doesn't stop if a file is empty?

Sub MergeTxtFiles()
    Dim fso As Object, txt As Object, strTxt As String
    Dim strParentFldr As String, strFile As String
    Dim iFreeFile As Integer, strOutPutFile As String

    KillProperly "D:\users\gf05856\Documents\TEst\RVA002ALL.txt"
    Call DeleteLine1
    Call DeleteLine2

    strOutPutFile = "D:\users\gf05856\Documents\TEst\RVA002ALL.txt"
    strParentFldr = "D:\users\gf05856\Documents\TEst"

    Set fso = CreateObject("Scripting.FileSystemObject")

    strFile = Dir(strParentFldr & "\Register van aankomst 002*.txt")

    If Len(strFile) > 0 Then
        Do
            Set txt = fso.OpenTextFile(strParentFldr & "\" & strFile)
            strTxt = strTxt & txt.ReadAll
            strFile = Dir
        Loop Until Len(strFile) = 0
        If Left(strTxt, 2) = vbCrLf Then strTxt = Mid(strTxt, 2)
    End If

    iFreeFile = FreeFile

    Open strOutPutFile For Output As #iFreeFile
    Print #iFreeFile, strTxt
    Close #iFreeFile

    Set txt = Nothing
    Set fso = Nothing
End Sub

Public Sub KillProperly(Killfile As String)
    If Len(Dir$(Killfile)) > 0 Then
        SetAttr Killfile, vbNormal
        Kill Killfile
    End If
End Sub

Sub DeleteLine1()
    Const ForReading = 1
    Const ForWriting = 2

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D (Histo).txt", ForReading)

    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        If InStr(strLine, "CLIFOUPAYCODE") = 0 Then
            strNewContents = strNewContents & strLine & vbCrLf
        End If
    Loop

    objFile.Close
    Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D (Histo).txt", ForWriting)

    objFile.Write strNewContents
    objFile.Close
End Sub

Sub DeleteLine2()
    Const ForReading = 1
    Const ForWriting = 2

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D.txt", ForReading)

    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        If InStr(strLine, "CLIFOUPAYCODE") = 0 Then
            strNewContents = strNewContents & strLine & vbCrLf
        End If
    Loop

    objFile.Close
    Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D.txt", ForWriting)

    objFile.Write strNewContents
    objFile.Close
End Sub

Body:
.ReadAll() fails on empty/zero length/size files:

>> WScript.Echo oFS.GetFile("x").Size
>> Set f = oFS.OpenTextFile("x")
>> s = f.ReadAll()
>>
0
Error Number:       62
Error Description:  Eingabe hinter Dateiende.
>>

So you should check the .Size to determine whether the file should be opened at all.

(BTW: What's the real world problem you try to solve?)


问:
Avoiding duplicates with factory_boy factories
I'm using factory_boy to create test fixtures. I've got two simple factories, backed by SQLAlchemy models (simplified below).

I'd like to be able to call AddressFactory.create() multiple times, and have it create a Country if it doesn't already exist, otherwise I want it to re-use the existing record.

```<code>class CountryFactory(factory.Factory):
    FACTORY_FOR = Country

    cc = "US"
    name = "United States"

class AddressFactory(factory.Factory):
    FACTORY_FOR = Address

    name = "Joe User"
    city = "Seven Mile Beach"
    country = factory.SubFactory(CountryFactory, cc="KY", name="Cayman Islands")
</code>```

My question is: how can I set up these factories so that factory_boy doesn't try to create a new Country every time it creates an Address?

答:
Another hacky solution is to overwrite the create method of the factory in a way that the object is searched by a querying and caching the results.

This simple example does no filtering on the **kwargs though:

```<code>class StaticFactory(SQLAlchemyModelFactory):

    counter = 0
    cache = []
    model = None

    @classmethod
    def create(cls, **kwargs):
        if not cls.cache:
            cls.cache = your_session.query(cls.model).all()
        instance = cls.cache[cls.counter]
        cls.counter = (cls.counter + 1) % len(cls.cache)
        return instance
</code>```

Body:
I'm using factory_boy to create test fixtures. I've got two simple factories, backed by SQLAlchemy models (simplified below).

I'd like to be able to call AddressFactory.create() multiple times, and have it create a Country if it doesn't already exist, otherwise I want it to re-use the existing record.

class CountryFactory(factory.Factory):
    FACTORY_FOR = Country

    cc = "US"
    name = "United States"

class AddressFactory(factory.Factory):
    FACTORY_FOR = Address

    name = "Joe User"
    city = "Seven Mile Beach"
    country = factory.SubFactory(CountryFactory, cc="KY", name="Cayman Islands")

My question is: how can I set up these factories so that factory_boy doesn't try to create a new Country every time it creates an Address?

Body:
Another hacky solution is to overwrite the create method of the factory in a way that the object is searched by a querying and caching the results.

This simple example does no filtering on the **kwargs though:

class StaticFactory(SQLAlchemyModelFactory):

    counter = 0
    cache = []
    model = None

    @classmethod
    def create(cls, **kwargs):
        if not cls.cache:
            cls.cache = your_session.query(cls.model).all()
        instance = cls.cache[cls.counter]
        cls.counter = (cls.counter + 1) % len(cls.cache)
        return instance


问:
Java ArrayList Index
```<code>int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");
</code>```

Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?

output:

banana

答:
Using an Array:

```<code>String[] fruits = new String[3]; // make a 3 element array
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
System.out.println(fruits[1]); // output the second element
</code>```

Using a List

```<code>ArrayList<String> fruits = new ArrayList<String>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
System.out.println(fruits.get(1));
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java ArrayList Index

Body:
int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");

Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?

output:

banana

Body:
Using an Array:

String[] fruits = new String[3]; // make a 3 element array
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
System.out.println(fruits[1]); // output the second element

Using a List

ArrayList<String> fruits = new ArrayList<String>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
System.out.println(fruits.get(1));


问:
Java generic parameter method to avoid code duplication
I have a function that parse an object. But this function is required in two services and the parameter have same class name, but different package name. What i need is to avoid duplicated code.

Suppose the function is:

```<code>    private HashMap<String, Integer> getPagination(PagingRequestType pagingRequestType) {
        int pageSize = 200;
        int pageNumber = 1;
        if(pagingRequestType != null) {
            if (pagingRequestType.getNumberOfRecordsPerPage() != 0) {
                pageSize = pagingRequestType.getNumberOfRecordsPerPage();
            }
            if (pagingRequestType.getStartAtRecordNumber() != 0) {
                pageNumber = pagingRequestType.getStartAtRecordNumber();
            }
        }
        HashMap<String, Integer> result = new HashMap<>();
        result.put("pageNumber", pageNumber);
        result.put("pageSize", pageSize);
        return result;
    }
</code>```

Possible function calls:

```<code>- getPagination(new Abc.PagingRequestType());
- getPagination(new Xyz.PagingRequestType());
</code>```

PagingRequestType is an auto-generated class in two different    packages. The function needs to be implemented once and used in both    services.

Thanks.

答:
If you can modify your PagingRequestType classes, it will be a good idea to use a common interface:

```<code>class Abc.PagingRequestType implements PagingRequestType
class Xyz.PagingRequestType implements PagingRequestType

interface PagingRequestType {
    getNumberOfRecordsPerPage();
    getStartAtRecordNumber();
}
</code>```

Body:
I have a function that parse an object. But this function is required in two services and the parameter have same class name, but different package name. What i need is to avoid duplicated code.

Suppose the function is:

    private HashMap<String, Integer> getPagination(PagingRequestType pagingRequestType) {
        int pageSize = 200;
        int pageNumber = 1;
        if(pagingRequestType != null) {
            if (pagingRequestType.getNumberOfRecordsPerPage() != 0) {
                pageSize = pagingRequestType.getNumberOfRecordsPerPage();
            }
            if (pagingRequestType.getStartAtRecordNumber() != 0) {
                pageNumber = pagingRequestType.getStartAtRecordNumber();
            }
        }
        HashMap<String, Integer> result = new HashMap<>();
        result.put("pageNumber", pageNumber);
        result.put("pageSize", pageSize);
        return result;
    }

Possible function calls:

- getPagination(new Abc.PagingRequestType());
- getPagination(new Xyz.PagingRequestType());

PagingRequestType is an auto-generated class in two different    packages. The function needs to be implemented once and used in both    services.

Thanks.

Body:
If you can modify your PagingRequestType classes, it will be a good idea to use a common interface:

class Abc.PagingRequestType implements PagingRequestType
class Xyz.PagingRequestType implements PagingRequestType

interface PagingRequestType {
    getNumberOfRecordsPerPage();
    getStartAtRecordNumber();
}


问:
npm is failing to compile – uikit3
I've just started using UIKit3 (getuitkit.com) and I keep getting this error when npm run watch is running – I also can't use npm run compile either. Any ideas?
This is the error I get with watch...

```<code>[compile-less] /Users/Michael/Sites/uikit-3/build/icons.js:10
glob(custom, (err, folders) =>
                            ^^
SyntaxError: Unexpected token =>
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3
[compile-less] [nodemon] app crashed - waiting for file changes before starting...
</code>```

And this for compile...

```<code>/Users/Michael/Sites/uikit-3/build/icons.js:10
glob(custom, (err, folders) =>
                            ^^
SyntaxError: Unexpected token =>
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

npm ERR! Darwin 16.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "icons"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! uikit@3.0.0-beta.18 icons: `node build/icons`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the uikit@3.0.0-beta.18 icons script 'node build/icons'.
npm ERR! This is most likely a problem with the uikit package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node build/icons
npm ERR! You can get their info via:
npm ERR!     npm owner ls uikit
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Michael/Sites/uikit-3/npm-debug.log

npm ERR! Darwin 16.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "compile-less"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! uikit@3.0.0-beta.18 compile-less: `npm run icons && node build/less`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the uikit@3.0.0-beta.18 compile-less script 'npm run icons && node build/less'.
npm ERR! This is most likely a problem with the uikit package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run icons && node build/less
npm ERR! You can get their info via:
npm ERR!     npm owner ls uikit
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Michael/Sites/uikit-3/npm-debug.log

npm ERR! Darwin 16.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "compile"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! uikit@3.0.0-beta.18 compile: `npm run compile-less && npm run compile-js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the uikit@3.0.0-beta.18 compile script 'npm run compile-less && npm run compile-js'.
npm ERR! This is most likely a problem with the uikit package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run compile-less && npm run compile-js
npm ERR! You can get their info via:
npm ERR!     npm owner ls uikit
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Michael/Sites/uikit-3/npm-debug.log
</code>```

答: You seem to be running node v0.12.0. UIkit's build tools require a minimum version of 4.4+. Please update to a current Node version. https://nodejs.org/en/</p>

Title: npm is failing to compile – uikit3

Body:
I've just started using UIKit3 (getuitkit.com) and I keep getting this error when npm run watch is running – I also can't use npm run compile either. Any ideas?
This is the error I get with watch...

[compile-less] /Users/Michael/Sites/uikit-3/build/icons.js:10
glob(custom, (err, folders) =>
                            ^^
SyntaxError: Unexpected token =>
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3
[compile-less] [nodemon] app crashed - waiting for file changes before starting...

And this for compile...

/Users/Michael/Sites/uikit-3/build/icons.js:10
glob(custom, (err, folders) =>
                            ^^
SyntaxError: Unexpected token =>
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

npm ERR! Darwin 16.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "icons"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! uikit@3.0.0-beta.18 icons: `node build/icons`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the uikit@3.0.0-beta.18 icons script 'node build/icons'.
npm ERR! This is most likely a problem with the uikit package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node build/icons
npm ERR! You can get their info via:
npm ERR!     npm owner ls uikit
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Michael/Sites/uikit-3/npm-debug.log

npm ERR! Darwin 16.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "compile-less"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! uikit@3.0.0-beta.18 compile-less: `npm run icons && node build/less`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the uikit@3.0.0-beta.18 compile-less script 'npm run icons && node build/less'.
npm ERR! This is most likely a problem with the uikit package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run icons && node build/less
npm ERR! You can get their info via:
npm ERR!     npm owner ls uikit
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Michael/Sites/uikit-3/npm-debug.log

npm ERR! Darwin 16.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "compile"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code ELIFECYCLE
npm ERR! uikit@3.0.0-beta.18 compile: `npm run compile-less && npm run compile-js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the uikit@3.0.0-beta.18 compile script 'npm run compile-less && npm run compile-js'.
npm ERR! This is most likely a problem with the uikit package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run compile-less && npm run compile-js
npm ERR! You can get their info via:
npm ERR!     npm owner ls uikit
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Michael/Sites/uikit-3/npm-debug.log


答:
The obvious answer is not to auto-generate PagingRequestType in two places.

If you can't do this, you need the two classes to implement a common interface, through which the requisite fields (getNumberOfRecordsPerPage and getStartAtRecordNumber) are available.

If you can't change the classes, you can create an interface with these fields:

```<code>interface YourInterface {
  int getNumberOfRecordsPerPage();
  int getStartAtRecordNumber();
}
</code>```

and implement for the two PagingRequestTypes:

```<code>class AbcYourInterface implements YourInterface {
  final Abc.PagingRequestType delegate;  // Set in constructor.

  @Override public int getNumberOfRecordsPerPage() {
   return delegate.getNumberOfRecordsPerPage();
  }

  // Same for other method.
}
</code>```

If all else fails, pass in the class fields as separate parameters:

```<code>private HashMap<String, Integer> getPagination(int numberOfRecordsPerPage, int startAtRecordNumber) {
</code>```

using some "special" value to indicate null, e.g. 0, since the conditional is a no-op if both parameters are zero.

Title: Java generic parameter method to avoid code duplication

Body:
The obvious answer is not to auto-generate PagingRequestType in two places.

If you can't do this, you need the two classes to implement a common interface, through which the requisite fields (getNumberOfRecordsPerPage and getStartAtRecordNumber) are available.

If you can't change the classes, you can create an interface with these fields:

interface YourInterface {
  int getNumberOfRecordsPerPage();
  int getStartAtRecordNumber();
}

and implement for the two PagingRequestTypes:

class AbcYourInterface implements YourInterface {
  final Abc.PagingRequestType delegate;  // Set in constructor.

  @Override public int getNumberOfRecordsPerPage() {
   return delegate.getNumberOfRecordsPerPage();
  }

  // Same for other method.
}

If all else fails, pass in the class fields as separate parameters:

private HashMap<String, Integer> getPagination(int numberOfRecordsPerPage, int startAtRecordNumber) {

using some "special" value to indicate null, e.g. 0, since the conditional is a no-op if both parameters are zero.


答:
You got array here, because you send one in your mail. Just use it like code below and send just on email instead of one email by file. I you like this behavior more.</p>

```<code> $info = '';

 for($i = 0; $i < count($tmp_name_array); $i++){
    if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
       $info .= 'Filename '.$i.': '.$name_array[$i]. "\r\n";
    }
 }

 mail($za, $od, $info);
 header("Location:");
</code>```

Title: How to send file name to my gmail with PHP and HTML form?

Body:
You got array here, because you send one in your mail. Just use it like code below and send just on email instead of one email by file. I you like this behavior more.

 $info = '';

 for($i = 0; $i < count($tmp_name_array); $i++){
    if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
       $info .= 'Filename '.$i.': '.$name_array[$i]. "\r\n";
    }
 }

 mail($za, $od, $info);
 header("Location:");


问:
Apply Middleware to all routes except `setup/*` in Laravel 5.4
I'm experimenting with Middleware in my Laravel application. I currently have it set up to run on every route for an authenticated user, however, I want it to ignore any requests that begin with the setup URI.

Here is what my CheckOnboarding middleware method looks like:

```<code>public function handle($request, Closure $next)
{
    /**
    * Check to see if the user has completed the onboarding, if not redirect.
    * Also checks that the requested URI isn't the setup route to ensure there isn't a redirect loop.
    */
    if ($request->user()->onboarding_complete == false && $request->path() != 'setup') {
        return redirect('setup');
    } else {
        return $next($request);
    }
}
</code>```

This is being used in my routes like this:

```<code>Route::group(['middleware' => ['auth','checkOnboarding']], function () {
    Route::get('/home', 'HomeController@index');
    Route::get('/account', 'AccountController@index');

    Route::group(['prefix' => 'setup'], function () {
        Route::get('/', 'OnboardingController@index')->name('setup');
        Route::post('/settings', 'SettingsController@store');
    });
});
</code>```

Now, if I go to /home or /account I get redirected to /setup as you would expect. This originally caused a redirect loop error hence why & $request->path() != 'setup' is in the Middleware.

I feel like this is a really clunky way of doing it, and obviously doesn't match anything after setup like the setup/settings route I have created.

Is there a better way to have this Middleware run on all routes for a user, but also set certain routes that should be exempt from this check?

答:
There's nothing wrong with what you're doing, however, I would suggest splitting your route groups up instead i.e.:

```<code>Route::group(['middleware' => ['auth', 'checkOnboarding']], function () {
    Route::get('/home', 'HomeController@index');
    Route::get('/account', 'AccountController@index');
});

Route::group(['prefix' => 'setup', 'middleware' => 'auth'], function () {
    Route::get('/', 'OnboardingController@index')->name('setup');
    Route::post('/settings', 'SettingsController@store');
});
</code>```

Alternatively, have a parent group for your auth:

```<code>Route::group(['middleware' => 'auth'], function () {

    Route::group(['middleware' => 'checkOnboarding'], function () {
        Route::get('/home', 'HomeController@index');
        Route::get('/account', 'AccountController@index');
    });

    Route::group(['prefix' => 'setup'], function () {
        Route::get('/', 'OnboardingController@index')->name('setup');
        Route::post('/settings', 'SettingsController@store');
    });
});
</code>```

This will also mean you can remove the extra condition in your middleware:

```<code>/**
 * Check to see if the user has completed the onboarding, if not redirect.
 * Also checks that the requested URI isn't the setup route to ensure there isn't a redirect loop.
 */
return $request->user()->onboarding_complete ? $next($request) : redirect('setup');
</code>```

Hope this helps!

Body:
I'm experimenting with Middleware in my Laravel application. I currently have it set up to run on every route for an authenticated user, however, I want it to ignore any requests that begin with the setup URI.

Here is what my CheckOnboarding middleware method looks like:

public function handle($request, Closure $next)
{
    /**
    * Check to see if the user has completed the onboarding, if not redirect.
    * Also checks that the requested URI isn't the setup route to ensure there isn't a redirect loop.
    */
    if ($request->user()->onboarding_complete == false && $request->path() != 'setup') {
        return redirect('setup');
    } else {
        return $next($request);
    }
}

This is being used in my routes like this:

Route::group(['middleware' => ['auth','checkOnboarding']], function () {
    Route::get('/home', 'HomeController@index');
    Route::get('/account', 'AccountController@index');

    Route::group(['prefix' => 'setup'], function () {
        Route::get('/', 'OnboardingController@index')->name('setup');
        Route::post('/settings', 'SettingsController@store');
    });
});

Now, if I go to /home or /account I get redirected to /setup as you would expect. This originally caused a redirect loop error hence why & $request->path() != 'setup' is in the Middleware.

I feel like this is a really clunky way of doing it, and obviously doesn't match anything after setup like the setup/settings route I have created.

Is there a better way to have this Middleware run on all routes for a user, but also set certain routes that should be exempt from this check?

Body:
There's nothing wrong with what you're doing, however, I would suggest splitting your route groups up instead i.e.:

Route::group(['middleware' => ['auth', 'checkOnboarding']], function () {
    Route::get('/home', 'HomeController@index');
    Route::get('/account', 'AccountController@index');
});

Route::group(['prefix' => 'setup', 'middleware' => 'auth'], function () {
    Route::get('/', 'OnboardingController@index')->name('setup');
    Route::post('/settings', 'SettingsController@store');
});

Alternatively, have a parent group for your auth:

Route::group(['middleware' => 'auth'], function () {

    Route::group(['middleware' => 'checkOnboarding'], function () {
        Route::get('/home', 'HomeController@index');
        Route::get('/account', 'AccountController@index');
    });

    Route::group(['prefix' => 'setup'], function () {
        Route::get('/', 'OnboardingController@index')->name('setup');
        Route::post('/settings', 'SettingsController@store');
    });
});

This will also mean you can remove the extra condition in your middleware:

/**
 * Check to see if the user has completed the onboarding, if not redirect.
 * Also checks that the requested URI isn't the setup route to ensure there isn't a redirect loop.
 */
return $request->user()->onboarding_complete ? $next($request) : redirect('setup');

Hope this helps!


问:
How to retrieve a list from another object that is in the list using stream
I have a little problem. From earlier steps I get this list:

```<code>List<Foo> fooList;
</code>```

I need now get all id to separate list:

```<code>List<Integer> newListIds;
</code>```

Is it possible to do it using streams, possibly as otherwise the easiest way to do it?

My clases:

```<code>public class Foo {

   List<Bar> barList;

   //getter, setter
}

public class Bar {

   private Integer id;

   //geter, setter
}
</code>```

答:
Just try this code:

List newListIds = new ArrayList ();

```<code>    for(Foo item : fooList){
       newListIds.addAll(item.barList.stream()
                               .map(Bar::GetId)
                               .collect(Collectors.toList()));
    }
</code>```

Body:
I have a little problem. From earlier steps I get this list:

List<Foo> fooList;

I need now get all id to separate list:

List<Integer> newListIds;

Is it possible to do it using streams, possibly as otherwise the easiest way to do it?

My clases:

public class Foo {

   List<Bar> barList;

   //getter, setter
}

public class Bar {

   private Integer id;

   //geter, setter
}

Body:
Just try this code:

List newListIds = new ArrayList ();

    for(Foo item : fooList){
       newListIds.addAll(item.barList.stream()
                               .map(Bar::GetId)
                               .collect(Collectors.toList()));
    }


问:
How to send json data to javascript in apache wicket?
Here is my java Code

```<code>     Gson gson = new Gson();
     json = gson.toJson(applicationsList);
     System.out.println(json);
</code>```

Here is my javascript file

```<code>       <html>
       <script>here i will use json data </script>
       </html
</code>```

答:
You need to use #renderHead() method of Component or Behavior. Read https://ci.apache.org/projects/wicket/guide/7.x/single.html#_adding_resources_to_page_header_section for more information.</p>

```<code>public class MyComponent extends Component{

    @Override
    public void renderHead(IHeaderResponse response) {
       String json = ...;
       response.render(JavaScriptHeaderItem.forScript(json));
    }
}
</code>```

Body:
Here is my java Code

     Gson gson = new Gson();
     json = gson.toJson(applicationsList);
     System.out.println(json);

Here is my javascript file

       </html

Body:
You need to use #renderHead() method of Component or Behavior. Read https://ci.apache.org/projects/wicket/guide/7.x/single.html#_adding_resources_to_page_header_section for more information.

public class MyComponent extends Component{

    @Override
    public void renderHead(IHeaderResponse response) {
       String json = ...;
       response.render(JavaScriptHeaderItem.forScript(json));
    }
}


问:
php/ajax success and error message
I have been working on a database for a few weeks now and I just cannot get my php code to work.  I created a database to enter new borrower information into a library database.  I would like a Success! message to post if all the fields are filled in and an error message to show if any field is empty. After this, i would like to incorporate ajax so that the Success and Failure messages populate on the HTML page and do not open a second page.  Any help would be appreciated. My HTML and PHP codes are below.

HTML:

```<code><body>
<form action="Addborrowerinfo.php" method="post">
    <fieldset>
        <legend><strong>Enter New Borrower Information</strong></legend>
        <legend>The form  below is used to send  data to  be stored in the database</legend>
        <p> Enter data in the  fields below and press Submit to add a new record to the database. To see the information you just entered, go back to the gather all data link below</p>

        <p>BorrowerID: <input type="text" name="BorrowerID" /></p>
        <p>First Name: <input type="text" name="FirstName" /></p>
        <p>Last Name: <input type="text" name="LastName" /></p>
        <p>Address: <input type="text" name="Address" /></p>
        <p>Phone Number: <input type="text" name="PhoneNumber" /></p>
        <p> <input type="submit" value="Submit"/> </p>
    </fieldset>
</form>
</code>```

PHP:

```<code><?php
(connection info)

$BorrowerID = mysql_real_escape_string($_POST["BorrowerID"]);
$FirstName = mysql_real_escape_string($_POST["FirstName"]);
$LastName = mysql_real_escape_string($_POST["LastName"]);
$Address = mysql_real_escape_string($_POST["Address"]);
$PhoneNumber = mysql_real_escape_string($_POST["PhoneNumber"]);

$insert = mysql_query("INSERT INTO duf47_library.Borrowers (BorrowerID, FirstName, LastName, Address, PhoneNumber) VALUES ('$BorrowerID', '$FirstName', '$LastName', '$Address', '$PhoneNumber')");

mysql_close();
?>
</code>```

答:
It depends on what your (connection info) is. This biggest thing I see is that your mysql_query("sql syntax") should be mysqli_query($db, "sql syntax"). Your database is not being called and this is required in procedural php.

Here is the link with examples in the php manual: http://php.net/manual/en/mysqli.query.php .

Title: php/ajax success and error message

Body:
I have been working on a database for a few weeks now and I just cannot get my php code to work.  I created a database to enter new borrower information into a library database.  I would like a Success! message to post if all the fields are filled in and an error message to show if any field is empty. After this, i would like to incorporate ajax so that the Success and Failure messages populate on the HTML page and do not open a second page.  Any help would be appreciated. My HTML and PHP codes are below.

HTML:

<form action="Addborrowerinfo.php" method="post">
    <fieldset>
        <legend>Enter New Borrower Information</legend>
        <legend>The form  below is used to send  data to  be stored in the database</legend>

 Enter data in the  fields below and press Submit to add a new record to the database. To see the information you just entered, go back to the gather all data link below

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

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

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

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

Phone Number: <input type="text" name="PhoneNumber" />

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

    </fieldset>
</form>

PHP:

<?php
(connection info)

$BorrowerID = mysql_real_escape_string($_POST["BorrowerID"]);
$FirstName = mysql_real_escape_string($_POST["FirstName"]);
$LastName = mysql_real_escape_string($_POST["LastName"]);
$Address = mysql_real_escape_string($_POST["Address"]);
$PhoneNumber = mysql_real_escape_string($_POST["PhoneNumber"]);

$insert = mysql_query("INSERT INTO duf47_library.Borrowers (BorrowerID, FirstName, LastName, Address, PhoneNumber) VALUES ('$BorrowerID', '$FirstName', '$LastName', '$Address', '$PhoneNumber')");

mysql_close();
?>


问:
Function calling wrong class
I am trying to use an intent to start two different classes in which I change either the text size or text colour of an entered message. Starting these classes is triggered by two different button push events in android studio. However, only the TextSize class is being started no matter what button I push and I cannot see the reason why. Below I have the problem activities class code and xml code

```<code>import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

public static final String EXTRAA_MESSAGE ="message2";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void changeText(View v){
    EditText messageView = (EditText)findViewById(R.id.message);
    String messageText = messageView.getText().toString();
    Intent result = new Intent(this, TextSize.class);
    result.putExtra("message",messageText);
    startActivity(result);
}

public void changeColour(View v){
    EditText messageView = (EditText)findViewById(R.id.message);
    String messageText = messageView.getText().toString();
    Intent result = new Intent(this, ColourChange.class);
    result.putExtra("message",messageText);
    startActivity(result);
}
</code>```

My XML File

```<code>    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_marginTop="14dp" />

    <EditText
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:ems="10"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true" />

    <Button
        android:text="Change Colour"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/Colour"
        android:onClick="changeColour"
        android:layout_centerVertical="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="36dp"
        android:onClick="changeText"
        android:text="Change Text Size"
        android:layout_alignBaseline="@+id/Colour"
        android:layout_alignBottom="@+id/Colour"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="33dp"
        android:id="@+id/TextSize" />
</code>```

答:
In Android just implements the OnClickListener for you when you define the android:onClick="someMethod" attribute.

you can implemented just different way.

```<code>Button btnColour = (Button) findViewById(R.id.Colour);

btnColour.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      // call your method here
      changeColour(v);
  }
});

// your method code

public void changeColour(View v) {
    // your method code
}
</code>```

As You doing
check your xml file that have you define context with parent layout or not

```<code>tools:context="com.example.YourActivity"
</code>```

// com.example.YourActivity should be your activity with package name

Title: Function calling wrong class

Body:
I am trying to use an intent to start two different classes in which I change either the text size or text colour of an entered message. Starting these classes is triggered by two different button push events in android studio. However, only the TextSize class is being started no matter what button I push and I cannot see the reason why. Below I have the problem activities class code and xml code

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

public static final String EXTRAA_MESSAGE ="message2";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void changeText(View v){
    EditText messageView = (EditText)findViewById(R.id.message);
    String messageText = messageView.getText().toString();
    Intent result = new Intent(this, TextSize.class);
    result.putExtra("message",messageText);
    startActivity(result);
}

public void changeColour(View v){
    EditText messageView = (EditText)findViewById(R.id.message);
    String messageText = messageView.getText().toString();
    Intent result = new Intent(this, ColourChange.class);
    result.putExtra("message",messageText);
    startActivity(result);
}

My XML File

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_marginTop="14dp" />

    <EditText
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:ems="10"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true" />

    <Button
        android:text="Change Colour"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/Colour"
        android:onClick="changeColour"
        android:layout_centerVertical="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="36dp"
        android:onClick="changeText"
        android:text="Change Text Size"
        android:layout_alignBaseline="@+id/Colour"
        android:layout_alignBottom="@+id/Colour"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="33dp"
        android:id="@+id/TextSize" />

Body:
In Android just implements the OnClickListener for you when you define the android:onClick="someMethod" attribute.

you can implemented just different way.

Button btnColour = (Button) findViewById(R.id.Colour);

btnColour.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      // call your method here
      changeColour(v);
  }
});

// your method code

public void changeColour(View v) {
    // your method code
}

As You doing
check your xml file that have you define context with parent layout or not

tools:context="com.example.YourActivity"

// com.example.YourActivity should be your activity with package name


问:
How to wait for all async tasks to finish in Node.js?
My program needs to run many async tasks.

And one task must run when all async tasks complete.

How can I make this function to wait all async functions?

```<code>let urls=[....]

for(var i=0; i<urls.length; i++){
    doRequest(urls[i])
}
finish()

function doRequest(url){
    request({
      uri: url,
    }, function(error, response, body) {
        //do some tasks
    });
}

function finish(){
    console.log('finish')
}
</code>```

答:
The easiest solution that doesn't require rewriting everything using promises, would be to check the number of completed requests at the end of doRequest function, and call finish if all requests have been completed.

```<code>let urls=[....]
let completed = 0

for(var i=0; i<urls.length; i++){
    doRequest(urls[i])
}

function doRequest(url){
    request({
        uri: url,
    }, function(error, response, body) {
        //do some tasks

        completed++
        if (completed === urls.length) {
            finish()
        }
    });
}

function finish(){
    console.log('finish')
}
</code>```

Body:
My program needs to run many async tasks.

And one task must run when all async tasks complete.

How can I make this function to wait all async functions?

let urls=[....]

for(var i=0; i<urls.length; i++){
    doRequest(urls[i])
}
finish()

function doRequest(url){
    request({
      uri: url,
    }, function(error, response, body) {
        //do some tasks
    });
}

function finish(){
    console.log('finish')
}

Body:
The easiest solution that doesn't require rewriting everything using promises, would be to check the number of completed requests at the end of doRequest function, and call finish if all requests have been completed.

let urls=[....]
let completed = 0

for(var i=0; i<urls.length; i++){
    doRequest(urls[i])
}

function doRequest(url){
    request({
        uri: url,
    }, function(error, response, body) {
        //do some tasks

        completed++
        if (completed === urls.length) {
            finish()
        }
    });
}

function finish(){
    console.log('finish')
}


问:
cx_Oracle query returns zero rows
Why does the below code not work ? It returns zero rows even though I have many multiple matching  the search criteria.

A simple query of the form select * from Table_1 works fine and returns positive number of rows

```<code>import cx_Oracle
def function_A (data):
    connection = cx_Oracle.connect('omitted details here')

    for index in range(len(data)):
        # connection is already open
        cursor = connection.cursor()

        query = "select * from Table_1 where column_1=:column1 and column_2=:column2 and column_3=:column3 and column_4=:column4"
        bindVars={'column1':data[index][3], 'column2':data[index][4], 'column4':data[index][5], 'column5':data[index][6]}
        cursor.execute(query, bindVars)
        cursor.arraysize = 256
        rowCount = 0
        resultSet = cursor.fetchall()
        if (resultSet != None):
            logger.debug("Obtained a resultSet with length = %s", len(resultSet))
            for index in range(len(resultSet)):
                logger.debug("Fetched one row from cursor, incrementing counter !!")
                rowCount = rowCount + 1
                logger.debug("Fetched one row from cursor, incremented counter !!")
            logger.debug("Successfully executed the select statement for table Table_1; that returned %s rows !!", rowCount)
            logger.debug("Successfully executed the select statement for table Table_1; that returned %s rows !!", cursor.rowcount)
</code>```

Please ignore minor formatting issues, code runs just does not give me a positive number of rows.

Code is being run on IBM AIX with python2.6 and a compatible version of cx_Oracle.

答:
banging my head against monitor on this one... you have to do something like below to check, as the cursor value changes once you operate on it:</p>

```<code>    result_set = DB_connector.execute(sql)
    result_list = result_set.fetchall()  # assign the return row to a list
    if result_set.rowcount == 0:
        print('DB check failed, no row returned')
        sql_result_set = None
    else:
        for row in result_list:  # use this instead result_set
            print('row fetched: ' + row[0])
            sql_result_set.append(row[0])
            print('DB test Passed')
</code>```

Title: cx_Oracle query returns zero rows

Body:
Why does the below code not work ? It returns zero rows even though I have many multiple matching  the search criteria.

A simple query of the form select * from Table_1 works fine and returns positive number of rows

import cx_Oracle
def function_A (data):
    connection = cx_Oracle.connect('omitted details here')

    for index in range(len(data)):
        # connection is already open
        cursor = connection.cursor()

        query = "select * from Table_1 where column_1=:column1 and column_2=:column2 and column_3=:column3 and column_4=:column4"
        bindVars={'column1':data[index][3], 'column2':data[index][4], 'column4':data[index][5], 'column5':data[index][6]}
        cursor.execute(query, bindVars)
        cursor.arraysize = 256
        rowCount = 0
        resultSet = cursor.fetchall()
        if (resultSet != None):
            logger.debug("Obtained a resultSet with length = %s", len(resultSet))
            for index in range(len(resultSet)):
                logger.debug("Fetched one row from cursor, incrementing counter !!")
                rowCount = rowCount + 1
                logger.debug("Fetched one row from cursor, incremented counter !!")
            logger.debug("Successfully executed the select statement for table Table_1; that returned %s rows !!", rowCount)
            logger.debug("Successfully executed the select statement for table Table_1; that returned %s rows !!", cursor.rowcount)

Please ignore minor formatting issues, code runs just does not give me a positive number of rows.

Code is being run on IBM AIX with python2.6 and a compatible version of cx_Oracle.

Body:
banging my head against monitor on this one... you have to do something like below to check, as the cursor value changes once you operate on it:

    result_set = DB_connector.execute(sql)
    result_list = result_set.fetchall()  # assign the return row to a list
    if result_set.rowcount == 0:
        print('DB check failed, no row returned')
        sql_result_set = None
    else:
        for row in result_list:  # use this instead result_set
            print('row fetched: ' + row[0])
            sql_result_set.append(row[0])
            print('DB test Passed')


问:
Get last modified object from S3 using AWS CLI
I have a use case where I programmatically bring up an EC2 instance, copy an executable file from S3, run it and shut down the instance (done in user-data). I need to get only the last added file from S3.

Is there a way to get the last modified file / object from a S3 bucket using the AWS CLI tool?

答:
```<code>aws s3api list-objects-v2 --bucket "bucket-name" |jq  -c ".[] | max_by(.LastModified)|.Key"
</code>```


问:
How to generate .ipa file for react-native?
I am currently using React-Native version 0.40.0.

Can somebody give me a link on the process and steps on how to generate an .ipa file for ios?? I'm currently new to react-native.

Btw I'm using version 8 of Xcode

答:
Get .app file : Run this command ->  react-native run-ios --configuration=release

Convert .app to .ipa :

Create folder Payload.

paste .app file into Payload folder.

compress the Payload folder.

change the name you want and put extension as .ipa.


问:
Laravel: Auth::user()->id trying to get a property of a non-object
I'm getting the following error "trying to get a property of a non-object" when I submit a form to add a user, the error is apparently on the first line: Auth::user()->id of the following:

```<code>$id = Auth::user()->id;
$currentuser = User::find($id);
$usergroup = $currentuser->user_group;
$group = Sentry::getGroupProvider()->findById($usergroup);

$generatedPassword = $this->_generatePassword(8,8);
$user = Sentry::register(array('email' => $input['email'], 'password' => $generatedPassword, 'user_group' => $usergroup));

$user->addGroup($group);
</code>```

Any ideas? I've searched for a while and everything I see says this should work fine. My user is logged in using the Sentry 2 authentication bundle.

答:
use Illuminate\Support\Facades\Auth;

In class:

```<code>protected $user;
</code>```

This code it`s works for me

In construct:

```<code>$this->user = User::find(Auth::user()->id);

In function:
$this->user->id;
$this->user->email;
</code>```

etc..

Body:
I'm getting the following error "trying to get a property of a non-object" when I submit a form to add a user, the error is apparently on the first line: Auth::user()->id of the following:

$id = Auth::user()->id;
$currentuser = User::find($id);
$usergroup = $currentuser->user_group;
$group = Sentry::getGroupProvider()->findById($usergroup);

$generatedPassword = $this->_generatePassword(8,8);
$user = Sentry::register(array('email' => $input['email'], 'password' => $generatedPassword, 'user_group' => $usergroup));

$user->addGroup($group);

Any ideas? I've searched for a while and everything I see says this should work fine. My user is logged in using the Sentry 2 authentication bundle.

Body:
use Illuminate\Support\Facades\Auth;

In class:

protected $user;

This code it`s works for me

In construct:

$this->user = User::find(Auth::user()->id);

In function:
$this->user->id;
$this->user->email;

etc..


问:
Adding custom header in Excel sheet
```<code>string strFileName = "LoginData.xls";

ds.Tables[0].TableName = "LoginUserData";

var stringXml = ExcelHelper.GetExcelXml(ds, strFileName);

Response.Clear();

Response.AppendHeader("content-Type", "application/vnt.ms-excel");

Response.AppendHeader("content-disposition", "attachment; filename=" + strFileName);
string headerTable = @"<Table><tr><td>Report Header</td></tr><tr><td></Table>";
Response.Write(headerTable);
Response.Write(stringXml);

Response.Flush();
Response.End();
</code>```

答:
A better approach would probably be to use epplus and create the Excel document that way.

See this for the example below.

```<code>private void DumpExcel(DataTable tbl)
{
    using (ExcelPackage pck = new ExcelPackage())
    {
        //Create the worksheet
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

        //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
        ws.Cells["A1"].LoadFromDataTable(tbl, true);

        //Format the header for column 1-3
        using (ExcelRange rng = ws.Cells["A1:C1"])
        {
            rng.Style.Font.Bold = true;
            rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
            rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
            rng.Style.Font.Color.SetColor(Color.White);
        }

        //Example how to Format Column 1 as numeric
        using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
        {
            col.Style.Numberformat.Format = "#,##0.00";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
        }

        //Write it back to the client
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
    }
}
</code>```

Title: Adding custom header in Excel sheet

Body:
string strFileName = "LoginData.xls";

ds.Tables[0].TableName = "LoginUserData";

var stringXml = ExcelHelper.GetExcelXml(ds, strFileName);

Response.Clear();

Response.AppendHeader("content-Type", "application/vnt.ms-excel");

Response.AppendHeader("content-disposition", "attachment; filename=" + strFileName);
string headerTable = @"

Report Header

";
Response.Write(headerTable);
Response.Write(stringXml);

Response.Flush();
Response.End();

Body:
A better approach would probably be to use epplus and create the Excel document that way.

See this for the example below.

private void DumpExcel(DataTable tbl)
{
    using (ExcelPackage pck = new ExcelPackage())
    {
        //Create the worksheet
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

        //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
        ws.Cells["A1"].LoadFromDataTable(tbl, true);

        //Format the header for column 1-3
        using (ExcelRange rng = ws.Cells["A1:C1"])
        {
            rng.Style.Font.Bold = true;
            rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
            rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
            rng.Style.Font.Color.SetColor(Color.White);
        }

        //Example how to Format Column 1 as numeric
        using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
        {
            col.Style.Numberformat.Format = "#,##0.00";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
        }

        //Write it back to the client
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
    }
}


问:
Establishing WebRTC peer connection
I have started to look into WebRTC a bit and I am using it to build a simple peer to peer chat application using the data channel. I have the following questions:

Do I need to establish a RTCPeerConnection to each peer I want to talk to? So if there are three peers they each need 2 RTCPeerConnections (unless I use one of the peers as a sort of ad-hoc server).

If peer A sends out a candidate and sdp when creating a offer to peer B. Can peer B connect to peer A using that info and send its answer (with candidate and its sdp) over the RTCPeerConnection, i.e. using the RTCPeerConnection (before it's been completely established) as a signaling channel? I would assume that when the offer is created by peer A it starts to listen for connections on some port.

My understanding of WebRTC is a bit limited so if I've missunderstood some concept of WebRTC in my questions above please point them out!

答:
Yes, as a direct P2P protocol everybody must be directly connected to everybody else if they want to communicate; unless you create some kind of mesh network in which one peer forwards messages to other peers.

No, the SDP offer and answer and ICE candidates all need to be exchanged through a signalling server; the connection cannot be established until both peers have actually agreed on a specific session configuration and ICE route to use, so you cannot send the SDP answer over a connection which isn't complete yet.

Especially for a simple text-only chat, going through a server is often easier than using P2P; the processing and bandwidth requirements are so minimal that the complications of P2P connections are probably not worth it. And you need a signalling server anyway. P2P only becomes really interesting once you start sending large files or audio/video streams.

Title: Establishing WebRTC peer connection


问:
SQL: Select all records when one column value change
I am having trouble to find the solution for this SQL Query.

Let me explain You on base of the table below:

```<code>   Group            DATUM    VALUE
    1002  2017-03-29 12:01:00     0.1
    1002  2017-03-29 12:02:36     0.2
    1002  2017-03-29 12:03:40     0.1
    1002  2017-03-29 12:04:44     0.2
    2523  2017-03-29 12:05:47     0.3
    2523  2017-03-29 12:06:51     0.1
    2523  2017-03-29 12:07:55     0.2
    2523  2017-03-29 12:08:59     0.3
    2523  2017-03-29 12:09:03     0.4
    3002  2017-03-29 12:10:07     0.5
</code>```

I would like to get the data of every group. So on the base of table above the GROUP: 1002 has changed to GROUP: 2523, so i wanna receive all the records of GROUP: 1002, which is:

```<code>Group             DATUM    VALUE
1002  2017-03-29 12:01:00     0.1
1002  2017-03-29 12:02:36     0.2
1002  2017-03-29 12:03:40     0.1
1002  2017-03-29 12:04:44     0.2
</code>```

and furtehrmore when the GROUP: 2523 is finished and the value changed to GROUP: 3002, i would get all the records for the GROUP: 2523 and so on...

The reason of doing this:

The raw data has to be read into another programme (KNIME) every time GROUP value changes (here is the part of SQL), then some specific values need to be calculated for each group, the new table has to be written in database.

Thanks for help!

答:
You would write a trigger to check whether a new insert has another group than the latest insert. In that case you'd have to call some routine that pushes the data to where you want it. Something like this:</p>

```<code>create or replace trigger trg_latest_group_to_knime
before insert on mytable
for each row
declare
  v_last_group integer;
begin
  select max("GROUP") keep (dense_rank last order by datum)
  into v_group
  from mytable;

  if :new.group <> v_last_group then
    push_records_to_knime_for_group(v_last_group);
  end if;
end trg_latest_group_to_knime;
</code>```

Body:
I am having trouble to find the solution for this SQL Query.

Let me explain You on base of the table below:

   Group            DATUM    VALUE
    1002  2017-03-29 12:01:00     0.1
    1002  2017-03-29 12:02:36     0.2
    1002  2017-03-29 12:03:40     0.1
    1002  2017-03-29 12:04:44     0.2
    2523  2017-03-29 12:05:47     0.3
    2523  2017-03-29 12:06:51     0.1
    2523  2017-03-29 12:07:55     0.2
    2523  2017-03-29 12:08:59     0.3
    2523  2017-03-29 12:09:03     0.4
    3002  2017-03-29 12:10:07     0.5

I would like to get the data of every group. So on the base of table above the GROUP: 1002 has changed to GROUP: 2523, so i wanna receive all the records of GROUP: 1002, which is:

Group             DATUM    VALUE
1002  2017-03-29 12:01:00     0.1
1002  2017-03-29 12:02:36     0.2
1002  2017-03-29 12:03:40     0.1
1002  2017-03-29 12:04:44     0.2

and furtehrmore when the GROUP: 2523 is finished and the value changed to GROUP: 3002, i would get all the records for the GROUP: 2523 and so on...

The reason of doing this:

The raw data has to be read into another programme (KNIME) every time GROUP value changes (here is the part of SQL), then some specific values need to be calculated for each group, the new table has to be written in database.

Thanks for help!

Body:
You would write a trigger to check whether a new insert has another group than the latest insert. In that case you'd have to call some routine that pushes the data to where you want it. Something like this:

create or replace trigger trg_latest_group_to_knime
before insert on mytable
for each row
declare
  v_last_group integer;
begin
  select max("GROUP") keep (dense_rank last order by datum)
  into v_group
  from mytable;

  if :new.group <> v_last_group then
    push_records_to_knime_for_group(v_last_group);
  end if;
end trg_latest_group_to_knime;


问:
homogenization the functions can be compiled into a calculate networks?
Inside of a network, information (package) can be passed to different node(hosts), by modify it's content it can carry different meaning. The final package depends on hosts input via it's given route of network.

Now I want to implement a calculating network model can do small jobs by give different calculate path.

Prototype:

```<code>def a(p): return p + 1
def b(p): return p + 2
def c(p): return p + 3
def d(p): return p + 4
def e(p): return p + 5

def link(p, r):
    p1 = p
    for x in r:
        p1 = x(p1)
    return p1

p = 100
route = [a,c,d]
result = link(p,result)
#========
target_result = 108
if result = target_result:
   # route is OK
</code>```

I think finally I need something like this:

```<code>  p with [init_payload, expected_target, passed_path, actual_calculated_result]
  |
  \/
 [CHAOS of possible of functions networks]
  |
  \/
  px [a,a,b,c,e]  # ok this path is ok and match the target
</code>```

Here is my questions hope may get your help:

can p carry(determin) the route(s) by inspect the function and estmated result？

(1.1 ) for example, if on the route there's a node x()

def x(p): return x / 0        # I suppose it can pass the compile

can p know in somehow this path is not good then avoid select this path?

(1.2) Another confuse is if p is a self-defined class type, the payload inside of this class essentially is a string, when it carry with a path [a,c,d], can p know a() must with a int type then avoid to select this node?'

same as 1.2 when generating the path, can I avoid such oops

def a(p): return p + 1

def b(p): return p + 2

def x(p): return p.append(1)

def y(p): return p.append(2)

full_node_list = [a,b,x,y]

path = random(2,full_node_list) # oops x,y will be trouble for the inttype P and a,b will be trouble to list type.
pls consider if the path is lambda list of functions

PS: as the whole model is not very clear in my mind the any leading and directing will be appreciated.

THANKS!

答:
Your functions can raise TypeError if they are not satisfied with the data types they receive. You can then catch this exception and see whether you are passing an appropriate type. You can also catch any other exception type. But trying to call the functions and catching the exceptions can be quite slow.

You could also organize your functions into different sets depending on the argument type.

```<code>functions = { list : [some functions taking a list], int : [some functions taking an int]}

...
x = choose_function(functions[type(p)])
p = x(p)
</code>```

Body:
Inside of a network, information (package) can be passed to different node(hosts), by modify it's content it can carry different meaning. The final package depends on hosts input via it's given route of network.

Now I want to implement a calculating network model can do small jobs by give different calculate path.

Prototype:

def a(p): return p + 1
def b(p): return p + 2
def c(p): return p + 3
def d(p): return p + 4
def e(p): return p + 5

def link(p, r):
    p1 = p
    for x in r:
        p1 = x(p1)
    return p1

p = 100
route = [a,c,d]
result = link(p,result)
#========
target_result = 108
if result = target_result:
   # route is OK

I think finally I need something like this:

  p with [init_payload, expected_target, passed_path, actual_calculated_result]
  |
  \/
 [CHAOS of possible of functions networks]
  |
  \/
  px [a,a,b,c,e]  # ok this path is ok and match the target

Here is my questions hope may get your help:

can p carry(determin) the route(s) by inspect the function and estmated result？

(1.1 ) for example, if on the route there's a node x()

def x(p): return x / 0        # I suppose it can pass the compile

can p know in somehow this path is not good then avoid select this path?

(1.2) Another confuse is if p is a self-defined class type, the payload inside of this class essentially is a string, when it carry with a path [a,c,d], can p know a() must with a int type then avoid to select this node?'

same as 1.2 when generating the path, can I avoid such oops

def a(p): return p + 1

def b(p): return p + 2

def x(p): return p.append(1)

def y(p): return p.append(2)

full_node_list = [a,b,x,y]

path = random(2,full_node_list) # oops x,y will be trouble for the inttype P and a,b will be trouble to list type.
pls consider if the path is lambda list of functions

PS: as the whole model is not very clear in my mind the any leading and directing will be appreciated.

THANKS!

Body:
Your functions can raise TypeError if they are not satisfied with the data types they receive. You can then catch this exception and see whether you are passing an appropriate type. You can also catch any other exception type. But trying to call the functions and catching the exceptions can be quite slow.

You could also organize your functions into different sets depending on the argument type.

functions = { list : [some functions taking a list], int : [some functions taking an int]}

...
x = choose_function(functions[type(p)])
p = x(p)


答: Both PagingRequestType could implement one common interface or extend one common class and you could take this "common part" as argument to your function. Although I don't know if you can modify your auto generated code in that way.</p>

Body:
I have a function that parse an object. But this function is required in two services and the parameter have same class name, but different package name. What i need is to avoid duplicated code.

Suppose the function is:

    private HashMap<String, Integer> getPagination(PagingRequestType pagingRequestType) {
        int pageSize = 200;
        int pageNumber = 1;
        if(pagingRequestType != null) {
            if (pagingRequestType.getNumberOfRecordsPerPage() != 0) {
                pageSize = pagingRequestType.getNumberOfRecordsPerPage();
            }
            if (pagingRequestType.getStartAtRecordNumber() != 0) {
                pageNumber = pagingRequestType.getStartAtRecordNumber();
            }
        }
        HashMap<String, Integer> result = new HashMap<>();
        result.put("pageNumber", pageNumber);
        result.put("pageSize", pageSize);
        return result;
    }

Possible function calls:

- getPagination(new Abc.PagingRequestType());
- getPagination(new Xyz.PagingRequestType());

PagingRequestType is an auto-generated class in two different    packages. The function needs to be implemented once and used in both    services.

Thanks.


问:
Web audio API and multiple inputs mic device
I have an audio device with 4 inputs microphones..

Someone knows if i can use all these inputs with Web audio API ?

Thanks !

答:
yes,you can list all  input devices and select one to use.</p>

```<code><html><body>

<select id="devices_list"></select>
<script>
function devices_list(){
        var handleMediaSourcesList = function(list){
            for(i=0;i<list.length;i++){
                var device= list[i];
                if(device.kind == 'audioinput') {
                    document.querySelector('#devices_list').options.add(new Option(device.label ,device.deviceId));
                }
            }

        }
        if (navigator["mediaDevices"] && navigator["mediaDevices"]["enumerateDevices"])
            {
                navigator["mediaDevices"]["enumerateDevices"]().then(handleMediaSourcesList);
            }
            // Old style API
            else if (window["MediaStreamTrack"] && window["MediaStreamTrack"]["getSources"])
            {
                window["MediaStreamTrack"]["getSources"](handleMediaSourcesList);
            }
}

function usemic(){

    navigator.getUserMedia ({
      "audio":{
            "optional": [{
            "sourceId": document.querySelector('#devices_list').value
             }]
        }}, function (stream) {
            //...some code to use stream from mic
        },function(err){
            debuginfo('getMedia ERR:'+err.message );
        });
}
</script>
</body></html>
</code>```

Body:
yes,you can list all  input devices and select one to use.

<html><body>

<select id="devices_list"></select>
<script>
function devices_list(){
        var handleMediaSourcesList = function(list){
            for(i=0;i<list.length;i++){
                var device= list[i];
                if(device.kind == 'audioinput') {
                    document.querySelector('#devices_list').options.add(new Option(device.label ,device.deviceId));
                }
            }

        }
        if (navigator["mediaDevices"] && navigator["mediaDevices"]["enumerateDevices"])
            {
                navigator["mediaDevices"]["enumerateDevices"]().then(handleMediaSourcesList);
            }
            // Old style API
            else if (window["MediaStreamTrack"] && window["MediaStreamTrack"]["getSources"])
            {
                window["MediaStreamTrack"]["getSources"](handleMediaSourcesList);
            }
}

function usemic(){

    navigator.getUserMedia ({
      "audio":{
            "optional": [{
            "sourceId": document.querySelector('#devices_list').value
             }]
        }}, function (stream) {
            //...some code to use stream from mic
        },function(err){
            debuginfo('getMedia ERR:'+err.message );
        });
}
</script>
</body></html>