问:
View is not getting updated (MVVM) but property associated is getting updated correctly
I am very new to WPF and working on MVVM, I have a scenario where my datagrid is not getting updated but the property to which it is bound is getting updated correctly, I am able to see new changes in the SlotFloorData property during PropertyChanged event.

below is XAML code (grid.row is bind to property SlotFloorData):

```<code><Page x:Class="CasinoCAD.V6.Views.DashboardView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:vm="clr-namespace:CasinoCAD.V6.ViewModels"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="300"
    Title="DashboardView">

    <Page.DataContext>
        <vm:CasinoCADDViewModel x:Name="viewModel"/>
    </Page.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="200"/>
            <RowDefinition Height="200"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0"  Text="Dashboard View" />

        <DataGrid Grid.Row="1" Name="grdDB" ItemsSource="{Binding Path=SlotFloorData}"  />

        <!--<DataGrid Grid.Row="2" ItemsSource="{Binding Path=Properties }" />-->
   </Grid>
</Page>
</code>```

I am implementing INotifyPropertyChanged in main model i.e. in CasinoCADDViewModel

and in DashboardView, I have only below (I tried INotifyPropertyChanged here too but it did not work):

Please let me know if I need to put any other information here

TIA!

答:
Set up as TwoWay Binding.

Example:

```<code>ItemsSource="{Binding Path=SlotFloorData, Mode=TwoWay}"
</code>```

Also, make the collection an ObservableCollection type (If not already).

Body:
I am very new to WPF and working on MVVM, I have a scenario where my datagrid is not getting updated but the property to which it is bound is getting updated correctly, I am able to see new changes in the SlotFloorData property during PropertyChanged event.

below is XAML code (grid.row is bind to property SlotFloorData):

<Page x:Class="CasinoCAD.V6.Views.DashboardView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:vm="clr-namespace:CasinoCAD.V6.ViewModels"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="300"
    Title="DashboardView">

    <Page.DataContext>
        <vm:CasinoCADDViewModel x:Name="viewModel"/>
    </Page.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="200"/>
            <RowDefinition Height="200"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0"  Text="Dashboard View" />

        <DataGrid Grid.Row="1" Name="grdDB" ItemsSource="{Binding Path=SlotFloorData}"  />

   </Grid>
</Page>

I am implementing INotifyPropertyChanged in main model i.e. in CasinoCADDViewModel

and in DashboardView, I have only below (I tried INotifyPropertyChanged here too but it did not work):

Please let me know if I need to put any other information here

TIA!

Body:
Set up as TwoWay Binding.

Example:

ItemsSource="{Binding Path=SlotFloorData, Mode=TwoWay}"

Also, make the collection an ObservableCollection type (If not already).


来源: stackexchange

问:
Hazelcast file upload from client to server
What is the best way to upload a file from hazelcast client to server?
Currently, I have a web application from where users can upload a file. The file then gets put into a queue and the server has an item listener to listen when a new item gets added to the list. The problem is the item listener doesn't always get fired straight away (not sure why) so I wanted to know what was the best way to upload a file.</p>

答: You can use Observer design pattern as your notification mechanism.</p>

ContentLicense: CC BY-SA 3.0


问:
How to perform AWS DynamoDB backup and restore operations by utilizing minimal read/write units?
We are looking for a solution which uses minimum read/write units of DynamoDB table for performing full backup, incremental backup and restore operations. Backup should store in AWS S3 (open to other alternatives). We have thought of few options such as:

1)  Using python multiprocessing and boto modules we were able to perform Full backup and Restore operations, it is performing well, but is taking more DynamoDB read/write Units.

2)  Using AWS Data Pipeline service, we were able to perform Full backup and Restore operations.

3)  Using Dynamo Streams and kinesis Adapter/ Dynamo Streams and Lambda function, we were able to perform Incremental backup.

Are there other alternatives for Full backup, Incremental backup and Restore operations. The main limitation/need is to have a scalable solution by utilizing minimal read/write units of DynamoDb table.

答:
On-Demand backups are a feature built into the DynamoDB service (Accessible via the API, AWS Management Console and CLI as usual), which allows you to take a full backup of a table at a point in time.

This task has no impact on performance or availability to your tables. All backups are automatically encrypted, cataloged, easily discoverable, and retained until you explicitly delete them.

Additionally, you can restore these backups to a new table at any point.

Along with data, the following is included in the backups:

```<code>Global secondary indexes (GSIs)
Local secondary indexes (LSIs)
Streams
Provisioned read and write capacity
</code>```

The following is NOT included in the backups:

```<code>Auto scaling policies
AWS Identity and Access Management (IAM) policies
Amazon CloudWatch metrics and alarms
Tags
Stream settings
Time To Live (TTL) settings
</code>```

I've blogged more information and a walkthrough here: https://www.abhayachauhan.com/2017/12/dynamodb-scheduling-on-demand-backups/

Body:
On-Demand backups are a feature built into the DynamoDB service (Accessible via the API, AWS Management Console and CLI as usual), which allows you to take a full backup of a table at a point in time.

This task has no impact on performance or availability to your tables. All backups are automatically encrypted, cataloged, easily discoverable, and retained until you explicitly delete them.

Additionally, you can restore these backups to a new table at any point.

Along with data, the following is included in the backups:

Global secondary indexes (GSIs)
Local secondary indexes (LSIs)
Streams
Provisioned read and write capacity

The following is NOT included in the backups:

Auto scaling policies
AWS Identity and Access Management (IAM) policies
Amazon CloudWatch metrics and alarms
Tags
Stream settings
Time To Live (TTL) settings

I've blogged more information and a walkthrough here: https://www.abhayachauhan.com/2017/12/dynamodb-scheduling-on-demand-backups/


问:
Why am i getting this number instead of the value, in this STACK program?
In this implementation of stack program in C, when i print the value of pop(),why do i get that number? It should have printed '4' but instead i get an address like number. What might be the problem here?

```<code>#define MAX 5

typedef struct stack{
    int data[MAX];
    int top;
}stack;

int empty(stack *s){
    if(s->top==-1)
        return 1;
    return 0;
}

int pop(stack *s){
    int x;
    x = s->data[s->top];
    s->top = s->top -1;
    return x;

}

void display(stack *s){

    while(!(empty(&s)) && (s->top)!=-1){
        printf("%d\n",s->data[s->top]);
        s->top=s->top-1;
    }

}

int main()
{
    stack s;
    init(&s);
    push(&s,2);
    push(&s,3);
    push(&s,4);
    display(&s);
    printf("Popped element is: ");
    printf("%d",pop(&s));
    return 0;
}
</code>```

Output:

```<code>4
3
2
Popped element is: 4200976
Process returned 0 (0x0)   execution time : 0.019 s
Press any key to continue.
</code>```

答:
After the display function your top will always have the value of -1.
When using the pop function it will return the -1'th element in the array.
This is undefined behaviour and so the returned x can be anything.</p>

Body:
In this implementation of stack program in C, when i print the value of pop(),why do i get that number? It should have printed '4' but instead i get an address like number. What might be the problem here?

#define MAX 5

typedef struct stack{
    int data[MAX];
    int top;
}stack;

int empty(stack *s){
    if(s->top==-1)
        return 1;
    return 0;
}

int pop(stack *s){
    int x;
    x = s->data[s->top];
    s->top = s->top -1;
    return x;

}

void display(stack *s){

    while(!(empty(&s)) && (s->top)!=-1){
        printf("%d\n",s->data[s->top]);
        s->top=s->top-1;
    }

}

int main()
{
    stack s;
    init(&s);
    push(&s,2);
    push(&s,3);
    push(&s,4);
    display(&s);
    printf("Popped element is: ");
    printf("%d",pop(&s));
    return 0;
}

Output:

4
3
2
Popped element is: 4200976
Process returned 0 (0x0)   execution time : 0.019 s
Press any key to continue.


问:
Wordpress customizer works perfectly in the customizer interface but doesnt in the actual design
I recently RESET customizer setting with wp customizer plugin, did this on purpose to know certain error theme users would get on a fresh install of the theme, and I found out that on the customizer interface everything works well but when I actually load my design, I get a total different result.

Here is what it looks like

Blog result after customizer resets

Here is the code i am using to change in settings from the customizer.php option ( dont think there is anything wrong with my settings pattern)

```<code>  $wp_customize->add_setting(
      'sq_hide_blog_info',
      array(
          'default'         => true,
      )
  );

     $wp_customize->add_control(
        new Toggle_Checkbox_Custom_control(
            $wp_customize,
            'sq_hide_blog_ctr',
            array(
                'description'    =>    __( 'Display Site name / Description' ),
                'label'    =>    __( 'Check here' ),
                'section'  => 'custom_footer_text',
                'settings' => 'sq_hide_blog_info',
                'type'     => 'checkbox',
                'section'  => 'sq_nav_design'
            )
        )
   );
</code>```

here is what i am using to change options in the actual code.

example

```<code> <?php if(get_theme_mod('nav_type_select') == 1): ?>
                <?php include get_template_directory() . '/template-parts/header/header-1.php'?>
                <?php else: ?>
               <?php include get_template_directory() . '/template-parts/header/header-2.php'?>
              <?php endif; ?>
</code>```

The above settings is a check box, and default output set to 1, and I meant that, if nav 1 is selected then output it else, output nav 2 as default, if nav 1, is not selected then output nav 2, things was working fine until i reset the customizer default, which i guess would pull same error when i get a fresh install.

i know the settings in the code doesn't tally with the one in the customizer.php just using this for reference purpose.

i am solely depending on the customizer default to output value in the theme, with no fallback .

my instinct is telling me that the issue is from the way i placed my if statement , cause i used that pattern through out my code.

Thanks in advance, i would truly appreciate your help.

To be clear: i need help in , checking if my if else pattern is correct, if yes, then any work around to make the customizer actually update the new settings in the default page.

