问:
Skip over function error and continue with next check (VLOOKUP)
I am running a basic VLOOKUP to get an employees email address.

However, when the lookup value enters an employees name that doesn't exist in the array, it throws an error.

I added an "On Error Resume Next" but this just caused the remainder of the email addresses to be the last email address encountered, instead of continuing the search and using the current employee as the search variable.

What I want is when the search variable ProjectManName doesn't exist in the array, to just skip over that line, and continue the search as normal. I will then go and fill in the empty email addresses manually.

```<code>Dim myLookupValue As Range
Dim strResult As String
Dim lngLastRow As Long
Dim lngLoop As Long
Dim ProjectManName As String

Set myLookupValue = Worksheets("Employees").Range("A1", Worksheets("Employees").Range("B1").End(xlDown))

With Worksheets("Project Summary")

    lngLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

    For lngLoop = 2 To lngLastRow
        On Error Resume Next
       ProjectManName = .Cells(lngLoop, 1).Value
       strResult = Application.WorksheetFunction.VLookup(ProjectManName, myLookupValue, 2, False)
       Range("K" & lngLoop).Value = strResult
       ActiveCell.Offset(1, 0).Select
    Next

End With
</code>```

Also, for the myLookupValue, do I need the second instance of Worksheets("Employees")? When I didn't do this it also gave an error because the second cell in the range looked at the current worksheet instead of the Employees worksheet.

Lastly, how can I replace "K" in Range("K" & lngLoop).Value to be the first empty column?

答:
when the lookup value enters an employees name that doesn't exist in the array, it throws an error.

That's entirely by design. Application.WorksheetFunction functions are early-bound and raise errors instead of returning them, which is completely idiomatic VB behavior.

Looks like you want the "Excel worksheet" behavior, where a worksheet function that errors out will return a Variant/Error value that the cell displays as #N/A: that Variant/Error value makes IsError return True, and can only be legally compared to other error values, e.g. CVErr(xlErrNa).

Like many COM types, the Excel.Application interface is extensible, meaning members can be added to it at run-time. Turns out, it's effectively extended with members of the WorksheetFunction interface, so Application.VLookup not only compiles perfectly fine (as does Application.AnythingWhatsoever), it's a late-bound implementation that behaves exactly like the worksheet function does when invoked by a worksheet cell: it returns a Variant/Error value rather than raising a standard, idiomatic run-time error... assuming you get all the parameters right (late-bound calls don't get IntelliSense/autocomplete), because if you make a typo (Option Explicit can't save you) or get the parameters wrong, expect error 438 or 1004 to be raised.

