问:
Declaration and use of function in c
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

```<code>#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}
</code>```

答:
compiler gives error because of below inline reason:

° too few arguments to function 'day_of_year'

Reason: called day_of_year() function without parameter.

° conflicting types for 'day_of_year'

Reason: prototype of day_of_year() function is different from day_of_year()definition.
Prototype says to compiler that it take 3 parameter but function definition having 5 parameter. this mismatch causing the error.

Title: Declaration and use of function in c

Body:
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}


来源: stackexchange

问:
What is the best way to design dynamic object that is updated in realtime?
I've got a problem that I'm trying to solve from sometime. Say that there is a web application with a page that has many input fields. Assume that there are many concurrent users accessing this page and entering data in said inputs.When one user edits a field that change should be reflected in all the other users interfaces. Can someone point me in the right direction or any web resources to get this done. Also currently there are two load balanced tomcat nodes hosting the web application and I have a thought of creating a common dynamic object to hold the data. Any suggestions would be helpful.</p>

答:
Your question is more an architectural one. How to you automatically update a second GUI upon actions in GUI #1?

You probably know how to forward the action to one of your tomcat instances. The first problem is how to broadcast this action to all server instances. You could write it to a database and let every instance poll regularly, but that would be poor design. You probably need to persist your data, but if you need to let all instances know about updates, I suggest to use a messaging queue (https://de.wikipedia.org/wiki/Java_Message_Service#JMS-Provider).

Part two of your problem is how to push the updates back to all browsers. There have been quite a few frameworks to achieve this. Example: https://en.wikipedia.org/wiki/Comet_(programming). Java 9 supports a brand new technology you could use: https://en.wikipedia.org/wiki/WebSocket. The quick-and-dirty solution would be a javascript polling regulary.

You basically have to decide between the easy polling and the more advanced pushing technologies both on the server and client side.

You could also choose NOT to implement it yourself at all and use something like that: https://firebase.googleblog.com/2017/10/introducing-cloud-firestore.html.

ContentLicense: CC BY-SA 3.0


问:
Filename match and export
I have several files in a folder. I have to match the filenames using a regex pattern. In the regex pattern I have a word which would be a variable. I want all the files matched with the pattern to be moved to a separate directory with an alternate filename replacing the string with which I had made the match.

Eg,

I have many files with filenames having the word foo in the directory like,

```<code>gadgeagfooafsa
fsafsaffooarwf
fasfsfoofsafff
</code>```

I have to list these files and copy it to another directory replacing the word foo from it. I have specified the new pattern to be "kuh", Like the above files should be copied to the new folder as

```<code>gadgeagkuhafsa
fsafsafkuharwf
fasfskuhfsafff
</code>```

Finally, can I pipe different commands together to execute these in one line? :)

I had tried this command, but it didn't work, somehow the copy is failing.

```<code>ls | grep ".*foo[} ].*" | xargs cp -t work/
</code>```

答:
I chose /tmp as the new destination, and only used two of the example files

```<code>newdest="/tmp"; fp="foo"; np="kuh"; for f in $(find . -type f -name "*$fp*"); do new=$(echo $f| sed  "s/$fp/$np/g"); cp -f $f $newdest/$new ; done
</code>```

which moves and renames the files

```<code>ls /tmp/*kuh*
/tmp/fsafsafkuharwf  /tmp/gadgeagkuhafsa
</code>```

Title: Filename match and export

Body:
I have several files in a folder. I have to match the filenames using a regex pattern. In the regex pattern I have a word which would be a variable. I want all the files matched with the pattern to be moved to a separate directory with an alternate filename replacing the string with which I had made the match.

Eg,

I have many files with filenames having the word foo in the directory like,

gadgeagfooafsa
fsafsaffooarwf
fasfsfoofsafff

I have to list these files and copy it to another directory replacing the word foo from it. I have specified the new pattern to be "kuh", Like the above files should be copied to the new folder as

gadgeagkuhafsa
fsafsafkuharwf
fasfskuhfsafff

Finally, can I pipe different commands together to execute these in one line? :)

I had tried this command, but it didn't work, somehow the copy is failing.

ls | grep ".*foo[} ].*" | xargs cp -t work/

Body:
I chose /tmp as the new destination, and only used two of the example files

newdest="/tmp"; fp="foo"; np="kuh"; for f in $(find . -type f -name "*$fp*"); do new=$(echo $f| sed  "s/$fp/$np/g"); cp -f $f $newdest/$new ; done

which moves and renames the files