答:
You need to pass Theme modification name in get_theme_mod()

Try this snippet

```<code><?php if( checked( get_theme_mod( 'sq_hide_blog_info', true ), true, false ) ) : ?>
 <?php include get_template_directory() . '/template-parts/header/header-1.php'?>
<?php else : ?>
 <?php include get_template_directory() . '/template-parts/header/header-2.php'?>
<?php endif; ?>
</code>```

Body:
I recently RESET customizer setting with wp customizer plugin, did this on purpose to know certain error theme users would get on a fresh install of the theme, and I found out that on the customizer interface everything works well but when I actually load my design, I get a total different result.

Here is what it looks like

Blog result after customizer resets

Here is the code i am using to change in settings from the customizer.php option ( dont think there is anything wrong with my settings pattern)

  $wp_customize->add_setting(
      'sq_hide_blog_info',
      array(
          'default'         => true,
      )
  );

     $wp_customize->add_control(
        new Toggle_Checkbox_Custom_control(
            $wp_customize,
            'sq_hide_blog_ctr',
            array(
                'description'    =>    __( 'Display Site name / Description' ),
                'label'    =>    __( 'Check here' ),
                'section'  => 'custom_footer_text',
                'settings' => 'sq_hide_blog_info',
                'type'     => 'checkbox',
                'section'  => 'sq_nav_design'
            )
        )
   );

here is what i am using to change options in the actual code.

example

 <?php if(get_theme_mod('nav_type_select') == 1): ?>
                <?php include get_template_directory() . '/template-parts/header/header-1.php'?>
                <?php else: ?>
               <?php include get_template_directory() . '/template-parts/header/header-2.php'?>
              <?php endif; ?>

The above settings is a check box, and default output set to 1, and I meant that, if nav 1 is selected then output it else, output nav 2 as default, if nav 1, is not selected then output nav 2, things was working fine until i reset the customizer default, which i guess would pull same error when i get a fresh install.

i know the settings in the code doesn't tally with the one in the customizer.php just using this for reference purpose.

i am solely depending on the customizer default to output value in the theme, with no fallback .

my instinct is telling me that the issue is from the way i placed my if statement , cause i used that pattern through out my code.

Thanks in advance, i would truly appreciate your help.

To be clear: i need help in , checking if my if else pattern is correct, if yes, then any work around to make the customizer actually update the new settings in the default page.

Body:
You need to pass Theme modification name in get_theme_mod()

Try this snippet

<?php if( checked( get_theme_mod( 'sq_hide_blog_info', true ), true, false ) ) : ?>
 <?php include get_template_directory() . '/template-parts/header/header-1.php'?>
<?php else : ?>
 <?php include get_template_directory() . '/template-parts/header/header-2.php'?>
<?php endif; ?>


问:
Adjusting XORShift generator to return a number within a maximum
I need to generate random integers within a maximum. Since performance is critical, I decided to use a XORShift generator instead of Java's Random class.

```<code>long seed = System.nanoTime();
seed ^= (seed << 21);
seed ^= (seed >>> 35);
seed ^= (seed << 4);
</code>```

This implementation (source) gives me a long integer, but what I really want is an integer between 0 and a maximum.

```<code>public int random(int max){ /*...*/}
</code>```

What it is the most efficient way to implement this method?

答:
Seeding

There are many problems here. In case, you're using nanoTime more than once, you'd definitely doing it wrong as nanoTime is slow (hundreds of nanoseconds). Moreover, doing this probably leads to bad quality.

So let's assume, you seed your generator just once.

Uniformity

If care about uniformity, then there are at least two problems:

Xorshift

It never generates zero (unless you unlucky with seeding and then zero is all you ever get).

This is easily solvable by something as simple as

```<code>private long nextLong() {
    x ^= x << 21;
    x ^= x >>> 35;
    x ^= x << 4;
    y += 123456789123456789L;
    return x + y;
}
</code>```

The used constant is pretty arbitrary, except for it must be odd. For best results, it should be big (so that all bits change often), it should have many bit transitions (occurrences of 10 and 01 in the binary representation) and it shouldn't be too regular (0x55...55 is bad).

However, with x!=0 and any odd constant, uniformity is guaranteed and the period of the generator is 2**64 * (2*64-1).

I'd suggest seeding like

```<code>seed = System.nanoTime();
x = seed | 1;
y = seed;
</code>```

nextInt(int limit)

The accepted answer provides non-uniformly distributed values for the reason I mentioned in a comment. Doing it right is a bit complicated, you can copy the code from Random#nextInt or you can try something like this (untested):

```<code>public int nextInt(int limit) {
    checkArgument(limit > 0);
    int mask = -1 >>> Integer.numberOfLeadingZeros(limit);
    while (true) {
        int result = (int) nextLong() & mask;
        if (result < limit) return result;
    }
}
</code>```

Above, the mask looks in binary like 0...01...1, where the highest one corresponds with the highest one of limit. Using it, a uniformly distributed number in the range 0..mask gets produced (unifomrnity is easy as mask+1 is a power of two). The conditional refuses numbers not below limit. As limit > mask/2, this happens with a probability below 50%, and therefore the expected number of iterations is below 2.

Recommendation

Fooling around with this is fun, but testing it is hard and I'd recommend using ThreadLocalRandom instead, unless you need reproducibility.

Body:
I need to generate random integers within a maximum. Since performance is critical, I decided to use a XORShift generator instead of Java's Random class.

long seed = System.nanoTime();
seed ^= (seed << 21);
seed ^= (seed >>> 35);
seed ^= (seed << 4);

This implementation (source) gives me a long integer, but what I really want is an integer between 0 and a maximum.

public int random(int max){ /*...*/}

What it is the most efficient way to implement this method?

Body:
Seeding

There are many problems here. In case, you're using nanoTime more than once, you'd definitely doing it wrong as nanoTime is slow (hundreds of nanoseconds). Moreover, doing this probably leads to bad quality.

So let's assume, you seed your generator just once.

Uniformity

If care about uniformity, then there are at least two problems:

Xorshift

It never generates zero (unless you unlucky with seeding and then zero is all you ever get).

This is easily solvable by something as simple as

private long nextLong() {
    x ^= x << 21;
    x ^= x >>> 35;
    x ^= x << 4;
    y += 123456789123456789L;
    return x + y;
}

The used constant is pretty arbitrary, except for it must be odd. For best results, it should be big (so that all bits change often), it should have many bit transitions (occurrences of 10 and 01 in the binary representation) and it shouldn't be too regular (0x55...55 is bad).

However, with x!=0 and any odd constant, uniformity is guaranteed and the period of the generator is 2**64 * (2*64-1).

I'd suggest seeding like

seed = System.nanoTime();
x = seed | 1;
y = seed;

nextInt(int limit)

The accepted answer provides non-uniformly distributed values for the reason I mentioned in a comment. Doing it right is a bit complicated, you can copy the code from Random#nextInt or you can try something like this (untested):

public int nextInt(int limit) {
    checkArgument(limit > 0);
    int mask = -1 >>> Integer.numberOfLeadingZeros(limit);
    while (true) {
        int result = (int) nextLong() & mask;
        if (result < limit) return result;
    }
}

Above, the mask looks in binary like 0...01...1, where the highest one corresponds with the highest one of limit. Using it, a uniformly distributed number in the range 0..mask gets produced (unifomrnity is easy as mask+1 is a power of two). The conditional refuses numbers not below limit. As limit > mask/2, this happens with a probability below 50%, and therefore the expected number of iterations is below 2.

Recommendation

Fooling around with this is fun, but testing it is hard and I'd recommend using ThreadLocalRandom instead, unless you need reproducibility.


问:
How to reset a select element with jQuery
I have

```<code><select id="baba">
<option>select something</option>
<option value="1">something 1</option>
<option value=2">something 2</option>
</select>
</code>```

Using jQuery, what would be the easiest (less to write) way to reset the select so the first option is selected?

答:
The best javascript solution I've found is this</p>

```<code>elm.options[0].selected="selected";
</code>```

Body:
I have

<select id="baba">
<option>select something</option>
<option value="1">something 1</option>
<option value=2">something 2</option>
</select>

Using jQuery, what would be the easiest (less to write) way to reset the select so the first option is selected?

Body:
The best javascript solution I've found is this

elm.options[0].selected="selected";


问:
invoke maven pluginManagment objects by reference
I have not found a way to do this, but it seems like a feature that should exist.  Is it possible to invoke a maven-2 plugin by inherited reference?  For example I would like to be able to do something like the following (yes I know you can't do this):

```<code><pluginManagment>
<plugin id="exec-inno-setup">
 <artifactId>maven-exec-plugin...
 <executions>...
  <configuration>...</configuration
 <executions>
</plugin>
</code>```

And somewhere in my child POM, I want to do something like:

```<code> <pluginRef id="exec-inno-setup">
  <configuration>
   <script>someFile.iss</script>
  </configuration>
 </pluginRef>
</code>```

The question is: is there some way to do this, (or come close).

答:
The workaround to your problem is to use maven properties. I'll admit I haven't tried this but I believe it should work...

In your parent you would do something like this...

```<code><pluginManagment>
  <plugin>
    <artifactId>maven-exec-plugin</artifactId>
    ...
    <executions>
      ...
      <configuration>
        <script>${maven.exec.plugin.config.script}</script>
      </configuration>
    <executions>
  </plugin>
</pluginManagment>
</code>```

And then in your child project, you just need to define the property...

```<code><properties>
    <maven.exec.plugin.config.script>someFile.iss</maven.exec.plugin.config.script>
</properties>
</code>```

This will only work where you childrens' config looks the exact same everywhere except for a few values. If you have different options you need set depending, this won't do it for you and you will have to define the entire plugin and it's configuration in each child pom.xml file.

ContentLicense: CC BY-SA 2.5

Body:
I have not found a way to do this, but it seems like a feature that should exist.  Is it possible to invoke a maven-2 plugin by inherited reference?  For example I would like to be able to do something like the following (yes I know you can't do this):

<pluginManagment>
<plugin id="exec-inno-setup">
 <artifactId>maven-exec-plugin...
 <executions>...
  <configuration>...</configuration
 <executions>
</plugin>

And somewhere in my child POM, I want to do something like:

 <pluginRef id="exec-inno-setup">
  <configuration>

  </configuration>
 </pluginRef>

The question is: is there some way to do this, (or come close).

Body:
The workaround to your problem is to use maven properties. I'll admit I haven't tried this but I believe it should work...

In your parent you would do something like this...

<pluginManagment>
  <plugin>
    <artifactId>maven-exec-plugin</artifactId>
    ...
    <executions>
      ...
      <configuration>
        <script>${maven.exec.plugin.config.script}</script>
      </configuration>
    <executions>
  </plugin>
</pluginManagment>

And then in your child project, you just need to define the property...

<properties>
    <maven.exec.plugin.config.script>someFile.iss</maven.exec.plugin.config.script>
</properties>

This will only work where you childrens' config looks the exact same everywhere except for a few values. If you have different options you need set depending, this won't do it for you and you will have to define the entire plugin and it's configuration in each child pom.xml file.


问:
Cannot load package in R
Since yesterday, I cannot load some common used packages, e.g. reshape2 and stringr through library command.

Step to reproduce my problem:

1) Start a new session in Rstudio server (Version 0.99.467). I also kill the active-sessions in Rstudio server.

2) Run these codes

