问:
convert different arrays to array of object using lodash or vanila js
I have different arrays of same size like this:

```<code>var a = ["x", "y", "z"];
var b = [1,2,3];
var c = ["l", "m", "n"];
</code>```

I want this to convert to an array of object like this:

```<code>final_array = [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]
</code>```

I know I can process the arrays using loops and somehow convert this in above format. What I have tried is this way (since size of all arrays will be same):

```<code>var final_array = [];
_.forEach(a, function(value, key){
  var each_list = {};
  each_list.a = a[key];
  each_list.b = b[key];
  each_list.c = c[key];
  final_array[key] = each_list;
})
console.log(final_array); // [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]
</code>```

But this seems to be a very lengthy way and I am sure there will be some good way to do this using lodash or some other approach.

Can any one please help me with this. I already have searched enough on stack overflow and lodash documentation but could not find a better approach for this.

答:
This should work:

```<code>_.zipWith(a, b, c, function(a, b, c) {
  return { a: a, b: b, c: c };
});
</code>```

Or, if you can use ES6, this:

```<code>_.zipWith(a, b, c, (a, b, c) => ({ a, b, c }) );
</code>```

Body:
I have different arrays of same size like this:

var a = ["x", "y", "z"];
var b = [1,2,3];
var c = ["l", "m", "n"];

I want this to convert to an array of object like this:

final_array = [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]

I know I can process the arrays using loops and somehow convert this in above format. What I have tried is this way (since size of all arrays will be same):

var final_array = [];
_.forEach(a, function(value, key){
  var each_list = {};
  each_list.a = a[key];
  each_list.b = b[key];
  each_list.c = c[key];
  final_array[key] = each_list;
})
console.log(final_array); // [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]

But this seems to be a very lengthy way and I am sure there will be some good way to do this using lodash or some other approach.

Can any one please help me with this. I already have searched enough on stack overflow and lodash documentation but could not find a better approach for this.

Body:
This should work:

_.zipWith(a, b, c, function(a, b, c) {
  return { a: a, b: b, c: c };
});

Or, if you can use ES6, this:

_.zipWith(a, b, c, (a, b, c) => ({ a, b, c }) );


来源: stackexchange