ls /tmp/*kuh*
/tmp/fsafsafkuharwf  /tmp/gadgeagkuhafsa


问:
winforms - gridview cell timespan edit problem
I'm following this question for formatting timespan value in the gridview.

Format TimeSpan in DataGridView column

I'm diaplying only minutes value in grid as follows

```<code>DataGridViewColumn idleTimeColumn = myGridView.Columns["IdleTime"];
idleTimeColumn.DefaultCellStyle.FormatProvider = new TimeSpanFormatter();
idleTimeColumn.DefaultCellStyle.Format = "m";
</code>```

This cell is editable, so when I enter 5 (that mean 5 min) in the cell, then it should take it minute, but it take it as day value (ie, 5.00:00:00).

I tried different values for format (mm,%m) but all these gives the same output.

答:
You have to implement the feature to parse an input value.

TimeSpanFormatter can be used to convert a bound TimeSpan data to a formatted string for displaying. But it can't convert an input value to TimeSpan. You have to convert an input value in DataGridView.CellParsing event handler.

The following is the sample code to parse an input value.

DataGridView.CellParsing event handler

```<code>private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
    if (e.DesiredType == typeof(TimeSpan))
    {
        TimeSpanParser parser = new TimeSpanParser();
        e.Value = parser.Parse(e.Value.ToString(), e.InheritedCellStyle.Format);
        e.ParsingApplied = true;
    }
}
</code>```

TimeSpanParser class

```<code>public class TimeSpanParser
{
    private Regex formatParser;

    private List<TimeSpanPart> parts;

    public TimeSpanParser()
    {
        this.formatParser = new Regex("d{1,2}|h{1,2}|m{1,2}|s{1,2}|f{1,7}", RegexOptions.Compiled);
        this.parts = new List<TimeSpanPart>();
    }

    public TimeSpan Parse(string input, string format)
    {
        this.parts.Clear();
        var pattern = this.formatParser.Replace(format, m => ReplaceFormat(m));
        var match = Regex.Match(input, "^" + pattern + "$");

        TimeSpan result = new TimeSpan();
        for (int i = 1; i < match.Groups.Count; i++)
        {
            var value = Convert.ToDouble(match.Groups[i].Value);
            switch (this.parts[i - 1])
            {
                case TimeSpanPart.Day:
                    result = result.Add(TimeSpan.FromDays(value));
                    break;
                case TimeSpanPart.Hour:
                    result = result.Add(TimeSpan.FromHours(value));
                    break;
                case TimeSpanPart.Minute:
                    result = result.Add(TimeSpan.FromMinutes(value));
                    break;
                case TimeSpanPart.Second:
                    result = result.Add(TimeSpan.FromSeconds(value));
                    break;
                case TimeSpanPart.Millisecond:
                    int digit = match.Groups[i].Value.Length;
                    value =value * Math.Pow(10, 3 - digit);
                    result = result.Add(TimeSpan.FromMilliseconds(value));
                    break;
            }
        }

        return result;
    }

    private string ReplaceFormat(Match match)
    {
        switch (match.Value)
        {
            case "dd":
            case "d":
                this.parts.Add(TimeSpanPart.Day);
                return "(\\d{1,2})";
            case "hh":
            case "h":
                this.parts.Add(TimeSpanPart.Hour);
                return "(\\d{1,2})";
            case "mm":
            case "m":
                this.parts.Add(TimeSpanPart.Minute);
                return "(\\d{1,2})";
            case "ss":
            case "s":
                this.parts.Add(TimeSpanPart.Second);
                return "(\\d{1,2})";
            case "fffffff":
            case "ffffff":
            case "fffff":
            case "ffff":
            case "fff":
            case "ff":
            case "f":
                this.parts.Add(TimeSpanPart.Millisecond);
                return "(\\d{1,7})";
            default:
                return match.Value;
        }
    }
}
</code>```

TimeSpanPart enum

```<code>public enum TimeSpanPart
{
    Day,
    Hour,
    Minute,
    Second,
    Millisecond,
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm following this question for formatting timespan value in the gridview.

Format TimeSpan in DataGridView column

I'm diaplying only minutes value in grid as follows

DataGridViewColumn idleTimeColumn = myGridView.Columns["IdleTime"];
idleTimeColumn.DefaultCellStyle.FormatProvider = new TimeSpanFormatter();
idleTimeColumn.DefaultCellStyle.Format = "m";

This cell is editable, so when I enter 5 (that mean 5 min) in the cell, then it should take it minute, but it take it as day value (ie, 5.00:00:00).

I tried different values for format (mm,%m) but all these gives the same output.

Body:
You have to implement the feature to parse an input value.

TimeSpanFormatter can be used to convert a bound TimeSpan data to a formatted string for displaying. But it can't convert an input value to TimeSpan. You have to convert an input value in DataGridView.CellParsing event handler.

The following is the sample code to parse an input value.

DataGridView.CellParsing event handler

private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
    if (e.DesiredType == typeof(TimeSpan))
    {
        TimeSpanParser parser = new TimeSpanParser();
        e.Value = parser.Parse(e.Value.ToString(), e.InheritedCellStyle.Format);
        e.ParsingApplied = true;
    }
}

TimeSpanParser class

public class TimeSpanParser
{
    private Regex formatParser;

    private List<TimeSpanPart> parts;

    public TimeSpanParser()
    {
        this.formatParser = new Regex("d{1,2}|h{1,2}|m{1,2}|s{1,2}|f{1,7}", RegexOptions.Compiled);
        this.parts = new List<TimeSpanPart>();
    }

    public TimeSpan Parse(string input, string format)
    {
        this.parts.Clear();
        var pattern = this.formatParser.Replace(format, m => ReplaceFormat(m));
        var match = Regex.Match(input, "^" + pattern + "$");

        TimeSpan result = new TimeSpan();
        for (int i = 1; i < match.Groups.Count; i++)
        {
            var value = Convert.ToDouble(match.Groups[i].Value);
            switch (this.parts[i - 1])
            {
                case TimeSpanPart.Day:
                    result = result.Add(TimeSpan.FromDays(value));
                    break;
                case TimeSpanPart.Hour:
                    result = result.Add(TimeSpan.FromHours(value));
                    break;
                case TimeSpanPart.Minute:
                    result = result.Add(TimeSpan.FromMinutes(value));
                    break;
                case TimeSpanPart.Second:
                    result = result.Add(TimeSpan.FromSeconds(value));
                    break;
                case TimeSpanPart.Millisecond:
                    int digit = match.Groups[i].Value.Length;
                    value =value * Math.Pow(10, 3 - digit);
                    result = result.Add(TimeSpan.FromMilliseconds(value));
                    break;
            }
        }

        return result;
    }

    private string ReplaceFormat(Match match)
    {
        switch (match.Value)
        {
            case "dd":
            case "d":
                this.parts.Add(TimeSpanPart.Day);
                return "(\\d{1,2})";
            case "hh":
            case "h":
                this.parts.Add(TimeSpanPart.Hour);
                return "(\\d{1,2})";
            case "mm":
            case "m":
                this.parts.Add(TimeSpanPart.Minute);
                return "(\\d{1,2})";
            case "ss":
            case "s":
                this.parts.Add(TimeSpanPart.Second);
                return "(\\d{1,2})";
            case "fffffff":
            case "ffffff":
            case "fffff":
            case "ffff":
            case "fff":
            case "ff":
            case "f":
                this.parts.Add(TimeSpanPart.Millisecond);
                return "(\\d{1,7})";
            default:
                return match.Value;
        }
    }
}

TimeSpanPart enum

public enum TimeSpanPart
{
    Day,
    Hour,
    Minute,
    Second,
    Millisecond,
}


问:
How would I constrain a generic method in C# to only allow T where T has TryParse?

public int DoSomething<T>(string someString)
```

I want to insist that I can call TryParse on T. Is it possible to restrict T in that way? TryParse is not part of an interface, it just seems to exist on a number of value types, so how would I do this?

答:
You cannot

Sorry. I don't know what else to say. It's simply not possible. You could allow any T and then do reflection somewhere and throw if it does not have a method called TryParse but as it's not part of an interface or base class... there is no way.

ContentLicense: CC BY-SA 4.0

Body:
public int DoSomething<T>(string someString)

I want to insist that I can call TryParse on T. Is it possible to restrict T in that way? TryParse is not part of an interface, it just seems to exist on a number of value types, so how would I do this?


问:
Tensorflow - how to use same dropout mask at each row
How can I use tf.nn.dropout to apply the same dropout mask to each row of a tensor?

Example:

I have a 3D tensor of shape (2,2,3):

```<code>[[[  1.   2.   3.]
  [  4.   5.   6.]]

 [[  7.   8.   9.]
  [ 10.  11.  12.]]]
</code>```

When using dropout, the same mask should be applied to each row. Also, when an entry is dropped out, all elements of the third dimension should be set to zero.
Let's say that in each row/horizontal slize, only the second entry is dropped out, corresponding to a dropout mask of [1,0] per row. This should give (not including the rescaling of the other entries):

```<code>[[[  1.   2.   3.]
  [  0.   0.   0.]]

 [[  7.   8.   9.]
  [ 0.  0.  0.]]]
</code>```

By providing a noise_shape to tf.nn.dropout I can make sure, that all elements in the third dimension are set to zero. This can be done using noise_shape=[2,2,1]. However, I don't know how I can ensure that the same dropout mask is used for each row/slice.

答: In case someone stumbles over this question in the future, I will post the answer myself. The behavior can be achieved by providing noise_shape=[1,2,1] to tf.nn.dropout. Or in general, when having a tensor of shape (m,n,e) setting noise_shape=[1,n,1]

Body:
How can I use tf.nn.dropout to apply the same dropout mask to each row of a tensor?

Example:

I have a 3D tensor of shape (2,2,3):

[[[  1.   2.   3.]
  [  4.   5.   6.]]

 [[  7.   8.   9.]
  [ 10.  11.  12.]]]

When using dropout, the same mask should be applied to each row. Also, when an entry is dropped out, all elements of the third dimension should be set to zero.
Let's say that in each row/horizontal slize, only the second entry is dropped out, corresponding to a dropout mask of [1,0] per row. This should give (not including the rescaling of the other entries):

[[[  1.   2.   3.]
  [  0.   0.   0.]]

 [[  7.   8.   9.]
  [ 0.  0.  0.]]]

By providing a noise_shape to tf.nn.dropout I can make sure, that all elements in the third dimension are set to zero. This can be done using noise_shape=[2,2,1]. However, I don't know how I can ensure that the same dropout mask is used for each row/slice.


问:
How do I remove a file from the FileList
I'm building a drag-and-drop-to-upload web application using HTML5, and I'm dropping the files onto a div and of course fetching the dataTransfer object, which gives me the FileList.

Now I want to remove some of the files, but I don't know how, or if it's even possible.

Preferably I'd like to just delete them from the FileList; I've got no use for them. But if that's not possible, should I instead write in checks in code that interacts with the FileList? That seems cumbersome.

答:
I have found very quick & short workaround for this. Tested in many popular browsers (Chrome, Firefox, Safari);

First, you have to convert FileList to an Array

```<code>var newFileList = Array.from(event.target.files);
</code>```

to delete the particular element use this

```<code>newFileList.splice(index,1);
</code>```

Body:
I have found very quick & short workaround for this. Tested in many popular browsers (Chrome, Firefox, Safari);

First, you have to convert FileList to an Array

var newFileList = Array.from(event.target.files);

to delete the particular element use this

newFileList.splice(index,1);


问:
Bias Google Places results to a specific region
I am using the official Google Documentation to create the Address lookup.

In the Android version I am able to bias the result to my area.

For example typing in "123 Main St" shows the Main st in my town first before showing me other results.

In iOS I can't figure out how to do that. I am using the "Add a Full-Screen Control" with the the GMSAutocompleteViewController delegate.

There is a GMSCoordinateBounds but the example is for a map. I am not using a map.

I have tinkered around with something like this but can't get it to work. Am I even on the right track?

```<code>- (void) placeAutocomplete : (NSString*) location : Bounds:(GMSCoordinateBounds *)bounds{
[_placesClient autocompleteQuery:location
                          bounds:bounds
                          filter:filter
                        callback:^(NSArray *results, NSError *error) {
                          if (error != nil) {
                            NSLog(@"Autocomplete error %@", [error localizedDescription]);
                            return;
                          }

                          for (GMSAutocompletePrediction* result in results) {
                            NSLog(@"Result '%@' with placeID %@", result.attributedFullText.string, result.placeID);
                          }
                        }];
}
</code>```

Any help?

答:
Create a bounds based on your location and set it as the bounds of GMSAutocompleteViewController

```<code>func presentAddressFinder(){
     let autocompleteController = GMSAutocompleteViewController()
        autocompleteController.delegate = self
        let bounds = GMSCoordinateBounds()
        autocompleteController.autocompleteBounds = bounds.includingCoordinate(currentLocation)
    present(autocompleteController, animated: true, completion: nil)
}
</code>```

here currentLocation  is the current device location in CLLocationCoordinate2D!

Body:
I am using the official Google Documentation to create the Address lookup.

In the Android version I am able to bias the result to my area.

For example typing in "123 Main St" shows the Main st in my town first before showing me other results.

In iOS I can't figure out how to do that. I am using the "Add a Full-Screen Control" with the the GMSAutocompleteViewController delegate.

There is a GMSCoordinateBounds but the example is for a map. I am not using a map.

I have tinkered around with something like this but can't get it to work. Am I even on the right track?

- (void) placeAutocomplete : (NSString*) location : Bounds:(GMSCoordinateBounds *)bounds{
[_placesClient autocompleteQuery:location
                          bounds:bounds
                          filter:filter
                        callback:^(NSArray *results, NSError *error) {
                          if (error != nil) {
                            NSLog(@"Autocomplete error %@", [error localizedDescription]);
                            return;
                          }

                          for (GMSAutocompletePrediction* result in results) {
                            NSLog(@"Result '%@' with placeID %@", result.attributedFullText.string, result.placeID);
                          }
                        }];
}

Any help?

Body:
Create a bounds based on your location and set it as the bounds of GMSAutocompleteViewController

func presentAddressFinder(){
     let autocompleteController = GMSAutocompleteViewController()
        autocompleteController.delegate = self
        let bounds = GMSCoordinateBounds()
        autocompleteController.autocompleteBounds = bounds.includingCoordinate(currentLocation)
    present(autocompleteController, animated: true, completion: nil)
}

here currentLocation  is the current device location in CLLocationCoordinate2D!


问:
How to break a long line in .pylintrc file?
I have a PyLint configuration file, .pylintrc, with some rules defined.

However, for one rule, I have quite a few items which results in a very long line.

```<code>[TYPECHECK]
generated-members = XXX, YYY, ZZZ......
</code>```

An example of a long line can be seen here on github:
https://github.com/behave/behave.example/blob/master/pylintrc#L263

Is it possible to break the line to keep listing items on the next line(s)? I've tried to move the items to the next line, however, this seems to make the file invalid.

答:
pylint parses the .pylintrc file using configparser, which says in its docs:

Values can also span multiple lines, as long as they are indented deeper than the first line of the value.

This means the solution is to use

```<code>[TYPECHECK]
generated-members =
  XXX,
  YYY,
  ZZZ......
</code>```

Body:
I have a PyLint configuration file, .pylintrc, with some rules defined.

However, for one rule, I have quite a few items which results in a very long line.

[TYPECHECK]
generated-members = XXX, YYY, ZZZ......

An example of a long line can be seen here on github:
https://github.com/behave/behave.example/blob/master/pylintrc#L263

Is it possible to break the line to keep listing items on the next line(s)? I've tried to move the items to the next line, however, this seems to make the file invalid.

Body:
pylint parses the .pylintrc file using configparser, which says in its docs:

Values can also span multiple lines, as long as they are indented deeper than the first line of the value.

This means the solution is to use

[TYPECHECK]
generated-members =
  XXX,
  YYY,
  ZZZ......


问:
ToggleClass doesn't work properly with FontAwesome
I'm trying to change the triangle direction on click and with this code, everything works perfect, but now I want to change the first direction because the list is hidden, so, why when I change the first fa-caret-down with right and change the other triangle accordingly it doesn't work?</p>

```<code>collapsible.append('<h5>' + scheme.name + " " + '<em class="fa fa-caret-down"></span></h5>');

if ($('.SchemeSearchExp').length) {
    $("div.schemeHead>h5").click(function () {
        $(this).next('.streetname').toggle();
        $(this).children("em").toggleClass('fa-caret-right');
    });
}
</code>```

答:
Use Event Delegation using .on(), when manipulation selector (i.e. removing and adding classes).

Change your code to

<s>

```<code>$(document).on('click', ".fa-caret-right", function(){
    $(this).next('.streetname').toggle();
    $(this).toggleClass('fa-caret-down');
});
</code>```

</s>

```<code>$(document).on('click', "em.fa", function () {
    $(this).next('.streetname').toggle();
    $(this).toggleClass('fa-caret-right fa-caret-down');
});
</code>```

In place of document you should use closest static container. A good read Direct and delegated events

Additionally, You should use if block in the event handlers

Body:
I'm trying to change the triangle direction on click and with this code, everything works perfect, but now I want to change the first direction because the list is hidden, so, why when I change the first fa-caret-down with right and change the other triangle accordingly it doesn't work?

collapsible.append('
' + scheme.name + " " + '
');

if ($('.SchemeSearchExp').length) {
    $("div.schemeHead>h5").click(function () {
        $(this).next('.streetname').toggle();
        $(this).children("em").toggleClass('fa-caret-right');
    });
}

Body:
Use Event Delegation using .on(), when manipulation selector (i.e. removing and adding classes).

Change your code to

<s>

$(document).on('click', ".fa-caret-right", function(){
    $(this).next('.streetname').toggle();
    $(this).toggleClass('fa-caret-down');
});

</s>

$(document).on('click', "em.fa", function () {
    $(this).next('.streetname').toggle();
    $(this).toggleClass('fa-caret-right fa-caret-down');
});

In place of document you should use closest static container. A good read Direct and delegated events

Additionally, You should use if block in the event handlers


问:
Error while building APK Android Studio 2.2.3
I am trying to generate a signed APK to test my app on a physical device. The app was working functionally before I tried to add the Google AdMob banner ad to my app. I keep getting this error:

```<code>Error:Execution failed for task ':app:transformClassesWithDexForRelease'.
com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzkf;
</code>```

Here is my build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.coolappsforall.fartboard"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 2
        versionName "1.0.1"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false;
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services-ads:11.6.0'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'

    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-appindexing:8.4.0'
}
</code>```

Not exactly sure what is causing the problem, if anyone knows, or if you need anything else, please let me know.

Thank you very much for your time and assistance in this matter.

答:
This is because you have mix different version of Google Play Service dependencies. Hence you need to make them the same:</p>

```<code>dependencies {
    ...
    compile 'com.google.android.gms:play-services-ads:11.6.0'
    compile 'com.google.android.gms:play-services-appindexing:11.6.0'
}
</code>```

Body:
I am trying to generate a signed APK to test my app on a physical device. The app was working functionally before I tried to add the Google AdMob banner ad to my app. I keep getting this error:

Error:Execution failed for task ':app:transformClassesWithDexForRelease'.
com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzkf;

Here is my build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.coolappsforall.fartboard"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 2
        versionName "1.0.1"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false;
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services-ads:11.6.0'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'

    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-appindexing:8.4.0'
}

Not exactly sure what is causing the problem, if anyone knows, or if you need anything else, please let me know.

Thank you very much for your time and assistance in this matter.

Body:
This is because you have mix different version of Google Play Service dependencies. Hence you need to make them the same:

dependencies {
    ...
    compile 'com.google.android.gms:play-services-ads:11.6.0'
    compile 'com.google.android.gms:play-services-appindexing:11.6.0'
}


问:
Javadoc link for vararg methods
Suppose I have this:

```<code>/**
 * Single-word method.
 */