```<code>library(ggplot2)
library(stringr)
</code>```

3) Get an error message:

Error in unloadNamespace(package) :
    namespace ‘stringr’ is imported by ‘reshape2’ so cannot be unloaded
   Show Traceback

Rerun with Debug

Error in library(stringr) : “stringr” version 0.6.2 cannot be unloaded.

But I don't get error if stringr is loaded before ggplot2. How should I fix this problem. Thanks for any suggestions.

I may have to update R to 3.2

My R session info:

```<code>R version 3.1.3 (2015-03-09)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu precise (12.04.5 LTS)

locale:
 [1] LC_CTYPE=en_AU.UTF-8       LC_NUMERIC=C               LC_TIME=en_AU.UTF-8        LC_COLLATE=en_AU.UTF-8
 [5] LC_MONETARY=en_AU.UTF-8    LC_MESSAGES=en_AU.UTF-8    LC_PAPER=en_AU.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_AU.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ggplot2_1.0.0

loaded via a namespace (and not attached):
 [1] colorspace_1.2-4 digest_0.6.4     grid_3.1.3       gtable_0.1.2     MASS_7.3-39      munsell_0.4.2    plyr_1.8.1
 [8] proto_0.3-10     Rcpp_0.11.2      reshape2_1.4     scales_0.2.4     stringr_0.6.2    tools_3.1.3
</code>```

答:
Even though it is a good practice to update R for me it was not necessary to solve the same issue. The problem can result from few .libPaths(). With .libPaths("C:/Program Files/R/R-3.4.3patched/library") you can point out one folder. After that just reinstall of packages, and it should work.
My code:

```<code>> .libPaths()

[1] "L:/My Documents/R/win-library/3.4"         "C:/Program Files/R/R-3.4.3patched/library"

> .libPaths("C:/Program Files/R/R-3.4.3patched/library")

> packages<-c('ggplot2','data.table','knitr','xtable')

> install.packages(packages)
> lapply(packages,library,character.only=T)
</code>```

Even though the issue is solved I hope it will help someone.

Title: Cannot load package in R

Body:
Since yesterday, I cannot load some common used packages, e.g. reshape2 and stringr through library command.

Step to reproduce my problem:

1) Start a new session in Rstudio server (Version 0.99.467). I also kill the active-sessions in Rstudio server.

2) Run these codes

library(ggplot2)
library(stringr)

3) Get an error message:

Error in unloadNamespace(package) :
    namespace ‘stringr’ is imported by ‘reshape2’ so cannot be unloaded
   Show Traceback

Rerun with Debug

Error in library(stringr) : “stringr” version 0.6.2 cannot be unloaded.

But I don't get error if stringr is loaded before ggplot2. How should I fix this problem. Thanks for any suggestions.

I may have to update R to 3.2

My R session info:

R version 3.1.3 (2015-03-09)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu precise (12.04.5 LTS)

locale:
 [1] LC_CTYPE=en_AU.UTF-8       LC_NUMERIC=C               LC_TIME=en_AU.UTF-8        LC_COLLATE=en_AU.UTF-8
 [5] LC_MONETARY=en_AU.UTF-8    LC_MESSAGES=en_AU.UTF-8    LC_PAPER=en_AU.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_AU.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ggplot2_1.0.0

loaded via a namespace (and not attached):
 [1] colorspace_1.2-4 digest_0.6.4     grid_3.1.3       gtable_0.1.2     MASS_7.3-39      munsell_0.4.2    plyr_1.8.1
 [8] proto_0.3-10     Rcpp_0.11.2      reshape2_1.4     scales_0.2.4     stringr_0.6.2    tools_3.1.3

Body:
Even though it is a good practice to update R for me it was not necessary to solve the same issue. The problem can result from few .libPaths(). With .libPaths("C:/Program Files/R/R-3.4.3patched/library") you can point out one folder. After that just reinstall of packages, and it should work.
My code:

> .libPaths()

[1] "L:/My Documents/R/win-library/3.4"         "C:/Program Files/R/R-3.4.3patched/library"

> .libPaths("C:/Program Files/R/R-3.4.3patched/library")

> packages<-c('ggplot2','data.table','knitr','xtable')

> install.packages(packages)
> lapply(packages,library,character.only=T)

Even though the issue is solved I hope it will help someone.


问:
Import methods and their advantages
As far as I understand, in Python there are 3 ways to import:

from name_module import name_class

import name_module

from name_module import *

In all other ways, there is no point, as if this class is already in our module. But for some reason they do not recommend using the third way, explaining this by the fact that there is a possibility of a name conflict between the names of the imported module's class and the module in which we are located.

Why does this not happen when we import the 2nd way. After all, there and there is the import of the entire file and the creation of the same variables in our namespace or not?

What is better to use in what case?

答:
Becuase you have to use the module name to call the module functions when using this import method.

Depends on what you mean with "best". import X is the safest. If you think that import aterriblyandunnecessarilylongpackagename makes your code inconvinient, use import aterriblyandunnecessarilylongpackagename as x. As soon as you use from there's a risk, and especially if you use *

Consider the following code. Assume that functions A,B and C exists in both X and Y.

```<code>from X import *
from Y import A
B
A
</code>```

This code will always work as intended, but now assume that both X and Y has functions A, B and C, but X also has the function D:

```<code>from X import *
from Y import *
D
A
</code>```

Now D will be called from X and A from Y. But what if a software upgrade adds a function called D to the package Y? Then the code will execute differently.

Never use from X import *

Title: Import methods and their advantages

Body:
Becuase you have to use the module name to call the module functions when using this import method.

Depends on what you mean with "best". import X is the safest. If you think that import aterriblyandunnecessarilylongpackagename makes your code inconvinient, use import aterriblyandunnecessarilylongpackagename as x. As soon as you use from there's a risk, and especially if you use *

Consider the following code. Assume that functions A,B and C exists in both X and Y.

from X import *
from Y import A
B
A

This code will always work as intended, but now assume that both X and Y has functions A, B and C, but X also has the function D:

from X import *
from Y import *
D
A

Now D will be called from X and A from Y. But what if a software upgrade adds a function called D to the package Y? Then the code will execute differently.

Never use from X import *


问:
How to get Post parameters in Spring MVC controller?
I am trying to get Post parameters in Spring MVC controller but ServletRequestUtils getStringParameters method cannot find this parameter and returns empty array. Is there any way to get array parameter with ServletRequestUtils?

My Controller;

```<code>@ResponseBody
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(HttpServletRequest request, HttpServletResponse response){

    //I can get id parameter without problem.
    String id = ServletRequestUtils.getStringParameter(request, "id", null);

    String[] types = ServletRequestUtils.getStringParameters(request, "types");
}
</code>```

My ajax post;

```<code>$.post("update", {
   id: id,
   types: types
   ....
}
</code>```

My form-data;

```<code>id=2a4e905d-8015-447c-9d52-896042367c8a&types%5B%5D=IP+Num&types%5B%5D=Ver+Tab
</code>```

答:
try adding traditional:true to the option like this

```<code> $.ajax({
         url:'update',
         type:'post',
         data:{
               id: id,
               types:types,
              ....
              },
          traditional:true
        })
</code>```

Or

```<code>$.post("update",  $.param({
   id: id,
   types:types,
   ....
  },true)

}
</code>```

Body:
I am trying to get Post parameters in Spring MVC controller but ServletRequestUtils getStringParameters method cannot find this parameter and returns empty array. Is there any way to get array parameter with ServletRequestUtils?

My Controller;

@ResponseBody
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(HttpServletRequest request, HttpServletResponse response){

    //I can get id parameter without problem.
    String id = ServletRequestUtils.getStringParameter(request, "id", null);

    String[] types = ServletRequestUtils.getStringParameters(request, "types");
}

My ajax post;

$.post("update", {
   id: id,
   types: types
   ....
}

My form-data;

id=2a4e905d-8015-447c-9d52-896042367c8a&types%5B%5D=IP+Num&types%5B%5D=Ver+Tab

Body:
try adding traditional:true to the option like this

 $.ajax({
         url:'update',
         type:'post',
         data:{
               id: id,
               types:types,
              ....
              },
          traditional:true
        })

Or

$.post("update",  $.param({
   id: id,
   types:types,
   ....
  },true)

}


问:
Retrieving a random record from DB
Wondering what is the best way to retrieve a random record from the database in my Ruby on Rails (2.3.9) applications. </p>

<p>The closest I got was using the below. SQLITE3 liked it by in production MySQL did not. </p>

```<code>#class PostsController < ApplicationController
...
@posts = Post.all(:order => "RANDOM()")
...
end

#view
<% @posts.each do |post| %>
...
<% end %>
</code>```

答: This may not be possible depending on the scope of your problem and the size of your database.  See Axiom of Choice.  ;)</p>