问:
Firing Quartz jobs manually
We have several Quartz jobs configured in our application. During development, we leave the quartz scheduler in standby - however, we sometimes want to start a job manually (for development purposes). If I call fireTrigger, it tells me I need to start the scheduler. However, if I start the scheduler, it will also immediately schedule all the other jobs, which is not what I want (since they may trigger while I'm debugging the manually fired job).

I could pause all triggers when I start the scheduler, but then I have to deal with misfire instructions etc.

Is there a simple way to fire off a job manually without having to deal with pausing and misfires (i.e. a fireTrigger which works even if the scheduler is in standby)?

答:
All the Jobs registered in the Quartz Scheduler are uniquely identified by the JobKey which is composed of a name and group . You can fire the job which has a given JobKey immediately by calling triggerJob(JobKey jobKey) of your Scheduler instance.

```<code>// Create a new Job
JobKey jobKey = JobKey.jobKey("myNewJob", "myJobGroup");
JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity(jobKey).storeDurably().build();

// Register this job to the scheduler
scheduler.addJob(job, true);

// Immediately fire the Job MyJob.class
scheduler.triggerJob(jobKey);
</code>```

Note:

scheduler is the Scheduler instance used throughout your application . Its start() method should be already called after it is created.

The job is the durable job which cannot attach any triggers or cron to it .It can only be fired programmatically by calling `triggerJob(JobKey jobKey)`.

ContentLicense: CC BY-SA 3.0

Title: Firing Quartz jobs manually

Body:
All the Jobs registered in the Quartz Scheduler are uniquely identified by the JobKey which is composed of a name and group . You can fire the job which has a given JobKey immediately by calling triggerJob(JobKey jobKey) of your Scheduler instance.

// Create a new Job
JobKey jobKey = JobKey.jobKey("myNewJob", "myJobGroup");
JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity(jobKey).storeDurably().build();

// Register this job to the scheduler
scheduler.addJob(job, true);

// Immediately fire the Job MyJob.class
scheduler.triggerJob(jobKey);

Note:

scheduler is the Scheduler instance used throughout your application . Its start() method should be already called after it is created.

The job is the durable job which cannot attach any triggers or cron to it .It can only be fired programmatically by calling `triggerJob(JobKey jobKey)`.

ContentLicense: CC BY-SA 4.0


问:
Convert Words in a string to sentence case for german sentences
I am searching for a way to change the words in a String to SentenceCase.
I know the Method TextInfo.ToTitleCase but this is not working the right way for german. Like in the documentation of the Method:

```<code>Input                            Language    Expected result                   Actual result
Per anhalter durch die Galaxis   German      Per Anhalter durch die Galaxis    Per Anhalter Durch Die Galaxis
</code>```

Is there another way to convert this right (get the expected result)? The verbs and adjectives should be in lower case.

There are a lot of question but I have not found one which is working the correct way with german.

edit:

I have tried

```<code>var ti = new CultureInfo("de-DE", false).TextInfo;
var res = ti.ToTitleCase("Per anhalter durch die Galaxis");
</code>```

res is know

```<code>Per Anhalter Durch Die Galaxis
</code>```

答:
You want to fix the casing for the German display of nouns, and nouns only. There's no built-in functionality in .NET for that. The method you chose, TextInfo.ToTitleCase(), is too "dumb" for that as it'll simply uppercase the first letter of each word.

As far as I know, you're going to need Natural Language Processing for that. A dictionary won't cut it, because there are words that can be interpreted both as a noun (should be capitalized) and a verb (shouldn't be capitalized).

Or, to put it in other words (and ignoring the noun part for a minute): when you encounter "sie", how do you know whether "they" ("sie") or "you", formal ("Sie") is meant?

You could give it a try though, with a naive approach that won't yield perfect but maybe acceptable results:

Preparation:

Obtain a dictionary file of all German words

Strip it so only nouns remain

Code:

Split your input on word boundaries

Match each word against your dictionary

Uppercase the first letter of the word if it's a hit

Reassemble the input

Body:
I am searching for a way to change the words in a String to SentenceCase.
I know the Method TextInfo.ToTitleCase but this is not working the right way for german. Like in the documentation of the Method:

Input                            Language    Expected result                   Actual result
Per anhalter durch die Galaxis   German      Per Anhalter durch die Galaxis    Per Anhalter Durch Die Galaxis

Is there another way to convert this right (get the expected result)? The verbs and adjectives should be in lower case.

There are a lot of question but I have not found one which is working the correct way with german.

edit:

I have tried

var ti = new CultureInfo("de-DE", false).TextInfo;
var res = ti.ToTitleCase("Per anhalter durch die Galaxis");

res is know

Per Anhalter Durch Die Galaxis


问:
DoEvent() Returns 0 BUT Run-time Error 2585 This action can't be carried out while processing a form or report event
This code was running without a hitch, but now getting Error 2585.

I have looked at Gustav's answer and Gord Thompson's answer but unless I am missing something (quite possible!) the first does not work and the second seems inapplicable. I saw on another site a suggestion that there might be a duplicate record ID, but I check for that possibility.

I put a call to DoEvent() in response to this error but it returns zero. I also wait for 10 seconds to let other processes run. Still receive the error.

```<code>Private Sub SaveData_Click()
  Dim myForm As Form
  Dim myTextBox As TextBox
  Dim myDate As Date
  Dim myResponse As Integer

If IsNull(Forms!Ecoli_Data!DateCollected.Value) Then

  myReponse = myResponse = MsgBox("You have not entered all the required data. You may quit data entry by hitting 'Cancel'", vbOKOnly, "No Sample Date")
  Forms!Ecoli_Data.SetFocus
  Forms!Ecoli_Data!Collected_By.SetFocus
  GoTo endOfSub
End If

If Me.Dirty Then Me.Dirty = False

myDate = Me.DateCollected.Value

Dim yearAsString As String, monthAsString As String, dayAsString As String, clientInitial As String

Dim reportNumberText As String

reportNumberText = Me!SampleNumber.Value
Debug.Print "reportNumberText = " & reportNumberText

Debug.Print "CollectedBy Index: " & Me!Collected_By & " Employee Name: " & DLookup("CollectedBy", "Data_Lookup", Me.Collected_By)

Dim whereString As String
whereString = "SampleNumber=" & "'" & reportNumberText & "'"
Debug.Print whereString
On Error GoTo errorHandling
DoCmd.OpenReport "ECOLI_Laboratory_Report", acViewPreview, , whereString
DoCmd.PrintOut
DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo

Dim eventsOpen As Integer
eventsOpen = DoEvents()
Debug.Print "Number of Open Events = " & DoEvents()

    Dim PauseTime, Start, Finish, TotalTime

        PauseTime = 10    ' Set duration.
        Start = Timer    ' Set start time.
        Do While Timer < Start + PauseTime
            DoEvents    ' Yield to other processes.
        Loop
        Finish = Timer    ' Set end time.
        TotalTime = Finish - Start  ' Calculate total time.
    myResponse = MsgBox("Processing Report Took " & TotalTime & " seconds.", vbOKOnly)

myResponse = MsgBox("Do you want to add more data?", vbYesNo, "What Next?")

If myResponse = vbYes Then

    DoCmd.Close acForm, "ECOLI_Data", acSaveYes
</code>```

Error Generated By Line Above and occurs whether response Y or N to MsgBox.

```<code>    DoCmd.OpenForm "ECOLI_Data", acNormal, , , acFormAdd
    DoCmd.GoToRecord , , acNewRec
Else
    DoCmd.Close acForm, "ECOLI_Data", acSaveYes

End If
Exit Sub

 errorHandling:
 If Err.Number = 2501 Then
   myResponse = MsgBox("Printing Job Cancelled", vbOkayOnly, "Report Not Printed")
ElseIf Err.Number = 0 Then
   'Do nothing
Else
   Debug.Print "Error Number: " & Err.Number & ": " & Err.Description

   myResponse = MsgBox("An Error occurred: " & Err.Description, vbOKOnly, "Error #" & Err.Number)
End If

If Application.CurrentProject.AllForms("ECOLI_Data").IsLoaded Then DoCmd.Close acForm, "ECOLI_Data", acSaveNo

If Application.CurrentProject.AllReports("ECOLI_Laboratory_Report").IsLoaded     Then DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo

endOfSub:
End Sub
</code>```

Any idea on what am I missing here? Thanks.

答:
This line of code

```<code>`DoCmd.Close acForm, "ECOLI_Data", acSaveYes`
</code>```

doesn't save the record you are on, it just saves any changes to the form design.

You should probably use

```<code>If Me.Dirty Then Me.dirty = False
</code>```

to force a save of the current record if any data has changed.

Body:
This code was running without a hitch, but now getting Error 2585.

I have looked at Gustav's answer and Gord Thompson's answer but unless I am missing something (quite possible!) the first does not work and the second seems inapplicable. I saw on another site a suggestion that there might be a duplicate record ID, but I check for that possibility.

I put a call to DoEvent() in response to this error but it returns zero. I also wait for 10 seconds to let other processes run. Still receive the error.

Private Sub SaveData_Click()
  Dim myForm As Form
  Dim myTextBox As TextBox
  Dim myDate As Date
  Dim myResponse As Integer

If IsNull(Forms!Ecoli_Data!DateCollected.Value) Then

  myReponse = myResponse = MsgBox("You have not entered all the required data. You may quit data entry by hitting 'Cancel'", vbOKOnly, "No Sample Date")
  Forms!Ecoli_Data.SetFocus
  Forms!Ecoli_Data!Collected_By.SetFocus
  GoTo endOfSub
End If

If Me.Dirty Then Me.Dirty = False

myDate = Me.DateCollected.Value

Dim yearAsString As String, monthAsString As String, dayAsString As String, clientInitial As String

Dim reportNumberText As String

reportNumberText = Me!SampleNumber.Value
Debug.Print "reportNumberText = " & reportNumberText

Debug.Print "CollectedBy Index: " & Me!Collected_By & " Employee Name: " & DLookup("CollectedBy", "Data_Lookup", Me.Collected_By)

Dim whereString As String
whereString = "SampleNumber=" & "'" & reportNumberText & "'"
Debug.Print whereString
On Error GoTo errorHandling
DoCmd.OpenReport "ECOLI_Laboratory_Report", acViewPreview, , whereString
DoCmd.PrintOut
DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo

Dim eventsOpen As Integer
eventsOpen = DoEvents()
Debug.Print "Number of Open Events = " & DoEvents()

    Dim PauseTime, Start, Finish, TotalTime

        PauseTime = 10    ' Set duration.
        Start = Timer    ' Set start time.
        Do While Timer < Start + PauseTime
            DoEvents    ' Yield to other processes.
        Loop
        Finish = Timer    ' Set end time.
        TotalTime = Finish - Start  ' Calculate total time.
    myResponse = MsgBox("Processing Report Took " & TotalTime & " seconds.", vbOKOnly)

myResponse = MsgBox("Do you want to add more data?", vbYesNo, "What Next?")

If myResponse = vbYes Then

    DoCmd.Close acForm, "ECOLI_Data", acSaveYes

Error Generated By Line Above and occurs whether response Y or N to MsgBox.

    DoCmd.OpenForm "ECOLI_Data", acNormal, , , acFormAdd
    DoCmd.GoToRecord , , acNewRec
Else
    DoCmd.Close acForm, "ECOLI_Data", acSaveYes

End If
Exit Sub

 errorHandling:
 If Err.Number = 2501 Then
   myResponse = MsgBox("Printing Job Cancelled", vbOkayOnly, "Report Not Printed")
ElseIf Err.Number = 0 Then
   'Do nothing
Else
   Debug.Print "Error Number: " & Err.Number & ": " & Err.Description

   myResponse = MsgBox("An Error occurred: " & Err.Description, vbOKOnly, "Error #" & Err.Number)
End If

If Application.CurrentProject.AllForms("ECOLI_Data").IsLoaded Then DoCmd.Close acForm, "ECOLI_Data", acSaveNo

If Application.CurrentProject.AllReports("ECOLI_Laboratory_Report").IsLoaded     Then DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo

endOfSub:
End Sub

Any idea on what am I missing here? Thanks.

Body:
This line of code

`DoCmd.Close acForm, "ECOLI_Data", acSaveYes`

doesn't save the record you are on, it just saves any changes to the form design.

You should probably use

If Me.Dirty Then Me.dirty = False

to force a save of the current record if any data has changed.


问:
Mount Azure storage in Docker Swarm
I have successfully set-up a docker swarm on an Azure scale-set, all good. Now, i need to mount an Azure storage device on my container to utilize my app, this is ofc. simple with "docker run" since i can add capabilities; but this cannot be achieved through "docker service create". What are the possibilities for me to mount storage shares (CIFS/Samba) on the autoscaling nodes for my container?

Thanks in advance.

答: There is a volume plugin for Docker to mount Azure storage entities as a volume using a volume driver: https://github.com/Azure/azurefile-dockervolumedriver

Title: Mount Azure storage in Docker Swarm


问:
How does BindingList<T> know the selected Item?
When you use a BindingList as Binding for lets say a ListBox

```<code>listBox.DataSource = myBindingList;
</code>```

and bind some labels to the same source:

```<code>labelName.DataBindings.Add("Text",
                           myBindingList,
                           "Name",
                           false,
                           DataSourceUpdateMode.OnPropertyChanged);
</code>```

The value of the labels change when the SelectedItem of my listBox is changed.

Why do the values of my labels always refer the currently selected item?

How do they know, by just giving them the BindingList as source, which item in the List is the selected one?

答:
When doing data-binding in windows-forms, the UI has access to a BindingContext and a CurrencyManager. The BindingContext comes (ultimately) from the parent form, and the CurrencyManager is obtained from the BindingContext via the data source reference. So: if two controls on the same form are given the same data-source, then assuming they use the normal binding patterns, they will get the same CurrencyManager. It is the CurrencyManager that tracks the selected item.

Note: it is possible to split the BindingContext on a per-control basis; but the default is for it to be inherited - thus all controls on the same form will share a BindingContext.

Body:
When you use a BindingList as Binding for lets say a ListBox

listBox.DataSource = myBindingList;

and bind some labels to the same source:

labelName.DataBindings.Add("Text",
                           myBindingList,
                           "Name",
                           false,
                           DataSourceUpdateMode.OnPropertyChanged);

The value of the labels change when the SelectedItem of my listBox is changed.

Why do the values of my labels always refer the currently selected item?

How do they know, by just giving them the BindingList as source, which item in the List is the selected one?


问:
Hazelcast - Locks acquired on distributed map are NOT shown in management center
I am trying to evaluate hazelcast for distributed lock solution.

I am creating a  hazelcast client instance from my application. Then I am acquiring lock over map using IMap.tryLock method. During debug and from logs I am seeing that I could acquire the lock successfully.

After successful lock acquisition I am putting an entry to map.

So at that time instant there is one entry and one lock in the map.

In management center, I can see that there is only one entry in the map  but can not see the lock.

Is this the expected behaviour? If this is the expected behaviour what does locks mean for maps in management center?

答:
It's not the expected behaviour. I have tried your scenario with Hazelcast 3.9.1 and Management Center 3.9.1, it shows the lock count correctly.

Which version of Hazelcast and Management Center are you using? I would advise checking if tryLock returns true - you might not be acquiring the lock correctly.


问:
Why does ignite-rest-http disable my logging?
I have ignite-core working nicely with my application's log by including the ignite-slf4j module and calling config.setGridLogger(new Slf4jLogger). However, when I include the ignite-rest-http module, all of my log output disappears. How do I get it back, and include any logging from ignite-rest-http?

答:
It happens because ignite-rest-http module has slf4j-log4j12 as a dependency for some reason.

To make logging over slf4j work with Rest API enabled I had to exclude slf4j-log4j12 and log4j dependencies from classpath.

For example, in Maven it is achieved by editing the dependency entry:

```<code><dependency>
    <groupId>org.apache.ignite</groupId>
    <artifactId>ignite-rest-http</artifactId>
    <version>2.3.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </exclusion>
    </exclusions>
</dependency>
</code>```

Body:
It happens because ignite-rest-http module has slf4j-log4j12 as a dependency for some reason.

To make logging over slf4j work with Rest API enabled I had to exclude slf4j-log4j12 and log4j dependencies from classpath.

For example, in Maven it is achieved by editing the dependency entry:

<dependency>
    <groupId>org.apache.ignite</groupId>
    <artifactId>ignite-rest-http</artifactId>
    <version>2.3.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </exclusion>
    </exclusions>
</dependency>


问:
handling dynamic pop-up error message in jmeter
I have a Jmeter script for an application for which i get pop up error message intermittently. Where as in jmeter we only come to know that flow got terminated by some failure.But we wont come to know the occurrence of Error pop -up message.

My requirement is if we encounter pop up error i want to write to an external file saying that ,the current page got failed due to pop-up error message.
If we can write the error message it's really great. I'm as of now not getting idea to achieve this.
Please can anyone help me in this. or can provide any hint to do R&D.

Thankyou in advance.

Updated the question with screen shot of error message.

答:
As per JMeter project main page:

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

Looking into your screenshot, it is a form of JavaScript popup, most likely window.alert so there is no way to detect it via JMeter.

You can add i.e. Response Assertion to your test in order to introduce some pass/fail criteria, i.e. if you were in the middle of some transaction when the error occurred it should not finish successfully resulting in missing expected entry in the web page (or database), so you can conditionally fail relevant sampler(s) in this case. See How to Use JMeter Assertions in Three Easy Steps to learn more about the concept.

Alternatively you can use WebDriver Sampler plugin which provides JMeter integration with Selenium browser automation framework which drives a real browser, so you will be able to capture this popups and record the page titles/take screenshots, check out IsAlertPresent() class for more information.


问:
Display selected checkbox in Textarea
Users want to select maximum 5 checkboxes and the values should display in the textarea. Validation is working fine and the values are coming to textarea. But when I click more than 5 checkboxes, sixth value is coming to textarea. Please check the below code and help me to fix.

If I select four or five checkboxes those values should be displayed in the textarea. Currently it display more than selected.

$(document).ready(function() {
    $('label.chkskillsedit>input[type=checkbox].hid').on('change', function(evt) {
        if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 5) {
            $(this).parent('label').toggleClass('highlightcheckboxedit', this.checked);

            function fullskilledit() {
                var allValsedit = [];
                $('label.chkskillsedit :checked').each(function() {
                    allValsedit.push($(this).val());
                });
                $('.txtValueshwskilledit').val(allValsedit);
            };
            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        } else {
            $(this).prop('checked', false);
            $(this).parent('label').removeClass('highlightcheckboxedit');
        }
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="51" checked>Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="52">Building Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="53">Draftsman</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="54" checked>Interior Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="55">Landscape Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="56">MEP Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="57" checked>Restoration Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="58">Surveyor</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="59">Sustainable Designer</label><br>
    <br>
    <textarea cols="50" class="txtValueshwskilledit" name="skills" value="">51,54,57</textarea></code>```

答:
You have to call

```<code>$(function() {
   $('.chkskillsedit>input.hid').click(fullskilledit);
   fullskilledit();
  });
</code>```

Both If and else condition in if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 5){...}else{....}

Check below

$(document).ready(function() {
    $('label.chkskillsedit>input[type=checkbox].hid').on('change', function(evt) {
        if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 5) {
          $(this).parent('label').toggleClass('highlightcheckboxedit', this.checked);

            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        } else {
            $(this).prop('checked', false);
            $(this).parent('label').removeClass('highlightcheckboxedit');
            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        }
    })
})
function fullskilledit() {
                var allValsedit = [];
                $('label.chkskillsedit :checked').each(function() {
                    allValsedit.push($(this).val());
                });
                $('.txtValueshwskilledit').val(allValsedit);
            };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="51" checked>Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="52">Building Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="53">Draftsman</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="54" checked>Interior Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="55">Landscape Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="56">MEP Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="57" checked>Restoration Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="58">Surveyor</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="59">Sustainable Designer</label><br>
    <br>
    <textarea cols="50" class="txtValueshwskilledit" name="skills" value="">51,54,57</textarea></code>```

Title: Display selected checkbox in Textarea

Body:
Users want to select maximum 5 checkboxes and the values should display in the textarea. Validation is working fine and the values are coming to textarea. But when I click more than 5 checkboxes, sixth value is coming to textarea. Please check the below code and help me to fix.

If I select four or five checkboxes those values should be displayed in the textarea. Currently it display more than selected.

$(document).ready(function() {
    $('label.chkskillsedit>input[type=checkbox].hid').on('change', function(evt) {
        if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 5) {
            $(this).parent('label').toggleClass('highlightcheckboxedit', this.checked);

            function fullskilledit() {
                var allValsedit = [];
                $('label.chkskillsedit :checked').each(function() {
                    allValsedit.push($(this).val());
                });
                $('.txtValueshwskilledit').val(allValsedit);
            };
            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        } else {
            $(this).prop('checked', false);
            $(this).parent('label').removeClass('highlightcheckboxedit');
        }
    })
})

    <input class="hid" name="fr_skills" type="checkbox" value="51" checked>Architect

    <input class="hid" name="fr_skills" type="checkbox" value="52">Building Designer

    <input class="hid" name="fr_skills" type="checkbox" value="53">Draftsman

    <input class="hid" name="fr_skills" type="checkbox" value="54" checked>Interior Designer

    <input class="hid" name="fr_skills" type="checkbox" value="55">Landscape Designer

    <input class="hid" name="fr_skills" type="checkbox" value="56">MEP Designer

    <input class="hid" name="fr_skills" type="checkbox" value="57" checked>Restoration Architect

    <input class="hid" name="fr_skills" type="checkbox" value="58">Surveyor

    <input class="hid" name="fr_skills" type="checkbox" value="59">Sustainable Designer

    <textarea cols="50" class="txtValueshwskilledit" name="skills" value="">51,54,57</textarea>

Body:
You have to call

$(function() {
   $('.chkskillsedit>input.hid').click(fullskilledit);
   fullskilledit();
  });

Both If and else condition in if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 5){...}else{....}

Check below

$(document).ready(function() {
    $('label.chkskillsedit>input[type=checkbox].hid').on('change', function(evt) {
        if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 5) {
          $(this).parent('label').toggleClass('highlightcheckboxedit', this.checked);

            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        } else {
            $(this).prop('checked', false);
            $(this).parent('label').removeClass('highlightcheckboxedit');
            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        }
    })
})
function fullskilledit() {
                var allValsedit = [];
                $('label.chkskillsedit :checked').each(function() {
                    allValsedit.push($(this).val());
                });
                $('.txtValueshwskilledit').val(allValsedit);
            };

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="51" checked>Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="52">Building Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="53">Draftsman</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="54" checked>Interior Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="55">Landscape Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="56">MEP Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="57" checked>Restoration Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="58">Surveyor</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="59">Sustainable Designer</label><br>
    <br>
    <textarea cols="50" class="txtValueshwskilledit" name="skills" value="">51,54,57</textarea>


问:
LiveData Transformations.map() with multiple arguments
I have a value in the UI that it's value depends on two LiveData objects. Imagine a shop where you need a subtotal = sum of all items price and a total = subtotal + shipment price. Using Transformations we can do the following for the subtotal LiveData object (as it only depends on itemsLiveData):

```<code>val itemsLiveData: LiveData<List<Items>> = ...
val subtotalLiveData = Transformations.map(itemsLiveData) {
   items ->
       getSubtotalPrice(items)
}
</code>```

In the case of the total it would be great to be able to do something like this:

```<code>val shipPriceLiveData: LiveData<Int> = ...
val totalLiveData = Transformations.map(itemsLiveData, shipPriceLiveData) {
   items, price ->
       getSubtotalPrice(items) + price
}
</code>```

But, unfortunately, that's not possible because we cannot put more than one argument in the map function. Anyone knows a good way of achieving this?

答:
UPDATE

Based on my previous answer, I created a generic way where we can add as many live datas as we want.

```<code>import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData

/**
 * CombinedLiveData is a helper class to combine results from multiple LiveData sources.
 * @param liveDatas Variable number of LiveData arguments.
 * @param combine   Function reference that will be used to combine all LiveData data.
 * @param R         The type of data returned after combining all LiveData data.
 * Usage:
 * CombinedLiveData<SomeType>(
 *     getLiveData1(),
 *     getLiveData2(),
 *     ... ,
 *     getLiveDataN()
 * ) { datas: List<Any?> ->
 *     // Use datas[0], datas[1], ..., datas[N] to return a SomeType value
 * }
 */
class CombinedLiveData<R>(vararg liveDatas: LiveData<*>,
                          private val combine: (datas: List<Any?>) -> R) : MediatorLiveData<R>() {

    private val datas: MutableList<Any?> = MutableList(liveDatas.size) { null }

    init {
        for(i in liveDatas.indices){
            super.addSource(liveDatas[i]) {
                datas[i] = it
                value = combine(datas)
            }
        }
    }
}
</code>```

OLD

At the end I used MediatorLiveData to achieve the same objective.

```<code>fun mapBasketTotal(source1: LiveData<List<Item>>, source2: LiveData<ShipPrice>): LiveData<String> {
    val result = MediatorLiveData<String>()
    uiThread {
        var subtotal: Int = 0
        var shipPrice: Int = 0
        fun sumAndFormat(){ result.value = format(subtotal + shipPrice)}
        result.addSource(source1, { items ->
            if (items != null) {
                subtotal = getSubtotalPrice(items)
                sumAndFormat()
            }
        })
        result.addSource(source2, { price ->
            if (price != null) {
                shipPrice = price
                sumAndFormat()
            }
        })
    }
    return result
}
</code>```

Body:
I have a value in the UI that it's value depends on two LiveData objects. Imagine a shop where you need a subtotal = sum of all items price and a total = subtotal + shipment price. Using Transformations we can do the following for the subtotal LiveData object (as it only depends on itemsLiveData):

val itemsLiveData: LiveData<List<Items>> = ...
val subtotalLiveData = Transformations.map(itemsLiveData) {
   items ->
       getSubtotalPrice(items)
}

In the case of the total it would be great to be able to do something like this:

val shipPriceLiveData: LiveData<Int> = ...
val totalLiveData = Transformations.map(itemsLiveData, shipPriceLiveData) {
   items, price ->
       getSubtotalPrice(items) + price
}

But, unfortunately, that's not possible because we cannot put more than one argument in the map function. Anyone knows a good way of achieving this?

Body:
UPDATE

Based on my previous answer, I created a generic way where we can add as many live datas as we want.

import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData

/**
 * CombinedLiveData is a helper class to combine results from multiple LiveData sources.
 * @param liveDatas Variable number of LiveData arguments.
 * @param combine   Function reference that will be used to combine all LiveData data.
 * @param R         The type of data returned after combining all LiveData data.
 * Usage:
 * CombinedLiveData<SomeType>(
 *     getLiveData1(),
 *     getLiveData2(),
 *     ... ,
 *     getLiveDataN()
 * ) { datas: List<Any?> ->
 *     // Use datas[0], datas[1], ..., datas[N] to return a SomeType value
 * }
 */
class CombinedLiveData<R>(vararg liveDatas: LiveData<*>,
                          private val combine: (datas: List<Any?>) -> R) : MediatorLiveData<R>() {

    private val datas: MutableList<Any?> = MutableList(liveDatas.size) { null }

    init {
        for(i in liveDatas.indices){
            super.addSource(liveDatas[i]) {
                datas[i] = it
                value = combine(datas)
            }
        }
    }
}

OLD

At the end I used MediatorLiveData to achieve the same objective.

fun mapBasketTotal(source1: LiveData<List<Item>>, source2: LiveData<ShipPrice>): LiveData<String> {
    val result = MediatorLiveData<String>()
    uiThread {
        var subtotal: Int = 0
        var shipPrice: Int = 0
        fun sumAndFormat(){ result.value = format(subtotal + shipPrice)}
        result.addSource(source1, { items ->
            if (items != null) {
                subtotal = getSubtotalPrice(items)
                sumAndFormat()
            }
        })
        result.addSource(source2, { price ->
            if (price != null) {
                shipPrice = price
                sumAndFormat()
            }
        })
    }
    return result
}


问:
How can I go back to the previous activity, without finishing my current activity
Basically, I have an activity which contains the code for a Video conferencing app. And I need to keep that in the background. So that when the user presses a button, I create a FloatingViewService, and send from my activity, the data to that FloatingViewService. And I can for example (This works), start a new intent, and use it to navigate through my app, while my previous activity is still working, and sending the data to the FloatingViewService.
Now my problem is that I don't want to start a random activity, but I want to go back to the previous activity, before starting the call.
When I start my call, I do it like this:

```<code>   Intent intent = new Intent(HomeActivity.this, InCallActivity.class);
    intent.putExtra("url", "url");
    intent.putExtra("test", false);
    startActivity(intent);
</code>```

And note! After the second activity is created, if I call finish, it will take me to my HomeActivity. Which is awesome.
BUT I don't want to finish, I simply just want to go to the activity from which my class is being called.

I tried with: moveTaskToBack(true); but it sends the app to the home screen.
Also I made this code:

```<code> ActivityManager m = (ActivityManager) getSystemService(ACTIVITY_SERVICE );
    List<ActivityManager.RunningTaskInfo> runningTaskInfoList =  m.getRunningTasks(10);
    Iterator<ActivityManager.RunningTaskInfo> itr = runningTaskInfoList.iterator();
    while(itr.hasNext()){
        ActivityManager.RunningTaskInfo runningTaskInfo = (ActivityManager.RunningTaskInfo)itr.next();
        int id = runningTaskInfo.id;
        CharSequence desc= runningTaskInfo.description;
        int numOfActivities = runningTaskInfo.numActivities;
        String topActivity = runningTaskInfo.topActivity.getShortClassName();
        Log.i("","top activity: " + topActivity);
    }
</code>```

Thinking that I can reinstate the activity from the backstack, using the FLAG_ACTIVITY_REORDER_TO_FRONT

BUT, I don't get my activity back, why is that?
All I get is:

```<code>12-06 13:17:54.213: D/HeartRateApplication(3168): top activity: com.vidyo.vidyocore.activities.WebViewActivity
12-06 13:17:54.213: D/HeartRateApplication(3168): top activity: com.google.android.launcher.GEL
</code>```

But if I do finish, clearly my HomeActivity is there, because it takes me back to it. Why don't I get it in my list from the running activities?
And how can I fix this?

EDIT:

There was a comment that said that I should start the activity with a intent. So I feel maybe I was not clear enough.
I cannot start an intent to a default Activity.
There is a chance that this InCallActivity will be called from multiple activities. Hence I need to know what activity was before it, so I can call an intent to that activity, WITH like I said FLAG_ACTIVITY_REORDER_TO_FRONT
Hence the logic to use the runningTaskInfo but that doesn't not provide me with the whole backstack. Is there another way to get the backstack, so I can actually know whay activity to start?

答:
Start the activity using  Intent.FLAG_ACTIVITY_CLEAR_TOP

Also you can refer
this

```<code>String Activity name= getIntent().getStringExtra("mActivityName");
</code>```

use this to track your activity flow and name.

Body:
Basically, I have an activity which contains the code for a Video conferencing app. And I need to keep that in the background. So that when the user presses a button, I create a FloatingViewService, and send from my activity, the data to that FloatingViewService. And I can for example (This works), start a new intent, and use it to navigate through my app, while my previous activity is still working, and sending the data to the FloatingViewService.
Now my problem is that I don't want to start a random activity, but I want to go back to the previous activity, before starting the call.
When I start my call, I do it like this:

   Intent intent = new Intent(HomeActivity.this, InCallActivity.class);
    intent.putExtra("url", "url");
    intent.putExtra("test", false);
    startActivity(intent);

And note! After the second activity is created, if I call finish, it will take me to my HomeActivity. Which is awesome.
BUT I don't want to finish, I simply just want to go to the activity from which my class is being called.

I tried with: moveTaskToBack(true); but it sends the app to the home screen.
Also I made this code:

 ActivityManager m = (ActivityManager) getSystemService(ACTIVITY_SERVICE );
    List<ActivityManager.RunningTaskInfo> runningTaskInfoList =  m.getRunningTasks(10);
    Iterator<ActivityManager.RunningTaskInfo> itr = runningTaskInfoList.iterator();
    while(itr.hasNext()){
        ActivityManager.RunningTaskInfo runningTaskInfo = (ActivityManager.RunningTaskInfo)itr.next();
        int id = runningTaskInfo.id;
        CharSequence desc= runningTaskInfo.description;
        int numOfActivities = runningTaskInfo.numActivities;
        String topActivity = runningTaskInfo.topActivity.getShortClassName();
        Log.i("","top activity: " + topActivity);
    }

Thinking that I can reinstate the activity from the backstack, using the FLAG_ACTIVITY_REORDER_TO_FRONT

BUT, I don't get my activity back, why is that?
All I get is:

12-06 13:17:54.213: D/HeartRateApplication(3168): top activity: com.vidyo.vidyocore.activities.WebViewActivity
12-06 13:17:54.213: D/HeartRateApplication(3168): top activity: com.google.android.launcher.GEL

But if I do finish, clearly my HomeActivity is there, because it takes me back to it. Why don't I get it in my list from the running activities?
And how can I fix this?

EDIT:

There was a comment that said that I should start the activity with a intent. So I feel maybe I was not clear enough.
I cannot start an intent to a default Activity.
There is a chance that this InCallActivity will be called from multiple activities. Hence I need to know what activity was before it, so I can call an intent to that activity, WITH like I said FLAG_ACTIVITY_REORDER_TO_FRONT
Hence the logic to use the runningTaskInfo but that doesn't not provide me with the whole backstack. Is there another way to get the backstack, so I can actually know whay activity to start?

Body:
Start the activity using  Intent.FLAG_ACTIVITY_CLEAR_TOP

Also you can refer
this

String Activity name= getIntent().getStringExtra("mActivityName");

use this to track your activity flow and name.


问:
mule: how to add value to payload array list
I have a payload as list of maps and another flow variable as map.
I wanted to add flow variable to payload list. I tried using this expression #[payload.addAll(flowVars['entitlement'])]in expression component. But it sets the payload to boolean value true.

答:
You set the payload as the value returned by addAll(). It's like doing payload = payload.addAll(flowVars['entitlement']) in Java addAll() returns a boolean, that's why your payload becomes true.

You can use instead:

```<code>#[payload.addAll(flowVars['entitlement']); payload)
</code>```

This will perform your addAll() operation on your payload and then return this modified payload afterward. ; allow your to perform multiple expressions in MEL

Body:
You set the payload as the value returned by addAll(). It's like doing payload = payload.addAll(flowVars['entitlement']) in Java addAll() returns a boolean, that's why your payload becomes true.

You can use instead:

#[payload.addAll(flowVars['entitlement']); payload)

This will perform your addAll() operation on your payload and then return this modified payload afterward. ; allow your to perform multiple expressions in MEL


问:
VBA Delete Duplicates code faster
Currently using this code, however, I have a huge set of data, and this runs really slow for that. I need to remove any duplicate information, and keep the highest row of information.

```<code>dim dup as variant, r as long, lncheckduplicatescolumn as long
With wb_DST.Sheets(sWs_DST)
     lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
     for r = lncheckduplicatescolumn  to 2 step -1
         dup = application.match(.cells(r, "A").value, .columns(1), 0)
             if dup < r then .rows(dup).delete
     next r
end with
</code>```

Data:

```<code>       Column A              Column B
          A                      1
          B                      2
          C                      3
          A                      3
</code>```

Result should be:

```<code>           B                     2
           C                     3
           A                     3
</code>```

The order of data in column A doesnt matter as long as it is unique, and retains the information that is in the higher row number. While the code I shared works, it is too slow for a large data set.

答:
Fast use of data field array

Looping through a range isn't that fast - you can speed it up considerably if you create a data field array with your search data (array = needed range in column "A" - see 1) and loop therein. If your data set grows, this gets even faster in comparison to the above shown dictionary approach, though it rests a good and reliable method.

Search Method

Any array value is checked against a concatenated search string with already found unique values and added if not yet included - see 2)

The completed string is transformed to an array and written back to a given target column (e.g. "H") - see 3) and 4)