private void say(String word) {
    System.out.println("Single word: " + word);
}

/**
 * Multiple-word method.
 */
private void say(String... words) {
    System.out.print("Multiple words: ");
    for (String word : words) {
        System.out.print(word);
    }
    System.out.println();
}

/**
 * {@link #say(String...)}
 */
@SuppressWarnings("unused")
private void testJavadoc() {
}

public static void main(String[] args) {
    say("hello");
    say("world");
    say("hello", "world");
}
</code>```

If I run this, I get:

```<code>Single word: hello
Single word: world
Multiple words: helloworld
</code>```

This proves that there is nothing wrong in defining a method with String and an overload with String....

When I mouse-over testJavadoc(), this is the Javadoc I see:

```<code>void testJavadoc()

@SuppressWarnings(value={"unused"})

say(String)
</code>```

Clicking on say(String) brings me to the Javadoc for the first method without vararg.

If I remove say(String) method, then the Javadoc works fine.

I'm using eclipse neon 3 (4.6.3). Is this supposed to be the correct behavior?

答:
This looks like it might be a bug in Eclipse, as you are correct in that it should reference the vararg method (I don't have Eclipse so I am unable to test).

Testing in IntelliJ, I can see the expected reference.

More-so, if you go ahead and actually generate the JavaDoc, you should be able to see the correct output.

Title: Javadoc link for vararg methods

Body:
Suppose I have this:

/**
 * Single-word method.
 */
private void say(String word) {
    System.out.println("Single word: " + word);
}

/**
 * Multiple-word method.
 */
private void say(String... words) {
    System.out.print("Multiple words: ");
    for (String word : words) {
        System.out.print(word);
    }
    System.out.println();
}

/**
 * {@link #say(String...)}
 */
@SuppressWarnings("unused")
private void testJavadoc() {
}

public static void main(String[] args) {
    say("hello");
    say("world");
    say("hello", "world");
}

If I run this, I get:

Single word: hello
Single word: world
Multiple words: helloworld

This proves that there is nothing wrong in defining a method with String and an overload with String....

When I mouse-over testJavadoc(), this is the Javadoc I see:

void testJavadoc()

@SuppressWarnings(value={"unused"})

say(String)

Clicking on say(String) brings me to the Javadoc for the first method without vararg.

If I remove say(String) method, then the Javadoc works fine.

I'm using eclipse neon 3 (4.6.3). Is this supposed to be the correct behavior?


问:
Multi-component application build with Excelsior-jet maven plugin
Is there a way to do multi-component applications with excelsior jet maven plugin?

Our normal way of building excelsior installer is to have two excelsior projects "app.prj/exe" and "dep.prj/dll". In "app.exe" there is our application code, in "dep.dll" there are third party dependencies which are not changed a lot. With this two components we can quickly build excelsior installer without having to rebuild "dep" again.

In "app.prj" we are using directive !uses, but I cannot find it in maven plugin.

Now we want to use maven excelsior jet plugin in our project, but can/how we do it as multi-component application?

答:
Copying the answer from the plugin's bug tracker on GitHub:

No, the plugin does not support it yet.

<...>

We are working on this problem and we are going to support global compilation cache in the compiler itself (so you will not need to recompile your dependencies). Multi-component support from the plugin is possible but as far as multi-component model is used as workaround for the compilation problem, we think that we need to provide a better solution for the problem.


问:
Casting, unboxing, conversion..?
Recently I am learning value types and I am bit confused. Also both casting and unboxing uses the same syntax - (expected type)(object), right?
And what about simple conversion between types, that is casting or just conversion?</p>

```<code>int x = (int)2.5; //casting?

object a=x;
int Y=(int)a;  //unboxing I think

Random r=new Random();
object X=r;
Random R=(Random)X;  // casting
</code>```

答:
There's a lot of things to consider here, but let's tackle the simplest first:

What is the syntax (type)expression?

Well, in its basic form, it is considered casting. You cast the expression from one type, to another. That's it.

However, what exactly happens, that depends on the type, and a lot of other things.

If casting a value type to something else, you depend on one of the two types involved to declare a casting operator that handles this. In other words, either the value type need to define a casting operator that can cast to that other type, or that other type need to define a casting operator that can cast from the original type.

What that operator does, is up to the author of that operator. It's a method, so it can do anything.

Casting a value type to some other type gives you a different value, a separate value type, or a new reference type, containing the new data after casting.

Example:

```<code>int a = (int)byteValue;
</code>```

Boxing and unboxing comes into play when you're casting a value type to and from a reference type, typically object, or one of the interfaces the value type implements.

Example:

```<code>object o = intValue; // boxing
int i = (int)o;      // unboxing
</code>```

Boxing also comes into play when casting to an interface. Let's assume that "someValueType" is a struct, which also implements IDisposable:

```<code>IDisposable disp = (IDisposable)someValueType; // boxed
</code>```

Casting a reference type, can do something else as well.

First, you can define the same casting operators that were involved in value types, which means casting one reference type to another can return a wholly new object, containing quite different type of information.

Boxing does not come into play when casting a reference type, unless you cast a reference type back to a value type (see above.)

Example:

```<code>string s = (string)myObjectThatCanBeConvertedToAString;
</code>```

Or, you can just reinterpret the reference, so that you still refer to the same object in question, but you are looking at it through a different pair of type glasses.

Example:

```<code>IDisposable disp = (IDisposable)someDisposableObject;
</code>```

Title: Casting, unboxing, conversion..?

Body:
Recently I am learning value types and I am bit confused. Also both casting and unboxing uses the same syntax - (expected type)(object), right?
And what about simple conversion between types, that is casting or just conversion?

int x = (int)2.5; //casting?

object a=x;
int Y=(int)a;  //unboxing I think

Random r=new Random();
object X=r;
Random R=(Random)X;  // casting

Body:
There's a lot of things to consider here, but let's tackle the simplest first:

What is the syntax (type)expression?

Well, in its basic form, it is considered casting. You cast the expression from one type, to another. That's it.

However, what exactly happens, that depends on the type, and a lot of other things.

If casting a value type to something else, you depend on one of the two types involved to declare a casting operator that handles this. In other words, either the value type need to define a casting operator that can cast to that other type, or that other type need to define a casting operator that can cast from the original type.

What that operator does, is up to the author of that operator. It's a method, so it can do anything.

Casting a value type to some other type gives you a different value, a separate value type, or a new reference type, containing the new data after casting.

Example:

int a = (int)byteValue;

Boxing and unboxing comes into play when you're casting a value type to and from a reference type, typically object, or one of the interfaces the value type implements.

Example:

object o = intValue; // boxing
int i = (int)o;      // unboxing

Boxing also comes into play when casting to an interface. Let's assume that "someValueType" is a struct, which also implements IDisposable:

IDisposable disp = (IDisposable)someValueType; // boxed

Casting a reference type, can do something else as well.

First, you can define the same casting operators that were involved in value types, which means casting one reference type to another can return a wholly new object, containing quite different type of information.

Boxing does not come into play when casting a reference type, unless you cast a reference type back to a value type (see above.)

Example:

string s = (string)myObjectThatCanBeConvertedToAString;

Or, you can just reinterpret the reference, so that you still refer to the same object in question, but you are looking at it through a different pair of type glasses.

Example:

IDisposable disp = (IDisposable)someDisposableObject;


问:
How to remake a request under query builder
Please, help me!

How i can remake this request under query builder. Doctrine2

```<code>    SELECT *
FROM orders AS o
  INNER JOIN states AS s ON o.OrderId = s.orderID