Title: Retrieving a random record from DB

Body:
Wondering what is the best way to retrieve a random record from the database in my Ruby on Rails (2.3.9) applications.

The closest I got was using the below. SQLITE3 liked it by in production MySQL did not.

#class PostsController < ApplicationController
...
@posts = Post.all(:order => "RANDOM()")
...
end

#view
<% @posts.each do |post| %>
...
<% end %>


问:
Converting a char to &str
I have a match statement which returns a &str:

```<code>match k {
    SP_KEY_1 => "KEY_1",
    SP_KEY_2 => "KEY_2",
    SP_KEY_3 => "KEY_3",
    SP_KEY_4 => "KEY_4",
    SP_KEY_5 => "KEY_5",
    SP_KEY_6 => "KEY_6",
    _ => (k as char), // I want to convert this to &str
}.as_bytes()
</code>```

I have tried to convert a char to a string first, and then taking a slice of that:

```<code>&(k as char).to_string()[..]
</code>```

But that gave me the lifetime error:

error[E0597]: borrowed value does not live long enough
```

Stating that (k as char).to_string()  is a temporary value, which makes sense as from what I can tell to_string() returns a clone.

I can add .to_string() to every &str literal above to make the return value String, but that seems both ugly (a lot of repeated code), and probably inefficient, as to_string() clones the original string slice.

The specific question is how would I make a char into a &str, but the broader question is that is there a better solution, what is commonly done this situation.

答:
Using Cow is simple enough:

```<code>use std::borrow::Cow;

fn cow_name(v: u8) -> Cow<'static, str> {
    match v {
        0 => "KEY_0",
        1 => "KEY_1",
        _ => return (v as char).to_string().into(),
    }.into()
}
</code>```

Given that k is a u8 (otherwise your code will not compile), you can also use a constant array:

```<code>const NAMES: [&'static str; 256] = [
    "KEY_0", "KEY_1", //  ...
    " ", "!", "\"", "#", // ...
];

fn const_name(k: u8) -> &'static str {
    NAMES[k as usize]
}
</code>```

Playground

Title: Converting a char to &str

Body:
I have a match statement which returns a &str:

match k {
    SP_KEY_1 => "KEY_1",
    SP_KEY_2 => "KEY_2",
    SP_KEY_3 => "KEY_3",
    SP_KEY_4 => "KEY_4",
    SP_KEY_5 => "KEY_5",
    SP_KEY_6 => "KEY_6",
    _ => (k as char), // I want to convert this to &str
}.as_bytes()

I have tried to convert a char to a string first, and then taking a slice of that:

&(k as char).to_string()[..]

But that gave me the lifetime error:

error[E0597]: borrowed value does not live long enough

Stating that (k as char).to_string()  is a temporary value, which makes sense as from what I can tell to_string() returns a clone.

I can add .to_string() to every &str literal above to make the return value String, but that seems both ugly (a lot of repeated code), and probably inefficient, as to_string() clones the original string slice.

The specific question is how would I make a char into a &str, but the broader question is that is there a better solution, what is commonly done this situation.

Body:
Using Cow is simple enough:

use std::borrow::Cow;

fn cow_name(v: u8) -> Cow<'static, str> {
    match v {
        0 => "KEY_0",
        1 => "KEY_1",
        _ => return (v as char).to_string().into(),
    }.into()
}

Given that k is a u8 (otherwise your code will not compile), you can also use a constant array:

const NAMES: [&'static str; 256] = [
    "KEY_0", "KEY_1", //  ...
    " ", "!", "\"", "#", // ...
];

fn const_name(k: u8) -> &'static str {
    NAMES[k as usize]
}

Playground


问:
Scenarios where automated testing is unhelpful
What are some situations where unit testing and TDD and the like are more trouble than they're worth?

Some things I've come up with are:

When generating test data is tricky: Sometimes, being able to come up with valid, non trivial test data is a challenge in itself.

When the only practical way of verifying correctness of the code is to run it.

When you're testing visual elements of the design.

What are some other cases?

答:
I'm a firm believer in thoughtful testing; however, I find Unit Testing and TDD to be mostly a waste of time.

From an empirical standpoint:

There is no empirical evidence that demonstrates higher quality code.

There is no empirical evidence that demonstrates higher productivity.

There is no empirical evidence that demonstrates cost savings.

There are 'stories' presented in a pseudoscientific manner that suggest TDD is beneficial, but there are no control groups and there are no real metrics.

The benefits of TDD:

The evangelists who 'know' TDD benefit by promoting their expertise.

The software groups who sell/promote Unit Testing tools benefit.

There may be some benefit to Unit Testing if your developers are not high-caliber.

Unit Testing only catches the most obvious errors

If a developer consistently finds bugs via Unit Testing, I would replace them.

If I were to outsource development to a body shop in Bangalore, I'd implement Unit Testing.  Otherwise, I'll stick to working with strong developers - these guys are much more cost effective in the long run.

Subjective Analysis:

If you listen to the arguments made by TDD proponents, you can readily replace TDD with prayer and the validity of the reasoning does not change...

Unit Tests are code - you are doubling/tripling the size of your code base...  That time could probably be better spent analyzing your code.

High quality software comes from having antagonistic/cooperative teams.  The same entity that writes the code has no business testing the code - that should be the job of a QA analyst.

High quality and cost effective software comes from following good design principals - SOLID/GRASP/GoF

After reviewing Unit Testing and TDD, the real world analogy I would draw is... it's sort of like running a check list on yourself with items like:

inhaling air check

exhaling air check

left foot forward check

right foot forward check

blink eyes check

insert gum check

close mouth check

open mouth check

iterate until swallow check...

Yes you might actually find an issue, but you'll never figure out anything of consequence without spending a huge effort to code for it.

Jebus told me that TDD is a false god.

OwnerDisplayName: Shalmanese

OwnerDisplayName: mson

LastEditorDisplayName: Jonathan Leffler


问:
Why does Monitor.Pulse need locked mutex? (.Net)
Monitor.Pulse and PulseAll requires that the lock it operates on is locked at the time of call. This requirement seems unnecessary and detrimental for performance. My first idea was that this results in 2 wasted context switches, but this was corrected by nobugz below (thanks). I am still unsure whether it involves a potential for wasted context switches, as the other thread(s) which were waiting on the monitor are already available for the sheduler, but if they are scheduled, they will only be able to run a few instructions before hitting the mutex, and having to context-switch again. This would look much simpler and faster if the lock was unlocked before invoking the Monitor.Pulse.

Pthread condition variables implement the same concept, but it does not have the above described limitation: you can call pthread_cond_broadcast even if you do not own the mutex. I see this as a proof that the requirement is not justified.

Edit:
I realize that a lock is required to protect the shared resource that is usually changed before the Monitor.Pulse. I was trying to say that that lock could have been unlocked after access to the resource but before the Pulse, given that Monitor would support this. This would help in limiting the lock to the shortest time during which the shared resource is accessed. As such:

```<code>void f(Item i)
{
  lock(somequeue) {
    somequeue.add(i);
  }
  Monitor.Pulse(somequeue);  // error
}
</code>```

答:
Wait is designed to be used with a conditional check.  If the conditional check were not done within a lock, it would be possible for the following sequence of events to occur:

The conditional check indicates a wait is necessary.

Another thread changes the condition so a wait isn't necessary, and then does a Pulse or PulseAll.

The first thread, having observed that a wait was necessary, performs a Wait.

Once that sequence of events occurs, it's entirely possible that nothing will ever Pulse the lock again (unless a situation arises where a wait would again be necessary, and again no longer be necessary).  Thread #1 could thus wait forever for an event that never arrives.

Putting the conditional check and Wait within a lock avoids this danger, since there will be no way for another thread to change the condition between the time the condition is checked and the time the Wait begins.  Consequently another thread that changes the Condition and does a Pulse can be assured that the first thread either checked the condition after it was changed (and thus avoided the wait) or else was executing the Wait when the Pulse executed (and was thus able to resume).

Body:
Monitor.Pulse and PulseAll requires that the lock it operates on is locked at the time of call. This requirement seems unnecessary and detrimental for performance. My first idea was that this results in 2 wasted context switches, but this was corrected by nobugz below (thanks). I am still unsure whether it involves a potential for wasted context switches, as the other thread(s) which were waiting on the monitor are already available for the sheduler, but if they are scheduled, they will only be able to run a few instructions before hitting the mutex, and having to context-switch again. This would look much simpler and faster if the lock was unlocked before invoking the Monitor.Pulse.

Pthread condition variables implement the same concept, but it does not have the above described limitation: you can call pthread_cond_broadcast even if you do not own the mutex. I see this as a proof that the requirement is not justified.

Edit:
I realize that a lock is required to protect the shared resource that is usually changed before the Monitor.Pulse. I was trying to say that that lock could have been unlocked after access to the resource but before the Pulse, given that Monitor would support this. This would help in limiting the lock to the shortest time during which the shared resource is accessed. As such:

void f(Item i)
{
  lock(somequeue) {
    somequeue.add(i);
  }
  Monitor.Pulse(somequeue);  // error
}


问:
how to use keyup/keydown and select with autocomplete function in ajax
I am able to select the value using onclick function but i want to select the value using keyup/keydown also.i tried so many things but those are not working.What function i need to use when i have to reach to the correct value using keyup/keydown and select that value.</p>

```<code>              $("#employer").autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            type: "POST",
                            url: "employerNameAutoSuggestionList?ajax=true",
                            data: { employer: request.term },
                            success: function (result) {
                                var arr =result.data;
                                $("#suggesstion-box").empty();
                                $("#suggesstion-box").show();
                                if($("#employer").val() == "")
                                {
                                    $("#suggesstion-box").hide();
                                }
                                $("#suggesstion-box").append('<ul id ="empVal" style="list-style-type: none; display:inline" ></ul>');
                                var ul = document.getElementById("empVal");
                                 for (var i = 0, length = arr.length; i < length; i++) {
                                   var li = document.createElement("li");
                                   li.appendChild(document.createTextNode(arr[i]));
                                   ul.appendChild(li);
                                   ul.onclick = function (li) {
                                        $("#employer").css("background","#FFF");
                                        $("#employer").val(li.target.innerText);
                                        $("#suggesstion-box").hide();

                                    }

                                }
                                arr = null;

                            },
                            error: function (xhr, status, error) {
                                alert(error.responseText);
                            }

                        });
                    }

                 });

            $("#employer").on({
                keyup: function () {
                    if ( $(this).val() == "" ) {
                        $("#suggesstion-box").hide();
                    }
                }
            });

        </script>