I even added a second column with the corresponding row numbers, so you should be in the position to use them for further action. You could write results to another sheet, too.

Code - method demo

```<code>Sub RemoveDuplicates()
Dim t    As Double: t = Timer   ' stop watch
Dim ws   As Worksheet           ' source sheet (object)
Dim i    As Long                ' row index
Dim a, arr, arr2                ' variant
Dim s    As String, si As String
Const SEP = "|"                 ' delimiter
s = SEP: si = SEP
' 0) fully qualified range reference to source sheet
  Set ws = ThisWorkbook.Worksheets("Sheet1")
' 1) write column A data to one based 2-dim data field array
  a = ws.Range("A1:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
' 2) loop through data and check for duplicates in concatenated string s
  For i = 2 To UBound(a)
     If InStr(s, SEP & a(i, 1) & SEP) = 0 Then
        If Len(a(i, 1)) > 0 Then
           s = s & a(i, 1) & SEP
           si = si & i & SEP
        End If
     End If
  Next i
' 3) transform unique values to zero based 1-dim array
  arr = Split(Mid(s, 2), SEP)          ' duplicates string to array
  arr2 = Split(Mid(si, 2), SEP)        ' found row numbers
' 4) write result to column H2:H...      ' <<< change target to wanted column
  ws.Range("H:H").ClearContents         '
  ws.Range("H2:H" & (2 + UBound(arr))).Value = Application.Transpose(arr)
  ws.Range("I2:I" & (2 + UBound(arr2))).Value = Application.Transpose(arr2)
  Debug.Print UBound(arr) + 0 & " unique items found", Format(Timer - t, "0.00 seconds needed")

End Sub
</code>```