WHERE o.partnerId = 52 AND
      (s.state = 'CANCEL' OR s.state = 'FINISH') AND
      (s.dt BETWEEN '2017-01-01 00:00:00' AND '2017-10-30 00:00:00')
</code>```

Orders

```<code>class Order
{
/**
     * @var State[] $states
     * @OneToMany(targetEntity="State", mappedBy="order", cascade={"persist"})
     * @OrderBy({"dt" = "DESC"})
     */
    protected $states;
}
</code>```

States

```<code>class State
{

    public function __construct($state = null)
    {
        $this->state = $state;
    }

    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Column(type="integer")
     */
    protected $orderId;

    /**
     * @Column(type="datetime")
     */
    protected $dt;

    /**
     * @Column(type="string", columnDefinition="enum('NEW','REGIST','SENTTOSHOP','ARRIVEDTOSHOP','FINISH','CANCEL','RETURNEDTOSTORAGE')")
     */
    protected $state;

    /**
     * @var $order
     * @ManyToOne(targetEntity="Zabberi\Order", inversedBy="states")
     * @JoinColumn(name="orderId", referencedColumnName="OrderId")
     */
    protected $order;
}
</code>```

Sorry if I did not understand you.

Some text... |  It provides a set of classes and methods that is able to programmatically build queries, and also provides a fluent API. This means that you can change between one methodology to the other as you want, or just pick a preferred one.>

答:
You can write your query using query builder as </p>

```<code> $qb = $em->getRepository('YourBundle:Order');
 $qb->createQueryBuilder('o')
    ->select('o,s')
    ->join('o.states','s')
    ->where("s.state IN(:states)")
    ->andWhere('s.dt BETWEEN :date1 AND :date2')
   ->setParameter('states', array('CANCEL','FINISH'))
   ->setParameter('date1', '2017-01-01 00:00:00')
   ->setParameter('date2', '2017-10-30 00:00:00')
   ->getQuery()
   ->getResult()
   ;
</code>```

Body:
Please, help me!

How i can remake this request under query builder. Doctrine2

    SELECT *
FROM orders AS o
  INNER JOIN states AS s ON o.OrderId = s.orderID

WHERE o.partnerId = 52 AND
      (s.state = 'CANCEL' OR s.state = 'FINISH') AND
      (s.dt BETWEEN '2017-01-01 00:00:00' AND '2017-10-30 00:00:00')

Orders

class Order
{
/**
     * @var State[] $states
     * @OneToMany(targetEntity="State", mappedBy="order", cascade={"persist"})
     * @OrderBy({"dt" = "DESC"})
     */
    protected $states;
}

States

class State
{

    public function __construct($state = null)
    {
        $this->state = $state;
    }

    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Column(type="integer")
     */
    protected $orderId;

    /**
     * @Column(type="datetime")
     */
    protected $dt;

    /**
     * @Column(type="string", columnDefinition="enum('NEW','REGIST','SENTTOSHOP','ARRIVEDTOSHOP','FINISH','CANCEL','RETURNEDTOSTORAGE')")
     */
    protected $state;

    /**
     * @var $order
     * @ManyToOne(targetEntity="Zabberi\Order", inversedBy="states")
     * @JoinColumn(name="orderId", referencedColumnName="OrderId")
     */
    protected $order;
}

Sorry if I did not understand you.

Some text... |  It provides a set of classes and methods that is able to programmatically build queries, and also provides a fluent API. This means that you can change between one methodology to the other as you want, or just pick a preferred one.>

Body:
You can write your query using query builder as

 $qb = $em->getRepository('YourBundle:Order');
 $qb->createQueryBuilder('o')
    ->select('o,s')
    ->join('o.states','s')
    ->where("s.state IN(:states)")
    ->andWhere('s.dt BETWEEN :date1 AND :date2')
   ->setParameter('states', array('CANCEL','FINISH'))
   ->setParameter('date1', '2017-01-01 00:00:00')
   ->setParameter('date2', '2017-10-30 00:00:00')
   ->getQuery()
   ->getResult()
   ;


问:
How to test view and controller logic that relies on the created_at property?
I'm brand new to Ruby on Rails.

I have an application with a simple controller and view that render an HTML page with a list of Active Record objects from my database in least-recently-created (oldest first) order.

I'm attempt to write a test that verifies this sorting behavior by creating two objects with different created_at values, then verifying that the generated HTML has the oldest item first (using assert_select).

However, when I try to manually alter the created_at value on one of my objects (to ensure that my objects don't have the same created_at value), the other properties of the object appear to be set to a default value.  For example, this code in my test results in an Image object with an url property value of http://www.example.com/image1.png, as expected:

```<code>@image1 = Image.create!(url: 'http://www.example.com/image1.png')
</code>```

However, this code results in the url property value in the database unexpectedly changing to MyString:

```<code>@image1 = Image.create!(url: 'http://www.example.com/image1.png')
@image1.created_at = '2017-09-25'
@image1.save
</code>```

I'm using ruby 2.3.3 and rails 5.1.1.1 (per my Gemfile).

I have two questions at this point:

Why does setting the created_at value on my object have the apparent side effect of changing the value of the url property to MyString? Is changing the created_at date just not allowed?

What's the proper way to go about arranging data in a test that exercises logic where the created_at dates of objects need to have particular values?

答:
The type of the created_at attribute should be DateTime instead of String. You mess up the test object when trying to assign a string to the created_at attribute. Try the following

```<code>@image1.created_at = 2.days.from_now
</code>```

or

```<code>@image1.created_at = 2.days.ago
</code>```

Body:
I'm brand new to Ruby on Rails.

I have an application with a simple controller and view that render an HTML page with a list of Active Record objects from my database in least-recently-created (oldest first) order.

I'm attempt to write a test that verifies this sorting behavior by creating two objects with different created_at values, then verifying that the generated HTML has the oldest item first (using assert_select).

However, when I try to manually alter the created_at value on one of my objects (to ensure that my objects don't have the same created_at value), the other properties of the object appear to be set to a default value.  For example, this code in my test results in an Image object with an url property value of http://www.example.com/image1.png, as expected:

@image1 = Image.create!(url: 'http://www.example.com/image1.png')

However, this code results in the url property value in the database unexpectedly changing to MyString:

@image1 = Image.create!(url: 'http://www.example.com/image1.png')
@image1.created_at = '2017-09-25'
@image1.save

I'm using ruby 2.3.3 and rails 5.1.1.1 (per my Gemfile).

I have two questions at this point:

Why does setting the created_at value on my object have the apparent side effect of changing the value of the url property to MyString? Is changing the created_at date just not allowed?

What's the proper way to go about arranging data in a test that exercises logic where the created_at dates of objects need to have particular values?

Body:
The type of the created_at attribute should be DateTime instead of String. You mess up the test object when trying to assign a string to the created_at attribute. Try the following

@image1.created_at = 2.days.from_now

or

@image1.created_at = 2.days.ago


问:
Optional monad and the Law of Demeter in Java
while I was reviewing some code, I came across this snippet.

```<code>List<User> users = /* Some code that initializes the list */;
users.stream()
     .filter(user -> user.getAddress().isPresent())
     .map(/* Some code */)