</code>```

答:
Please check with the syntax. Sample below.</p>

```<code>$("#employer").on("keyup", function () {
                    if ( $(this).val() == "" ) {
                        $("#suggesstion-box").hide();
                    }
});
</code>```

Body:
I am able to select the value using onclick function but i want to select the value using keyup/keydown also.i tried so many things but those are not working.What function i need to use when i have to reach to the correct value using keyup/keydown and select that value.

              $("#employer").autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            type: "POST",
                            url: "employerNameAutoSuggestionList?ajax=true",
                            data: { employer: request.term },
                            success: function (result) {
                                var arr =result.data;
                                $("#suggesstion-box").empty();
                                $("#suggesstion-box").show();
                                if($("#employer").val() == "")
                                {
                                    $("#suggesstion-box").hide();
                                }
                                $("#suggesstion-box").append('

');
                                var ul = document.getElementById("empVal");
                                 for (var i = 0, length = arr.length; i < length; i++) {
                                   var li = document.createElement("li");
                                   li.appendChild(document.createTextNode(arr[i]));
                                   ul.appendChild(li);
                                   ul.onclick = function (li) {
                                        $("#employer").css("background","#FFF");
                                        $("#employer").val(li.target.innerText);
                                        $("#suggesstion-box").hide();

                                    }

                                }
                                arr = null;

                            },
                            error: function (xhr, status, error) {
                                alert(error.responseText);
                            }

                        });
                    }

                 });

            $("#employer").on({
                keyup: function () {
                    if ( $(this).val() == "" ) {
                        $("#suggesstion-box").hide();
                    }
                }
            });

        </script>

Body:
Please check with the syntax. Sample below.

$("#employer").on("keyup", function () {
                    if ( $(this).val() == "" ) {
                        $("#suggesstion-box").hide();
                    }
});


问:
Communication between App and iWatch: is using app group the only way?
I have an iPhone app that performs some computations. It works well. Now I'd like to create a WatchKit extension and target in order to control the start of the computations and display the results once the computations are finished as well as update the progress (e.g. percentage completed when Watch app is displayed, and send a notification from the iPhone app to the iWatch when the progress reaches a significant percentage mark).

I have found some tutorials that explain to use NSUserDefaults and initWithSuitName providing an app group and then add the data object to synchronise. I could use KVO to display a percentage label on the Watch.

As I am exploring the possible architectures here, are you aware of some alternative methods to achieve this? Is using app group the method that Apple recommends?

答:
App groups no longer work above watchOS 1. You need to use WatchConnectivity framework. Once you get the values in watch you can use Reactive or Rx to update the values instead of KVO.

Helpful Links:

https://developer.apple.com/documentation/watchconnectivity

https://kristina.io/watchos-2-how-to-communicate-between-devices-using-watch-connectivity/

https://www.natashatherobot.com/watchconnectivity-application-context/


问:
ProgressDialog not showing/only showing after asyncTask
i'm trying to add a indeterminate progressDialog to my UI once i click a list element that calls a AsyncTask, but unfortunately, if I call the dialog on the onPreExecute like this:

```<code>@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog.setProgressStyle(R.style.AppTheme_Dark_Dialog);
    dialog.setIndeterminate(true);
    dialog.setMessage(activity.getString(R.string.Buscando));
    dialog.show();
}
</code>```

Obs: Worth noting that the Async is not a subClass of the Activity Class, i'm passing the activity as a parameter to the constructor.

and

```<code>@Override
protected void onPostExecute(BuscaPendentesFechamento buscaPendentesFechamento) {
    super.onPostExecute(buscaPendentesFechamento);
    if(dialog.isShowing())
        dialog.dismiss();
}
</code>```

the dialog simply doesn't show at all, although it is created and called(alredy checked, the activity instance is correct)

and if I set the dialog on the activity itself, like:

```<code>final ProgressDialog progressDialog = new ProgressDialog(RegistraPeso.this, R.style.AppTheme_Dark_Dialog);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage(getString(R.string.Buscando));
    progressDialog.show();
    BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(getApplicationContext());
    response = exportProjectRequisition.execute(nomeEquip,RegistraPeso.this);
    progressDialog.dismiss();
</code>```

the Dialog shows on the Ui, but only after the AsyncTask alredy performed, and not before it is called, and according to the code, it should be showing before the Async even gets created.

What can I do? What am I doing wrong? Please help.

Edit: Added where the Dialog is created:

```<code>private ProgressDialog dialog;
private RegistraPeso activity;
BuscaPendentesFechamento(RegistraPeso activity) {
    this.dialog = new ProgressDialog(activity);
    this.activity = activity;
}
</code>```

Edit: Added the doInBackground:

```<code>    @Override
protected BuscaPendentesFechamento doInBackground(String... params) {
    ArrayList<UmData> jsonArrayResponse = JSONParser.makeHttpRequestArray(
            Constants.URL_PENDENTES_FECHAMENTO,
            Constants.METHOD_POST, requisition.writeJSON(params[0]),
            requisition.getContext());
    if(jsonArrayResponse!=null)
    requisition.setJsonArrayResponse(jsonArrayResponse);
    else {
        UmData umData = new UmData();
        umData.setItemUm("Server not responding");
        jsonArrayResponse = new ArrayList<>();
        jsonArrayResponse.add(umData);
        requisition.setJsonArrayResponse(jsonArrayResponse);
    }
    return requisition;
}
</code>```

答:
Application context would not work in this case . Replace line below

```<code> BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(getApplicationContext());
</code>```

To

```<code> BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(YourActivity.this);
</code>```

I see your code you are calling dismiss() just after execute(). Remove this line.

```<code> progressDialog.dismiss();
</code>```

Body:
i'm trying to add a indeterminate progressDialog to my UI once i click a list element that calls a AsyncTask, but unfortunately, if I call the dialog on the onPreExecute like this:

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog.setProgressStyle(R.style.AppTheme_Dark_Dialog);
    dialog.setIndeterminate(true);
    dialog.setMessage(activity.getString(R.string.Buscando));
    dialog.show();
}

Obs: Worth noting that the Async is not a subClass of the Activity Class, i'm passing the activity as a parameter to the constructor.

and

@Override
protected void onPostExecute(BuscaPendentesFechamento buscaPendentesFechamento) {
    super.onPostExecute(buscaPendentesFechamento);
    if(dialog.isShowing())
        dialog.dismiss();
}

the dialog simply doesn't show at all, although it is created and called(alredy checked, the activity instance is correct)

and if I set the dialog on the activity itself, like:

final ProgressDialog progressDialog = new ProgressDialog(RegistraPeso.this, R.style.AppTheme_Dark_Dialog);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage(getString(R.string.Buscando));
    progressDialog.show();
    BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(getApplicationContext());
    response = exportProjectRequisition.execute(nomeEquip,RegistraPeso.this);
    progressDialog.dismiss();

the Dialog shows on the Ui, but only after the AsyncTask alredy performed, and not before it is called, and according to the code, it should be showing before the Async even gets created.

What can I do? What am I doing wrong? Please help.

Edit: Added where the Dialog is created:

private ProgressDialog dialog;
private RegistraPeso activity;
BuscaPendentesFechamento(RegistraPeso activity) {
    this.dialog = new ProgressDialog(activity);
    this.activity = activity;
}

Edit: Added the doInBackground:

    @Override
protected BuscaPendentesFechamento doInBackground(String... params) {
    ArrayList<UmData> jsonArrayResponse = JSONParser.makeHttpRequestArray(
            Constants.URL_PENDENTES_FECHAMENTO,
            Constants.METHOD_POST, requisition.writeJSON(params[0]),
            requisition.getContext());
    if(jsonArrayResponse!=null)
    requisition.setJsonArrayResponse(jsonArrayResponse);
    else {
        UmData umData = new UmData();
        umData.setItemUm("Server not responding");
        jsonArrayResponse = new ArrayList<>();
        jsonArrayResponse.add(umData);
        requisition.setJsonArrayResponse(jsonArrayResponse);
    }
    return requisition;
}

Body:
Application context would not work in this case . Replace line below

 BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(getApplicationContext());

To

 BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(YourActivity.this);

I see your code you are calling dismiss() just after execute(). Remove this line.

 progressDialog.dismiss();


答:
The function display is invalid.

For starters this call

```<code>!(empty(&s))
</code>```

has the argument type stack ** while the parameter type is stack *. There should be

```<code>!(empty(s))
</code>```

Though this check is redundant and may be removed.

And the function changes the data member top of the stack. As result the function pop called after the function display has undefined behavior.

The function can look like

```<code>void display(const stack *s)
{
    for ( int i = s->top; i != -1; i-- )
    {
        printf("%d\n",s->data[i]);
    }
}
</code>```

Here is a demonstrative program

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

#define MAX 5

typedef struct stack
{
    int data[MAX];
    int top;
}   stack;

void init( stack *s )
{
    s->top = -1;
}

int empty( const stack *s )
{
    return s->top == -1;
}

void push( stack *s, int x )
{
    if ( s->top + 1 != MAX ) s->data[++s->top] = x;
}

int pop( stack *s )
{
    int x  = s->data[s->top--];
    return x;
}

void display(const stack *s)
{
    for ( int i = s->top; i != -1; i-- )
    {
        printf("%d\n",s->data[i]);
    }
}

int main(void)
{
    stack s = { { 0 }, -1 };

    init( &s );

    push (&s, 2 );
    push( &s, 3 );
    push( &s, 4 );
    display( &s );

    printf( "Popped element is: " );
    printf( "%d\n", pop( &s ) );

    return 0;
}
</code>```