=================================================================

EDIT

Version 2 -- includes overwriting original data with unique values

Here you find a slightly modified version overwriting the original data in 35 columns (A2:AI..) with unique values.

```<code>Sub RemoveDuplicates2()
' Edit: overwrite original data A2:AI{..} with unique values
Dim t    As Double: t = Timer   ' stop watch
Dim ws   As Worksheet           ' source sheet (object)
Dim i    As Long                ' row index
Dim a, arr, arr2                ' variant
Dim s    As String, si As String
Const SEP = "|"                 ' delimiter
Const MyLastColumn = "AI"       ' letter of last column (no 35) = "AI"
s = SEP: si = SEP
' fully qualified range reference to source sheet
  Set ws = ThisWorkbook.Worksheets("Sheet1")
' write column A data to one based 2-dim data field array
  a = ws.Range("A1:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
' loop through data and check for duplicates in concatenated string s
  For i = 2 To UBound(a)        '  For i = UBound(a) To 2 Step -1
     If InStr(s, SEP & a(i, 1) & SEP) = 0 Then
        If Len(Trim(a(i, 1))) > 0 Then
           s = s & a(i, 1) & SEP
           si = si & i & SEP
        End If
     End If
  Next i
' write unique values to zero based 1-dim array (starts with index 0; last delimiter removed in this version)
  arr2 = Split(Mid(si, 2, Len(si) - 2), SEP)     ' found row numbers
' overwrite original data
  For i = LBound(arr2) To UBound(arr2)  ' starts with index 0!
      s = "A" & arr2(i) & ":" & MyLastColumn & arr2(i)
      arr = ws.Range(s)        ' create 1-based 1-line (2-dim) array
      s = "A" & i + 2 & ":" & MyLastColumn & i + 2   ' 0 + 2 = +2 ... start in row 2
      ws.Range(s) = arr        ' write back unique row values
  Next i
  s = "A" & UBound(arr2) + 3 & ":" & MyLastColumn & UBound(a) + 1
  ws.Range(s).ClearContents     ' clear rest of original data
  Debug.Print UBound(arr2) + 1 & " unique items found", Format(Timer - t, "0.00 seconds needed")          ' result
End Sub
</code>```