// And so on...
</code>```

The call of method user.getAddress() returns an Optional<Address>. Following the famous Law of Demeter (LoD), the above code is not clean. However, I cannot figure out how to refactor it to make it cleaner.

As a first attempt could be to add to the User class a method hasAddress(), but this method overcomes the need of having an Optional<Address>, IMO.

How should I refactor the above code? In this case, is it worth to satisfy the LoD?

EDIT: I missed specifying that in the map method I do not want to return the address.

答:
Well, you summarized it yourself pretty well: If you wanted to couple more loosely by introducing hasAddress(), why return an Optional.

Reading into what the LoD says, it talks about having "limited" knowledge about "closely related" units. Sounds like a gray area to me, but going further it also mentions the "Only one dot" rule. Still, I would agree with the comments to your question that a null check (or isPresent()) is entirely fine (heck, a real null check technically doesn't even need a dot ;P ).

If you wanted to really encapsulate more, you could remove the getAddress() completely and instead offer:

```<code>class User {
    private Optional<Address> address;

    boolean hasAddress() {
        return address.isPresent();
    }

    // still exposes address to the consumer, guard your properties
    void ifAddressPresent(Consumer<Address> then) {
        address.ifPresent(then::accept);
    }

    // does not expose address, but caller has no info about it
    void ifAddressPresent(Runnable then) {
        address.ifPresent(address -> then.run());
    }

    // really keep everything to yourself, allowing no outside interference
    void ifAddressPresentDoSomeSpecificAction() {
        address.ifPresent(address -> {
            // do this
            // do that
        });
    }
}
</code>```

But again, as the commenters pointed out: Is it worth it/necessary? All these laws/principles are rarely absolute and more guidelines than dogmas. In this case it might be about balancing LoD vs. KISS.

In the end, it is up to you to decide whether this specific example benefits from moving the functionality of your stream into the User class. Both are valid, and readability/maintainability/cleanliness depend on:

the specific case

how exposed this code is to other modules

the number of delegate methods you would need in the User class

your architecture (If you are in a UserDao class for example, do you really want to move database access your User POJO class? Isn't the DAO made for exactly this purpose? Does this qualify as "closely related" and would allow a violation of the "Only one dot" rule?)

...

Body:
while I was reviewing some code, I came across this snippet.

List<User> users = /* Some code that initializes the list */;
users.stream()
     .filter(user -> user.getAddress().isPresent())
     .map(/* Some code */)
// And so on...

The call of method user.getAddress() returns an Optional<Address>. Following the famous Law of Demeter (LoD), the above code is not clean. However, I cannot figure out how to refactor it to make it cleaner.

As a first attempt could be to add to the User class a method hasAddress(), but this method overcomes the need of having an Optional<Address>, IMO.

How should I refactor the above code? In this case, is it worth to satisfy the LoD?

EDIT: I missed specifying that in the map method I do not want to return the address.

Body:
Well, you summarized it yourself pretty well: If you wanted to couple more loosely by introducing hasAddress(), why return an Optional.

Reading into what the LoD says, it talks about having "limited" knowledge about "closely related" units. Sounds like a gray area to me, but going further it also mentions the "Only one dot" rule. Still, I would agree with the comments to your question that a null check (or isPresent()) is entirely fine (heck, a real null check technically doesn't even need a dot ;P ).

If you wanted to really encapsulate more, you could remove the getAddress() completely and instead offer:

class User {
    private Optional<Address> address;

    boolean hasAddress() {
        return address.isPresent();
    }

    // still exposes address to the consumer, guard your properties
    void ifAddressPresent(Consumer<Address> then) {
        address.ifPresent(then::accept);
    }

    // does not expose address, but caller has no info about it
    void ifAddressPresent(Runnable then) {
        address.ifPresent(address -> then.run());
    }

    // really keep everything to yourself, allowing no outside interference
    void ifAddressPresentDoSomeSpecificAction() {
        address.ifPresent(address -> {
            // do this
            // do that
        });
    }
}

But again, as the commenters pointed out: Is it worth it/necessary? All these laws/principles are rarely absolute and more guidelines than dogmas. In this case it might be about balancing LoD vs. KISS.

In the end, it is up to you to decide whether this specific example benefits from moving the functionality of your stream into the User class. Both are valid, and readability/maintainability/cleanliness depend on:

the specific case

how exposed this code is to other modules

the number of delegate methods you would need in the User class

your architecture (If you are in a UserDao class for example, do you really want to move database access your User POJO class? Isn't the DAO made for exactly this purpose? Does this qualify as "closely related" and would allow a violation of the "Only one dot" rule?)

...


问:
Remove words from string
I'm trying to remove certain words from a data frame:

```<code>name    age words
James   34  hello, my name is James.
John    30  hello, my name is John. Here is my favourite website https://stackoverflow.com
Jim 27  Hi! I'm another person whose name begins with a J! Here is something that should be filtered out: <filter>
</code>```

```<code>df<-structure(list(name = structure(c(1L, 3L, 2L), .Label = c("James",
"Jim", "John"), class = "factor"), age = c(34L, 30L, 27L), message = structure(1:3, .Label = c("hello, my name is James. ",
"hello, my name is John. Here is my favourite website https://stackoverflow.com",
"Hi! I'm another person whose name begins with a J! Here is something that should be filtered out: <filter>"
), class = "factor")), .Names = c("name", "age", "message"), class = "data.frame", row.names = c(NA,
-3L))
</code>```

I'm trying to remove all words containing matches to http or filter.

I would like to iterate over each row, split the string on white space and then ask whether the word contains either http or <filter> (or other words). If so, then I want to replace the word with a space.

There are a load of questions concerning removing words that exatly match another word, or list of words, but I can't find much on removing words that match some criteria (e.g. http or www.).

I've tried:

gsub, !grepl and tm_map approaches (e.g. this), but I can't get any of them to produce my expected output of:

```<code>name    age words
James   34  hello, my name is James.
John    30  hello, my name is John. Here is my favourite website
Jim 27  Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out:
</code>```

答:
To remove any non-whitespace chunks containing either http or filter (or other words) as whole words you may use gsub with the following PCRE regex (add perl=TRUE argument):

```<code>(?:\s+|^)\S*(?<!\w)(?:https?|<filter>)(?!\w)\S*
</code>```

See the regex demo

Details

(?:\s+|^) - 1+ wjhitespaces or start of string

\S* - 0+ non-whitespace chars as many as possible

(?<!\w) - no word char allowed immediately to the left of the current location

(?:https?|<filter>) - http, https or <filter>

(?!\w) - no word char allowed immediately to the right of the current location (after the words in the alternation group)

\S* - 0+ non-whitespace chars as many as possible.

See an online R demo:

```<code>df<-structure(list(name = structure(c(1L, 3L, 2L), .Label = c("James",
"Jim", "John"), class = "factor"), age = c(34L, 30L, 27L), message = structure(1:3, .Label = c("hello, my name is James. ",
"hello, my name is John. Here is my favourite website https://stackoverflow.com",
"Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out: <filter>"
), class = "factor")), .Names = c("name", "age", "message"), class = "data.frame", row.names = c(NA,
-3L))
df$message <- gsub("(?:\\s+|^)\\S*(?<!\\w)(?:https?|<filter>)(?!\\w)\\S*", "", df$message, perl=TRUE)
df$message
</code>```

Result:

```<code>[1] "hello, my name is James. "
[2] "hello, my name is John. Here is my favourite website"
[3] "Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out:"
</code>```

Title: Remove words from string

Body:
I'm trying to remove certain words from a data frame:

name    age words
James   34  hello, my name is James.
John    30  hello, my name is John. Here is my favourite website https://stackoverflow.com
Jim 27  Hi! I'm another person whose name begins with a J! Here is something that should be filtered out: <filter>

df<-structure(list(name = structure(c(1L, 3L, 2L), .Label = c("James",
"Jim", "John"), class = "factor"), age = c(34L, 30L, 27L), message = structure(1:3, .Label = c("hello, my name is James. ",
"hello, my name is John. Here is my favourite website https://stackoverflow.com",
"Hi! I'm another person whose name begins with a J! Here is something that should be filtered out: <filter>"
), class = "factor")), .Names = c("name", "age", "message"), class = "data.frame", row.names = c(NA,
-3L))

I'm trying to remove all words containing matches to http or filter.

I would like to iterate over each row, split the string on white space and then ask whether the word contains either http or <filter> (or other words). If so, then I want to replace the word with a space.

There are a load of questions concerning removing words that exatly match another word, or list of words, but I can't find much on removing words that match some criteria (e.g. http or www.).

I've tried:

gsub, !grepl and tm_map approaches (e.g. this), but I can't get any of them to produce my expected output of:

name    age words
James   34  hello, my name is James.
John    30  hello, my name is John. Here is my favourite website
Jim 27  Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out:

Body:
To remove any non-whitespace chunks containing either http or filter (or other words) as whole words you may use gsub with the following PCRE regex (add perl=TRUE argument):

(?:\s+|^)\S*(?<!\w)(?:https?|<filter>)(?!\w)\S*

See the regex demo

Details

(?:\s+|^) - 1+ wjhitespaces or start of string

\S* - 0+ non-whitespace chars as many as possible

(?<!\w) - no word char allowed immediately to the left of the current location

(?:https?|<filter>) - http, https or <filter>

(?!\w) - no word char allowed immediately to the right of the current location (after the words in the alternation group)

\S* - 0+ non-whitespace chars as many as possible.

See an online R demo:

df<-structure(list(name = structure(c(1L, 3L, 2L), .Label = c("James",
"Jim", "John"), class = "factor"), age = c(34L, 30L, 27L), message = structure(1:3, .Label = c("hello, my name is James. ",
"hello, my name is John. Here is my favourite website https://stackoverflow.com",
"Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out: <filter>"
), class = "factor")), .Names = c("name", "age", "message"), class = "data.frame", row.names = c(NA,
-3L))
df$message <- gsub("(?:\\s+|^)\\S*(?<!\\w)(?:https?|<filter>)(?!\\w)\\S*", "", df$message, perl=TRUE)
df$message

Result:

[1] "hello, my name is James. "
[2] "hello, my name is John. Here is my favourite website"
[3] "Hi! I'm another persoon whose name begins with a J! Here is something that should be filtered out:"


问:
How to read the birthday_date from the Facebook API
I have been chasing my tail on this! And it should be so simple!!

I have an app in FaceBook that is working fine. However, I need to get the user's birth date. I have successfully got the request for extended permissions, but cannot get the birthday_date out and into a variable/store in database.

```<code><?php
require_once('facebook.php');
$facebook = new Facebook(array(
'appId'  => 'xxxxx',
'secret' => 'yyyyyyy',
'cookie' => true
));
if ($facebook->getSession()) {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} else {
$params = array(
    'fbconnect'=>0,
    'canvas'=>1,
    'req_perms'=>'publish_stream','email','user_location','user_birthday'
);
$loginUrl = $facebook->getLoginUrl($params);
print "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
}
$session = $facebook->getSession();
$token = $session['access_token'];
</code>```

I would be very grateful if someone could show me the PHP code that reads the extended permissions and places the results into variables.

Thanks Steve

答:
this works in Linux

NOW=$(date +"%m/%d")

curl "https://api.facebook.com/method/fql.query?access_token=[ACCESS_TOKEN]&query=SELECT%20first_name,uid%20from%20user%20where%20uid%20in%20(SELECT%20uid2%20from%20friend%20where%20uid1=[YourFaceID])AND%20substr(birthday_date,0,5)%20==%20'$NOW'"

Body:
I have been chasing my tail on this! And it should be so simple!!

I have an app in FaceBook that is working fine. However, I need to get the user's birth date. I have successfully got the request for extended permissions, but cannot get the birthday_date out and into a variable/store in database.

<?php
require_once('facebook.php');
$facebook = new Facebook(array(
'appId'  => 'xxxxx',
'secret' => 'yyyyyyy',
'cookie' => true
));
if ($facebook->getSession()) {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} else {
$params = array(
    'fbconnect'=>0,
    'canvas'=>1,
    'req_perms'=>'publish_stream','email','user_location','user_birthday'
);
$loginUrl = $facebook->getLoginUrl($params);
print "";
}
$session = $facebook->getSession();
$token = $session['access_token'];

I would be very grateful if someone could show me the PHP code that reads the extended permissions and places the results into variables.

Thanks Steve


问:
How to control cells table alignment on a plot?
I am currently trying to align the cells table with a gaussian using
colWidths:

But colWidths seems to not work with bbox.
Do you have any idea how I can proceed?

```<code>plt.table(cellText=tableData,
                  rowLabels=rowLabels,
                  colLabels=None,loc='center',colWidths=[0.2]*5,
                  bbox=[0., -0.5,1, 0.3])