It yields the expected result

```<code>4
3
2
Popped element is: 4
</code>```

Title: Why am i getting this number instead of the value, in this STACK program?

Body:
In this implementation of stack program in C, when i print the value of pop(),why do i get that number? It should have printed '4' but instead i get an address like number. What might be the problem here?

#define MAX 5

typedef struct stack{
    int data[MAX];
    int top;
}stack;

int empty(stack *s){
    if(s->top==-1)
        return 1;
    return 0;
}

int pop(stack *s){
    int x;
    x = s->data[s->top];
    s->top = s->top -1;
    return x;

}

void display(stack *s){

    while(!(empty(&s)) && (s->top)!=-1){
        printf("%d\n",s->data[s->top]);
        s->top=s->top-1;
    }

}

int main()
{
    stack s;
    init(&s);
    push(&s,2);
    push(&s,3);
    push(&s,4);
    display(&s);
    printf("Popped element is: ");
    printf("%d",pop(&s));
    return 0;
}

Output:

4
3
2
Popped element is: 4200976
Process returned 0 (0x0)   execution time : 0.019 s
Press any key to continue.

Body:
The function display is invalid.

For starters this call

!(empty(&s))

has the argument type stack ** while the parameter type is stack *. There should be

!(empty(s))

Though this check is redundant and may be removed.

And the function changes the data member top of the stack. As result the function pop called after the function display has undefined behavior.

The function can look like

void display(const stack *s)
{
    for ( int i = s->top; i != -1; i-- )
    {
        printf("%d\n",s->data[i]);
    }
}

Here is a demonstrative program

#include <stdio.h>

#define MAX 5

typedef struct stack
{
    int data[MAX];
    int top;
}   stack;

void init( stack *s )
{
    s->top = -1;
}

int empty( const stack *s )
{
    return s->top == -1;
}

void push( stack *s, int x )
{
    if ( s->top + 1 != MAX ) s->data[++s->top] = x;
}

int pop( stack *s )
{
    int x  = s->data[s->top--];
    return x;
}

void display(const stack *s)
{
    for ( int i = s->top; i != -1; i-- )
    {
        printf("%d\n",s->data[i]);
    }
}

int main(void)
{
    stack s = { { 0 }, -1 };

    init( &s );

    push (&s, 2 );
    push( &s, 3 );
    push( &s, 4 );
    display( &s );

    printf( "Popped element is: " );
    printf( "%d\n", pop( &s ) );

    return 0;
}

It yields the expected result

4
3
2
Popped element is: 4


问:
Get distance travelled if the starting and ending point is the same in Google Maps
I'm working on Google Maps directions API.

I need to calculate the distance traveled between two points.

If the starting and ending point is same how can we calculate the distance traveled?

Can anyone help me or give some suggestions regarding this?

答:
Try this code</p>

```<code>public double Distance(LatLng StartP, LatLng EndP) {
        int Radius = 6371;// radius of earth in Km
        double lat1 = StartP.latitude;
        double lat2 = EndP.latitude;
        double lon1 = StartP.longitude;
        double lon2 = EndP.longitude;
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
                * Math.sin(dLon / 2);
        double c = 2 * Math.asin(Math.sqrt(a));
        double valueResult = Radius * c;
        double km = valueResult / 1;
        DecimalFormat newFormat = new DecimalFormat("####");
        int kmInDec = Integer.valueOf(newFormat.format(km));
        double meter = valueResult % 1000;
        int meterInDec = Integer.valueOf(newFormat.format(meter));
        Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
                + " Meter   " + meterInDec);

        return Radius * c;
    }
</code>```

Body:
Try this code

public double Distance(LatLng StartP, LatLng EndP) {
        int Radius = 6371;// radius of earth in Km
        double lat1 = StartP.latitude;
        double lat2 = EndP.latitude;
        double lon1 = StartP.longitude;
        double lon2 = EndP.longitude;
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
                * Math.sin(dLon / 2);
        double c = 2 * Math.asin(Math.sqrt(a));
        double valueResult = Radius * c;
        double km = valueResult / 1;
        DecimalFormat newFormat = new DecimalFormat("####");
        int kmInDec = Integer.valueOf(newFormat.format(km));
        double meter = valueResult % 1000;
        int meterInDec = Integer.valueOf(newFormat.format(meter));
        Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
                + " Meter   " + meterInDec);

        return Radius * c;
    }


问:
CKEditor editor1.insertHtml() not working for me
I am using CKEditor to be able to edit comments to posts. I am also using JQuery. Because there can be multiple comments per post I'm trying to keep it all class based.

The following function is supposed to hide the display area of the comment, insert the text form the display area into the editor, and finally display the editor.

```<code>function fnCommentControl_edit(divEditBtn){
    divEditBtn = $(divEditBtn);
    var divSaveBtn = divEditBtn.parent().find('.save');
    var divCancelBtn = divEditBtn.parent().find('.cancel');
    var divEdit = divEditBtn.parent().parent().parent().find('.text').find('.edit');
    var divDisplay = divEditBtn.parent().parent().parent().find('.text').find('.display');
    var divEditor = divEdit.find('.editor');

    var ckEditor1 = CKEDITOR.replace(divEditor[0],
        {
            toolbar : 'Basic',
            customConfig : '/includes/ckEditorConfig.js'
        });

    ckEditor1.insertHtml('<p>test</p>');

    divEditBtn.hide();
    divSaveBtn.show();
    divCancelBtn.show();
    divEdit.show();
    divDisplay.hide();
}
</code>```

After I call the function everything seems to work fine, except the editor has no text in it.

I am new at using CKEditor and would appreciate any assistance.

答:
The creation process isn't synchronous, so the editor isn't fully ready to edit (specially the first instance) just after the call to create it.

You should listen for the instanceReady event to work with it.

Body:
I am using CKEditor to be able to edit comments to posts. I am also using JQuery. Because there can be multiple comments per post I'm trying to keep it all class based.

The following function is supposed to hide the display area of the comment, insert the text form the display area into the editor, and finally display the editor.

function fnCommentControl_edit(divEditBtn){
    divEditBtn = $(divEditBtn);
    var divSaveBtn = divEditBtn.parent().find('.save');
    var divCancelBtn = divEditBtn.parent().find('.cancel');
    var divEdit = divEditBtn.parent().parent().parent().find('.text').find('.edit');
    var divDisplay = divEditBtn.parent().parent().parent().find('.text').find('.display');
    var divEditor = divEdit.find('.editor');

    var ckEditor1 = CKEDITOR.replace(divEditor[0],
        {
            toolbar : 'Basic',
            customConfig : '/includes/ckEditorConfig.js'
        });

    ckEditor1.insertHtml('
test
');

    divEditBtn.hide();
    divSaveBtn.show();
    divCancelBtn.show();
    divEdit.show();
    divDisplay.hide();
}

After I call the function everything seems to work fine, except the editor has no text in it.

I am new at using CKEditor and would appreciate any assistance.


问:
WatchKit Extension is not seeing data saved in NSUserDefaults with App Group
I've been through a ton of SO posts, and this USED to work, but it stopped working. I'm not sure what happened. I developed this iPhone+WatchKit app with watchOS 1.0 and everything worked fine.

I've upgraded my app, project, and Apple Watch to watchOS 2.0, and now I can't get any data via NSUserDefaults using my App Group.

App Groups is enabled in Xcode on the host App, and WatchKit Extension. I even tried turning it on for the WatchKit App as well.

My group name is called "group.com.mycompany.myapp" (with my real company name and app name) and it's selected on all of the targets.

I've confirmed the Build settings for my host app and WatchKit extension reference the entitlements files and I've checked that those entitlements files contain the app groups security option for my chosen app group.

I've made sure the bundle identifiers are different for the host app, watchkit extension, and watchkit app. I use "com.mycompany.myapp", "com.mycompany.myapp.watchkitextension", and "com.mycompany.myapp.watchkitapp", respectively.

Here are some screenshots of my Xcode config for the host app, watchkit extension, and watchkit app, just in case:

Here is the code in my host app that is able to read the data properly:

```<code>NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:kAppGroupName];
NSLog(@"app defaults: %@", [defaults dictionaryRepresentation]);
</code>```

That produces this in my console, with kKeyEmployeeId and kKeyStoreNumber being the data that I'm trying to share between the host and watch.

```<code>2015-12-13 13:51:35.618 MyApp[27516:16126253] app defaults: {
    AppleLanguages =     (
        "en-US",
        en
    );
    INNextHearbeatDate = "472211882.83309";
    NSInterfaceStyle = macintosh;
    NSLanguages =     (
        "en-US",
        en
    );
    "com.apple.content-rating.AppRating" = 1000;
    "com.apple.content-rating.ExplicitBooksAllowed" = 1;
    "com.apple.content-rating.ExplicitMusicPodcastsAllowed" = 1;
    "com.apple.content-rating.MovieRating" = 1000;
    "com.apple.content-rating.TVShowRating" = 1000;
    kKeyEmployeeId = Kenny;
    kKeyStoreNumber = 001;
}
</code>```

In my WatchKit Extension, I have the same code, but it doesn't provide me the two key:value pairs that I need:

```<code>- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];

    NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:kAppGroupName];
    NSLog(@"defaults: %@", [defaults dictionaryRepresentation]);

}
</code>```

It produces this, which is very similar to the one above, but without the two keys I really need:

```<code>2015-12-13 13:28:29.840 MyApp WatchKit Extension[720:322804] defaults: {
    AppleLanguages =     (
        en
    );
    INNextHearbeatDate = "472434306.599217";
    NSInterfaceStyle = macintosh;
    NSLanguages =     (
        en
    );
    "com.apple.content-rating.AppRating" = 1000;
    "com.apple.content-rating.ExplicitBooksAllowed" = 1;
    "com.apple.content-rating.ExplicitMusicPodcastsAllowed" = 1;
    "com.apple.content-rating.MovieRating" = 1000;
    "com.apple.content-rating.TVShowRating" = 1000;
}
</code>```

The kAppGroupName and other constants are defined like so:

```<code>NSString * const kAppGroupName = @"group.com.inadaydevelopment.MyApp";
NSString * const kKeyStoreNumber = @"kKeyStoreNumber";
NSString * const kKeyEmployeeId = @"kKeyEmployeeId";
</code>```

答:
You can follow this steps

1) set the session