But you can't capture the return value in a String - that'll be a type mismatch error when the lookup yields an Error value (you can't coerce that type into anything other than a Variant).

```<code>Dim lookupResult As Variant
lookupResult = Application.VLookup(ProjectManName, myLookupValue, 2, False)
If Not IsError(lookupResult) Then
    strResult = CStr(lookupResult)
    '...
''Else
''    'lookup failed
End If
</code>```

That said the early-bound version should generally be preferred, be it only for IntelliSense. On Error Resume Next used correctly can be helpful here - simply pull the lookup into its own scope:

```<code>For lngLoop = 2 To lngLastRow
    ProjectManName = .Cells(lngLoop, 1).Value
    [ActiveSheet.]Range("K" & lngLoop).Value = GetProjectManager(ProjectManName)
    'ActiveCell.Offset(1, 0).Select '<~ why?
Next
</code>```

```<code>Private Function GetProjectManager(ByVal name As String) As String
     Dim source As Range
     With Worksheets("Employees")
         On Error Resume Next
         GetProjectManager = Application.WorksheetFunction.VLookup(name, .Range("A1", .Range("B1").End(xlDown)), 2, False)
         On Error GoTo 0
     End With
End Function
</code>```

As for myLookupValue (bad name: should be myLookupRange or lookupSource or lookupTable - "lookup value" is generally understood/read as being the value you're looking for) - you absolutely do need a reference to the Employees sheet (unqualified Range calls are a very good recipe for error 1004) - that doesn't mean you need to dereference that object from the Worksheets collection twice - as shown above... note that by moving the lookup into its own scope, we also remove the need for the caller to even need to care about the lookup source table.

Body:
I am running a basic VLOOKUP to get an employees email address.

However, when the lookup value enters an employees name that doesn't exist in the array, it throws an error.

I added an "On Error Resume Next" but this just caused the remainder of the email addresses to be the last email address encountered, instead of continuing the search and using the current employee as the search variable.

What I want is when the search variable ProjectManName doesn't exist in the array, to just skip over that line, and continue the search as normal. I will then go and fill in the empty email addresses manually.

Dim myLookupValue As Range
Dim strResult As String
Dim lngLastRow As Long
Dim lngLoop As Long
Dim ProjectManName As String

Set myLookupValue = Worksheets("Employees").Range("A1", Worksheets("Employees").Range("B1").End(xlDown))

With Worksheets("Project Summary")

    lngLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

    For lngLoop = 2 To lngLastRow
        On Error Resume Next
       ProjectManName = .Cells(lngLoop, 1).Value
       strResult = Application.WorksheetFunction.VLookup(ProjectManName, myLookupValue, 2, False)
       Range("K" & lngLoop).Value = strResult
       ActiveCell.Offset(1, 0).Select
    Next

End With

Also, for the myLookupValue, do I need the second instance of Worksheets("Employees")? When I didn't do this it also gave an error because the second cell in the range looked at the current worksheet instead of the Employees worksheet.

Lastly, how can I replace "K" in Range("K" & lngLoop).Value to be the first empty column?

Body:
when the lookup value enters an employees name that doesn't exist in the array, it throws an error.

That's entirely by design. Application.WorksheetFunction functions are early-bound and raise errors instead of returning them, which is completely idiomatic VB behavior.

Looks like you want the "Excel worksheet" behavior, where a worksheet function that errors out will return a Variant/Error value that the cell displays as #N/A: that Variant/Error value makes IsError return True, and can only be legally compared to other error values, e.g. CVErr(xlErrNa).

Like many COM types, the Excel.Application interface is extensible, meaning members can be added to it at run-time. Turns out, it's effectively extended with members of the WorksheetFunction interface, so Application.VLookup not only compiles perfectly fine (as does Application.AnythingWhatsoever), it's a late-bound implementation that behaves exactly like the worksheet function does when invoked by a worksheet cell: it returns a Variant/Error value rather than raising a standard, idiomatic run-time error... assuming you get all the parameters right (late-bound calls don't get IntelliSense/autocomplete), because if you make a typo (Option Explicit can't save you) or get the parameters wrong, expect error 438 or 1004 to be raised.

But you can't capture the return value in a String - that'll be a type mismatch error when the lookup yields an Error value (you can't coerce that type into anything other than a Variant).

Dim lookupResult As Variant
lookupResult = Application.VLookup(ProjectManName, myLookupValue, 2, False)
If Not IsError(lookupResult) Then
    strResult = CStr(lookupResult)
    '...
''Else
''    'lookup failed
End If

That said the early-bound version should generally be preferred, be it only for IntelliSense. On Error Resume Next used correctly can be helpful here - simply pull the lookup into its own scope:

For lngLoop = 2 To lngLastRow
    ProjectManName = .Cells(lngLoop, 1).Value
    [ActiveSheet.]Range("K" & lngLoop).Value = GetProjectManager(ProjectManName)
    'ActiveCell.Offset(1, 0).Select '<~ why?
Next

Private Function GetProjectManager(ByVal name As String) As String
     Dim source As Range
     With Worksheets("Employees")
         On Error Resume Next
         GetProjectManager = Application.WorksheetFunction.VLookup(name, .Range("A1", .Range("B1").End(xlDown)), 2, False)
         On Error GoTo 0
     End With
End Function

As for myLookupValue (bad name: should be myLookupRange or lookupSource or lookupTable - "lookup value" is generally understood/read as being the value you're looking for) - you absolutely do need a reference to the Employees sheet (unqualified Range calls are a very good recipe for error 1004) - that doesn't mean you need to dereference that object from the Worksheets collection twice - as shown above... note that by moving the lookup into its own scope, we also remove the need for the caller to even need to care about the lookup source table.


来源: stackexchange

答:
Posting comment as answer to be easier to read.  Only answers the last question in the multi-question post.

You will want to find the last column so that you can replace "K" in your range. I would recommend using Cells() rather than Range() since you can use the number as is from:

```<code>dim lc as long
lc = sheets("project summary").cells(1, sheets("project summary").columns.count).end(xltoleft).column
</code>```

where "1" in cells is the first row (typically headers) and "lc" stands for last column. The cells reference would be Cells(ingLoop, lc), given your example.

ContentLicense: CC BY-SA 4.0

Title: Skip over function error and continue with next check (VLOOKUP)

Body:
Posting comment as answer to be easier to read.  Only answers the last question in the multi-question post.

You will want to find the last column so that you can replace "K" in your range. I would recommend using Cells() rather than Range() since you can use the number as is from:

dim lc as long
lc = sheets("project summary").cells(1, sheets("project summary").columns.count).end(xltoleft).column

where "1" in cells is the first row (typically headers) and "lc" stands for last column. The cells reference would be Cells(ingLoop, lc), given your example.


问:
How to add spacing between columns?
I have two columns:

```<code><div class="col-md-6"></div>
<div class="col-md-6"></div>
</code>```

How can I add a space between them?

The output would simply be two columns right next to each other taking up the whole width of the page. Say the width was set to 1000px then each div would be 500px wide.

If I wanted a 100px space between the two how could I achieve this automatically with Bootstrap: the divs sizes would become 450px each to compensate for the spacing.

答:
I needed one column on mobile and two columns from tablet portrait up, with equal spacing between them in the middle (also without any grid-added padding inside columns). Could be achieved using spacing utilities and omitting the number in col-md:

Column 1

Column 1

```

Title: How to add spacing between columns?

Body:
I have two columns:

How can I add a space between them?

The output would simply be two columns right next to each other taking up the whole width of the page. Say the width was set to 1000px then each div would be 500px wide.

If I wanted a 100px space between the two how could I achieve this automatically with Bootstrap: the divs sizes would become 450px each to compensate for the spacing.

Body:
I needed one column on mobile and two columns from tablet portrait up, with equal spacing between them in the middle (also without any grid-added padding inside columns). Could be achieved using spacing utilities and omitting the number in col-md:

    <div class="container-fluid px-0">
        <div class="row no-gutters">
            <div class="col-sm-12 col-md mr-md-3" style="background-color: orange">
                <p><strong>Column 1</strong></p>
            </div>
            <div class="col-sm-12 col-md ml-md-3" style="background-color: orange">
                <p><strong>Column 1</strong></p>
            </div>
        </div>
    </div>


问:
Parsing CSV data using a finite state machine
I want to read a file containing comma-separated values, so have written a finite state machine:

```<code>private IList<string> Split(string line)
{
    List<string> values = new List<string>();
    string value = string.Empty;
    ParseState state = ParseState.Initial;
    foreach (char c in line)
    {
        switch (state)
        {
            case ParseState.Initial:
                switch (c)
                {
                    case COMMA:
                        values.Add(string.Empty);
                        break;
                    case QUOTE:
                        state = ParseState.Quote;
                        break;
                    default:
                        value += c;
                        state = ParseState.Data;
                        break;
                }
                break;
            case ParseState.Data:
                switch (c)
                {
                    case COMMA:
                        values.Add(value);
                        value = string.Empty;
                        state = ParseState.Initial;
                        break;
                    case QUOTE:
                        throw new InvalidDataException("Improper quotes");
                    default:
                        value += c;
                        break;
                }
                break;
            case ParseState.Quote:
                switch (c)
                {
                    case QUOTE:
                        state = ParseState.QuoteInQuote;
                        break;
                    default:
                        value += c;
                        break;
                }
                break;
            case ParseState.QuoteInQuote:
                switch (c)
                {
                    case COMMA:
                        values.Add(value);
                        value = string.Empty;
                        state = ParseState.Initial;
                        break;
                    case QUOTE:
                        value += c;
                        state = ParseState.Quote;
                        break;
                    default:
                        throw new InvalidDataException("Unpaired quotes");
                }
                break;
        }
    }

    switch (state)
    {
        case ParseState.Initial:
        case ParseState.Data:
        case ParseState.QuoteInQuote:
            values.Add(value);
            break;
        case ParseState.Quote:
            throw new InvalidDataException("Unclosed quotes");
    }

    return values;
}
</code>```

Yes, I know the advice about CSV parsers is "don't write your own", but

I needed it quickly and

our download policy at work would take several days to allow me to
get open source off the 'net.

Hey, at least I didn't start with string.Split() or, worse, try using a Regex!

And yes, I know it could be improved by using a StringBuilder, and it's restrictive on quotes in the data, but

performance is not an issue and

this is only to generate well-defined test data in-house,

so I don't care about those.

What I do care about is the apparent trailing block at the end for mopping up all the data after the final comma, and the way that it's starting to look like some sort of an anti-pattern down there, which was exactly the sort of thing that "good" patterns such as a FSM were supposed to avoid.

So my question is this: is this block at the end some sort of anti-pattern, and is it something that's going to come back to bite me in the future?

答: In a FSM you identify which states are the permitted halting states.  So in a typical implementation, when you come out of the loop you need to at least check to make sure that your last state is one of the permitting halting states or throw a jam error.  So having that one last state check outside of the loop is part of the pattern.</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to read a file containing comma-separated values, so have written a finite state machine:

private IList<string> Split(string line)
{
    List<string> values = new List<string>();
    string value = string.Empty;
    ParseState state = ParseState.Initial;
    foreach (char c in line)
    {
        switch (state)
        {
            case ParseState.Initial:
                switch (c)
                {
                    case COMMA:
                        values.Add(string.Empty);
                        break;
                    case QUOTE:
                        state = ParseState.Quote;
                        break;
                    default:
                        value += c;
                        state = ParseState.Data;
                        break;
                }
                break;
            case ParseState.Data:
                switch (c)
                {
                    case COMMA:
                        values.Add(value);
                        value = string.Empty;
                        state = ParseState.Initial;
                        break;
                    case QUOTE:
                        throw new InvalidDataException("Improper quotes");
                    default:
                        value += c;
                        break;
                }
                break;
            case ParseState.Quote:
                switch (c)
                {
                    case QUOTE:
                        state = ParseState.QuoteInQuote;
                        break;
                    default:
                        value += c;
                        break;
                }
                break;
            case ParseState.QuoteInQuote:
                switch (c)
                {
                    case COMMA:
                        values.Add(value);
                        value = string.Empty;
                        state = ParseState.Initial;
                        break;
                    case QUOTE:
                        value += c;
                        state = ParseState.Quote;
                        break;
                    default:
                        throw new InvalidDataException("Unpaired quotes");
                }
                break;
        }
    }

    switch (state)
    {
        case ParseState.Initial:
        case ParseState.Data:
        case ParseState.QuoteInQuote:
            values.Add(value);
            break;
        case ParseState.Quote:
            throw new InvalidDataException("Unclosed quotes");
    }

    return values;
}

Yes, I know the advice about CSV parsers is "don't write your own", but

I needed it quickly and

our download policy at work would take several days to allow me to
get open source off the 'net.

Hey, at least I didn't start with string.Split() or, worse, try using a Regex!

And yes, I know it could be improved by using a StringBuilder, and it's restrictive on quotes in the data, but

performance is not an issue and

this is only to generate well-defined test data in-house,

so I don't care about those.

What I do care about is the apparent trailing block at the end for mopping up all the data after the final comma, and the way that it's starting to look like some sort of an anti-pattern down there, which was exactly the sort of thing that "good" patterns such as a FSM were supposed to avoid.

So my question is this: is this block at the end some sort of anti-pattern, and is it something that's going to come back to bite me in the future?


问:
How to change activity in android?

I am making simple game. I have 3 activities. First activity is main menu (FirstActivity class).

First activity has following code:

```<code>Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
</code>```

It calls second activity where, second activity has following code:

```<code>setContentView(new MovementView(this));
</code>```

MovementView class extends SurfaceView. MovementView class is where I write all game code.

So I want to make when lives == 0, it changes to ThirdActivity. How do I do that?

I have tried putting code similar to FirstActivity's class but it doesn't seems to work.

If I put

 ((Activity)getContext()).finish();

it just jumps back to FirstActivity, but that's not what I need, I need it to go to ThirdActivity class.

答: It didn't work when you tried it because you're trying to create an intent from a View, not an Activity. You'll need to use the view's context (getContext()) instead of this. You'll also need to use startActivity rather than startActivityForResult, unless you're actually planning to use the result (although casting the context to an Activity should be fairly safe if you're only using it from your own code).

Title: How to change activity in android?

Body:
I am making simple game. I have 3 activities. First activity is main menu (FirstActivity class).

First activity has following code:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);

It calls second activity where, second activity has following code:

setContentView(new MovementView(this));

MovementView class extends SurfaceView. MovementView class is where I write all game code.

So I want to make when lives == 0, it changes to ThirdActivity. How do I do that?

I have tried putting code similar to FirstActivity's class but it doesn't seems to work.

If I put

 ((Activity)getContext()).finish();

it just jumps back to FirstActivity, but that's not what I need, I need it to go to ThirdActivity class.


问:
Api Explorer for external project or assembly
I want to use Web API's Api Explorer in order to start generating my own documentation html pages. What I'm trying to aim at is something like described here:
http://blogs.msdn.com/b/yaohuang1/archive/2013/01/20/design-time-generation-of-help-page-or-proxy-for-asp-net-web-api.aspx

However, this project is a bit outdated and does not work with the current web api.
I want to have:

A console program that has api explorer core libraries installed in it.

It takes in an assembly from another project and runs Api explorer on it to get all the REST paths and methods.

I don't want Api explorer or the help pages to be installed on the project I am targeting. I just want to use the assembly of the project and the console application will have all the necessary API explorer packages.

Is this possible?

Can I load an assembly and run Api explorer on it?

答:
This is inspired by a swashbuckle sample, but is also possible using only ApiExplorer.

You can create an OWIN TestServer, create a HttpConfiguration, run your WebApi OWIN init code, and then create the ApiExplorer from the initialized HttpConfiguration. The only problem you might have is finding the WebApi portion of the startup code in the target assembly. In my case I'm referencing the WebAPi project in the same solution, so it's easier to call the relevant startup code.

```<code>private static Collection<ApiDescription> GetApiDescriptions()
{
  Collection<ApiDescription> descriptions = null;
  TestServer.Create(app => {
    var httpConfiguration = new HttpConfiguration();
    // This is the call to my webapi startup method in the target project, this may be tricky to find (using reflection) in your case
    new Startup().ConfigureWebApi(app, httpConfiguration);
    var apiExplorer = new ApiExplorer(httpConfiguration);
    httpConfiguration.EnsureInitialized();
    descriptions = apiExplorer.ApiDescriptions;
  });
  return descriptions;
}
</code>```

Body:
This is inspired by a swashbuckle sample, but is also possible using only ApiExplorer.

You can create an OWIN TestServer, create a HttpConfiguration, run your WebApi OWIN init code, and then create the ApiExplorer from the initialized HttpConfiguration. The only problem you might have is finding the WebApi portion of the startup code in the target assembly. In my case I'm referencing the WebAPi project in the same solution, so it's easier to call the relevant startup code.

private static Collection<ApiDescription> GetApiDescriptions()
{
  Collection<ApiDescription> descriptions = null;
  TestServer.Create(app => {
    var httpConfiguration = new HttpConfiguration();
    // This is the call to my webapi startup method in the target project, this may be tricky to find (using reflection) in your case
    new Startup().ConfigureWebApi(app, httpConfiguration);
    var apiExplorer = new ApiExplorer(httpConfiguration);
    httpConfiguration.EnsureInitialized();
    descriptions = apiExplorer.ApiDescriptions;
  });
  return descriptions;
}


问:
Is there any simple way to benchmark Python script?
Usually I use shell command time. My purpose is to test if data is small, medium, large or very large set, how much time and memory usage will be.

Any tools for Linux or just Python to do this?

答:
If you don't want to write boilerplate code for timeit and get easy to analyze results, take a look at benchmarkit. Also it saves history of previous runs, so it is easy to compare the same function over the course of development.

```<code># pip install benchmarkit

from benchmarkit import benchmark, benchmark_run

N = 10000
seq_list = list(range(N))
seq_set = set(range(N))

SAVE_PATH = '/tmp/benchmark_time.jsonl'

@benchmark(num_iters=100, save_params=True)
def search_in_list(num_items=N):
    return num_items - 1 in seq_list

@benchmark(num_iters=100, save_params=True)
def search_in_set(num_items=N):
    return num_items - 1 in seq_set

benchmark_results = benchmark_run(
   [search_in_list, search_in_set],
   SAVE_PATH,
   comment='initial benchmark search',
)
</code>```

Prints to terminal and returns list of dictionaries with data for the last run. Command line entrypoints also available.

If you change N=1000000 and rerun

Body:
If you don't want to write boilerplate code for timeit and get easy to analyze results, take a look at benchmarkit. Also it saves history of previous runs, so it is easy to compare the same function over the course of development.

# pip install benchmarkit

from benchmarkit import benchmark, benchmark_run

N = 10000
seq_list = list(range(N))
seq_set = set(range(N))

SAVE_PATH = '/tmp/benchmark_time.jsonl'

@benchmark(num_iters=100, save_params=True)
def search_in_list(num_items=N):
    return num_items - 1 in seq_list

@benchmark(num_iters=100, save_params=True)
def search_in_set(num_items=N):
    return num_items - 1 in seq_set

benchmark_results = benchmark_run(
   [search_in_list, search_in_set],
   SAVE_PATH,
   comment='initial benchmark search',
)

Prints to terminal and returns list of dictionaries with data for the last run. Command line entrypoints also available.

If you change N=1000000 and rerun


问:
Improving on the basic, existing GloVe model
I am using GloVe as part of my research. I've downloaded the models from here. I've been using GloVe for sentence classification. The sentences I'm classifying are specific to a particular domain, say some STEM subject. However, since the existing GloVe models are trained on a general corpus, they may not yield the best results for my particular task. </p>

<p>So my question is, how would I go about loading the retrained model and just retraining it a little more on my own corpus to learn the semantics of my corpus as well? There would be merit in doing this were it possible. </p>

答:
I believe GloVe (Global Vectors) is not meant to be appended, since it is based on the corpus' overall word co-occurrence statistics from a single corpus known only at initial training time

You can do is use gensim.scripts.glove2word2vec api to convert GloVe vectors into word2vec, but i dont think you can continue training since its loading in a KeyedVector not a Full Model

Body:
I am using GloVe as part of my research. I've downloaded the models from here. I've been using GloVe for sentence classification. The sentences I'm classifying are specific to a particular domain, say some STEM subject. However, since the existing GloVe models are trained on a general corpus, they may not yield the best results for my particular task.

So my question is, how would I go about loading the retrained model and just retraining it a little more on my own corpus to learn the semantics of my corpus as well? There would be merit in doing this were it possible.


问:
How to send a bitmap using serversocket
I am making a multiplayer drawing application for android and I need to send the drawings that every user made to one player. I am using a server socket for this.

First thing I do is convert the Bitmap to a byte array, so I can send it to the Host with host.write(byteArray);

```<code>        Bitmap bitmapImage = drawView.getBitmap();
        byte[] byteArray = getByteArray(bitmapImage);
        byteArrayLength = byteArray.length;

        MainWifiActivity.SendReceive host = MainWifiActivity.sendReceiveHost;
        if (host != null) {
            host.write(byteArray);
        }
</code>```

The following code is my SendReceive class, which listenes to the inputStream and then starts a Handler, that is supposed to save the Bitmap to Internal Storage

```<code>    public class SendReceive extends Thread {
    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public SendReceive(Socket s) {
        socket = s;
        try {
            inputStream = s.getInputStream();
            outputStream = s.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {

        byte[] buffer = new byte[1024];
        int bytes;
        int filesize;

        while (socket != null) {
            try {
                filesize = DrawingActivity.byteArrayLength;
                if(buffer.length != filesize && filesize > 0){
                    buffer = new byte[filesize];
                }
                bytes = inputStream.read(buffer,0 ,buffer.length);

                if (bytes > 0) {
                        Message mesg = handler.obtainMessage(IMAGE_MSG, bytes, -1, buffer);
                        mesg.sendToTarget();

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  }
</code>```

And the Handler:

```<code>    Handler handler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {

        switch (msg.what) {
            case IMAGE_MSG:
                byte[] byteArray = (byte[]) msg.obj;
                Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                saveBitmapToInternalStorage(bitmap);
        }
        return false;
    }
});
</code>```

In the saveBitmapToInternalStorage Method I get a java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference

```<code>    private void saveBitmapToInternalStorage(Bitmap bmp) {
    File directory = getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
    File myPath = new File(directory, UUID.randomUUID().toString() + ".png");
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myPath);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        Log.d("HELLO", "MY ERROR: " + e);
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

I know that BitmapFactory.decodeByteArray returns the decoded bitmap, or null if the image could not be decoded.

But why could it not be decoded?

答:
I think this piece is wrong

```<code>FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myPath);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
</code>```

It should be

```<code>FileOutputStream fos = new FileOutputStream(myPath);
    try {
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
</code>```

Title: How to send a bitmap using serversocket

Body:
I am making a multiplayer drawing application for android and I need to send the drawings that every user made to one player. I am using a server socket for this.

First thing I do is convert the Bitmap to a byte array, so I can send it to the Host with host.write(byteArray);

        Bitmap bitmapImage = drawView.getBitmap();
        byte[] byteArray = getByteArray(bitmapImage);
        byteArrayLength = byteArray.length;

        MainWifiActivity.SendReceive host = MainWifiActivity.sendReceiveHost;
        if (host != null) {
            host.write(byteArray);
        }

The following code is my SendReceive class, which listenes to the inputStream and then starts a Handler, that is supposed to save the Bitmap to Internal Storage

    public class SendReceive extends Thread {
    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public SendReceive(Socket s) {
        socket = s;
        try {
            inputStream = s.getInputStream();
            outputStream = s.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {

        byte[] buffer = new byte[1024];
        int bytes;
        int filesize;

        while (socket != null) {
            try {
                filesize = DrawingActivity.byteArrayLength;
                if(buffer.length != filesize && filesize > 0){
                    buffer = new byte[filesize];
                }
                bytes = inputStream.read(buffer,0 ,buffer.length);

                if (bytes > 0) {
                        Message mesg = handler.obtainMessage(IMAGE_MSG, bytes, -1, buffer);
                        mesg.sendToTarget();

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  }

And the Handler:

    Handler handler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {

        switch (msg.what) {
            case IMAGE_MSG:
                byte[] byteArray = (byte[]) msg.obj;
                Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                saveBitmapToInternalStorage(bitmap);
        }
        return false;
    }
});

In the saveBitmapToInternalStorage Method I get a java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference

    private void saveBitmapToInternalStorage(Bitmap bmp) {
    File directory = getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
    File myPath = new File(directory, UUID.randomUUID().toString() + ".png");
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myPath);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        Log.d("HELLO", "MY ERROR: " + e);
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I know that BitmapFactory.decodeByteArray returns the decoded bitmap, or null if the image could not be decoded.

But why could it not be decoded?

Body:
I think this piece is wrong

FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myPath);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {

It should be

FileOutputStream fos = new FileOutputStream(myPath);
    try {
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {


问:
Python list append different lists in the same scope for the same variable
Okay. I write an algorithm for show me all the permutations of a list of integers. But during the algorithm I got a problem to append a permuted list to my result list.

The code is the heap's algorithm. I got my finished permutation when size == 1. So a can append the permutated list V to my final list res. Here's the code:

The function for permutate the list

def permutations(V, size):
    global res

    if size == 1:
        print(V)
        res.append(V)

    for i in range(0, size):
        permutations(V, size-1)

        if size % 2 == 1:
            V[size-1], V[0] = V[0], V[size-1]
        else:
            V[i], V[size-1] = V[size-1], V[i]

A = [1,2,3]
res = []
permutation(A, len(A))
print(res)

```

<p>And this is the output:</p>

```[1, 2, 3]
[2, 1, 3]
[3, 1, 2]
[1, 3, 2]
[2, 3, 1]
[3, 2, 1]
res: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
```

<p>The printed permutations of V are all correct. But the list V append to my <code>global res</code> are not change. They are being append right after the print and the list append is different. </p>

<p>If you change the lines like this:</p>

<pre class="lang-py prettyprint-override"><code>res.append(V)
  |
  |
  v
D = [V[i] for i in range(len(V))]
res.append(D)
</code>```

The results is correct on the final. Anyone can explain how can a printed list can be different from a appended list using the same variable.

答:
Replace res.append(V) with res.append(list(V)) simply fixes your issue.

All V you appended to the res are references to the same object. This can be observed by printing the id of each element in the list:

```<code>for i in res:
    print(id(i))
</code>```

Body:
Okay. I write an algorithm for show me all the permutations of a list of integers. But during the algorithm I got a problem to append a permuted list to my result list.

The code is the heap's algorithm. I got my finished permutation when size == 1. So a can append the permutated list V to my final list res. Here's the code:

The function for permutate the list

def permutations(V, size):
    global res

    if size == 1:
        print(V)
        res.append(V)

    for i in range(0, size):
        permutations(V, size-1)

        if size % 2 == 1:
            V[size-1], V[0] = V[0], V[size-1]
        else:
            V[i], V[size-1] = V[size-1], V[i]

A = [1,2,3]
res = []
permutation(A, len(A))
print(res)

And this is the output:

[1, 2, 3]
[2, 1, 3]
[3, 1, 2]
[1, 3, 2]
[2, 3, 1]
[3, 2, 1]
res: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

The printed permutations of V are all correct. But the list V append to my global res are not change. They are being append right after the print and the list append is different.

If you change the lines like this:

res.append(V)
  |
  |
  v
D = [V[i] for i in range(len(V))]
res.append(D)

The results is correct on the final. Anyone can explain how can a printed list can be different from a appended list using the same variable.

Body:
Replace res.append(V) with res.append(list(V)) simply fixes your issue.

All V you appended to the res are references to the same object. This can be observed by printing the id of each element in the list:

for i in res:
    print(id(i))


问:
Jquery 1.5 breaks old 1.4 $.get calls
I recently upgraded to 1.5, and functions like:

```<code>function showData(id) {

 $.get("/url/getdata", {id : id}, function(data) {
 $("#dialogData").html(data);
 $("#dialogData").dialog({width: 500, modal: true, zIndex:22000});
 }, "json");
}
</code>```

no longer work with the addition of 1.5.

Looking at firebug, the correct data is returned, but the function breaks after entering the callback.
Everything simply stops.

How can I fix this? I read about the changes to Ajax call in 1.5, but I have over a thousand such calls through my project -> I cannot even begin to think about hunting them all down and changing them, let alone bug testing it all.

Edit: Oddly enough, if I put "text json" instead of "json" for dataType, it works. I don't think going through all my code and changing that is a viable option...

Edit 2: Instead of returning json_encode($string), I tried returning json_encode(array("string" => $string)), and then I did $(element).html(data.string).
This did not work either, and the JSON data I got with this call was valid on jsonlint.com

Edit 3: Tried setting headers prior to the json_encode output, didn't work. So far the only solution has been setting the datatype to text json.

答:
Sounds like you need to set the Content-Type header on the server-side. PHP can easily do this, just call header('Content-Type: application/json'); sometime before you start outputting your encoded JSON data.

jQuery will see that header, and automatically parse your JSON for you. I'm guessing that in the never version, it probably is more strict with dataType. If it tried to parse it as HTML (since PHP sends Content-Type: text/html by default) then it will probably hit an error.

Once you've got your JSON data, you can build your HTML to use with html().

Title: Jquery 1.5 breaks old 1.4 $.get calls

Body:
I recently upgraded to 1.5, and functions like:

function showData(id) {

 $.get("/url/getdata", {id : id}, function(data) {
 $("#dialogData").html(data);
 $("#dialogData").dialog({width: 500, modal: true, zIndex:22000});
 }, "json");
}

no longer work with the addition of 1.5.

Looking at firebug, the correct data is returned, but the function breaks after entering the callback.
Everything simply stops.

How can I fix this? I read about the changes to Ajax call in 1.5, but I have over a thousand such calls through my project -> I cannot even begin to think about hunting them all down and changing them, let alone bug testing it all.

Edit: Oddly enough, if I put "text json" instead of "json" for dataType, it works. I don't think going through all my code and changing that is a viable option...

Edit 2: Instead of returning json_encode($string), I tried returning json_encode(array("string" => $string)), and then I did $(element).html(data.string).
This did not work either, and the JSON data I got with this call was valid on jsonlint.com

Edit 3: Tried setting headers prior to the json_encode output, didn't work. So far the only solution has been setting the datatype to text json.


问:
Can this forwardRef be moved into a function for reusability?
I am in the process of moving my application to Material UI V4 and I am struggling to move my react router Link components into forwardRef wrapped components when the 'to' prop is set programmatically.

The below code works but requires duplicating the call to forwardRef and building the props object and I would prefer to do that work in a function that is called once with arguments but I cannot work out how to do it.

```<code>const ViewLink = (props, ref) => {
    console.log(props);
    switch (props.type) {
        case 'entities':
            return <Link to={`/entities/${props.id}`} {...props} innerRef={ref} />;
        case 'templates':
            return <Link to={`/templates/${props.id}`} {...props} innerRef={ref} />;
        default:
            return null;
    }
}

<Button
    className={classes.buttonFont}
    component={React.forwardRef((props, ref) => ViewLink(
        {
            id: childData.id,
            type: type,
            ...props
        },
            ref
    ))}
>
    {childData[column]}
</Button>
</code>```

Is there a way to create a single function that handles both the switch statement and the forwardRef? Ideally, something called as per below:

```<code><Button
    className={classes.buttonFont}
    component={(props) => ViewLink(id, type, props)}
>
    {childData[column]}
</Button>
</code>```

答:
Something like the following should work fine. ViewLink can be defined in a separate file and imported if you want to reuse it. Any properties that you need to pass to ViewLink can be passed by specifying them on the Button element. That allows the component prop to point at a reusable type rather than an inline function.

```<code>const ViewLink = React.forwardRef((props, ref) => {
    console.log(props);
    switch (props.type) {
        case 'entities':
            return <Link to={`/entities/${props.id}`} {...props} innerRef={ref} />;
        case 'templates':
            return <Link to={`/templates/${props.id}`} {...props} innerRef={ref} />;
        default:
            return null;
    }
});
</code>```

```<code><Button
    className={classes.buttonFont}
    id={childData.id}
    component={ViewLink}
>
    {childData[column]}
</Button>
</code>```

Body:
I am in the process of moving my application to Material UI V4 and I am struggling to move my react router Link components into forwardRef wrapped components when the 'to' prop is set programmatically.

The below code works but requires duplicating the call to forwardRef and building the props object and I would prefer to do that work in a function that is called once with arguments but I cannot work out how to do it.

const ViewLink = (props, ref) => {
    console.log(props);
    switch (props.type) {
        case 'entities':
            return <Link to={`/entities/${props.id}`} {...props} innerRef={ref} />;
        case 'templates':
            return <Link to={`/templates/${props.id}`} {...props} innerRef={ref} />;
        default:
            return null;
    }
}

<Button
    className={classes.buttonFont}
    component={React.forwardRef((props, ref) => ViewLink(
        {
            id: childData.id,
            type: type,
            ...props
        },
            ref
    ))}
>
    {childData[column]}
</Button>

Is there a way to create a single function that handles both the switch statement and the forwardRef? Ideally, something called as per below:

<Button
    className={classes.buttonFont}
    component={(props) => ViewLink(id, type, props)}
>
    {childData[column]}
</Button>

Body:
Something like the following should work fine. ViewLink can be defined in a separate file and imported if you want to reuse it. Any properties that you need to pass to ViewLink can be passed by specifying them on the Button element. That allows the component prop to point at a reusable type rather than an inline function.

const ViewLink = React.forwardRef((props, ref) => {
    console.log(props);
    switch (props.type) {
        case 'entities':
            return <Link to={`/entities/${props.id}`} {...props} innerRef={ref} />;
        case 'templates':
            return <Link to={`/templates/${props.id}`} {...props} innerRef={ref} />;
        default:
            return null;
    }
});

<Button
    className={classes.buttonFont}
    id={childData.id}
    component={ViewLink}
>
    {childData[column]}
</Button>


问:
Creating grouped barplot in R
I have a data frame in R, that looks something  like this:

```<code> Requirements   Documentation   Development  Delivery

 After          After           During       During
 Before         After           Before       After
 After          Before          Before       During
 During         During          After        Before
...
</code>```

And I need to create a histogram that it has to look like the image below, but I can't create the right dataset

Any help would be much appreciated.

答:
Please check this: https://stackoverflow.com/help/minimal-reproducible-example

```<code>  df <- data.frame(
      Requirement = c("After", "Before", "After", "During"),
      Documentation = c("After", "After", "Before", "During"),
      Development = c("During", "Before", "Before", "After"),
      Delivery = c("During", "After", "During", "Before")
    )
</code>```

You first have to reshape your dataframe in a long format

```<code>library(tidyr)
newdf <- gather(df)

p <- ggplot(data=newdf, aes(x=key, y=value, fill = value)) +
  geom_bar(stat="identity", color="black", position=position_dodge())+
  theme_minimal()
p
</code>```

Title: Creating grouped barplot in R

Body:
I have a data frame in R, that looks something  like this:

 Requirements   Documentation   Development  Delivery

 After          After           During       During
 Before         After           Before       After
 After          Before          Before       During
 During         During          After        Before
...

And I need to create a histogram that it has to look like the image below, but I can't create the right dataset

Any help would be much appreciated.

Body:
Please check this: https://stackoverflow.com/help/minimal-reproducible-example

  df <- data.frame(
      Requirement = c("After", "Before", "After", "During"),
      Documentation = c("After", "After", "Before", "During"),
      Development = c("During", "Before", "Before", "After"),
      Delivery = c("During", "After", "During", "Before")
    )

You first have to reshape your dataframe in a long format

library(tidyr)
newdf <- gather(df)

p <- ggplot(data=newdf, aes(x=key, y=value, fill = value)) +
  geom_bar(stat="identity", color="black", position=position_dodge())+
  theme_minimal()
p


问:
Using The Max Function In LINQ
I am trying to convert this sql into my LINQ query and am having alot of problems.

```<code>select Heading,CreatedBy,ReleaseID, MAX(PublishDate)
from Releases
group by Heading,CreatedBy,ReleaseID
</code>```

I need to use this query in this LINQ format

```<code>  List<RelData> cmsPress = (from Release in dataContext.Releases
                                        select new RelData
                                        {

                                            Heading = Release.Heading,
                                            ReleaseID = Release.ReleaseID,
                                            CreatedBy = Release.CreatedBy,
                                            PublishDate =   Release.PublishDate.ToShortDateString()
                                        }).ToList();
</code>```

答:
Something like this:</p>

```<code>List<RelData> cmsPress = (from Release in dataContext.Releases
    group Release by new { Release.Heading, Release.ReleaseID, Release.CreatedBy } into g
    select new RelData
    {
        Heading = g.Key.Heading,
        ReleaseID = g.Key.ReleaseID,
        CreatedBy = g.Key.CreatedBy,
        PublishDate = g.Max(x => x.PublishDate).ToShortDateString()
    }).ToList();
</code>```

Title: Using The Max Function In LINQ

Body:
I am trying to convert this sql into my LINQ query and am having alot of problems.

select Heading,CreatedBy,ReleaseID, MAX(PublishDate)
from Releases
group by Heading,CreatedBy,ReleaseID

I need to use this query in this LINQ format

  List<RelData> cmsPress = (from Release in dataContext.Releases
                                        select new RelData
                                        {

                                            Heading = Release.Heading,
                                            ReleaseID = Release.ReleaseID,
                                            CreatedBy = Release.CreatedBy,
                                            PublishDate =   Release.PublishDate.ToShortDateString()
                                        }).ToList();

Body:
Something like this:

List<RelData> cmsPress = (from Release in dataContext.Releases
    group Release by new { Release.Heading, Release.ReleaseID, Release.CreatedBy } into g
    select new RelData
    {
        Heading = g.Key.Heading,
        ReleaseID = g.Key.ReleaseID,
        CreatedBy = g.Key.CreatedBy,
        PublishDate = g.Max(x => x.PublishDate).ToShortDateString()
    }).ToList();


问:
Using Polyline for making custom route with google_maps_flutter plugin - Flutter
google_maps_flutter 0.5.6 Added support for Polylines on GoogleMap.
But there is no code or documentation available under my view.

A plugin named maps_view exists which supports polylines

```<code>import 'package:map_view/map_view.dart';
import 'package:map_view/polyline.dart';
...
MapView mapView = MapView();
mapView.addPolyline(Polyline('my_polyline', [
  Location(45.52309483308097, -122.67339684069155),
  Location(45.52298442915803, -122.66339991241693),
]));
</code>```

I need the same function that's built-in with google_maps_flutter.

答:
Try this in your StatefulWidget subclass.

```<code>Map<PolylineId, Polyline> _mapPolylines = {};
int _polylineIdCounter = 1;

void _add() {
  final String polylineIdVal = 'polyline_id_$_polylineIdCounter';
  _polylineIdCounter++;
  final PolylineId polylineId = PolylineId(polylineIdVal);

  final Polyline polyline = Polyline(
    polylineId: polylineId,
    consumeTapEvents: true,
    color: Colors.red,
    width: 5,
    points: _createPoints(),
  );

  setState(() {
    _mapPolylines[polylineId] = polyline;
  });
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Maps"),
      actions: <Widget>[IconButton(icon: Icon(Icons.add), onPressed: _add)],
    ),
    body: GoogleMap(
      initialCameraPosition: const CameraPosition(target: LatLng(0, 0), zoom: 4.0),
      polylines: Set<Polyline>.of(_mapPolylines.values),
    ),
  );
}

List<LatLng> _createPoints() {
  final List<LatLng> points = <LatLng>[];
  points.add(LatLng(1.875249, 0.845140));
  points.add(LatLng(4.851221, 1.715736));
  points.add(LatLng(8.196142, 2.094979));
  points.add(LatLng(12.196142, 3.094979));
  points.add(LatLng(16.196142, 4.094979));
  points.add(LatLng(20.196142, 5.094979));
  return points;
}
</code>```

Body:
google_maps_flutter 0.5.6 Added support for Polylines on GoogleMap.
But there is no code or documentation available under my view.

A plugin named maps_view exists which supports polylines

import 'package:map_view/map_view.dart';
import 'package:map_view/polyline.dart';
...
MapView mapView = MapView();
mapView.addPolyline(Polyline('my_polyline', [
  Location(45.52309483308097, -122.67339684069155),
  Location(45.52298442915803, -122.66339991241693),
]));

I need the same function that's built-in with google_maps_flutter.

Body:
Try this in your StatefulWidget subclass.

Map<PolylineId, Polyline> _mapPolylines = {};
int _polylineIdCounter = 1;

void _add() {
  final String polylineIdVal = 'polyline_id_$_polylineIdCounter';
  _polylineIdCounter++;
  final PolylineId polylineId = PolylineId(polylineIdVal);

  final Polyline polyline = Polyline(
    polylineId: polylineId,
    consumeTapEvents: true,
    color: Colors.red,
    width: 5,
    points: _createPoints(),
  );

  setState(() {
    _mapPolylines[polylineId] = polyline;
  });
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Maps"),
      actions: <Widget>[IconButton(icon: Icon(Icons.add), onPressed: _add)],
    ),
    body: GoogleMap(
      initialCameraPosition: const CameraPosition(target: LatLng(0, 0), zoom: 4.0),
      polylines: Set<Polyline>.of(_mapPolylines.values),
    ),
  );
}

List<LatLng> _createPoints() {
  final List<LatLng> points = <LatLng>[];
  points.add(LatLng(1.875249, 0.845140));
  points.add(LatLng(4.851221, 1.715736));
  points.add(LatLng(8.196142, 2.094979));
  points.add(LatLng(12.196142, 3.094979));
  points.add(LatLng(16.196142, 4.094979));
  points.add(LatLng(20.196142, 5.094979));
  return points;
}


问:
How do I block HTML in my form input?
So, I have a basic little script that takes input from an HTML form, is processes by PHP and then writes it to a text file in the form of CSS. I've already got some jerkwad trying to drop tables on the server (There is no SQL but I'd like to keep people from trying none the less) Here is the code that I have thus far, can someone help me block potentially bad input via htmlentities or something else?

The HTML Form

```<code><html><body>
<h4>Codes Form</h4>
<form action="codes.php" method="post">

Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" />

<input type="submit" value="Post It!" />
</form>
</body></html>
</code>```

The PHP

```<code>    <html><body>
 <?php

 $Friendcode = $_POST['Usercode'];
 $Username = $_POST['Username'];

echo "You have recorded the following information on the server ". $Username . " " . $Usercode . ".<br />"; echo "Thanks for contributing!";

$output = ".author[href\$=\"$Username\"]:after { \n"
       ."content: \" ($Usercode)\" !important\n"
       ."}";
}
$fp = fopen('file.txt', 'a');
fwrite($fp, $output);
fwrite($fp, "\n");
fclose($fp);
?>

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

答: Use PHP to convert every symbol to HTML numbers! Head on over to htmlentities() for details about doing so.</p>

Title: How do I block HTML in my form input?

Body:
So, I have a basic little script that takes input from an HTML form, is processes by PHP and then writes it to a text file in the form of CSS. I've already got some jerkwad trying to drop tables on the server (There is no SQL but I'd like to keep people from trying none the less) Here is the code that I have thus far, can someone help me block potentially bad input via htmlentities or something else?

The HTML Form

Codes Form

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

Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" />

<input type="submit" value="Post It!" />
</form>

The PHP

 <?php

 $Friendcode = $_POST['Usercode'];
 $Username = $_POST['Username'];

echo "You have recorded the following information on the server ". $Username . " " . $Usercode . ".
"; echo "Thanks for contributing!";

$output = ".author[href\$=\"$Username\"]:after { \n"
       ."content: \" ($Usercode)\" !important\n"
       ."}";
}
$fp = fopen('file.txt', 'a');
fwrite($fp, $output);
fwrite($fp, "\n");
fclose($fp);
?>


问:
Mockito: how to test method that changes private field value?
I have a method void create(File file); which creates data structure (map) in a class, which will instantiate and put data into the private field:

```<code>private Map<String> myMap
</code>```

of the class.

Now I want to unit test the method create, how could I do it ?
Thanks!

答:
You can use the @InjectMocks & @Mock annotation.

Here is a example for JUnit 5 with the latest Mockito version (v2.27).

```<code>class SomeClass {

    private Map<String, String> myMap = new HashMap<>();

    public boolean doSomething(String fileName) {
        return myMap.containsKey(fileName);
    }
}

@ExtendWith(MockitoExtension.class)
class SomeClassTest {

    @InjectMocks
    SomeClass someClass;

    @Mock
    Map<String, String> map;

    @Test
    public void test() {

        Mockito.when(map.containsKey("test")).thenReturn(true);

        Assert.assertTrue(someClass.doSomething("test"));

        Mockito.verify(map, Mockito.times(1)).containsKey("test");
    }
}
</code>```

Body:
I have a method void create(File file); which creates data structure (map) in a class, which will instantiate and put data into the private field:

private Map<String> myMap

of the class.

Now I want to unit test the method create, how could I do it ?
Thanks!

Body:
You can use the @InjectMocks & @Mock annotation.

Here is a example for JUnit 5 with the latest Mockito version (v2.27).

class SomeClass {

    private Map<String, String> myMap = new HashMap<>();

    public boolean doSomething(String fileName) {
        return myMap.containsKey(fileName);
    }
}

@ExtendWith(MockitoExtension.class)
class SomeClassTest {

    @InjectMocks
    SomeClass someClass;

    @Mock
    Map<String, String> map;

    @Test
    public void test() {

        Mockito.when(map.containsKey("test")).thenReturn(true);

        Assert.assertTrue(someClass.doSomething("test"));

        Mockito.verify(map, Mockito.times(1)).containsKey("test");
    }
}


问:
Trying to fetch data from an api using javascript
I'am trying to fetch data from a online MongoDb database using javascript and html. but it doesn't work properly. Also using jquery library too

    <input type="submit" value="GET DATA FROM API" id="getAPI">

Input Form

    <form id="postData" >
    </form>

```

答:
fetch("https://jsonplaceholder.typicode.com/users")
  .then(res => {
    return res.json();
  })
  .then(data => {
    let result = `<h2> Random User Info From Jsonplaceholder API</h2>`;
    data.forEach(seller => {
      const {
        id,
        name,
        email
      } = seller;
      result += `

 User ID: ${id}

 User Full Name : ${name}

 User Email : ${email}

`;
      document.getElementById("app").innerHTML = result;
    });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app"></div></code>```

Your Front End works well. I replaced the api url in your code and everything is fine. It might be something on the Back End. Did you check the status code that you get from the server?

Body:
fetch("https://jsonplaceholder.typicode.com/users")
  .then(res => {
    return res.json();
  })
  .then(data => {
    let result = `<h2> Random User Info From Jsonplaceholder API</h2>`;
    data.forEach(seller => {
      const {
        id,
        name,
        email
      } = seller;
      result += `<div>
                   <h5> User ID: ${id} </h5>
                   <ul>
                     <li> User Full Name : ${name}</li>
                     <li> User Email : ${email} </li>
                   </ul>
                 </div>`;
      document.getElementById("app").innerHTML = result;
    });
  });

<div id="app"></div>

Your Front End works well. I replaced the api url in your code and everything is fine. It might be something on the Back End. Did you check the status code that you get from the server?


问:
How to use quantifier in regular expressions?
I'm trying to enter a string without any numbers with a minimum of 4 characters
but when I enter a string without numbers it still gives me an error and I don't know why.

Attempt

```<code>string pattern = "^[a-zA-Z]{4}$";
            Regex rgx = new Regex(pattern);
            string name = "evvFss";
            if(!rgx.IsMatch(name))
            {
              throw new Exception("error");
            }
            else
            {
               Console.WriteLine("correct");
            }

</code>```

It shouldn't give an error because the string doesn't contain any numbers.

答:
{4} tells it to match exactly that many characters, not at least that many.

Use {4,} to make it a minimum of four characters.

Body:
I'm trying to enter a string without any numbers with a minimum of 4 characters
but when I enter a string without numbers it still gives me an error and I don't know why.

Attempt

string pattern = "^[a-zA-Z]{4}$";
            Regex rgx = new Regex(pattern);
            string name = "evvFss";
            if(!rgx.IsMatch(name))
            {
              throw new Exception("error");
            }
            else
            {
               Console.WriteLine("correct");
            }

It shouldn't give an error because the string doesn't contain any numbers.


问:
Cluster analysis of large dataset containing only categorical variables
I have been given the task of clustering our customers base on products they bought together. My data contains 500,000 rows related to each customer and 8,000 variables (product ids). Each variable is a one hot encode vector that shows if a customer bought that product or not.

I have tried to reduce the dimensions of my data with MCA (multiple correspondence algorithm) and then use k-means and dbscan for cluster analysis, but my results were not satisfying.

What are some proper algorithms for cluster analysis of large datasets with high dimensions and their python implementation?

答:
Instead of clustering, what you should likely be using is frequent pattern mining.

One-hot encoding variables often does more harm than good. Either use a well-chosen distance for such data (could be as simple as Hamming or Jaccard on some data sets) with a suitable clustering algorithm (e.g., hierarchical, DBSCAN, but not k-means). Alternatively, try k-modes. But most likely, frequent itemsets is the more meaningful analysis onnsuvh data.


问:
How to handle ProgressBar while image is uploading to firebase
I am uploading image to the firebase storage. But i am not able to handle the ProgressBar in my code.

Component

```<code>onSubmit(){
      const fileRef = this.storage.ref(filepath)
      this.storage.upload(filepath,this.selectedImage).snapshotChanges().pipe(
        finalize(() => {
          fileRef.getDownloadURL().subscribe((url) => {
            this.upSvc.insertImageDetails(this.daydetails.value);
            this.toaster.success("Submitted successfully")
            this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
          })
        }),
      ).subscribe()
}
</code>```

HTML

```<code><div class="progress">
   <div class="progress-bar progress-bar-animated" [ngStyle]="{ 'width': progress + '%' }"></div>
</div>
Progress: {{progress}}% Complete
</code>```

答:
Through Firebase SDK

You can catch the state_changed event on the node where you are uploading file and then call snapshotChanges() on that to get the data necessary to calculate current file upload progress.
Here is an example

```<code>var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case firebase.storage.TaskState.PAUSED: // or 'paused'
      console.log('Upload is paused');
      break;
    case firebase.storage.TaskState.RUNNING: // or 'running'
      console.log('Upload is running');
      break;
  }
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log('File available at', downloadURL);
  });
});
</code>```

You can find more information here

Through AngularFire2

You can use the AngularFireUploadTask which is return by upload()

Then you can call percentageChanges() which is a Observable which emits the percentage of the upload progress

```<code>uploadProgress:Observable<number>;
uploadTask: any;
onSubmit(){
  const fileRef = this.storage.ref(filepath)

  this.uploadTask = this.storage.upload(filepath,this.selectedImage).snapshotChanges().pipe(
    finalize(() => {
      fileRef.getDownloadURL().subscribe((url) => {
        this.upSvc.insertImageDetails(this.daydetails.value);
        this.toaster.success("Submitted successfully")
        this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
      })
    })).subscribe()
   this.uploadProgress = this.uploadTask.percentageChanges();
    }
</code>```

In your HTML:

```<code><div class="progress">
   <div class="progress-bar progress-bar-animated" [ngStyle]="{ 'width': progress + '%' }"></div>
</div>

Progress: {{ uploadProgress | async }}% Complete
</code>```

You can find more info here

Body:
I am uploading image to the firebase storage. But i am not able to handle the ProgressBar in my code.

Component

onSubmit(){
      const fileRef = this.storage.ref(filepath)
      this.storage.upload(filepath,this.selectedImage).snapshotChanges().pipe(
        finalize(() => {
          fileRef.getDownloadURL().subscribe((url) => {
            this.upSvc.insertImageDetails(this.daydetails.value);
            this.toaster.success("Submitted successfully")
            this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
          })
        }),
      ).subscribe()
}

HTML

Progress: {{progress}}% Complete

Body:
Through Firebase SDK

You can catch the state_changed event on the node where you are uploading file and then call snapshotChanges() on that to get the data necessary to calculate current file upload progress.
Here is an example

var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case firebase.storage.TaskState.PAUSED: // or 'paused'
      console.log('Upload is paused');
      break;
    case firebase.storage.TaskState.RUNNING: // or 'running'
      console.log('Upload is running');
      break;
  }
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log('File available at', downloadURL);
  });
});

You can find more information here

Through AngularFire2

You can use the AngularFireUploadTask which is return by upload()

Then you can call percentageChanges() which is a Observable which emits the percentage of the upload progress

uploadProgress:Observable<number>;
uploadTask: any;
onSubmit(){
  const fileRef = this.storage.ref(filepath)

  this.uploadTask = this.storage.upload(filepath,this.selectedImage).snapshotChanges().pipe(
    finalize(() => {
      fileRef.getDownloadURL().subscribe((url) => {
        this.upSvc.insertImageDetails(this.daydetails.value);
        this.toaster.success("Submitted successfully")
        this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
      })
    })).subscribe()
   this.uploadProgress = this.uploadTask.percentageChanges();
    }

In your HTML:

<div class="progress">
   <div class="progress-bar progress-bar-animated" [ngStyle]="{ 'width': progress + '%' }"></div>
</div>

Progress: {{ uploadProgress | async }}% Complete

You can find more info here


问:
Block php files except in one directory
I'm trying to block all calls to php files in a specific folder and subfolders except for one specific folder and its subfolders.

I've tried a number of different regex permutations and I can get the regex to match properly, it's implementing in htaccess where I have a problem.

This is the htaccess file as it is now:

```<code><FilesMatch "\.(?i:php)$">
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
</FilesMatch>
</code>```

and this is the regex expression that matches properly outside of htaccess:

```<code>^(?!.*(thedirectory)).*(?i:php)$
</code>```

When I check that regex against index.php it matches. When I check against /thedirectory/index.php it does not match. When I check against /someotherdirectory/style.css it does not match.

How I'd like it to work is:

```<code>domain.com/folder/index.php -> 404 Error
domain.com/folder/thedirectory/index.php -> resolves
domain.com/folder/someotherdirectory/index.php -> 404 Error
domain.com/folder/someotherdirectory/afunction.php -> 404 Error
domain.com/folder/someotherdirectory/style.css -> resolves
</code>```

答:
Turned out to be a lot more straightforward than I thought it would be:</p>

```<code><IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_URI} ^(?!.*(thedirectory)).*(?i:php)$ [NC]
    RewriteRule "(.*)" /404.php
</IfModule>
</code>```

Title: Block php files except in one directory

Body:
I'm trying to block all calls to php files in a specific folder and subfolders except for one specific folder and its subfolders.

I've tried a number of different regex permutations and I can get the regex to match properly, it's implementing in htaccess where I have a problem.

This is the htaccess file as it is now:

<FilesMatch "\.(?i:php)$">
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
</FilesMatch>

and this is the regex expression that matches properly outside of htaccess:

^(?!.*(thedirectory)).*(?i:php)$

When I check that regex against index.php it matches. When I check against /thedirectory/index.php it does not match. When I check against /someotherdirectory/style.css it does not match.

How I'd like it to work is:

domain.com/folder/index.php -> 404 Error
domain.com/folder/thedirectory/index.php -> resolves
domain.com/folder/someotherdirectory/index.php -> 404 Error
domain.com/folder/someotherdirectory/afunction.php -> 404 Error
domain.com/folder/someotherdirectory/style.css -> resolves

Body:
Turned out to be a lot more straightforward than I thought it would be:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_URI} ^(?!.*(thedirectory)).*(?i:php)$ [NC]
    RewriteRule "(.*)" /404.php
</IfModule>


问:
R Tidy solution to select from group_by output based on a column's data availability
I have following R dplyr dataframe in df_pub (Science/Nature Publication Data)

Please note that there are same PMID (or paper) with contributing authors in each row (Authors info is not shown here).

I need to select and store publications (PMID) which has no email attached to it and store the last observation of it in data-frame.

Actually I want to remove all PMIDs having any email in any observation. I need to collect the Publications (PMIDs) which does not have an attached email, and then find the last author or last observation (usually she/he/xe are the group leader or PI, we'll contact them manually and request them to update their email).

So for the example above, the expected output will not contain PMID 22522932 because it has an email attached. For other PMIDs only the last row of each such PMID will be stored.

I started with this but then lost

```<code>df_pub %>%
  group_by(pmid) %>%
  filter(is.na(email)) # This does not do the expected
</code>```

答:
I think this is what you wanted. It checks which pmids have no email attached and then shows only the last row.</p>

```<code>df_pub %>%
    group_by(pmid) %>%
    filter(sum(is.na(email)) == n()) %>% #chooses pmids that number of NAs equals number os rows
    filter(row_number() == n()) #chooses the last row for each pmid
</code>```

Body:
I have following R dplyr dataframe in df_pub (Science/Nature Publication Data)

Please note that there are same PMID (or paper) with contributing authors in each row (Authors info is not shown here).

I need to select and store publications (PMID) which has no email attached to it and store the last observation of it in data-frame.

Actually I want to remove all PMIDs having any email in any observation. I need to collect the Publications (PMIDs) which does not have an attached email, and then find the last author or last observation (usually she/he/xe are the group leader or PI, we'll contact them manually and request them to update their email).

So for the example above, the expected output will not contain PMID 22522932 because it has an email attached. For other PMIDs only the last row of each such PMID will be stored.

I started with this but then lost

df_pub %>%
  group_by(pmid) %>%
  filter(is.na(email)) # This does not do the expected

Body:
I think this is what you wanted. It checks which pmids have no email attached and then shows only the last row.

df_pub %>%
    group_by(pmid) %>%
    filter(sum(is.na(email)) == n()) %>% #chooses pmids that number of NAs equals number os rows
    filter(row_number() == n()) #chooses the last row for each pmid


问:
Replace diagonal elements with vector in PyTorch
I have been searching everywhere for something equivalent of the following to PyTorch, but I cannot find anything.

```<code>L_1 = np.tril(np.random.normal(scale=1., size=(D, D)), k=0)
L_1[np.diag_indices_from(L_1)] = np.exp(np.diagonal(L_1))
</code>```

I guess there is no way to replace the diagonal elements in such an elegant way using Pytorch.

答:
There is an easier way to do it

```<code>dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector
</code>```

In fact we have to generate diagonal indices ourselves.

Usage example:

```<code>dest_matrix = torch.randint(10, (3, 3))
source_vector = torch.randint(100, 200, (len(dest_matrix), ))
print('dest_matrix:\n', dest_matrix)
print('source_vector:\n', source_vector)

dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector

print('result:\n', dest_matrix)

# dest_matrix:
#  tensor([[3, 2, 5],
#         [0, 3, 5],
#         [3, 1, 1]])
# source_vector:
#  tensor([182, 169, 147])
# result:
#  tensor([[182,   2,   5],
#         [  0, 169,   5],
#         [  3,   1, 147]])
</code>```

in case dest_matrix is not square you have to take min(dest_matrix.size()) instead of len(dest_matrix) in range()

Not as elegant as numpy but this doesn't require to store a new matrix of indices.

And yes, this preserves gradients

Body:
I have been searching everywhere for something equivalent of the following to PyTorch, but I cannot find anything.

L_1 = np.tril(np.random.normal(scale=1., size=(D, D)), k=0)
L_1[np.diag_indices_from(L_1)] = np.exp(np.diagonal(L_1))

I guess there is no way to replace the diagonal elements in such an elegant way using Pytorch.

Body:
There is an easier way to do it

dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector

In fact we have to generate diagonal indices ourselves.

Usage example:

dest_matrix = torch.randint(10, (3, 3))
source_vector = torch.randint(100, 200, (len(dest_matrix), ))
print('dest_matrix:\n', dest_matrix)
print('source_vector:\n', source_vector)

dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector

print('result:\n', dest_matrix)

# dest_matrix:
#  tensor([[3, 2, 5],
#         [0, 3, 5],
#         [3, 1, 1]])
# source_vector:
#  tensor([182, 169, 147])
# result:
#  tensor([[182,   2,   5],
#         [  0, 169,   5],
#         [  3,   1, 147]])

in case dest_matrix is not square you have to take min(dest_matrix.size()) instead of len(dest_matrix) in range()

Not as elegant as numpy but this doesn't require to store a new matrix of indices.

And yes, this preserves gradients


问:
get() in picasso cannot be applied to (android.content.context)
I have the following code on android studio, after I followed a tutorial video. However, in the tutorial video, the uploader used:

implementation 'com.android.picasso:picasso:2.5.2'

while I had to use

```<code>implementation 'com.squareup.picasso:picasso:2.71828'
</code>```

Adapter Class

```<code>public class adapter extends RecyclerView.Adapter<adapter.viewHolder> {
    private Context mContext;
    private ArrayList<ItemActivity> mExampleList;

    public adapter(Context context, ArrayList<ItemActivity> exampleList)
    {
        mContext = context;
        mExampleList = exampleList;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
    viewType) {
            View v =
LayoutInflater.from(mContext).inflate(R.layout.itemlayout, parent, false);
        return new viewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull viewHolder holder, int position)
    {
        ItemActivity currentItem = mExampleList.get(position);

        String imageUrl = currentItem.getImageUrl();
        String creatorName = currentItem.getCreator();
        int likeCount = currentItem.getLikeCount();

        holder.mTextViewCreator.setText(creatorName);
        holder.mTextViewLikes.setText("Likes: "+likeCount);

        Picasso.get(mContext).load(imageUrl).
        fit().centerInside.into(holder.mImageView);//get() in picasso
                                                     cannot be applied to
                                                 (android.content.context)
    }

    @Override
    public int getItemCount() {
        return mExampleList.size();
    }

    public class viewHolder extends RecyclerView.ViewHolder
    {
        public ImageView mImageView;
        public TextView mTextViewCreator;
        public TextView mTextViewLikes;

        public viewHolder(@NonNull View itemView) {
            super(itemView);
            mTextViewCreator = itemView.findViewById(R.id.image_view);
            mImageView = itemView.findViewById(R.id.text_view_creator);
            mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
        }
    }

}
</code>```

As stated above, the Picasso line gives me the error: get() in picasso cannot be applied to (android.content.context)

Thanks!

答:
Picasso#get() doesn't have a context. If you need to use a different context, you can use new Picasso.Builder(mContext).build();

Or, Picasso.get() will suffice.

Body:
I have the following code on android studio, after I followed a tutorial video. However, in the tutorial video, the uploader used:

implementation 'com.android.picasso:picasso:2.5.2'

while I had to use

implementation 'com.squareup.picasso:picasso:2.71828'

Adapter Class

public class adapter extends RecyclerView.Adapter<adapter.viewHolder> {
    private Context mContext;
    private ArrayList<ItemActivity> mExampleList;

    public adapter(Context context, ArrayList<ItemActivity> exampleList)
    {
        mContext = context;
        mExampleList = exampleList;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
    viewType) {
            View v =
LayoutInflater.from(mContext).inflate(R.layout.itemlayout, parent, false);
        return new viewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull viewHolder holder, int position)
    {
        ItemActivity currentItem = mExampleList.get(position);

        String imageUrl = currentItem.getImageUrl();
        String creatorName = currentItem.getCreator();
        int likeCount = currentItem.getLikeCount();

        holder.mTextViewCreator.setText(creatorName);
        holder.mTextViewLikes.setText("Likes: "+likeCount);

        Picasso.get(mContext).load(imageUrl).
        fit().centerInside.into(holder.mImageView);//get() in picasso
                                                     cannot be applied to
                                                 (android.content.context)
    }

    @Override
    public int getItemCount() {
        return mExampleList.size();
    }

    public class viewHolder extends RecyclerView.ViewHolder
    {
        public ImageView mImageView;
        public TextView mTextViewCreator;
        public TextView mTextViewLikes;

        public viewHolder(@NonNull View itemView) {
            super(itemView);
            mTextViewCreator = itemView.findViewById(R.id.image_view);
            mImageView = itemView.findViewById(R.id.text_view_creator);
            mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
        }
    }

}

As stated above, the Picasso line gives me the error: get() in picasso cannot be applied to (android.content.context)

Thanks!


问:
WPF Smith HTML editor is changing all my HTML tags to upper case
I'm building WPF application that's using the Smith HTML Editor. The application is MVVM and I've got the Smith control bound to a field with HTML content. Everything is working ok, except that the IsDirty implementation that I'm working on gets triggered if you click in or even mouse over the HTML control. I looked a little closer and found that as soon as the control looses focus it changes all my tags to upper case (thus the app sees the field as changed and sets the model to dirty.)

I'm having a hard time putting my hands on any documentation for this control, but so far I haven't been able to find anywhere to control this behaviour.

Here's the XAML for the control:

```<code><smith:HtmlEditor Name="fldcomments" Height="320" BindingContent="{Binding Path=Student.Comments, Mode=TwoWay }"/>
</code>```

I'd appreciate any hints.

答:
So this is kludgey as hell, but it's the best I came up with. I used NUglify to extract the plain text and added that as a comparison for my field setter function. Here's the code for the function:

```<code>protected void SetField<T>(ref T field, T value, string propertyName)
    {

           if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                IsDirty = true;

            if ((propertyName == "Comments") && (value != null) && (field != null))
            {

                var ugField = Uglify.HtmlToText((value as string));
                var ugValue = Uglify.HtmlToText(field as string);
                string strField = Regex.Replace(ugField.Code, @"\s+", string.Empty);
                string strValue = Regex.Replace(ugValue.Code, @"\s+", string.Empty);

                if (strField == strValue)
                { IsDirty = false; }
            }

                field = value;

                OnPropertyChanged(propertyName);
            }

        }
</code>```

I had to add the regex.replace to get rid of some extra whitespace that the HTMLToText function left in there.

I'm not proud, but it works. Still very open to a better solution.

Body:
I'm building WPF application that's using the Smith HTML Editor. The application is MVVM and I've got the Smith control bound to a field with HTML content. Everything is working ok, except that the IsDirty implementation that I'm working on gets triggered if you click in or even mouse over the HTML control. I looked a little closer and found that as soon as the control looses focus it changes all my tags to upper case (thus the app sees the field as changed and sets the model to dirty.)

I'm having a hard time putting my hands on any documentation for this control, but so far I haven't been able to find anywhere to control this behaviour.

Here's the XAML for the control:

<smith:HtmlEditor Name="fldcomments" Height="320" BindingContent="{Binding Path=Student.Comments, Mode=TwoWay }"/>

I'd appreciate any hints.

Body:
So this is kludgey as hell, but it's the best I came up with. I used NUglify to extract the plain text and added that as a comparison for my field setter function. Here's the code for the function:

protected void SetField<T>(ref T field, T value, string propertyName)
    {

           if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                IsDirty = true;

            if ((propertyName == "Comments") && (value != null) && (field != null))
            {

                var ugField = Uglify.HtmlToText((value as string));
                var ugValue = Uglify.HtmlToText(field as string);
                string strField = Regex.Replace(ugField.Code, @"\s+", string.Empty);
                string strValue = Regex.Replace(ugValue.Code, @"\s+", string.Empty);

                if (strField == strValue)
                { IsDirty = false; }
            }

                field = value;

                OnPropertyChanged(propertyName);
            }

        }

I had to add the regex.replace to get rid of some extra whitespace that the HTMLToText function left in there.

I'm not proud, but it works. Still very open to a better solution.


问:
django - Upload a folder under media
I'm trying to upload an entire folder (of images) inside the media_root in django.

I want something like im = models.ImageField(upload_to="images/", blank=True, null=True) but I do not want to upload many images one by one.
How can I do that? There is a simple way to use FileField or ImageField that upload directly the folder instead of a file/image?

答: I've done some digging around and it doesn't seem possible. According to this answer. You can use some JS to select all the files in the directory you want to upload and then create an upload field for each of the files.</p>

Title: django - Upload a folder under media


问:
UISwitch duplicating/weird overlay in CollectionViewCells when scrolling
I have programmatically created UISwitches in collection cells and as scrolling happens these switches are added over and over again, which is causing the half toggles (guessing is because another UISwitch is right beneath it).

This is the entire block of how the UISwitch is created.

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FlagCell", for: indexPath)

    let switchOnOff = UISwitch()

    switchOnOff.translatesAutoresizingMaskIntoConstraints = false
    switchOnOff.setOn(true, animated: true)

    cell.contentView.addSubview(switchOnOff)

    NSLayoutConstraint(item: switchOnOff, attribute: .trailing, relatedBy: .equal, toItem: cell, attribute: .trailing, multiplier: 1, constant: -10).isActive = true

    NSLayoutConstraint(item: switchOnOff, attribute: .centerY, relatedBy: .equal, toItem: cell, attribute: .centerY, multiplier: 1, constant: 0).isActive = true

    return cell
}
</code>```

I was able to do this via Storyboard, but perhaps you guys may have a solution doing it programmatically.

答:
As rmaddy suggested, creating a custom cell class solved it.

```<code>let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! FlagCell
</code>```

And move all the subviews being added in that class.

Body:
I have programmatically created UISwitches in collection cells and as scrolling happens these switches are added over and over again, which is causing the half toggles (guessing is because another UISwitch is right beneath it).

This is the entire block of how the UISwitch is created.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FlagCell", for: indexPath)

    let switchOnOff = UISwitch()

    switchOnOff.translatesAutoresizingMaskIntoConstraints = false
    switchOnOff.setOn(true, animated: true)

    cell.contentView.addSubview(switchOnOff)

    NSLayoutConstraint(item: switchOnOff, attribute: .trailing, relatedBy: .equal, toItem: cell, attribute: .trailing, multiplier: 1, constant: -10).isActive = true

    NSLayoutConstraint(item: switchOnOff, attribute: .centerY, relatedBy: .equal, toItem: cell, attribute: .centerY, multiplier: 1, constant: 0).isActive = true

    return cell
}

I was able to do this via Storyboard, but perhaps you guys may have a solution doing it programmatically.

Body:
As rmaddy suggested, creating a custom cell class solved it.

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! FlagCell

And move all the subviews being added in that class.


问:
Deploy docker on AWS beanstalk with docker composer
I'm trying to deploy multiple node.js micro services on AWS beanstalk, and I want them to be deployed on the same instance. It's my first time to deploy multiple services, so there're some failures I need someone to help me out. So, I tried to package them in a docker container first. Meanwhile I'm using docker composer to manage the structure. It's up and running locally in my virtual machine, but when I deployed it on to beanstalk, I met a few problems.

What I know:

I know I have to choose to deploy as multi-container docker.

The best practice to manage multiple node.js services is using docker composer.

I need a dockerrun.aws.json for node.js app.

I need to create task definition for that ecs instance.

Where I have problems:

I can only find dockerrun.aws.json and task_definition.json
template for php, so I can't verify if my configuration for node.js
in those two json files are in correct shape.

It seems like docker-compose.yml, dockerrun.aws.json and task_definition.json are doing similar jobs. I must keep
task_definition, but do I still need dockerrun.aws.json?

I tried to run the task in ecs, but it stopped right away. How can I check the log for the task?

I got:

No ecs task definition (or empty definition file) found in environment

because my task will always stop immediately. If I can check the log, it will be much easier for me to do trouble shooting.

Here is my task_definition.json:

```<code>{
  "requiresAttributes": [],
  "taskDefinitionArn": "arn:aws:ecs:us-east-1:231440562752:task-definition/ComposerExample:1",
  "status": "ACTIVE",
  "revision": 1,
  "containerDefinitions": [
    {
      "volumesFrom": [],
      "memory": 100,
      "extraHosts": null,
      "dnsServers": null,
      "disableNetworking": null,
      "dnsSearchDomains": null,
      "portMappings": [
        {
          "hostPort": 80,
          "containerPort": 80,
          "protocol": "tcp"
        }
      ],
      "hostname": null,
      "essential": true,
      "entryPoint": null,
      "mountPoints": [
        {
          "containerPath": "/usr/share/nginx/html",
          "sourceVolume": "webdata",
          "readOnly": true
        }
      ],
      "name": "nginxexpressredisnodemon_nginx_1",
      "ulimits": null,
      "dockerSecurityOptions": null,
      "environment": [],
      "links": null,
      "workingDirectory": null,
      "readonlyRootFilesystem": null,
      "image": "nginxexpressredisnodemon_nginx",
      "command": null,
      "user": null,
      "dockerLabels": null,
      "logConfiguration": null,
      "cpu": 99,
      "privileged": null
    }
  ],
  "volumes": [
    {
      "host": {
        "sourcePath": "/ecs/webdata"
      },
      "name": "webdata"
    }
  ],
  "family": "ComposerExample"
}
</code>```

答:
I've had this issue as well. For me the problem was that Dockerrun.aws.json wasn't added in git. eb deploy detects the presence of git.

I ran eb deploy --verbose to figure this out:

```<code>INFO: Getting version label from git with git-describe
INFO: creating zip using git archive HEAD
</code>```

It further lists all the files that'll go in to the zip, Dockerrun.aws.json isn't there.

git status reports this:

```<code>On branch master
Your branch is up to date with 'origin/master'.

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Dockerrun.aws.json

nothing added to commit but untracked files present (use "git add" to track)
</code>```

Adding the file to git and committing helped.
In my specific case I could just remove the .git directory in a scripted deploy.

Body:
I'm trying to deploy multiple node.js micro services on AWS beanstalk, and I want them to be deployed on the same instance. It's my first time to deploy multiple services, so there're some failures I need someone to help me out. So, I tried to package them in a docker container first. Meanwhile I'm using docker composer to manage the structure. It's up and running locally in my virtual machine, but when I deployed it on to beanstalk, I met a few problems.

What I know:

I know I have to choose to deploy as multi-container docker.

The best practice to manage multiple node.js services is using docker composer.

I need a dockerrun.aws.json for node.js app.

I need to create task definition for that ecs instance.

Where I have problems:

I can only find dockerrun.aws.json and task_definition.json
template for php, so I can't verify if my configuration for node.js
in those two json files are in correct shape.

It seems like docker-compose.yml, dockerrun.aws.json and task_definition.json are doing similar jobs. I must keep
task_definition, but do I still need dockerrun.aws.json?

I tried to run the task in ecs, but it stopped right away. How can I check the log for the task?

I got:

No ecs task definition (or empty definition file) found in environment

because my task will always stop immediately. If I can check the log, it will be much easier for me to do trouble shooting.

Here is my task_definition.json:

{
  "requiresAttributes": [],
  "taskDefinitionArn": "arn:aws:ecs:us-east-1:231440562752:task-definition/ComposerExample:1",
  "status": "ACTIVE",
  "revision": 1,
  "containerDefinitions": [
    {
      "volumesFrom": [],
      "memory": 100,
      "extraHosts": null,
      "dnsServers": null,
      "disableNetworking": null,
      "dnsSearchDomains": null,
      "portMappings": [
        {
          "hostPort": 80,
          "containerPort": 80,
          "protocol": "tcp"
        }
      ],
      "hostname": null,
      "essential": true,
      "entryPoint": null,
      "mountPoints": [
        {
          "containerPath": "/usr/share/nginx/html",
          "sourceVolume": "webdata",
          "readOnly": true
        }
      ],
      "name": "nginxexpressredisnodemon_nginx_1",
      "ulimits": null,
      "dockerSecurityOptions": null,
      "environment": [],
      "links": null,
      "workingDirectory": null,
      "readonlyRootFilesystem": null,
      "image": "nginxexpressredisnodemon_nginx",
      "command": null,
      "user": null,
      "dockerLabels": null,
      "logConfiguration": null,
      "cpu": 99,
      "privileged": null
    }
  ],
  "volumes": [
    {
      "host": {
        "sourcePath": "/ecs/webdata"
      },
      "name": "webdata"
    }
  ],
  "family": "ComposerExample"
}

Body:
I've had this issue as well. For me the problem was that Dockerrun.aws.json wasn't added in git. eb deploy detects the presence of git.

I ran eb deploy --verbose to figure this out:

INFO: Getting version label from git with git-describe
INFO: creating zip using git archive HEAD

It further lists all the files that'll go in to the zip, Dockerrun.aws.json isn't there.

git status reports this:

On branch master
Your branch is up to date with 'origin/master'.

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Dockerrun.aws.json

nothing added to commit but untracked files present (use "git add" to track)

Adding the file to git and committing helped.
In my specific case I could just remove the .git directory in a scripted deploy.


问:
Are there any conventions for how to order Java annotations?
For projects heavily used of Java annotations, is there any suggestion on the annotation order? So as to uniform the code style in the team.</p>

答:
I'm going to say there's not. I could be proven wrong on this.

My reasoning is there are hundreds of projects that have annotations, in addition to the ones baked into Java, and the ones baked into our IDEs (specifically Eclipse but I'm sure others have them too.)

So, with all these libraries potentially competitng for "whose on top" I doubt they would agree on a standard.

I would encourage your team to sit down and make decisions about what's best for you guys.

Factors I would consider:

Which annotations are most important? They should be near the top.

Which annotations are most likely to be indicative of potential bugs? They should be near the top.

Which annotations are likely to be on every method in the class? They should be near the bottom.