</code>```

答:
Finally, I decided to suppress the x axis of my plot.
I haven't use bbox and I sticked the table to the plot using loc='bottom'.
Concerning the size of the cell I use : cell.set_width

```<code>table_prop = stats_table.properties()

table_cells = table_prop['child_artists']
for cell in table_cells:

    cell.set_width((z2-z1)/4.4)
    cell.set_linewidth(2)
#needed for precision problem between line from the gaussian and line from the border of the cell
</code>```

Here the result

Body:
I am currently trying to align the cells table with a gaussian using
colWidths:

But colWidths seems to not work with bbox.
Do you have any idea how I can proceed?

plt.table(cellText=tableData,
                  rowLabels=rowLabels,
                  colLabels=None,loc='center',colWidths=[0.2]*5,
                  bbox=[0., -0.5,1, 0.3])

Body:
Finally, I decided to suppress the x axis of my plot.
I haven't use bbox and I sticked the table to the plot using loc='bottom'.
Concerning the size of the cell I use : cell.set_width

table_prop = stats_table.properties()

table_cells = table_prop['child_artists']
for cell in table_cells:

    cell.set_width((z2-z1)/4.4)
    cell.set_linewidth(2)
#needed for precision problem between line from the gaussian and line from the border of the cell

Here the result


问:
apk running on AVD but not on phone
My compileSdkVersion is 26

minSdkVersion is 15

and TargetSdkVersion is 26

App runs fine on AVD of API level 22 but when installed on phone and opened it shows "Unfortunately APP has stopped". My phone is running in jellybean.

答:
If you are using below 6.0 version you don't need to write permission at runtime but you have to mention in manifest.

Maybe you have use third party library which is not supported in your device.

Title: apk running on AVD but not on phone


问:
How do I deep compile nested handlebars content?
A project I'm working on uses Handlebars.js template system. It reads in content and when compiling the template injects the content where appropriate:

```<code><div class="content">
  <p>lorem ipsum</p>

  {{{ content }}}

</div>
</code>```

In this case the handlebars is compiled with a JS object who has a content property that is a string of text or HTML (hence the triple brackets).

However it is entirely possible that the content value (being text or HTML) could also include handlebars interpolation code:

```<code>var contentPassedToHandlebars = {
  content: '<p>{{ foobar }}</p>',
  foobar: 'foo'
};
</code>```

Which currently outputs
{{ foobar }}
 but what I would intend to get is
foo
.

Does handlebars have a facility for this nested content or is a custom helper required? ({{{custom_parse content}}})?

For context to this question

The situation derived from a build system (metalsmith) that reads in files as markdown, converted them to HTML, attach result to the content property of the file object, then parse a handlebars template which injects the file.content into it output. All this and I was hoping there was a solution to place handlebars or string interpolation into the markdown so the markdown files could have access to the same variables the templates have access to (obviously more global values in a config.json not the values associated with the file object being constructed).

答:
OR use this:

metalsmith-in-place

```<code>```
index.js
var inPlace = require('metalsmith-in-place')

....
.use(inPlace(true))
.....
```

Now, if you
write {{> footer }}
it will do the work.

Body:
A project I'm working on uses Handlebars.js template system. It reads in content and when compiling the template injects the content where appropriate:

lorem ipsum

  {{{ content }}}

In this case the handlebars is compiled with a JS object who has a content property that is a string of text or HTML (hence the triple brackets).

However it is entirely possible that the content value (being text or HTML) could also include handlebars interpolation code:

var contentPassedToHandlebars = {
  content: '
{{ foobar }}
',
  foobar: 'foo'
};

Which currently outputs
{{ foobar }}
 but what I would intend to get is
foo
.

Does handlebars have a facility for this nested content or is a custom helper required? ({{{custom_parse content}}})?

For context to this question

The situation derived from a build system (metalsmith) that reads in files as markdown, converted them to HTML, attach result to the content property of the file object, then parse a handlebars template which injects the file.content into it output. All this and I was hoping there was a solution to place handlebars or string interpolation into the markdown so the markdown files could have access to the same variables the templates have access to (obviously more global values in a config.json not the values associated with the file object being constructed).

Body:
OR use this:

metalsmith-in-place

```
index.js
var inPlace = require('metalsmith-in-place')

....
.use(inPlace(true))
.....

Now, if you
write {{> footer }}
it will do the work.


问:
Safest way to update game score from client to server database? Javascript
So I have this game that is completely run on the client. No server interaction what so ever apart from downloading the initial scripts to play the game. Anyway at the end of the game I would like for the client to send me back the scores which should be updated in the server database. Now I have come to accept the fact that there is no way on earth I can hide this from a hacker and send the scores unaltered. But I would like to know till what level can I modify the whole process that it virtually becomes pretty infeasible for the hacker manipulate the data which is being sent. For sure I would not like the score to be sent as plain text from client machine and I don't want my server to perform complex decryption algorithm. What is the best way hence to achieve considerable amount of security that every tom dick and harry doesn't hack the scores... I hope someone could provide a nice little way that I could work on... :) Thanks

So my ideal result should be -> have trusted result from a calculation (of score) made by an untrusted party (the player)!

-Edit-

Someone told me something about hiding the data in a picture get request. Like, I am implementing this game on canvas (html5). So he asked me at the end of the game to fetch a game over image from my server, and they request should contain the hashed score. I did not exactly understand the complete process but if you could explain it, would be really glad! :)

coda^   so you can mask the requests nicely

shouvik how do I do it!?

coda^   you can compose the checksum you want to submit. like 12312312a12313a232 is your md5 which contains the score. bring in an asset into the canvas like

coda^   server.com/images/md5_hash_of_score/congratulations.png

coda^   which you can rewrite server side via htaccess

答:
You seem to know this already, but just to stress; you cannot stop someone doing this; you can only make it as hard as possible!

Assume you currently submit the score as:

```<code>/submit_score.php?score=5
</code>```

Someone watching in Firebug can easily distinguish where the score is submitted, and to alter it. submit_score.php gives it away, as does the name of the parameter. The score is a easily distinguishable integer.

Change the end point: /interaction.php?score=5

Change the parameter name: /interaction.php?a=5

It's getting harder for the user to work out what is going on.

Now you can make the score harder (again, harder, not impossible), to change. First, you can encrypt it (obviously you'll need to be able to decrpt it later).

Base 64 encode it.

Numbers -> Letters (1=a, 2=b, etc).

Reverse the order of the score representation.

You name it, you do it. So you now have interaction.php?a=e.

The next thing you can do is hash the score with something else. Send the hash with the score, and recalculate it on the server. For example, md5() the score with a random string, and send the score (encoded), the string, and the hash in the request:

```<code>/interaction.php?a=e&str=abcde&hash=123456789abcefbc
</code>```

When the request hits the server, do:

```<code>if (md5($_GET['a'] . $_GET['str']) !== $_GET['hash']) exit;
</code>```

Obviously people can (relatively) easily go through your JavaScript code and see what's going on; so make it harder for them there. Minify and Obfuscate the code.

If you make it hard enough for someone, they're going to try understand your JavaScript, try using Firebug, not understand what's going on, and not bother; for the sake of getting a few extra points on your game.

Body:
You seem to know this already, but just to stress; you cannot stop someone doing this; you can only make it as hard as possible!

Assume you currently submit the score as:

/submit_score.php?score=5

Someone watching in Firebug can easily distinguish where the score is submitted, and to alter it. submit_score.php gives it away, as does the name of the parameter. The score is a easily distinguishable integer.

Change the end point: /interaction.php?score=5

Change the parameter name: /interaction.php?a=5

It's getting harder for the user to work out what is going on.

Now you can make the score harder (again, harder, not impossible), to change. First, you can encrypt it (obviously you'll need to be able to decrpt it later).

Base 64 encode it.

Numbers -> Letters (1=a, 2=b, etc).

Reverse the order of the score representation.

You name it, you do it. So you now have interaction.php?a=e.

The next thing you can do is hash the score with something else. Send the hash with the score, and recalculate it on the server. For example, md5() the score with a random string, and send the score (encoded), the string, and the hash in the request:

/interaction.php?a=e&str=abcde&hash=123456789abcefbc

When the request hits the server, do:

if (md5($_GET['a'] . $_GET['str']) !== $_GET['hash']) exit;

Obviously people can (relatively) easily go through your JavaScript code and see what's going on; so make it harder for them there. Minify and Obfuscate the code.

If you make it hard enough for someone, they're going to try understand your JavaScript, try using Firebug, not understand what's going on, and not bother; for the sake of getting a few extra points on your game.


问:
How Stencil is different from React and Angular?
I am familiar with Angular and know basics of React. I was exploring stencil docs,  I found stencil component has both @Component decorator and render() method -

component.tsx

```<code>import { Component, Prop } from '@stencil/core';