```<code>if ([WCSession isSupported])
{
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
}
</code>```

2) Prepare data dictionary and send it with below method

```<code>[WCSession defaultSession] sendMessage:dataDict replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {

            //You task on completion

        } errorHandler:^(NSError * _Nonnull error) {

            if (error)
            {
                //Handle the error
            }
        }];
</code>```

3) And in watch app code
You can set delegate method

```<code> - (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message replyHandler:(void(^)(NSDictionary<NSString *, id> *replyMessage))replyHandler
    {
          //Handle the response
    }
</code>```

Body:
I've been through a ton of SO posts, and this USED to work, but it stopped working. I'm not sure what happened. I developed this iPhone+WatchKit app with watchOS 1.0 and everything worked fine.

I've upgraded my app, project, and Apple Watch to watchOS 2.0, and now I can't get any data via NSUserDefaults using my App Group.

App Groups is enabled in Xcode on the host App, and WatchKit Extension. I even tried turning it on for the WatchKit App as well.

My group name is called "group.com.mycompany.myapp" (with my real company name and app name) and it's selected on all of the targets.

I've confirmed the Build settings for my host app and WatchKit extension reference the entitlements files and I've checked that those entitlements files contain the app groups security option for my chosen app group.

I've made sure the bundle identifiers are different for the host app, watchkit extension, and watchkit app. I use "com.mycompany.myapp", "com.mycompany.myapp.watchkitextension", and "com.mycompany.myapp.watchkitapp", respectively.

Here are some screenshots of my Xcode config for the host app, watchkit extension, and watchkit app, just in case:

Here is the code in my host app that is able to read the data properly:

NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:kAppGroupName];
NSLog(@"app defaults: %@", [defaults dictionaryRepresentation]);

That produces this in my console, with kKeyEmployeeId and kKeyStoreNumber being the data that I'm trying to share between the host and watch.

2015-12-13 13:51:35.618 MyApp[27516:16126253] app defaults: {
    AppleLanguages =     (
        "en-US",
        en
    );
    INNextHearbeatDate = "472211882.83309";
    NSInterfaceStyle = macintosh;
    NSLanguages =     (
        "en-US",
        en
    );
    "com.apple.content-rating.AppRating" = 1000;
    "com.apple.content-rating.ExplicitBooksAllowed" = 1;
    "com.apple.content-rating.ExplicitMusicPodcastsAllowed" = 1;
    "com.apple.content-rating.MovieRating" = 1000;
    "com.apple.content-rating.TVShowRating" = 1000;
    kKeyEmployeeId = Kenny;
    kKeyStoreNumber = 001;
}

In my WatchKit Extension, I have the same code, but it doesn't provide me the two key:value pairs that I need:

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];

    NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:kAppGroupName];
    NSLog(@"defaults: %@", [defaults dictionaryRepresentation]);

}

It produces this, which is very similar to the one above, but without the two keys I really need:

2015-12-13 13:28:29.840 MyApp WatchKit Extension[720:322804] defaults: {
    AppleLanguages =     (
        en
    );
    INNextHearbeatDate = "472434306.599217";
    NSInterfaceStyle = macintosh;
    NSLanguages =     (
        en
    );
    "com.apple.content-rating.AppRating" = 1000;
    "com.apple.content-rating.ExplicitBooksAllowed" = 1;
    "com.apple.content-rating.ExplicitMusicPodcastsAllowed" = 1;
    "com.apple.content-rating.MovieRating" = 1000;
    "com.apple.content-rating.TVShowRating" = 1000;
}

The kAppGroupName and other constants are defined like so:

NSString * const kAppGroupName = @"group.com.inadaydevelopment.MyApp";
NSString * const kKeyStoreNumber = @"kKeyStoreNumber";
NSString * const kKeyEmployeeId = @"kKeyEmployeeId";

Body:
You can follow this steps

1) set the session

if ([WCSession isSupported])
{
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
}

2) Prepare data dictionary and send it with below method

[WCSession defaultSession] sendMessage:dataDict replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {

            //You task on completion

        } errorHandler:^(NSError * _Nonnull error) {

            if (error)
            {
                //Handle the error
            }
        }];

3) And in watch app code
You can set delegate method

 - (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message replyHandler:(void(^)(NSDictionary<NSString *, id> *replyMessage))replyHandler
    {
          //Handle the response
    }


问:
Can't load CSS file after form submitted in node js
Let me give more details first. I use node's nodemailer to send emails from submitted info on form. When I had one recipient and one html body, which sends it all at once, was working fine. But when I put mailOptions2 in a for loop so I'm able to send the email with the recipients and html bodies that are in different arrays. Then it still sends the emails and html contents differently how I wanted. But when the form is submitted, in the /send state it keeps loading and it ends up only loading the page's raw html, no css. I get this error:

```<code>Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:489:11)
    at ServerResponse.setHeader (_http_outgoing.js:496:3)
    at ServerResponse.header (C:\Users\Ahmet Ömer\Desktop\Repairtechnician\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\Ahmet Ömer\Desktop\Repairtechnician\node_modules\express\lib\response.js:170:12)
    at done (C:\Users\Ahmet Ömer\Desktop\Repairtechnician\node_modules\express\lib\response.js:1004:10)
    at Immediate._onImmediate (C:\Users\Ahmet Ömer\Desktop\Repairtechnician\node_modules\express-handlebars\lib\utils.js:26:13)
    at runCallback (timers.js:781:20)
    at tryOnImmediate (timers.js:743:5)
    at processImmediate [as _immediateCallback] (timers.js:714:5)
</code>```

I know there were posts on this error but could not know how to solve it in my case, since I am fairly beginner.

Nodejs:

```<code>app2.engine('handlebars', exphbs2());
app2.set('view engine', 'handlebars');

// Static folder
app2.use('/public', express2.static(path2.join(__dirname, 'public')));
app2.use('/', express2.static(path2.join(__dirname, '')));

// Body Parser Middleware
app2.use(bodyParser2.urlencoded({ extended: false }));
app2.use(bodyParser2.json());

app2.get('/', (req, res) => {
  res.render('services');
});

app2.post('/send', (req, res) => {
  let mailList = ['xyz', 'xyz@gmail.com'];
  let outputs = [
    `
    <div>
    </div>
  `,
  `
   <div>
   </div>
`];

  // create reusable transporter object using the default SMTP transport
  let transporter2 = nodemailer2.createTransport({
    service: 'gmail',
    port: 25,
    secure: false,
    auth: {
        user: 'xyz@gmail.com', // senders email
        pass: 'xyz' // senders password
    },
    tls:{
      rejectUnauthorized:false
    }
  });

  for ( var i = 0; i < mailList.length; i++) {
      // setup email data with raw html
      let mailOptions2 = {
        from: '"xyz" <xyz@info.com>', // sender address
        to: mailList[i], // receiver or receivers
        subject: 'xyz', // Subject line
        html: outputs[i] // html body
    };

        // send mail with defined transport object
      transporter2.sendMail(mailOptions2, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        console.log('Preview URL: %s', nodemailer2.getTestMessageUrl(info));

        res.render('services', {msg2:'xyz'});
    });
  }
});
</code>```

As I said, if I had not used a for loop for mailOptions2 to pass different values to specified areas, it would've worked just fine.

Here's my structure of mentioned files if might help:

```<code>server.js
services.html
public
   css
      styles.css
</code>```

答:
You can't call res.render() multiple time because res.render send the compiled html to the client. So you have to call res.render only when you want to send the final response to your client.

For this case you can use Promise to manage the sendMail callback:

```<code>// init this array outside the for loop
let sendMailPromises = [];

// this is inside the for loop
let promise = new Promise((resolve, reject) => {
    transporter2.sendMail(mailOptions2, (err, infos) => {
        if(err) reject(err)

        console.log('Mail sent %s', info.messageId);
        console.info('Preview URL: %s', nodeMailer2.getTest(info));
        resolve(infos)
    });

});
sendMailPromises.push(promise);

// this is after (and outside) the for loop.
Promise.all(sendMailPromises)
    .then(() => {
        res.render(mailOptions, {msg2: '...'})
    }).catch((err) => {
        console.error(err);
    })
</code>```

Body:
Let me give more details first. I use node's nodemailer to send emails from submitted info on form. When I had one recipient and one html body, which sends it all at once, was working fine. But when I put mailOptions2 in a for loop so I'm able to send the email with the recipients and html bodies that are in different arrays. Then it still sends the emails and html contents differently how I wanted. But when the form is submitted, in the /send state it keeps loading and it ends up only loading the page's raw html, no css. I get this error:

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:489:11)
    at ServerResponse.setHeader (_http_outgoing.js:496:3)
    at ServerResponse.header (C:\Users\Ahmet Ömer\Desktop\Repairtechnician\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\Ahmet Ömer\Desktop\Repairtechnician\node_modules\express\lib\response.js:170:12)
    at done (C:\Users\Ahmet Ömer\Desktop\Repairtechnician\node_modules\express\lib\response.js:1004:10)
    at Immediate._onImmediate (C:\Users\Ahmet Ömer\Desktop\Repairtechnician\node_modules\express-handlebars\lib\utils.js:26:13)
    at runCallback (timers.js:781:20)
    at tryOnImmediate (timers.js:743:5)
    at processImmediate [as _immediateCallback] (timers.js:714:5)