Title: VBA Delete Duplicates code faster

Body:
Currently using this code, however, I have a huge set of data, and this runs really slow for that. I need to remove any duplicate information, and keep the highest row of information.

dim dup as variant, r as long, lncheckduplicatescolumn as long
With wb_DST.Sheets(sWs_DST)
     lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
     for r = lncheckduplicatescolumn  to 2 step -1
         dup = application.match(.cells(r, "A").value, .columns(1), 0)
             if dup < r then .rows(dup).delete
     next r
end with

Data:

       Column A              Column B
          A                      1
          B                      2
          C                      3
          A                      3

Result should be:

           B                     2
           C                     3
           A                     3

The order of data in column A doesnt matter as long as it is unique, and retains the information that is in the higher row number. While the code I shared works, it is too slow for a large data set.

Body:
Fast use of data field array

Looping through a range isn't that fast - you can speed it up considerably if you create a data field array with your search data (array = needed range in column "A" - see 1) and loop therein. If your data set grows, this gets even faster in comparison to the above shown dictionary approach, though it rests a good and reliable method.

Search Method

Any array value is checked against a concatenated search string with already found unique values and added if not yet included - see 2)

The completed string is transformed to an array and written back to a given target column (e.g. "H") - see 3) and 4)

I even added a second column with the corresponding row numbers, so you should be in the position to use them for further action. You could write results to another sheet, too.

Code - method demo

Sub RemoveDuplicates()
Dim t    As Double: t = Timer   ' stop watch
Dim ws   As Worksheet           ' source sheet (object)
Dim i    As Long                ' row index
Dim a, arr, arr2                ' variant
Dim s    As String, si As String
Const SEP = "|"                 ' delimiter
s = SEP: si = SEP
' 0) fully qualified range reference to source sheet
  Set ws = ThisWorkbook.Worksheets("Sheet1")