@Component({
    tag: 'my-first-component',
    styleUrl: 'my-first-component.scss'
})
export class MyComponent {
    // Indicate that name should be a public property on the component
    @Prop() firstName: string;

    render() {
        return (
            <p>
            My name is {this.firstName}
            </p>
        );
    }
}
</code>```

Help me to understand that how Stencil is different from angular and react and how it works?

答:
First of all stencil is a compiler which compile the stencil web component (tsx) to the vanilla javascript without any dependency.

The curious question is does we don't use angular , vue etc.

Even it is possible to make whole app with stencil , the idea is to make individual component independent of framework . You can use them in any framework or can use independently .

So that you don't have to take a pain for switching framework(angular, vue etc.) from an version to higher version.

Body:
I am familiar with Angular and know basics of React. I was exploring stencil docs,  I found stencil component has both @Component decorator and render() method -

component.tsx

import { Component, Prop } from '@stencil/core';

@Component({
    tag: 'my-first-component',
    styleUrl: 'my-first-component.scss'
})
export class MyComponent {
    // Indicate that name should be a public property on the component
    @Prop() firstName: string;

    render() {
        return (

            My name is {this.firstName}

        );
    }
}

Help me to understand that how Stencil is different from angular and react and how it works?


答:
I'm assuming an empty line breaks one block from another. Feel free to change that condition in the first line inside the for loop.

```<code>blocks, currentBlock = [], []
for line in lines:
    if line=='' and currentBlock:
        blocks.append(currentBlock)
        currentBlock = []
    else:
        currentBlock.append(line)
# if last line was not an empty, currentBlock is not empty, and must be appended:
if currentBlock:
    blocks.append(currentBlock)
</code>```

This would give you in blocks an array of arrays of lines:

```<code>[
    ['C5401D8E17292151102G41+0NN003EXE00812 ', '+0000.,+13.53,+24.39,+23.15,+09.02,+1010.,+254.9,+21.32,-8190.,+0.039,+17.58,+263.2,+10.00,+0.000,+0.000,+5.442,+237.7,+0.000,+764.1,', ...],
    ['C5401D8E17292141102G43+0NN003EXE00812 ', ...
</code>```

To sort these blocks use list.sort and supply a key function to extract the sort key (date, contained in first line in characters 8:15):

```<code>blocks.sort(key=lambda lines: datetime.datetime.strptime(lines[0][8:15],'%y%j%H'))
</code>```

Now you can print the blocks in the same format:

```<code>for block in blocks:
    for line in block:
        print(line)
    print('')
</code>```

Title: python: Read blocked data to list

Body:
I'm assuming an empty line breaks one block from another. Feel free to change that condition in the first line inside the for loop.

blocks, currentBlock = [], []
for line in lines:
    if line=='' and currentBlock:
        blocks.append(currentBlock)
        currentBlock = []
    else:
        currentBlock.append(line)
# if last line was not an empty, currentBlock is not empty, and must be appended:
if currentBlock:
    blocks.append(currentBlock)

This would give you in blocks an array of arrays of lines:

[
    ['C5401D8E17292151102G41+0NN003EXE00812 ', '+0000.,+13.53,+24.39,+23.15,+09.02,+1010.,+254.9,+21.32,-8190.,+0.039,+17.58,+263.2,+10.00,+0.000,+0.000,+5.442,+237.7,+0.000,+764.1,', ...],
    ['C5401D8E17292141102G43+0NN003EXE00812 ', ...

To sort these blocks use list.sort and supply a key function to extract the sort key (date, contained in first line in characters 8:15):

blocks.sort(key=lambda lines: datetime.datetime.strptime(lines[0][8:15],'%y%j%H'))

Now you can print the blocks in the same format:

for block in blocks:
    for line in block:
        print(line)
    print('')


问:
How to get clipboard data in non main thread?
I'm trying to get data from Clipboard with the below code.

```<code>private void TestBtn_Click(object sender, EventArgs e)
{
 Thread sampleThread = new Thread(SampleMethod);
 sampleThread.IsBackground = true;
 sampleThread.Start();
 Thread.Sleep(2000);
 var textFromMain = Clipboard.GetText(TextDataFormat.Text);
}

private void SampleMethod()
{
 var textFromThread = Clipboard.GetText(TextDataFormat.Text);
 Thread.Sleep(1000);
}
</code>```

I'm getting whatever text copied to clipboard with this line -

var textFromMain = Clipboard.GetText(TextDataFormat.Text);

But below line returns empty string or blank string.

var textFromThread = Clipboard.GetText(TextDataFormat.Text);

I'm not getting what's the issue. Can somebody help me to understand. If it's multi-threading, please point me to right direction.

答:
I finally used below method to access Clipboard text.</p>
```<code>private string GetClipboardData()
    {
        try
        {
            string clipboardData= null;
            Exception threadEx = null;
            Thread staThread = new Thread(
                delegate ()
                {
                    try
                    {
                        clipboardData= Clipboard.GetText(TextDataFormat.Text);
                    }

                    catch (Exception ex)
                    {
                        threadEx = ex;
                    }
                });
            staThread.SetApartmentState(ApartmentState.STA);
            staThread.Start();
            staThread.Join();
            return clipboardData;
        }
        catch (Exception exception)
        {
            return string.Empty;
        }
    }
</code>```

Body:
I'm trying to get data from Clipboard with the below code.

private void TestBtn_Click(object sender, EventArgs e)
{
 Thread sampleThread = new Thread(SampleMethod);
 sampleThread.IsBackground = true;
 sampleThread.Start();
 Thread.Sleep(2000);
 var textFromMain = Clipboard.GetText(TextDataFormat.Text);
}

private void SampleMethod()
{
 var textFromThread = Clipboard.GetText(TextDataFormat.Text);
 Thread.Sleep(1000);
}

I'm getting whatever text copied to clipboard with this line -

var textFromMain = Clipboard.GetText(TextDataFormat.Text);

But below line returns empty string or blank string.

var textFromThread = Clipboard.GetText(TextDataFormat.Text);

I'm not getting what's the issue. Can somebody help me to understand. If it's multi-threading, please point me to right direction.

Body:
I finally used below method to access Clipboard text.

private string GetClipboardData()
    {
        try
        {
            string clipboardData= null;
            Exception threadEx = null;
            Thread staThread = new Thread(
                delegate ()
                {
                    try
                    {
                        clipboardData= Clipboard.GetText(TextDataFormat.Text);
                    }

                    catch (Exception ex)
                    {
                        threadEx = ex;
                    }
                });
            staThread.SetApartmentState(ApartmentState.STA);
            staThread.Start();
            staThread.Join();
            return clipboardData;
        }
        catch (Exception exception)
        {
            return string.Empty;
        }
    }


问:
Executing controller's method from another controller - on save -> refresh corresponding table
Departments controllers are loaded from SceneWithButtonsController. StageAddController is loaded from LayoutWithHomeAndAddController. I want to execute this method from StageAddController which executes corresponding method from departments controller :

//Show Stage to add a worker

```<code>public class LayoutWithHomeAndAddController {
    @FXML
    private void addButtonClicked() throws IOException{
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("/views/StageAdd.fxml"));
        BorderPane addWorkerPane = loader.load();

        StageAddController stageAddController = loader.getController();

        Stage stageAdd = new Stage();
        stageAdd.setTitle("Add New Worker");
        stageAdd.resizableProperty().setValue(Boolean.FALSE);
        Scene scene = new Scene(addWorkerPane);
        scene.getStylesheets().add("/css/redBorder.css");
        stageAdd.setScene(scene);
        stageAdd.initModality(Modality.WINDOW_MODAL);
        Stage mainStage = (Stage) root.getScene().getWindow();
        stageAdd.initOwner(mainStage);
        stageAdd.show();}
}
</code>```

Controller class where departments are loaded:

```<code>public class SceneWithButtonsController {

//Show workers from Mechanical Department
   @FXML
    private void mechanicalDepartmentButtonClicked() throws IOException {
       FXMLLoader loader = new FXMLLoader();
       loader.setLocation(Main.class.getResource("/views/MechanicalDepartment.fxml"));
       BorderPane mehOdjel = loader.load();
       MechanicalDepartmentController mechanicalDepartmentController = loader.getController();
       mechanicalDepartmentController.populateTable();
       BorderPane borderPane = (BorderPane) pane.getParent();
       borderPane.setCenter(mehOdjel);

    }

    //Show workers from Electrical Department
    @FXML
    private  void electricalDepartmentButtonClicked() throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(Main.class.getResource("/views/ElectricalDepartment.fxml"));
        BorderPane elOdjel = loader.load();
        ElectricalDepartmentController electricalDepartmentController = loader.getController();
        electricalDepartmentController.populateTable();
        BorderPane borderPane = (BorderPane) pane.getParent();
        borderPane.setCenter(elOdjel);

    }
}
</code>```

StageAddController:

```<code>public class StageAddController {

private ElectricalDepartmentController electricalDepartmentController;
    private MechanicalDepartmentController mechanicalDepartmentController;

    public void setElectricalDepartmentController(ElectricalDepartmentController electricalDepartmentController) {
        this.electricalDepartmentController = electricalDepartmentController;
    }

    public void setMechanicalDepartmentController(MechanicalDepartmentController mechanicalDepartmentController) {
        this.mechanicalDepartmentController = mechanicalDepartmentController;
    }

public void refreshTableOnSaveButtonClicked() {
    if (departmentBox.getValue().equals("Electrical")) {
        electricalDepartmentController.refreshButtonClicked();
    }
    else if(departmentBox.getValue().equals("Mechanical")) {
        mechanicalDepartmentController.refreshButtonClicked();
    }
}
}
</code>```

This means that refreshButtonClicked() method  from ElectricalDepartmentController or MechanicalDepartmentController will be executed.

ElectricalDepartmentController (same is with MechanicalDepartmentController):

```<code>public class ElectricalDepartmentController {

public void initialize() throws IOException {
        StageAddController stageAddController = new StageAddController();
        stageAddController.setElectricalDepartmentController(this);
        workersTableColumn.setCellValueFactory(new PropertyValueFactory<>("nameSurname"));
        rowSelected();
    }
 @FXML
    public void populateTable() {
        for(Worker worker : workerDao.getWorkersNameSurname("Electrical")) workersList.addAll(worker);
        workersTable.setItems(workersList);
    }

@FXML
    public void refreshButtonClicked() {
        workersList.removeAll(workersList);
        populateTable();
    }
}
</code>```

How to achieve this.

答:
You need to link controllers. In order to do that, when loading the respective FXML for the subordinate form, you have to set the parent controller for it manually so that you can have access to it.

Unfortunately, FXML does not provide a native way to link controllers. What you want to do is you want to use the full FXMLLoader functionality (instead of using FXMLLoader.load()), since the FXMLLoader also has a getController() method. It's probably a wise idea for your controllers to implement something like this:

```<code>public interface HierarchicalController {
    HierarchicalController getParentController();
    void setParentController(HierarchicalController controller);
}
</code>```

EDIT: Component preload code:

```<code>public class SceneWithButtonsController {

   protected FXMLLoader<?> mechanicalLoader;
   protected FXMLLoader<?> electricalLoader;
   protected BorderPane mechanicalPane;
   protected BorderPane electricalPane;

   public void initialize() {
       mechanicalLoader = new FXMLLoader(Main.class.getResource("/views/MechanicalDepartment.fxml"));
       mechanicalPane = loader.load();
       MechanicalDepartmentController mechanicalDepartmentController = loader.getController();
       mechanicalDepartmentController.populateTable();

       electricalLoader = new FXMLLoader(Main.class.getResource("/views/MechanicalDepartment.fxml"));
       electricalPane = loader.load();
       ElectricalDepartmentController electricalDepartmentController = loader.getController();
       electricalDepartmentController.populateTable();

       // now what is the relation between StageAddController and SceneWithButtonsController ?

   }

   //Show workers from Mechanical Department
   @FXML
    private void mechanicalDepartmentButtonClicked() throws IOException {
       BorderPane borderPane = (BorderPane) pane.getParent();
       borderPane.setCenter(mechanicalPane);

    }

    //Show workers from Electrical Department
    @FXML
    private  void electricalDepartmentButtonClicked() throws IOException {
        BorderPane borderPane = (BorderPane) pane.getParent();
        borderPane.setCenter(electricalPane);

    }
}
</code>```

Body:
Departments controllers are loaded from SceneWithButtonsController. StageAddController is loaded from LayoutWithHomeAndAddController. I want to execute this method from StageAddController which executes corresponding method from departments controller :

//Show Stage to add a worker

public class LayoutWithHomeAndAddController {
    @FXML
    private void addButtonClicked() throws IOException{
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("/views/StageAdd.fxml"));
        BorderPane addWorkerPane = loader.load();

        StageAddController stageAddController = loader.getController();

        Stage stageAdd = new Stage();
        stageAdd.setTitle("Add New Worker");
        stageAdd.resizableProperty().setValue(Boolean.FALSE);
        Scene scene = new Scene(addWorkerPane);
        scene.getStylesheets().add("/css/redBorder.css");
        stageAdd.setScene(scene);
        stageAdd.initModality(Modality.WINDOW_MODAL);
        Stage mainStage = (Stage) root.getScene().getWindow();
        stageAdd.initOwner(mainStage);
        stageAdd.show();}
}

Controller class where departments are loaded:

public class SceneWithButtonsController {

//Show workers from Mechanical Department
   @FXML
    private void mechanicalDepartmentButtonClicked() throws IOException {
       FXMLLoader loader = new FXMLLoader();
       loader.setLocation(Main.class.getResource("/views/MechanicalDepartment.fxml"));
       BorderPane mehOdjel = loader.load();
       MechanicalDepartmentController mechanicalDepartmentController = loader.getController();
       mechanicalDepartmentController.populateTable();
       BorderPane borderPane = (BorderPane) pane.getParent();
       borderPane.setCenter(mehOdjel);

    }

    //Show workers from Electrical Department
    @FXML
    private  void electricalDepartmentButtonClicked() throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(Main.class.getResource("/views/ElectricalDepartment.fxml"));
        BorderPane elOdjel = loader.load();
        ElectricalDepartmentController electricalDepartmentController = loader.getController();
        electricalDepartmentController.populateTable();
        BorderPane borderPane = (BorderPane) pane.getParent();
        borderPane.setCenter(elOdjel);

    }
}

StageAddController:

public class StageAddController {

private ElectricalDepartmentController electricalDepartmentController;
    private MechanicalDepartmentController mechanicalDepartmentController;

    public void setElectricalDepartmentController(ElectricalDepartmentController electricalDepartmentController) {
        this.electricalDepartmentController = electricalDepartmentController;
    }

    public void setMechanicalDepartmentController(MechanicalDepartmentController mechanicalDepartmentController) {
        this.mechanicalDepartmentController = mechanicalDepartmentController;
    }

public void refreshTableOnSaveButtonClicked() {
    if (departmentBox.getValue().equals("Electrical")) {
        electricalDepartmentController.refreshButtonClicked();
    }
    else if(departmentBox.getValue().equals("Mechanical")) {
        mechanicalDepartmentController.refreshButtonClicked();
    }
}
}

This means that refreshButtonClicked() method  from ElectricalDepartmentController or MechanicalDepartmentController will be executed.

ElectricalDepartmentController (same is with MechanicalDepartmentController):

public class ElectricalDepartmentController {

public void initialize() throws IOException {
        StageAddController stageAddController = new StageAddController();
        stageAddController.setElectricalDepartmentController(this);
        workersTableColumn.setCellValueFactory(new PropertyValueFactory<>("nameSurname"));
        rowSelected();
    }
 @FXML
    public void populateTable() {
        for(Worker worker : workerDao.getWorkersNameSurname("Electrical")) workersList.addAll(worker);
        workersTable.setItems(workersList);
    }

@FXML
    public void refreshButtonClicked() {
        workersList.removeAll(workersList);
        populateTable();
    }
}

How to achieve this.

Body:
You need to link controllers. In order to do that, when loading the respective FXML for the subordinate form, you have to set the parent controller for it manually so that you can have access to it.

Unfortunately, FXML does not provide a native way to link controllers. What you want to do is you want to use the full FXMLLoader functionality (instead of using FXMLLoader.load()), since the FXMLLoader also has a getController() method. It's probably a wise idea for your controllers to implement something like this:

public interface HierarchicalController {
    HierarchicalController getParentController();
    void setParentController(HierarchicalController controller);
}

EDIT: Component preload code:

public class SceneWithButtonsController {

   protected FXMLLoader<?> mechanicalLoader;
   protected FXMLLoader<?> electricalLoader;
   protected BorderPane mechanicalPane;
   protected BorderPane electricalPane;

   public void initialize() {
       mechanicalLoader = new FXMLLoader(Main.class.getResource("/views/MechanicalDepartment.fxml"));
       mechanicalPane = loader.load();
       MechanicalDepartmentController mechanicalDepartmentController = loader.getController();
       mechanicalDepartmentController.populateTable();

       electricalLoader = new FXMLLoader(Main.class.getResource("/views/MechanicalDepartment.fxml"));
       electricalPane = loader.load();
       ElectricalDepartmentController electricalDepartmentController = loader.getController();
       electricalDepartmentController.populateTable();

       // now what is the relation between StageAddController and SceneWithButtonsController ?

   }

   //Show workers from Mechanical Department
   @FXML
    private void mechanicalDepartmentButtonClicked() throws IOException {
       BorderPane borderPane = (BorderPane) pane.getParent();
       borderPane.setCenter(mechanicalPane);

    }

    //Show workers from Electrical Department
    @FXML
    private  void electricalDepartmentButtonClicked() throws IOException {
        BorderPane borderPane = (BorderPane) pane.getParent();
        borderPane.setCenter(electricalPane);

    }
}


问:
How to activate found cell with find function?
I am trying to create a Macro that will find each cell that contains a specific value (e.g.:Location) then deletes the whole row of that cell. There will be multiple cells that contain that value and I want all of them deleted so I have created a loop but because of the way I've done it, it breaks after the last one and it doesn't carry on with the last bit of the macro. I cannot find another way around so I am hoping someone will be smarter than me and can help me out with this one. The code looks like this now:</p>

```<code>  Do
   If Cells.Find(What:="Location").Activate Then
    ActiveCell.EntireRow.Select
    Selection.Delete
   Else MsgBox ("All headers deleted")
   End If
  Loop