I know there were posts on this error but could not know how to solve it in my case, since I am fairly beginner.

Nodejs:

app2.engine('handlebars', exphbs2());
app2.set('view engine', 'handlebars');

// Static folder
app2.use('/public', express2.static(path2.join(__dirname, 'public')));
app2.use('/', express2.static(path2.join(__dirname, '')));

// Body Parser Middleware
app2.use(bodyParser2.urlencoded({ extended: false }));
app2.use(bodyParser2.json());

app2.get('/', (req, res) => {
  res.render('services');
});

app2.post('/send', (req, res) => {
  let mailList = ['xyz', 'xyz@gmail.com'];
  let outputs = [
    `

  `,
  `

`];

  // create reusable transporter object using the default SMTP transport
  let transporter2 = nodemailer2.createTransport({
    service: 'gmail',
    port: 25,
    secure: false,
    auth: {
        user: 'xyz@gmail.com', // senders email
        pass: 'xyz' // senders password
    },
    tls:{
      rejectUnauthorized:false
    }
  });

  for ( var i = 0; i < mailList.length; i++) {
      // setup email data with raw html
      let mailOptions2 = {
        from: '"xyz" <xyz@info.com>', // sender address
        to: mailList[i], // receiver or receivers
        subject: 'xyz', // Subject line
        html: outputs[i] // html body
    };

        // send mail with defined transport object
      transporter2.sendMail(mailOptions2, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        console.log('Preview URL: %s', nodemailer2.getTestMessageUrl(info));

        res.render('services', {msg2:'xyz'});
    });
  }
});

As I said, if I had not used a for loop for mailOptions2 to pass different values to specified areas, it would've worked just fine.

Here's my structure of mentioned files if might help:

server.js
services.html
public
   css
      styles.css

Body:
You can't call res.render() multiple time because res.render send the compiled html to the client. So you have to call res.render only when you want to send the final response to your client.

For this case you can use Promise to manage the sendMail callback:

// init this array outside the for loop
let sendMailPromises = [];

// this is inside the for loop
let promise = new Promise((resolve, reject) => {
    transporter2.sendMail(mailOptions2, (err, infos) => {
        if(err) reject(err)

        console.log('Mail sent %s', info.messageId);
        console.info('Preview URL: %s', nodeMailer2.getTest(info));
        resolve(infos)
    });

});
sendMailPromises.push(promise);

// this is after (and outside) the for loop.
Promise.all(sendMailPromises)
    .then(() => {
        res.render(mailOptions, {msg2: '...'})
    }).catch((err) => {
        console.error(err);
    })


问:
How do you poll AWS Simple Queue Service?
The title may be slightly misleading, because I know how to make a call to SQS and receive one or more visible messages. But where do you put the polling code if you're developing a web application that will be deployed to Elastic Beanstalk? I mean, you can't deploy a windows service to EB and you can't make a web application run a poll in the background natively. So what do you do and where do you put it?</p>

答:
You can receive messages Asynchronously using SQS and you do not need to write code to poll queue. Amazon has library which acts as a wrapper to make SQS JMS compliant. You can register your message listener and function will be called whenever a new message arrives at Queue.

Using JMS with Amazon SQS

[Example, Please have a look at Receive Message Asynchronously]


问:
Is it possible to 'bin' values by date to get a total per 2 weeks in ggplot2 and R?
I have a dataframe which is a history of runs.  Some fo the variables include a date (in POSIXct) and a value for that run (here = size).  I want to produce various graphs showing a line based on the total fo the size column for a particular date range.  Ideally I'd like to use the same dataset and change from totals per week, 2 weeks, month quarter.

Here's an example dataset;

```<code>require(ggplot2)
set.seed(666)

seq(Sys.time()-(365*24*60*60), Sys.time(), by="day")

foo<-data.frame(Date=sample(seq(today-(365*24*60*60), today, by="day"),50, replace=FALSE),
        value=rnorm(50, mean=100, sd=25),
        type=sample(c("Red", "Blue", "Green"), 50, replace=TRUE))
</code>```

I can create this plot which shows individual values;

```<code>ggplot(data=foo, aes(x=Date, y=value, colour=type))+stat_summary(fun.y=sum, geom="line")
</code>```

Or I can do this to show a sum per Month;

```<code>ggplot(data=foo, aes(x=format(Date, "%m %y"), y=value, colour=type))+stat_summary(fun.y=sum, geom="line", aes(group=type))
</code>```

However it gets more complicated to do sums per quarter / 2 weeks etc.  Ideally I'd like something like the stat_bin and stat_summary combined so I could specify a binwidth (or have ggplot make a best guess based on the range)

Am I missing something obvious, or is this just not possible ?

答:
The chron package could be very useful to convert dates in a way not covered in the "basic" format command. But the latter can also do smart things (like the strftime in PHP), e.g.:

Show given year and month of a date:

```<code>format(foo$Date, "%Y-%m")
</code>```

And with package chron showing the appropriate quarter of year:

```<code>quarters(foo$Date)
</code>```

To compute the 2-weeks period, you might not find a complete function, but could be computed from a the week number easily, e.g.:

```<code>floor(as.numeric(format(foo$Date, "%V"))/2)+1
</code>```

After computing the new variables in the dataframe, you could easily plot your data just like in your original example.

Body:
I have a dataframe which is a history of runs.  Some fo the variables include a date (in POSIXct) and a value for that run (here = size).  I want to produce various graphs showing a line based on the total fo the size column for a particular date range.  Ideally I'd like to use the same dataset and change from totals per week, 2 weeks, month quarter.

Here's an example dataset;

require(ggplot2)
set.seed(666)

seq(Sys.time()-(365*24*60*60), Sys.time(), by="day")

foo<-data.frame(Date=sample(seq(today-(365*24*60*60), today, by="day"),50, replace=FALSE),
        value=rnorm(50, mean=100, sd=25),
        type=sample(c("Red", "Blue", "Green"), 50, replace=TRUE))

I can create this plot which shows individual values;

ggplot(data=foo, aes(x=Date, y=value, colour=type))+stat_summary(fun.y=sum, geom="line")

Or I can do this to show a sum per Month;

ggplot(data=foo, aes(x=format(Date, "%m %y"), y=value, colour=type))+stat_summary(fun.y=sum, geom="line", aes(group=type))

However it gets more complicated to do sums per quarter / 2 weeks etc.  Ideally I'd like something like the stat_bin and stat_summary combined so I could specify a binwidth (or have ggplot make a best guess based on the range)

Am I missing something obvious, or is this just not possible ?

Body:
The chron package could be very useful to convert dates in a way not covered in the "basic" format command. But the latter can also do smart things (like the strftime in PHP), e.g.:

Show given year and month of a date:

format(foo$Date, "%Y-%m")

And with package chron showing the appropriate quarter of year:

quarters(foo$Date)

To compute the 2-weeks period, you might not find a complete function, but could be computed from a the week number easily, e.g.:

floor(as.numeric(format(foo$Date, "%V"))/2)+1

After computing the new variables in the dataframe, you could easily plot your data just like in your original example.


问:
Regular expression to validate Customer name of format ABC PVT (ltd)
I have to validate a customer name. The following are the valid criteria  for customer name

A customer name can start with letters digits

It can have    alphabets digits  (.) hyphen(-) and ampersand
or ( in between

It should end with alphabets number or can have spaces. or
    closing ')'

Valid names example 'ABC pvt ltd', 'A.B.C' 'L&T'

Ideally  It should match  only if parenthesis open onced should be closed.

This is my regex

```<code><code>
      (^[a-zA-Z\s][a-zA-Z0-9-&\'\\.\\(\s]+[a-zA-Z0-9\s\\.\\)]
</code>
</code>```

Can this be made more elegant?

Issue with current regex

It matches E(test

The regex is very long

Body:
I have to validate a customer name. The following are the valid criteria  for customer name

A customer name can start with letters digits

It can have    alphabets digits  (.) hyphen(-) and ampersand
or ( in between

It should end with alphabets number or can have spaces. or
    closing ')'

Valid names example 'ABC pvt ltd', 'A.B.C' 'L&T'

Ideally  It should match  only if parenthesis open onced should be closed.

This is my regex

      (^[a-zA-Z\s][a-zA-Z0-9-&\'\\.\\(\s]+[a-zA-Z0-9\s\\.\\)]

Can this be made more elegant?

Issue with current regex

It matches E(test

The regex is very long

Body:
You violated your own first rule even, you may go with:

(?i)^[a-z0-9]([a-z0-9 (.&-](?(?<=\()(?=[^()]++\)$)))*[a-z0-9) ]$

Live demo


问:
How to rename a DynamoDB table
I have DynamoDB table and I would like to rename it. There does not seems to be any commands or options to rename a table. Has anybody renamed a table before?</p>

答:
You should be able to achieve this using on demand backup / restore functionality.

Check out a walk through on backing up a table, and restore to a new table:

https://www.abhayachauhan.com/2017/12/dynamodb-scheduling-on-demand-backups/

Title: How to rename a DynamoDB table