' 1) write column A data to one based 2-dim data field array
  a = ws.Range("A1:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
' 2) loop through data and check for duplicates in concatenated string s
  For i = 2 To UBound(a)
     If InStr(s, SEP & a(i, 1) & SEP) = 0 Then
        If Len(a(i, 1)) > 0 Then
           s = s & a(i, 1) & SEP
           si = si & i & SEP
        End If
     End If
  Next i
' 3) transform unique values to zero based 1-dim array
  arr = Split(Mid(s, 2), SEP)          ' duplicates string to array
  arr2 = Split(Mid(si, 2), SEP)        ' found row numbers
' 4) write result to column H2:H...      ' <<< change target to wanted column
  ws.Range("H:H").ClearContents         '
  ws.Range("H2:H" & (2 + UBound(arr))).Value = Application.Transpose(arr)
  ws.Range("I2:I" & (2 + UBound(arr2))).Value = Application.Transpose(arr2)
  Debug.Print UBound(arr) + 0 & " unique items found", Format(Timer - t, "0.00 seconds needed")

End Sub

=================================================================

EDIT

Version 2 -- includes overwriting original data with unique values

Here you find a slightly modified version overwriting the original data in 35 columns (A2:AI..) with unique values.

Sub RemoveDuplicates2()
' Edit: overwrite original data A2:AI{..} with unique values
Dim t    As Double: t = Timer   ' stop watch
Dim ws   As Worksheet           ' source sheet (object)
Dim i    As Long                ' row index
Dim a, arr, arr2                ' variant
Dim s    As String, si As String
Const SEP = "|"                 ' delimiter
Const MyLastColumn = "AI"       ' letter of last column (no 35) = "AI"
s = SEP: si = SEP
' fully qualified range reference to source sheet
  Set ws = ThisWorkbook.Worksheets("Sheet1")
' write column A data to one based 2-dim data field array
  a = ws.Range("A1:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
' loop through data and check for duplicates in concatenated string s
  For i = 2 To UBound(a)        '  For i = UBound(a) To 2 Step -1
     If InStr(s, SEP & a(i, 1) & SEP) = 0 Then
        If Len(Trim(a(i, 1))) > 0 Then
           s = s & a(i, 1) & SEP
           si = si & i & SEP
        End If
     End If
  Next i
' write unique values to zero based 1-dim array (starts with index 0; last delimiter removed in this version)
  arr2 = Split(Mid(si, 2, Len(si) - 2), SEP)     ' found row numbers
' overwrite original data
  For i = LBound(arr2) To UBound(arr2)  ' starts with index 0!
      s = "A" & arr2(i) & ":" & MyLastColumn & arr2(i)
      arr = ws.Range(s)        ' create 1-based 1-line (2-dim) array
      s = "A" & i + 2 & ":" & MyLastColumn & i + 2   ' 0 + 2 = +2 ... start in row 2
      ws.Range(s) = arr        ' write back unique row values
  Next i
  s = "A" & UBound(arr2) + 3 & ":" & MyLastColumn & UBound(a) + 1
  ws.Range(s).ClearContents     ' clear rest of original data
  Debug.Print UBound(arr2) + 1 & " unique items found", Format(Timer - t, "0.00 seconds needed")          ' result
End Sub


问:
Shiny progress bar completed before do.call() is terminated
I am trying to implement a shiny app that calls a function with a set of arguments. Such function returns a plot which is rendered with renderPlot(). A progress bar is generated to keep the user updated.

I am particularly interested in calling this function and its arguments using do.call, as my final goal is to wrap it up as a shiny module. However, the progress bar is "completed" before the plot gets the chance to be generated. Only after the progress bar disappears, the plots are rendered. I assume this is caused by the fact that I am trying to use do.call() to handle the plotting function. I have created here a simplified version of the problem:

```<code>ui <- fixedPage(
  wellPanel(
    plotOutput("plot")
    , fluidPage(actionButton("Btn", "plot", class = "btn-primary"))
  )
)

server <- function(input, output, session) {

  observeEvent(input$Btn, {

    message("button triggered")

    withProgress(message = "Progress bar"
                   , detail ='Rendering plot...'
                   , value = 0,{

                     # pausa
                     Sys.sleep(1)
                     # updade progress bar
                     setProgress(0.5)

                     output$plot <- renderPlot({
                       # plot to render
                       do.call(plot, list(1:10, 11:20))
                       # pause
                       do.call(Sys.sleep, list(2))
                     })

                     # update progress to complete status
                     setProgress(1)
                   })

    showNotification("DONE!", duration = 5, closeButton =  TRUE, type = "warning")

  })
}

shinyApp(ui, server)
</code>```

I am expecting the progress bar to be completed AFTER the plot is generated and visualized. Any suggestions?

答:
I've added two options, one with shinycssloaders if you're not aware and another fixing your existing code to sync plot and bar.

```<code>library(shinycssloaders)

ui <- fixedPage(
  wellPanel(
    #withSpinner(plotOutput("plot")) #uncomment if you need to use the pkg
    plotOutput("plot")
    , fluidPage(actionButton("Btn", "plot", class = "btn-primary"))
  )
)

server <- function(input, output, session) {

  observeEvent(input$Btn, {

    message("button triggered")

    withProgress(message = "Progress bar"
                 , detail ='Rendering plot...'
                 , value = 0,{

                   # pausa
                   Sys.sleep(1)
                   # updade progress bar
                   setProgress(0.5)

                   # update progress to complete status
                   setProgress(1)
                 })

    output$plot <- renderPlot({
      # plot to render
      do.call(plot, list(1:10, 11:20))
      # pause
      #do.call(Sys.sleep, list(2))
    })

    showNotification("DONE!", duration = 5, closeButton =  TRUE, type = "warning")

  })
}

shinyApp(ui, server)
</code>```

Body:
I am trying to implement a shiny app that calls a function with a set of arguments. Such function returns a plot which is rendered with renderPlot(). A progress bar is generated to keep the user updated.

I am particularly interested in calling this function and its arguments using do.call, as my final goal is to wrap it up as a shiny module. However, the progress bar is "completed" before the plot gets the chance to be generated. Only after the progress bar disappears, the plots are rendered. I assume this is caused by the fact that I am trying to use do.call() to handle the plotting function. I have created here a simplified version of the problem:

ui <- fixedPage(
  wellPanel(
    plotOutput("plot")
    , fluidPage(actionButton("Btn", "plot", class = "btn-primary"))
  )
)

server <- function(input, output, session) {

  observeEvent(input$Btn, {

    message("button triggered")

    withProgress(message = "Progress bar"
                   , detail ='Rendering plot...'
                   , value = 0,{

                     # pausa
                     Sys.sleep(1)
                     # updade progress bar
                     setProgress(0.5)

                     output$plot <- renderPlot({
                       # plot to render
                       do.call(plot, list(1:10, 11:20))
                       # pause
                       do.call(Sys.sleep, list(2))
                     })

                     # update progress to complete status
                     setProgress(1)
                   })

    showNotification("DONE!", duration = 5, closeButton =  TRUE, type = "warning")

  })
}

shinyApp(ui, server)

I am expecting the progress bar to be completed AFTER the plot is generated and visualized. Any suggestions?

Body:
I've added two options, one with shinycssloaders if you're not aware and another fixing your existing code to sync plot and bar.

library(shinycssloaders)

ui <- fixedPage(
  wellPanel(
    #withSpinner(plotOutput("plot")) #uncomment if you need to use the pkg
    plotOutput("plot")
    , fluidPage(actionButton("Btn", "plot", class = "btn-primary"))
  )
)

server <- function(input, output, session) {

  observeEvent(input$Btn, {

    message("button triggered")

    withProgress(message = "Progress bar"
                 , detail ='Rendering plot...'
                 , value = 0,{

                   # pausa
                   Sys.sleep(1)
                   # updade progress bar
                   setProgress(0.5)

                   # update progress to complete status
                   setProgress(1)
                 })

    output$plot <- renderPlot({
      # plot to render
      do.call(plot, list(1:10, 11:20))
      # pause
      #do.call(Sys.sleep, list(2))
    })

    showNotification("DONE!", duration = 5, closeButton =  TRUE, type = "warning")

  })
}

shinyApp(ui, server)


答: ToTitleCase simply and naively changes the case of each word in a string so that the first letter of a word is uppercase. The culture info will be used to determine what counts as a first letter to a word (such as what symbols/punctuation separate words), but it's not for determining which words of the given language should (not) be titlecased.. You'll need to roll your own solution for this level of language understanding

Title: Convert Words in a string to sentence case for german sentences


问:
Error: No value for "ColumnName". Get JSON value in Android
I want to get f_index value from JSON into my Android App. I am getting an error "No value for f_index.

```<code>W/System.err: org.json.JSONException: No value for f_index
</code>```

If I remove the below line then I am able to get the lat, long and is_local values properly and further use them.

```<code>ill_id_data.add(ill_jo.getInt("f_index"));
</code>```

I am not able to understand what is going wrong here?

JSON received in the app which I pass to parse method.

```<code>{
"server_response": [{
    "f_index": "3",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "6",
    "lat": "25.0751",
    "long": "54.9476",
    "is_local": "0"
}, {
    "f_index": "7",
    "lat": "14.6773",
    "long": "75.542",
    "is_local": "1"
}, {
    "f_index": "8",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "9",
    "lat": "25.8079",
    "long": "86.0449",
    "is_local": "1"
}]
}
</code>```

Code for parsing the JSON in my App.

```<code>ArrayList<Double> ill_lat_data = new ArrayList<Double>(3);
ArrayList<Double> ill_long_data = new ArrayList<Double>(3);
ArrayList<Interger> ill_id_data = new ArrayList<Integer>(3);
ArrayList<Integer> ill_is_local_data = new ArrayList<Integer>(3);

public void parseIndexLatLngJSON() {

    int count_ill = 0;

    try {
        ill_json_object = new JSONObject(json_index_latlng);
        ill_json_array = gm_json_object.getJSONArray("server_response");

        while (count_ill < ill_json_array.length()) {
            JSONObject ill_jo = ill_json_array.getJSONObject(count_ill);

            ill_id_data.add(ill_jo.getInt("f_index"));
            Log.d("tag_last_check", String.valueOf(ill_jo.getInt("f_index")));
            ill_lat_data.add(ill_jo.getDouble("lat"));
            ill_is_local_data.add(ill_jo.getInt("is_local"));
            ill_long_data.add(ill_jo.getDouble("long"));

            count_ill++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

This is my php file.

```<code>$sql="SELECT id,lat,`long` FROM newsphere_one WHERE lat != 0 OR `long` != 0;";

$con=mysqli_connect($host,$hostname,$password,$db);

$result = mysqli_query($con,$sql);

$response = array();

while($row=mysqli_fetch_array($result)){
array_push($response, array("f_index" => $row[0],"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));
}

echo json_encode(array("server_response"=>$response));
</code>```

答:
Carefully observe the below two lines once again

```<code>ill_json_object = new JSONObject(json_index_latlng);
ill_json_array = gm_json_object.getJSONArray("server_response");
</code>```

In line 1, you had assigned the json_index_latlng to the object ill_json_object

But In line 2, you are accessing your server response from  gm_json_object.

Check your code once again,
Good luck

Body:
I want to get f_index value from JSON into my Android App. I am getting an error "No value for f_index.

W/System.err: org.json.JSONException: No value for f_index

If I remove the below line then I am able to get the lat, long and is_local values properly and further use them.

ill_id_data.add(ill_jo.getInt("f_index"));

I am not able to understand what is going wrong here?

JSON received in the app which I pass to parse method.

{
"server_response": [{
    "f_index": "3",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "6",
    "lat": "25.0751",
    "long": "54.9476",
    "is_local": "0"
}, {
    "f_index": "7",
    "lat": "14.6773",
    "long": "75.542",
    "is_local": "1"
}, {
    "f_index": "8",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "9",
    "lat": "25.8079",
    "long": "86.0449",
    "is_local": "1"
}]
}

Code for parsing the JSON in my App.

ArrayList<Double> ill_lat_data = new ArrayList<Double>(3);
ArrayList<Double> ill_long_data = new ArrayList<Double>(3);
ArrayList<Interger> ill_id_data = new ArrayList<Integer>(3);
ArrayList<Integer> ill_is_local_data = new ArrayList<Integer>(3);

public void parseIndexLatLngJSON() {

    int count_ill = 0;

    try {
        ill_json_object = new JSONObject(json_index_latlng);
        ill_json_array = gm_json_object.getJSONArray("server_response");

        while (count_ill < ill_json_array.length()) {
            JSONObject ill_jo = ill_json_array.getJSONObject(count_ill);

            ill_id_data.add(ill_jo.getInt("f_index"));
            Log.d("tag_last_check", String.valueOf(ill_jo.getInt("f_index")));
            ill_lat_data.add(ill_jo.getDouble("lat"));
            ill_is_local_data.add(ill_jo.getInt("is_local"));
            ill_long_data.add(ill_jo.getDouble("long"));

            count_ill++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

This is my php file.

$sql="SELECT id,lat,`long` FROM newsphere_one WHERE lat != 0 OR `long` != 0;";

$con=mysqli_connect($host,$hostname,$password,$db);

$result = mysqli_query($con,$sql);

$response = array();

while($row=mysqli_fetch_array($result)){
array_push($response, array("f_index" => $row[0],"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));
}

echo json_encode(array("server_response"=>$response));

Body:
Carefully observe the below two lines once again

ill_json_object = new JSONObject(json_index_latlng);
ill_json_array = gm_json_object.getJSONArray("server_response");

In line 1, you had assigned the json_index_latlng to the object ill_json_object

But In line 2, you are accessing your server response from  gm_json_object.

Check your code once again,
Good luck


问:
Android Library: Release .aar getting classes.jar empty when using proguard
I'm trying to generate a library with minifyEnabled true but, inside the release .aar, classes.jar is getting empty.

I have checked my proguard-rules.pro and it seems to be all right.

I've even created a new module with the default .gradle files and when i set minifyEnable true the release version still gets the classes.jar with no class inside.

After all, is it possible to generate an android library obfuscating the code?

EDIT 1: Adding module build.gradle

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

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.0'

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
                minifyEnabled true
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
    }

    lintOptions {
        abortOnError false
    }
}

repositories {
    maven { url 'https://maven.google.com' }
    jcenter()
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'org.apache.httpcomponents:httpcore:4.3.3'
    compile('org.apache.httpcomponents:httpmime:4.3.6') {
        exclude module: 'httpclient'
    }

    compile 'fr.bmartel:jspeedtest:1.25'
    compile "com.android.support:appcompat-v7:27.0.0"
    testCompile 'junit:junit:4.12'
}
</code>```

答:
Ok, after some time I solved my problem.

I copy/paste a default proguard rules configuration (library.pro) to my proguard-rules.pro.
You can find this file and more examples in path-to-your-sdk/tools/proguard/examples.

For more information, read this.

In my build.gradle I chagend:

```<code>defaultConfig {
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}

buildTypes {
    release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
}
</code>```

to:

```<code>defaultConfig {
    minSdkVersion 14
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}

buildTypes {
     release {
         minifyEnabled true
         proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
         consumerProguardFiles 'proguard-rules.pro' //added this line
     }
 }
</code>```

Thanks for the help!

Body:
I'm trying to generate a library with minifyEnabled true but, inside the release .aar, classes.jar is getting empty.

I have checked my proguard-rules.pro and it seems to be all right.

I've even created a new module with the default .gradle files and when i set minifyEnable true the release version still gets the classes.jar with no class inside.

After all, is it possible to generate an android library obfuscating the code?

EDIT 1: Adding module build.gradle

apply plugin: 'com.android.library'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.0'

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
                minifyEnabled true
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
    }

    lintOptions {
        abortOnError false
    }
}

repositories {
    maven { url 'https://maven.google.com' }
    jcenter()
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'org.apache.httpcomponents:httpcore:4.3.3'
    compile('org.apache.httpcomponents:httpmime:4.3.6') {
        exclude module: 'httpclient'
    }

    compile 'fr.bmartel:jspeedtest:1.25'
    compile "com.android.support:appcompat-v7:27.0.0"
    testCompile 'junit:junit:4.12'
}

Body:
Ok, after some time I solved my problem.

I copy/paste a default proguard rules configuration (library.pro) to my proguard-rules.pro.
You can find this file and more examples in path-to-your-sdk/tools/proguard/examples.

For more information, read this.

In my build.gradle I chagend:

defaultConfig {
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}

buildTypes {
    release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
}

to:

defaultConfig {
    minSdkVersion 14
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}

buildTypes {
     release {
         minifyEnabled true
         proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
         consumerProguardFiles 'proguard-rules.pro' //added this line
     }
 }

Thanks for the help!


问:
find_element_by_partial_link_text ascii code issue
http://www.m2sys.com/.

When I click on CloudApper™ under Solutions I get an ascii code error.

I find the element using:

```<code>driver.find_element_by_partial_link_text('CloudApper™')
</code>```

How can I click the partial link?

答:
CloudApper™ is a label, you have to click logo, use this xpath</p>

```<code>//a[@href='http://www.m2sys.com/cloudapper-modularized-framework-enterprise-cloud-application/']
</code>```

Body:
http://www.m2sys.com/.

When I click on CloudApper™ under Solutions I get an ascii code error.

I find the element using:

driver.find_element_by_partial_link_text('CloudApper™')

How can I click the partial link?

Body:
CloudApper™ is a label, you have to click logo, use this xpath

//a[@href='http://www.m2sys.com/cloudapper-modularized-framework-enterprise-cloud-application/']


问:
C: sorting 2d arrays row by row using qsort
So, what I'm trying to achieve here, is to use the C implementation of qsort in a 2d array, in witch I want only the rows to be sorted based on the its first element, for example:

```<code>        int arr[3][2]={{65,1},
                       {45,2},
                       {66,3}}
</code>```

I want the output to be:

```<code>        int arr[3][2]={{45,2},
                       {65,1},
                       {66,3}}
</code>```

Is there a way of doing this without implementing quicksort myself? If so, how?

EDIT

This is what my code looks like:

```<code>int f(int a, int b)
{
return a-b;
}

qsort(arr[0],3,sizeof(int),f);
</code>```

答:
You're not sorting integers, you're sorting "things" that happen to be a number of integers in size.

So, don't lie to qsort() about your element size:

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

static int cmprow(const void *a, const void *b)
{
    const int * const ia = a, * const ib = b;
    return ia[0] < ib[0] ? -1 : ia[0] > ib[0];
}

int main(void) {
    int arr[3][2]={{65,1},
                   {45,2},
                   {66,3}};

    qsort(arr, sizeof arr / sizeof *arr, sizeof *arr, cmprow);
    for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
    {
        for (size_t j = 0; j < sizeof *arr / sizeof **arr; ++j)
            printf("%d ", arr[i][j]);
        putchar('\n');
    }
    return 0;
}
</code>```

This prints:

```<code>45 2
65 1
66 3
</code>```

Body:
So, what I'm trying to achieve here, is to use the C implementation of qsort in a 2d array, in witch I want only the rows to be sorted based on the its first element, for example:

        int arr[3][2]={{65,1},
                       {45,2},
                       {66,3}}

I want the output to be:

        int arr[3][2]={{45,2},
                       {65,1},
                       {66,3}}

Is there a way of doing this without implementing quicksort myself? If so, how?

EDIT

This is what my code looks like:

int f(int a, int b)
{
return a-b;
}

qsort(arr[0],3,sizeof(int),f);

Body:
You're not sorting integers, you're sorting "things" that happen to be a number of integers in size.

So, don't lie to qsort() about your element size:

#include <stdio.h>
#include <stdlib.h>

static int cmprow(const void *a, const void *b)
{
    const int * const ia = a, * const ib = b;
    return ia[0] < ib[0] ? -1 : ia[0] > ib[0];
}

int main(void) {
    int arr[3][2]={{65,1},
                   {45,2},
                   {66,3}};

    qsort(arr, sizeof arr / sizeof *arr, sizeof *arr, cmprow);
    for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
    {
        for (size_t j = 0; j < sizeof *arr / sizeof **arr; ++j)
            printf("%d ", arr[i][j]);
        putchar('\n');
    }
    return 0;
}

This prints:

45 2
65 1
66 3


问:
How to find the last child in lodash map object?
I looping the array of lists by lodash map function and I've try to remove the Image on last child. But I couldn't find solution. </p>

```<code> const menus =[
    {
        name: 'Home',
        key:'dashboard'
    },
    {
        name:'change your pin',
        key:'resetpin'
    },
    {
        name:'Contact',
        key:'contact'
    },
    {
        name:'Sign Out',
        key:'signout'
    }
]
const menuList = map(menus, (el, i) => {
        return <Main>
            <Row>
                <Text />
                <Image />
            </Row>
        </Main>
})
</code>```

<p>I don't want the image on last loop </p>

答:
map() receives 2 params value and index, so you can check if your array index is the last in your map function, something like arr.map((item, index) => index === arr.length-1 && arr.splice(index, 1))

But if you only want to remove the last item, you can do something like this arr.splice(-1,1)

Hope it helps

Body:
I looping the array of lists by lodash map function and I've try to remove the Image on last child. But I couldn't find solution.

 const menus =[
    {
        name: 'Home',
        key:'dashboard'
    },
    {
        name:'change your pin',
        key:'resetpin'
    },
    {
        name:'Contact',
        key:'contact'
    },
    {
        name:'Sign Out',
        key:'signout'
    }
]
const menuList = map(menus, (el, i) => {
        return
            <Row>
                <Text />
                <Image />
            </Row>

})

I don't want the image on last loop


问:
Changing label position of data point in plot
I have plotted some datapoints with plot function together with a Duncan's multiple range test. When i change the limits of the y-axis the grouping label of the first datapoint exceeds the plot and can no longer be seen.

How can i reduce the spacing between the datapoint and label?

My code:

```<code>data(FILIPPA)
model<-aov(TA~DATO + GE,data=FILIPPA)
out <- duncan.test(model,"DATO",
               main="Syre i Filippa")
plot(out,variation="IQR", ylim=c(7,9.5), )
duncan.test(model,"DATO",alpha=0.05,console=TRUE)
</code>```

答:
I couldn't find the FILIPPA dataset (apples and titratable acidity?).

But maybe the graphical parameter xpd is what you're looking for?

It doesn't look like plot.group() allows for adjusting the position of the labels.

```<code>library(agricolae)
data(mtcars)

model <- aov(mpg ~ wt + cyl, data=mtcars)
out <- duncan.test(model,"cyl", main="Fuel efficiency")

par(xpd=TRUE, mar=c(2, 2, 3, 1))
plot(out, variation="IQR", ylim=c(13, 30))
duncan.test(model, "cyl", alpha=0.05, console=TRUE)
</code>```

Body:
I have plotted some datapoints with plot function together with a Duncan's multiple range test. When i change the limits of the y-axis the grouping label of the first datapoint exceeds the plot and can no longer be seen.

How can i reduce the spacing between the datapoint and label?

My code:

data(FILIPPA)
model<-aov(TA~DATO + GE,data=FILIPPA)
out <- duncan.test(model,"DATO",
               main="Syre i Filippa")
plot(out,variation="IQR", ylim=c(7,9.5), )
duncan.test(model,"DATO",alpha=0.05,console=TRUE)

Body:
I couldn't find the FILIPPA dataset (apples and titratable acidity?).

But maybe the graphical parameter xpd is what you're looking for?

It doesn't look like plot.group() allows for adjusting the position of the labels.

library(agricolae)
data(mtcars)

model <- aov(mpg ~ wt + cyl, data=mtcars)
out <- duncan.test(model,"cyl", main="Fuel efficiency")

par(xpd=TRUE, mar=c(2, 2, 3, 1))
plot(out, variation="IQR", ylim=c(13, 30))
duncan.test(model, "cyl", alpha=0.05, console=TRUE)


问:
gsub not working while implementing in a loop
here i have the following dataframe df in R.

```<code>kyid    industry    amount
112     Apparel     345436
234     APPEARELS   234567
213     apparels    345678
345     Airlines    235678
123     IT          456789
124     IT          897685
</code>```

i want to replace in industry which incorrectly written Apparel, or APPEARLS to Apparels .

i tried using creating a list and run it through a loop.

```<code>l<-c('Apparel ','APPEARELS','apparels')

for(i in range(1:3)){
    df$industry<-gsub(pattern=l[i],"Apparels",df$industry)
}
</code>```

it is not working.only one element changes.

But, when i take the statement individually it is not creating an error and its working.

```<code>df$industry<-gsub(pattern=","Apparels",df$industry)
</code>```

but this is a large dataset so i nned this to work in R please help.

答:
While range returns a sequence in Python, it returns the minimum and maximum of a vector in R:

```<code>range(1:3)
# [1] 1 3
</code>```

Instead, you could use 1:3 or seq(1,3) or seq_along(l), which all return

```<code># [1] 1 2 3
</code>```

Also note the difference between 'Apparel' and 'Apparel '.

So

```<code>df<-read.table(header=T, text="kyid    industry    amount
112     Apparel     345436
234     APPEARELS   234567
213     apparels    345678
345     Airlines    235678
123     IT          456789
124     IT          897685")
l<-c('Apparel','APPEARELS','apparels')
for(i in seq_along(l)){
  df$industry<-gsub(pattern=l[i],"Apparels",df$industry)
}
df
# kyid industry amount
# 1  112 Apparels 345436
# 2  234 Apparels 234567
# 3  213 Apparels 345678
# 4  345 Airlines 235678
# 5  123       IT 456789
# 6  124       IT 897685
</code>```

Body:
here i have the following dataframe df in R.

kyid    industry    amount
112     Apparel     345436
234     APPEARELS   234567
213     apparels    345678
345     Airlines    235678
123     IT          456789
124     IT          897685

i want to replace in industry which incorrectly written Apparel, or APPEARLS to Apparels .

i tried using creating a list and run it through a loop.

l<-c('Apparel ','APPEARELS','apparels')

for(i in range(1:3)){
    df$industry<-gsub(pattern=l[i],"Apparels",df$industry)
}

it is not working.only one element changes.

But, when i take the statement individually it is not creating an error and its working.

df$industry<-gsub(pattern=","Apparels",df$industry)

but this is a large dataset so i nned this to work in R please help.

Body:
While range returns a sequence in Python, it returns the minimum and maximum of a vector in R:

range(1:3)
# [1] 1 3

Instead, you could use 1:3 or seq(1,3) or seq_along(l), which all return

# [1] 1 2 3

Also note the difference between 'Apparel' and 'Apparel '.

So

df<-read.table(header=T, text="kyid    industry    amount
112     Apparel     345436
234     APPEARELS   234567
213     apparels    345678
345     Airlines    235678
123     IT          456789
124     IT          897685")
l<-c('Apparel','APPEARELS','apparels')
for(i in seq_along(l)){
  df$industry<-gsub(pattern=l[i],"Apparels",df$industry)
}
df
# kyid industry amount
# 1  112 Apparels 345436
# 2  234 Apparels 234567
# 3  213 Apparels 345678
# 4  345 Airlines 235678
# 5  123       IT 456789
# 6  124       IT 897685