</code>```

答:
This worked for me.</p>

```<code>Set cell = Selection.Find(What:=valueToFind, After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
If Not cell Is Nothing Then
    cell.Select
 else
   msgbox "Cell with given Data not found"
end if
</code>```

Body:
I am trying to create a Macro that will find each cell that contains a specific value (e.g.:Location) then deletes the whole row of that cell. There will be multiple cells that contain that value and I want all of them deleted so I have created a loop but because of the way I've done it, it breaks after the last one and it doesn't carry on with the last bit of the macro. I cannot find another way around so I am hoping someone will be smarter than me and can help me out with this one. The code looks like this now:

  Do
   If Cells.Find(What:="Location").Activate Then
    ActiveCell.EntireRow.Select
    Selection.Delete
   Else MsgBox ("All headers deleted")
   End If
  Loop

Body:
This worked for me.

Set cell = Selection.Find(What:=valueToFind, After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
If Not cell Is Nothing Then
    cell.Select
 else
   msgbox "Cell with given Data not found"
end if


问:
My Flex app sometimes take a time navigating away to another tab and back to load in browser
In my Flex app I give the user the ability to open up a new item form ( s:Panel ) and create multiple items on the page.

Sometimes for some odd reason bringing up the panel (simple task) seems to take a really long time to load (like 30 seconds or so) However, the weird thing is that if right after I click to open I navigate away from the Tab and back again to the Flex app tab it shows up right away.

I'm not sure if this has to do with refresh rate or some setting or is it general performance/memory issue with my app that I have to consider. When the application work it works fairly fast which is making me think it's not memory/performance issue.

答: It's hard to be sure without more details, but are you following the component life cycle? Just to be sure we're talking about the same thing, here's a nice presentation about it: http://www.slideshare.net/rjowen/adobe-flex-component-lifecycle-presentation</p>