问:
Determine the AWS lambda name on runtime in Java
I really like the approach of calling AWS lambdas from Java described in this blog post.

However, if I have 3 environments (int/test/live), and on each of them the lambda has a slightly different name (created via cloudformation), I can't think of a way to have one interface, and call lambda with a different name depending on the environment.

I am using Spring, and so if I could do something like:

```<code>@Component
interface MyLambdas {
    @Value("${name}")
    String name;

    @LambdaFunction(name = name)
    String callMyLambda(String stuff);
}

//and then
service = LambdaInvokerFactory.build(MyLambdas.class, lambda);
</code>```

But obviously I can't do this on an interface, this won't be a bean! Is there any way at all to do this? I feel like I hit a brick wall...

Right now I am calling lambda "the old way":

```<code>String readLambdaName = "My_Lambda";

ObjectMapper objectMapper = new ObjectMapper();
AWSLambdaClient lambda = new AWSLambdaClient();
lambda.configureRegion(Regions.EU_WEST_1);

String json = objectMapper.writeValueAsString(request);
InvokeRequest req = new InvokeRequest()
        .withFunctionName(readLambdaName)
        .withPayload(json);

InvokeResult res = lambda.invoke(req);
int result = objectMapper.readTree(res.getPayload().array()).asInt();
</code>```

Obviously with some exception handling here and there. This is not as nice of a solution tho...

For anyone following this, I have submitted an issue and a solution on aws-sdk github. hopefully something similar to my solution will make it to the next release of the SDK...

答:
I resolved it by overriding the function name using "lambdaFunctionNameResolver".

```<code>//my lambda interface
public interface MyLambdaService {
    @LambdaFunction
    ApiGatewayProxyResponse execute(ApiGatewayRequest bit);
}
</code>```

this is how to create the lambda client:

```<code>MyLambdaService lambdaService = LambdaInvokerFactory.builder().lambdaClient(AWSLambdaClientBuilder.defaultClient())
                    .lambdaFunctionNameResolver((method, annotation, config) -> "ENV_SPECIFIC_FUNCTION_NAME").build(MyLambdaService.class);
</code>```

or

My method call "generalConfigHelper.getString("function_name"))" figure outs the correct function name according to the env (dev/qa/prod).

```<code>MyLambdaService lambdaService = LambdaInvokerFactory.builder().lambdaClient(AWSLambdaClientBuilder.defaultClient())
                .lambdaFunctionNameResolver((method, annotation, config) -> generalConfigHelper.getString("function_name")).build(MyLambdaService.class);
</code>```

Official aws issue: https://github.com/aws/aws-sdk-java/pull/603

Body:
I really like the approach of calling AWS lambdas from Java described in this blog post.

However, if I have 3 environments (int/test/live), and on each of them the lambda has a slightly different name (created via cloudformation), I can't think of a way to have one interface, and call lambda with a different name depending on the environment.

I am using Spring, and so if I could do something like:

@Component
interface MyLambdas {
    @Value("${name}")
    String name;

    @LambdaFunction(name = name)
    String callMyLambda(String stuff);
}

//and then
service = LambdaInvokerFactory.build(MyLambdas.class, lambda);

But obviously I can't do this on an interface, this won't be a bean! Is there any way at all to do this? I feel like I hit a brick wall...

Right now I am calling lambda "the old way":

String readLambdaName = "My_Lambda";

ObjectMapper objectMapper = new ObjectMapper();
AWSLambdaClient lambda = new AWSLambdaClient();
lambda.configureRegion(Regions.EU_WEST_1);

String json = objectMapper.writeValueAsString(request);
InvokeRequest req = new InvokeRequest()
        .withFunctionName(readLambdaName)
        .withPayload(json);

InvokeResult res = lambda.invoke(req);
int result = objectMapper.readTree(res.getPayload().array()).asInt();

Obviously with some exception handling here and there. This is not as nice of a solution tho...

For anyone following this, I have submitted an issue and a solution on aws-sdk github. hopefully something similar to my solution will make it to the next release of the SDK...

Body:
I resolved it by overriding the function name using "lambdaFunctionNameResolver".

//my lambda interface
public interface MyLambdaService {
    @LambdaFunction
    ApiGatewayProxyResponse execute(ApiGatewayRequest bit);
}

this is how to create the lambda client:

MyLambdaService lambdaService = LambdaInvokerFactory.builder().lambdaClient(AWSLambdaClientBuilder.defaultClient())
                    .lambdaFunctionNameResolver((method, annotation, config) -> "ENV_SPECIFIC_FUNCTION_NAME").build(MyLambdaService.class);

or

My method call "generalConfigHelper.getString("function_name"))" figure outs the correct function name according to the env (dev/qa/prod).

MyLambdaService lambdaService = LambdaInvokerFactory.builder().lambdaClient(AWSLambdaClientBuilder.defaultClient())
                .lambdaFunctionNameResolver((method, annotation, config) -> generalConfigHelper.getString("function_name")).build(MyLambdaService.class);

Official aws issue: https://github.com/aws/aws-sdk-java/pull/603


来源: stackexchange

问:
While submitting flink job through savepoint it's throwing java.io.FileNotFoundException: (Access is denied) in windows server 2012
I have given full access to the savepoint folder then also it's getting access denied exception, but in Linux it's working as expected.</p>

答:
Flink savepoint command is expecting full path of the file including Filename.
So i have changed accordingly ,now it's working in both windows and linux.</p>

ContentLicense: CC BY-SA 3.0


问:
Can't change css modal bootstrap. Modal fade in bootstrap auto add padding-left 15px
I created this question but there is no answer. so i recreated.

I use modal bootstrap. When no scroll bar appears, everything is normal. But when I add more data, modal auto add style="display: block; padding-left: 15px;":

```<code><div class="modal fade in" id="tags_modal" role="dialog" style="display: block; padding-left: 15px;">
</code>```

I try change it but I can't.
My code: https://jsbin.com/fusinoc/1/edit?html,css,output

My layout:
my layout

答:
Instead of adding styles inline, add below code in your css.

```<code>#myModal2 {
  padding-left: 0 !important;
}
</code>```

working bin

Hope this helps :)

ContentLicense: CC BY-SA 4.0

Body:
I created this question but there is no answer. so i recreated.

I use modal bootstrap. When no scroll bar appears, everything is normal. But when I add more data, modal auto add style="display: block; padding-left: 15px;":

I try change it but I can't.
My code: https://jsbin.com/fusinoc/1/edit?html,css,output

My layout:
my layout

Body:
Instead of adding styles inline, add below code in your css.

#myModal2 {
  padding-left: 0 !important;
}

working bin

Hope this helps :)


问:
Potentially dangerous script with forms['formName'].submit but not with <input type=submit>
I had just fixed a bunch of issues I was having in some forms that contained rich text editors (CK Editor) and getting XSS errors ("Potentially dangerous script..."). It was all working after setting the editors to HTML encode output.

Then I switched my submit buttons (<input type=submit />) to anchor tags with a javascript submit (submit) and it started giving me the errors again.

Somehow it seems the javascript submit doesn't cause the encoding to take place. Does anyone know why this might be happening and how I could fix it?

答: Try setting the htmlEncodeOutput property first.</p>

ContentLicense: CC BY-SA 2.5


问:
Firebase auth state sharing between apps
I have a firebase project that contains multiple android apps and I use firebase authentication like email, google and Facebook. Now when users sign in into one of our app can I share that Sign In with the another app that user installs which is also present in the same firebase project.</p>

答:
Yes you can use same authentication in every app in same Project. it doesn't matter if its iOS/Android or two or many android apps as long as those are in same Firebase Project.

Here is one use case for you:

I have 4 Apps two Android and two iOS Apps

Bundle IDS are like this :

Demo_iOS1 : com.ios.demo1

Demo_iOS2 : com.ios.demo2

Note: All Four apps are in the same Firebase Project

Now If I Create User IN Demo1 iOS app, then I can login using that user credentials in all other 3 apps same goes for other conditions.


问:
salesforce application create a generic xpath using selenium webdriver with java
This is the salesforce application, i want to click the admin menu, so below is the source

```<code><li class="slds-context-bar__item slds-shrink-none" is="one-app-nav-bar-item-root">
<a class="slds-context-bar__label-action" href="#/n/admin" title="Admin" tabindex="0">
<span class="slds-truncate">Admin</span>
</a>
</li>
</code>```

i framed below xpath using contains, but its not working

```<code>driver.findElement(By.xpath("//span[contains(.,'Admin')]"));
</code>```

I get the path from firepath/IDE, its working

```<code>@FindBy(how =How.XPATH, using = "//header[@id='oneHeader']/div[3]/one-appnav/div/one-app-nav-bar/nav/ul/li[2]/a/span")
</code>```

but i want to frame generic xpath with above html either using menu name or title (admin), please guid me, because in feature if any ul or li tag added in between its not working

答:
As you are trying to identify the node with text as Admin you can use the following line of code :

```<code>driver.findElement(By.xpath("//a[@class='slds-context-bar__label-action' and @title='Admin']/span[@class='slds-truncate']"));
</code>```

Body:
This is the salesforce application, i want to click the admin menu, so below is the source

Admin

i framed below xpath using contains, but its not working

driver.findElement(By.xpath("//span[contains(.,'Admin')]"));

I get the path from firepath/IDE, its working

@FindBy(how =How.XPATH, using = "//header[@id='oneHeader']/div[3]/one-appnav/div/one-app-nav-bar/nav/ul/li[2]/a/span")

but i want to frame generic xpath with above html either using menu name or title (admin), please guid me, because in feature if any ul or li tag added in between its not working

Body:
As you are trying to identify the node with text as Admin you can use the following line of code :

driver.findElement(By.xpath("//a[@class='slds-context-bar__label-action' and @title='Admin']/span[@class='slds-truncate']"));


问:
How to minimize load time of a landing page
I'm honestly confused about where to start with minimizing the load time of a website i'm building - https://projectrhea.herokuapp.com/ . Currently takes around 9 seconds to load the website which I want to try and bring down to sub 3 seconds.

I've done a diagnostic test, shown here https://www.webpagetest.org/result/171113_T2_851758db144ac117ab4e986a3798b1b5/1/details/#waterfall_view_step1 .

From what I can see there are three main reasons it would be taking awhile to load.

The first is the javascript.

I only need a small amount of it to run the site but I am very
confused about how to separate the code I need from the code I don't
need. I use it for the banner to show multiple phrases underneath the
banner that I would rather keep.

The second part is the shear amount of CSS files I'm drawing from.

I used a template to begin the site (it was a good way for me to learn
how to design the site). Now I think this has meant there is way too
many css and other files connected to this landing page.

The third part is the video file I have.

I would love to keep this
video as I just like how it fits in the site. I'll try and minimize
the file size after I have worked out the above issues.

This is my first real time trying to solve an issue like this and I would really appreciate the knowledge a more experienced coder could bring to this. Thanks!

答:
Trying to address the specific points raised by you.

The first is the javascript.

I only need a small amount of it to run the site but I am very
  confused about how to separate the code I need from the code I don't
  need. I use it for the banner to show multiple phrases underneath the
  banner that I would rather keep.

Your JS files are not minified. Please make sure you are minifying your js files and order as suggested by Ante Jablan Adamović.

The second part is the shear amount of CSS files I'm drawing from.

I used a template to begin the site (it was a good way for me to learn
  how to design the site). Now I think this has meant there is way too
  many css and other files connected to this landing page.

You should combine and minify all the CSS files.

For minification and combining of JS and CSS you can use gulp.
https://github.com/gulpjs/gulp

The third part is the video file I have.

I would love to keep this video as I just like how it fits in the
  site. I'll try and minimize the file size after I have worked out the
  above issues.

I can see that you are serving some resources through S3. See if you can move your video as well to S3 and serve it through cloudfront.


问:
Python: define arguments of a function which include the arguments of the other function
Please let me know if there are duplicated ones (I believe there are) and I will remove the post. I am just not sure about the jargon for this question.

When writing a new function augmented_func which contains the other function already defined original_func, I am trying to avoid defining arguments that are already in original_func:

```<code>def original_func(a1, a2 ,a3):
    print(a1, a2, a3)

def augmented_func(b, a1, a2, a3):
    print(original_func(a1, a2, a3), b)
</code>```

How do I avoid writing a's when defining augmented_func, and make it simpler especially when the number of arguments for original_func is more than, say, three in the example?

答:
I think what you looking for is something like

```<code>def original_func(a1, a2 ,a3):
    print(a1, a2, a3)

def augmented_func(b, *args):
    print(original_func(*args), b)
</code>```

you can call it then as augmented_func(1, 2, 3, 4)

*args and **kwargs is a good way for passing the variable number of arguments and passing them to other internal function calls.

Python docs for further info.

Body:
Please let me know if there are duplicated ones (I believe there are) and I will remove the post. I am just not sure about the jargon for this question.

When writing a new function augmented_func which contains the other function already defined original_func, I am trying to avoid defining arguments that are already in original_func:

def original_func(a1, a2 ,a3):
    print(a1, a2, a3)

def augmented_func(b, a1, a2, a3):
    print(original_func(a1, a2, a3), b)

How do I avoid writing a's when defining augmented_func, and make it simpler especially when the number of arguments for original_func is more than, say, three in the example?

Body:
I think what you looking for is something like

def original_func(a1, a2 ,a3):
    print(a1, a2, a3)

def augmented_func(b, *args):
    print(original_func(*args), b)

you can call it then as augmented_func(1, 2, 3, 4)

*args and **kwargs is a good way for passing the variable number of arguments and passing them to other internal function calls.

Python docs for further info.


问:
How to display error message for field validation in SugarCRM?
Using SugarCRM v6.5.26. I need to display an inline error message instead of "alert" for validation of the last name.

JavaScript file path (sample code is given):

/custom/modules/Contacts/js/editview.js

```<code>$('input#last_name').on('change', function () {
      var node = $(this);
      node.val(node.val().replace(/[^a-z]/g, ''));
      alert("Please enter only charcter");
});
</code>```

Again, I don't want to show an alert, only inline message.

答:
This is something related to javsacrip/jquery error handling and you can find many logics on google as well.

Try following code:

```<code>$('input#last_name').on('change', function () {
    handleLastNameValidation();
    return false;
});

 var clickAttr = $("#SAVE_HEADER").attr("onclick");
 $("#SAVE_HEADER").attr("onclick","return handleLastNameValidation(); "+clickAttr);

function handleLastNameValidation(){

    clear_all_errors();

    var node = $('input#last_name');
        current_val = node.val();
        trimmed_val = node.val().replace(/[^a-z]/g, '');

    if( current_val != trimmed_val || trimmed_val =='')
    {
        add_error_style('EditView', 'last_name', 'Please enter correct value for last name',true);
        return false;
    }
    else
    {
        return true;
    }

    return false;
}
</code>```

Body:
Using SugarCRM v6.5.26. I need to display an inline error message instead of "alert" for validation of the last name.

JavaScript file path (sample code is given):

/custom/modules/Contacts/js/editview.js

$('input#last_name').on('change', function () {
      var node = $(this);
      node.val(node.val().replace(/[^a-z]/g, ''));
      alert("Please enter only charcter");
});

Again, I don't want to show an alert, only inline message.

Body:
This is something related to javsacrip/jquery error handling and you can find many logics on google as well.

Try following code:

$('input#last_name').on('change', function () {
    handleLastNameValidation();
    return false;
});

 var clickAttr = $("#SAVE_HEADER").attr("onclick");
 $("#SAVE_HEADER").attr("onclick","return handleLastNameValidation(); "+clickAttr);

function handleLastNameValidation(){

    clear_all_errors();

    var node = $('input#last_name');
        current_val = node.val();
        trimmed_val = node.val().replace(/[^a-z]/g, '');

    if( current_val != trimmed_val || trimmed_val =='')
    {
        add_error_style('EditView', 'last_name', 'Please enter correct value for last name',true);
        return false;
    }
    else
    {
        return true;
    }

    return false;
}


问:
Spring Security - multiple configurations - add LogoutHandler
I have a spring-boot application using spring-security. The security configuration is split into multiple instances of WebSecurityConfigurerAdapter.

I have one where I configure logout in general:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {

    // configure logout
    http
            .logout()
            .logoutUrl("/logout")
            .invalidateHttpSession(true)
            .addLogoutHandler((request, response, authentication) -> {
                System.out.println("logged out 1!");
            })
            .permitAll();

    // ... more security configuration, e.g. login, CSRF, rememberme
}
</code>```

And there is another WebSecurityConfigurerAdapter, where I want to do almost nothing, except adding another LogoutHandler:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {

    // configure logout
    http
            .logout()
            .logoutUrl("/logout")
            .addLogoutHandler((request, response, authentication) -> {
                System.out.println("logged out 2!");
            });
}
</code>```

Both configure() methods are called. However, if I do log out, only the first LogoutHandler is called. Changing the @Order of both configurations does not change the result.

What is missing in my configuration?

答:
When you create several security configurations Spring Boot will create a separate SecurityFilterChain for each of them. See WebSecurity:

```<code>@Override
protected Filter performBuild() throws Exception {
    // ...
    for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : securityFilterChainBuilders) {
        securityFilterChains.add(securityFilterChainBuilder.build());
    }
    // ...
}
</code>```

When application gets logout request FilterChainProxy will return only one SecurityFilterChain:

```<code>private List<Filter> getFilters(HttpServletRequest request) {
    for (SecurityFilterChain chain : filterChains) {
        // Only the first chain that matches logout request will be used:
        if (chain.matches(request)) {
            return chain.getFilters();
        }
    }

    return null;
}
</code>```

If you really need modular security configuration I would suggest to create a separate security configuration for logout and other realms. You can define logout handlers as beans (using @Bean annotation) in different configuration classes and collect these handlers in logout configuration:

WebSecurityLogoutConfiguration.java

```<code>@Configuration
@Order(99)
public class WebSecurityLogoutConfiguration extends WebSecurityConfigurerAdapter {

    // ALL YOUR LOGOUT HANDLERS WILL BE IN THIS LIST
    @Autowired
    private List<LogoutHandler> logoutHandlers;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // configure only logout
        http
                .logout()
                .logoutUrl("/logout")
                .invalidateHttpSession(true)
                // USE CompositeLogoutHandler
                .addLogoutHandler(new CompositeLogoutHandler(logoutHandlers));
        http.csrf().disable(); // for demo purposes
    }
}
</code>```

WebSecurity1Configuration.java

```<code>@Configuration
@Order(101)
public class WebSecurity1Configuration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ... more security configuration, e.g. login, CSRF, rememberme
        http.authorizeRequests()
                .antMatchers("/secured/**")
                .authenticated();
    }

    // LOGOUT HANDLER 1
    @Bean
    public LogoutHandler logoutHandler1() {
        return (request, response, authentication) -> {
            System.out.println("logged out 1!");
        };
    }
}
</code>```

WebSecurity2Configuration.java

```<code>@Configuration
@Order(102)
public class WebSecurity2Configuration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**")
                .permitAll();
    }

    // LOGOUT HANDLER 2
    @Bean
    public LogoutHandler logoutHandler2() {
        return (request, response, authentication) -> {
            System.out.println("logged out 2!");
        };
    }
}
</code>```

Body:
I have a spring-boot application using spring-security. The security configuration is split into multiple instances of WebSecurityConfigurerAdapter.

I have one where I configure logout in general:

@Override
protected void configure(HttpSecurity http) throws Exception {

    // configure logout
    http
            .logout()
            .logoutUrl("/logout")
            .invalidateHttpSession(true)
            .addLogoutHandler((request, response, authentication) -> {
                System.out.println("logged out 1!");
            })
            .permitAll();

    // ... more security configuration, e.g. login, CSRF, rememberme
}

And there is another WebSecurityConfigurerAdapter, where I want to do almost nothing, except adding another LogoutHandler:

@Override
protected void configure(HttpSecurity http) throws Exception {

    // configure logout
    http
            .logout()
            .logoutUrl("/logout")
            .addLogoutHandler((request, response, authentication) -> {
                System.out.println("logged out 2!");
            });
}

Both configure() methods are called. However, if I do log out, only the first LogoutHandler is called. Changing the @Order of both configurations does not change the result.

What is missing in my configuration?

Body:
When you create several security configurations Spring Boot will create a separate SecurityFilterChain for each of them. See WebSecurity:

@Override
protected Filter performBuild() throws Exception {
    // ...
    for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : securityFilterChainBuilders) {
        securityFilterChains.add(securityFilterChainBuilder.build());
    }
    // ...
}

When application gets logout request FilterChainProxy will return only one SecurityFilterChain:

private List<Filter> getFilters(HttpServletRequest request) {
    for (SecurityFilterChain chain : filterChains) {
        // Only the first chain that matches logout request will be used:
        if (chain.matches(request)) {
            return chain.getFilters();
        }
    }

    return null;
}

If you really need modular security configuration I would suggest to create a separate security configuration for logout and other realms. You can define logout handlers as beans (using @Bean annotation) in different configuration classes and collect these handlers in logout configuration:

WebSecurityLogoutConfiguration.java

@Configuration
@Order(99)
public class WebSecurityLogoutConfiguration extends WebSecurityConfigurerAdapter {

    // ALL YOUR LOGOUT HANDLERS WILL BE IN THIS LIST
    @Autowired
    private List<LogoutHandler> logoutHandlers;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // configure only logout
        http
                .logout()
                .logoutUrl("/logout")
                .invalidateHttpSession(true)
                // USE CompositeLogoutHandler
                .addLogoutHandler(new CompositeLogoutHandler(logoutHandlers));
        http.csrf().disable(); // for demo purposes
    }
}

WebSecurity1Configuration.java

@Configuration
@Order(101)
public class WebSecurity1Configuration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ... more security configuration, e.g. login, CSRF, rememberme
        http.authorizeRequests()
                .antMatchers("/secured/**")
                .authenticated();
    }

    // LOGOUT HANDLER 1
    @Bean
    public LogoutHandler logoutHandler1() {
        return (request, response, authentication) -> {
            System.out.println("logged out 1!");
        };
    }
}

WebSecurity2Configuration.java

@Configuration
@Order(102)
public class WebSecurity2Configuration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**")
                .permitAll();
    }

    // LOGOUT HANDLER 2
    @Bean
    public LogoutHandler logoutHandler2() {
        return (request, response, authentication) -> {
            System.out.println("logged out 2!");
        };
    }
}


问:
skew normal distribution in multivariate case using matlab
how can we generate random numbers using skew normal distribution in multivariate case?</p>

答:
Use the rsn function from the sn package in R (as I think from another question that R will work for you also):

```<code>rsn(n=100, location=1.256269, scale=1.605681, shape=5)
</code>```

Will generate 100 (n) random numbers from a skew-normal distribution with the required location, scale and shape. Use higher sample size for plotting, e.g.:

```<code>hist(rsn(n=10000, location=1.256269, scale=1.605681, shape=5))
</code>```

Body:
Use the rsn function from the sn package in R (as I think from another question that R will work for you also):

rsn(n=100, location=1.256269, scale=1.605681, shape=5)

Will generate 100 (n) random numbers from a skew-normal distribution with the required location, scale and shape. Use higher sample size for plotting, e.g.:

hist(rsn(n=10000, location=1.256269, scale=1.605681, shape=5))


问:
Stream to RDD to DataFrame to CSV
I am really getting desperate here.

What I am trying to do is, capturing a stream, aggregated stream data for some seconds, and after save it as a CSV file.

```<code>val sparkSession : SparkSession = SparkSession.builder()
  .master("local[*]")
  .appName("Streaming")
  .config(conf)
  //.enableHiveSupport()
  .getOrCreate()
</code>```

So, I am capturing the stream

```<code>val lines = streamingContext.socketTextStream(HOST, PORT)
val linesMessage = lines.map(_.split(DELIMITER)(1))
</code>```

and count the incidents

```<code>val counts = linesMessage.map(tag => (tag, 1))
        .reduceByKeyAndWindow({ (x, y) => x + y }, { (x, y) => x - y }, Seconds(EVENT_PERIOD_SECONDS*4), Seconds(EVENT_PERIOD_SECONDS))
</code>```

which is so far working.

Now, I would like so save each windowLength in a CSV file, and stucking there:

```<code>  val schema = new StructType()
    .add(StructField("text", StringType, true))
    .add(StructField("count", IntegerType, true))

  counts.foreachRDD(rdd =>
  {
    //rdd.saveAsTextFile(CHECKPOINT_DIR + "/output_" + sdf.format(System.currentTimeMillis()))

    val df = sparkSession.createDataFrame(rdd.map(attributes => Row(attributes._1, attributes._2)), schema)
    df.write.format("csv").save(CHECKPOINT_DIR + "/output_" + sdf.format(System.currentTimeMillis()))
  })
</code>```

Can anybody assist me with that please?

Sorry, for get the error:

When I just run rdd.saveAsTextFile it creates various plain text file that had to be merged.

By creating the createDataFrame is get this error

```<code>17/11/12 23:06:04 ERROR JobScheduler: Error running job streaming job 1510490490000 ms.1

java.lang.NullPointerException
    at org.apache.spark.sql.SparkSession.sessionState$lzycompute(SparkSession.scala:128)
    at org.apache.spark.sql.SparkSession.sessionState(SparkSession.scala:126)
    at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:65)
    at org.apache.spark.sql.SparkSession.createDataFrame(SparkSession.scala:578)
    at org.apache.spark.sql.SparkSession.createDataFrame(SparkSession.scala:335)
    at main.scala.Main$$anonfun$main$scala$Main$$functionToCreateContext$1$1.apply(Main.scala:152)
    at main.scala.Main$$anonfun$main$scala$Main$$functionToCreateContext$1$1.apply(Main.scala:146)
</code>```

Line 146 is the sparkSession.createDataFrame line

答:
I "solved" it by changing my code like this:</p>

```<code>  linesFilter.window(Seconds(EVENT_PERIOD_SECONDS*WRITE_EVERY_N_SECONDS), Seconds(EVENT_PERIOD_SECONDS*WRITE_EVERY_N_SECONDS)).foreachRDD { (rdd, time) =>
    if (rdd.count() > 0) {
      rdd
        .coalesce(1,true)
        .map(_.replace(DELIMITER_STREAM, DELIMITER_OUTPUT))
        //.map{_.mkString(DELIMITER_OUTPUT) }
        .saveAsTextFile(CHECKPOINT_DIR + "/output/o_" + sdf.format(System.currentTimeMillis()))
    }
  }
</code>```

Title: Stream to RDD to DataFrame to CSV

Body:
I am really getting desperate here.

What I am trying to do is, capturing a stream, aggregated stream data for some seconds, and after save it as a CSV file.

val sparkSession : SparkSession = SparkSession.builder()
  .master("local[*]")
  .appName("Streaming")
  .config(conf)
  //.enableHiveSupport()
  .getOrCreate()

So, I am capturing the stream

val lines = streamingContext.socketTextStream(HOST, PORT)
val linesMessage = lines.map(_.split(DELIMITER)(1))

and count the incidents

val counts = linesMessage.map(tag => (tag, 1))
        .reduceByKeyAndWindow({ (x, y) => x + y }, { (x, y) => x - y }, Seconds(EVENT_PERIOD_SECONDS*4), Seconds(EVENT_PERIOD_SECONDS))

which is so far working.

Now, I would like so save each windowLength in a CSV file, and stucking there:

  val schema = new StructType()
    .add(StructField("text", StringType, true))
    .add(StructField("count", IntegerType, true))

  counts.foreachRDD(rdd =>
  {
    //rdd.saveAsTextFile(CHECKPOINT_DIR + "/output_" + sdf.format(System.currentTimeMillis()))

    val df = sparkSession.createDataFrame(rdd.map(attributes => Row(attributes._1, attributes._2)), schema)
    df.write.format("csv").save(CHECKPOINT_DIR + "/output_" + sdf.format(System.currentTimeMillis()))
  })

Can anybody assist me with that please?

Sorry, for get the error:

When I just run rdd.saveAsTextFile it creates various plain text file that had to be merged.

By creating the createDataFrame is get this error

17/11/12 23:06:04 ERROR JobScheduler: Error running job streaming job 1510490490000 ms.1

java.lang.NullPointerException
    at org.apache.spark.sql.SparkSession.sessionState$lzycompute(SparkSession.scala:128)
    at org.apache.spark.sql.SparkSession.sessionState(SparkSession.scala:126)
    at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:65)
    at org.apache.spark.sql.SparkSession.createDataFrame(SparkSession.scala:578)
    at org.apache.spark.sql.SparkSession.createDataFrame(SparkSession.scala:335)
    at main.scala.Main$$anonfun$main$scala$Main$$functionToCreateContext$1$1.apply(Main.scala:152)
    at main.scala.Main$$anonfun$main$scala$Main$$functionToCreateContext$1$1.apply(Main.scala:146)

Line 146 is the sparkSession.createDataFrame line

Body:
I "solved" it by changing my code like this:

  linesFilter.window(Seconds(EVENT_PERIOD_SECONDS*WRITE_EVERY_N_SECONDS), Seconds(EVENT_PERIOD_SECONDS*WRITE_EVERY_N_SECONDS)).foreachRDD { (rdd, time) =>
    if (rdd.count() > 0) {
      rdd
        .coalesce(1,true)
        .map(_.replace(DELIMITER_STREAM, DELIMITER_OUTPUT))
        //.map{_.mkString(DELIMITER_OUTPUT) }
        .saveAsTextFile(CHECKPOINT_DIR + "/output/o_" + sdf.format(System.currentTimeMillis()))
    }
  }


问:
How to get data value of one input field from a list?
How can I get the value of the first input field from a list?

```<code><button id="hello">get data</button><br><br>
   <table> <td><label for="voucher_<?php echo $counter; ?>">D/N Number <?php echo $counter; ?></label><br>
    <input type="text" name="voucher_<?php echo $counter; ?>" class="input-field exsmall-input" value="<?php echo $voucher; ?>" placeholder="D/N Number" id="voucher_<?php echo $counter; ?>" required>
    </td></table>
</code>```

When I run the above code the number of rows varies depending on the counter.If I want to get the value of the first DN number ,what shall I do ?

```<code>$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("#voucher").val();
        alert(name);
    });
});
</code>```

When I run this javascript I get undefined vales.

答:
Try this:-</p>

```<code>$(document).ready(function() {
    $('#hello').click(function() {
        var name = $('table').find('input[type=text]').filter(':visible:first')
            .val();

    });
});
</code>```

Body:
How can I get the value of the first input field from a list?

<button id="hello">get data</button>

 <label for="voucher_<?php echo $counter; ?>">D/N Number <?php echo $counter; ?>

    <input type="text" name="voucher_<?php echo $counter; ?>" class="input-field exsmall-input" value="<?php echo $voucher; ?>" placeholder="D/N Number" id="voucher_<?php echo $counter; ?>" required>

When I run the above code the number of rows varies depending on the counter.If I want to get the value of the first DN number ,what shall I do ?

$(document).ready(function(){
    $('#hello').click(function(){
          var name = $("#voucher").val();
        alert(name);
    });
});

When I run this javascript I get undefined vales.

Body:
Try this:-

$(document).ready(function() {
    $('#hello').click(function() {
        var name = $('table').find('input[type=text]').filter(':visible:first')
            .val();

    });
});


问:
LaunchScreen.storyboard bug in swift
I was using LaunchScreen.storyboard without problems.
but I changed LaunchScreen.storyboard file name to LaunchScreen2.storyboard since I hoped not to use the splash image.
(I thought it could decrease loading time)
However, I couldn't see the loading time differences.

So I renamed the file to LaunchScreen.storyboard to use splash image again.
But the problem began from here.

Even though I change images in LaunchScreen.Storyboard:-

Only black screen is shown shortly when I run my app on simulators.

Old LaunscScreen.storyboard is shown when I run the app on my iPad.

I took some.. actions but it didn't work.
(use image in Assets.cassettes, make sure Launch Screen File name in project option)

Is there anyone who can help me?

*I attached screenshots

(I'm using the latest Xcode, Version 9.1 (9B55))

答:
This is iOS issue(OS Level) iOS caching LaunchScreen.storyboard image resource and reuse it

why your action did't work because

app on simulators have not cached LaunchScreen so show black screen(LaunchScreen.storyboard not found)

iPad has cached and used LaunchScreen Resource(LaunchScreen.storyboard) so old Resource shown

Common solution is delete app or shut down and on iPhone or iPad for removing cashed resource. iOS mananing this resource in Srpingboard(OS Level) so It is not a complete solution but promotes the cache to be quickly erased from OS. just waiting.. until iOS erase it

Title: LaunchScreen.storyboard bug in swift


问:
Oracle Forms-Error 103 at line 11 column 2- Encountered the symbol USER_PASSWORD where expecting
```<code>declare

    v varchar2(3);
begin
    select 'x'
    into v
    from user_details
    where
    USER_NAME = login.USER_NAME;
'and'
    USER_PASSWORD = login.USER_PASSWORD;

    if sql%found then
        open_form('D:\CREDEN SOFT\MENU\MAIN.FMX');

    end if;
    exception

    when no_data_found then
    message('invalid user name or password....!');
    end;
</code>```

答:
Please check the below code that I modefied (though not tested) , please note that you have to add a column instead of x ( and make sure the length of the variable is correct 3 might be small)</p>

```<code>declare
    v varchar2(3);
begin
    select 'x'
    into v
    from user_details
    where
    USER_NAME = login.USER_NAME
    and
    USER_PASSWORD = login.USER_PASSWORD;

    if v is not null then
        open_form('D:\CREDEN SOFT\MENU\MAIN.FMX');

    end if;

    exception
    when no_data_found
    then DBMS_OUTPUT.PUT_LINE('invalid user name or password....');

    end;
</code>```

Body:
Please check the below code that I modefied (though not tested) , please note that you have to add a column instead of x ( and make sure the length of the variable is correct 3 might be small)

declare
    v varchar2(3);
begin
    select 'x'
    into v
    from user_details
    where
    USER_NAME = login.USER_NAME
    and
    USER_PASSWORD = login.USER_PASSWORD;

    if v is not null then
        open_form('D:\CREDEN SOFT\MENU\MAIN.FMX');

    end if;

    exception
    when no_data_found
    then DBMS_OUTPUT.PUT_LINE('invalid user name or password....');

    end;


问:
TabLayout Not Binding to Viewpager
I have a fragment which hosts a TabLayout and a ViewPager. The host fragment is part of a container that switches based on the item selection of a bottom navigation bar.

For some reason, the ViewPager isn't inflating the fragments, and the TabLayout is unresponsive. When sliding left or right, the indicator stops as soon as you stop sliding, and doesn't snap like it should. And, of course, the fragments don't show.

Here is my code...I'm wondering what I am doing wrong.

PopularHolderFragment.java

```<code>import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import ai.gab.android.R;
import ai.gab.android.ui.adapters.fragment.PopularFragmentsAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Andrew Quebe on 10/20/2017.
 */

@SuppressWarnings("ConstantConditions")
public class PopularHolderFragment extends Fragment {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    public static PopularHolderFragment newInstance() {
        return new PopularHolderFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewPager.setAdapter(new PopularFragmentsAdapter(getActivity().getSupportFragmentManager()));

        tabLayout.addTab(tabLayout.newTab().setText("Posts"));
        tabLayout.addTab(tabLayout.newTab().setText("Users"));
        tabLayout.setupWithViewPager(viewPager);
    }
}
</code>```

PopularFragmentsAdapter.java

```<code>import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import ai.gab.android.ui.fragments.popular.PopularPostsFragment;
import ai.gab.android.ui.fragments.popular.PopularUsersFragment;

/**
 * Created by Andrew Quebe on 8/7/2017.
 */

public class PopularFragmentsAdapter extends FragmentStatePagerAdapter {

    public PopularFragmentsAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return PopularPostsFragment.newInstance();
            case 1:
                return PopularUsersFragment.newInstance();
        }
        return null;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Posts";
            case 1:
                return "Users";
        }
        return super.getPageTitle(position);
    }

    @Override
    public int getCount() {
        return 2;
    }
}
</code>```

fragment_popular_holder.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activities.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Light">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="2dp"
            tools:targetApi="lollipop" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/util_popular_main_content" />

</android.support.design.widget.CoordinatorLayout>
</code>```

util_popular_main_content.xml

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/fragment_popular_holder">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Screenshots

Also wondering why the text isn't its normal size.

Note that I do not want a toolbar in this layout, and perhaps that is my issue, but I don't see why it would be as the widgets should be able to work independently of each other.

答:
do the binding of pager and tabs in onCreateView. Not in the onActivityCreated.

And you don't need to manually add tabs to TabLayout, it'll do so automatically.
just get the tabs by position and set their text.

Title: TabLayout Not Binding to Viewpager

Body:
I have a fragment which hosts a TabLayout and a ViewPager. The host fragment is part of a container that switches based on the item selection of a bottom navigation bar.

For some reason, the ViewPager isn't inflating the fragments, and the TabLayout is unresponsive. When sliding left or right, the indicator stops as soon as you stop sliding, and doesn't snap like it should. And, of course, the fragments don't show.

Here is my code...I'm wondering what I am doing wrong.

PopularHolderFragment.java

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import ai.gab.android.R;
import ai.gab.android.ui.adapters.fragment.PopularFragmentsAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Andrew Quebe on 10/20/2017.
 */

@SuppressWarnings("ConstantConditions")
public class PopularHolderFragment extends Fragment {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    public static PopularHolderFragment newInstance() {
        return new PopularHolderFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewPager.setAdapter(new PopularFragmentsAdapter(getActivity().getSupportFragmentManager()));

        tabLayout.addTab(tabLayout.newTab().setText("Posts"));
        tabLayout.addTab(tabLayout.newTab().setText("Users"));
        tabLayout.setupWithViewPager(viewPager);
    }
}

PopularFragmentsAdapter.java

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import ai.gab.android.ui.fragments.popular.PopularPostsFragment;
import ai.gab.android.ui.fragments.popular.PopularUsersFragment;

/**
 * Created by Andrew Quebe on 8/7/2017.
 */

public class PopularFragmentsAdapter extends FragmentStatePagerAdapter {

    public PopularFragmentsAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return PopularPostsFragment.newInstance();
            case 1:
                return PopularUsersFragment.newInstance();
        }
        return null;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Posts";
            case 1:
                return "Users";
        }
        return super.getPageTitle(position);
    }

    @Override
    public int getCount() {
        return 2;
    }
}

fragment_popular_holder.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activities.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Light">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="2dp"
            tools:targetApi="lollipop" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/util_popular_main_content" />

</android.support.design.widget.CoordinatorLayout>

util_popular_main_content.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/fragment_popular_holder">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

Screenshots

Also wondering why the text isn't its normal size.

Note that I do not want a toolbar in this layout, and perhaps that is my issue, but I don't see why it would be as the widgets should be able to work independently of each other.


问:
what is the difference between ` ` and ' '?
Hey guys i want to know that what is the difference between these two type of single quotes` and '

i tried to execute the below command with ` then it worked

```<code>axios.get(`https://api.github.com/users/${this.state.userName}`)
      .then(resp => {
        console.log(resp);
      });
</code>```

but when i tried to run the same command using '' it doesnt work

```<code>axios.get('https://api.github.com/users/${this.state.userName}')
          .then(resp => {
            console.log(resp);
          });
</code>```

答:
The first is called template literals added in the ES6 - It first evaluates the given embedded expressions, gets the results and replaces the expressions with the results. In the ${} you give expressions (variable, function call, ...), and it creates a string replacing the ${expression} part with the result.

This code part

var str = 'text';
var template = `Some ${str}`; // `str` is a expression which returns the value

console.log(template);```
</div>
</div>
</p>

<p>is equivalent of concatenation of strings. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var str = 'text';
var template = 'Some ' + str; // Just concatenate the strings

console.log(template);</code>```

Template literals also allow you to create multi-line strings

const multiLine = `This is a multi-
line text`;

console.log(multiLine);```

Body:
Hey guys i want to know that what is the difference between these two type of single quotes` and '

i tried to execute the below command with ` then it worked

axios.get(`https://api.github.com/users/${this.state.userName}`)
      .then(resp => {
        console.log(resp);
      });

but when i tried to run the same command using '' it doesnt work

axios.get('https://api.github.com/users/${this.state.userName}')
          .then(resp => {
            console.log(resp);
          });

Body:
The first is called template literals added in the ES6 - It first evaluates the given embedded expressions, gets the results and replaces the expressions with the results. In the ${} you give expressions (variable, function call, ...), and it creates a string replacing the ${expression} part with the result.

This code part

var str = 'text';
var template = `Some ${str}`; // `str` is a expression which returns the value

console.log(template);

is equivalent of concatenation of strings.

var str = 'text';
var template = 'Some ' + str; // Just concatenate the strings

console.log(template);

Template literals also allow you to create multi-line strings

const multiLine = `This is a multi-
line text`;

console.log(multiLine);


问:
In MVC the deleting a record can be achieved by POST, so whats the need of DELETE verb?
Deletion can be achieved through HTTP POST, so why do we need a separate HTTP verb called DELETE?</p>

答:
To quote Jurassic Park:

Having a DELETE verb is a convention. It makes your API easily exploitable and self-descriptive.

Technically, you could just use a GET verb with a action= and data= URL parameters to do any CRUD operation, but that would be unintuitive, making your application hard to use (and to maintain!) by anyone other than yourself.


问:
Retrieving distinct records based on a column on Django
I need to retrieve a list of records for the following table with distinct values in regards to name:

```<code>Class C:

name                value
A ------------------ 10
A ------------------ 20
A ------------------ 20
B ------------------ 50
C ------------------ 20
D ------------------ 10
B ------------------ 10
A ------------------ 30
</code>```

I need to get rid of all the duplicate values for name and only show the following:

```<code>name                value
A ------------------ 30
B ------------------ 10
C ------------------ 20
D ------------------ 10
</code>```

As you can see, it almost looks like a python set. I can probably generate the set using Python, but I'm wondering if Django's ORM has this feature.

I tried using distinct, but it doesn't accept any argument to specify which column has to have distinct values. Any idea how to get this query working?

答:
.distinct() is the tool, but here's the syntax I had to use :

```<code>Model.objects.values_list('name', flat=True).distinct()
</code>```

This way you only get a list [A,B,C,D] of values, not the objects themseleves.

Body:
I need to retrieve a list of records for the following table with distinct values in regards to name:

Class C:

name                value
A ------------------ 10
A ------------------ 20
A ------------------ 20
B ------------------ 50
C ------------------ 20
D ------------------ 10
B ------------------ 10
A ------------------ 30

I need to get rid of all the duplicate values for name and only show the following:

name                value
A ------------------ 30
B ------------------ 10
C ------------------ 20
D ------------------ 10

As you can see, it almost looks like a python set. I can probably generate the set using Python, but I'm wondering if Django's ORM has this feature.

I tried using distinct, but it doesn't accept any argument to specify which column has to have distinct values. Any idea how to get this query working?

Body:
.distinct() is the tool, but here's the syntax I had to use :

Model.objects.values_list('name', flat=True).distinct()

This way you only get a list [A,B,C,D] of values, not the objects themseleves.


问:
Group array objects
I have a array with objects like this:

[{recordID:'123'},{recordID:'123-opp'},{recordsID:'456'},{recordID:'456-opp'},{recordID:'789'}, {recordID:'980'},...]

So there are some objects with the same recordID just added a -opp and some are single ones and there is no -opp
What I want to do is to combine the corresponding objects in a array. and the other one alone in a array. For example:

[[{recordID:'123'},{recordID:'123-opp'}], [{recordID:'456'},{recordID:'456-opp'}],[{recordID:'789'}],[{recordID:'980'}],...]

To mention: sometimes it could be -opp at the end and sometimes -ref.

I tried multiple ways but don't get the right result. This is my Code:

```<code>.then(function(dbResult){ //sort and filter the corresponding records
    var records = [];
    var indexToDelete;
    dbResult.forEach(function(item, index){
      var recordPair = dbResult.filter(function(element, i){
        if(element.recordId.includes(item.recordId)){
          indexToDelete = i;
          return true;
        }else{
          return false;
        }
      })
      records.splice(indexToDelete,1);
      records.push(recordPair);
    })
    console.log(records)
    return records;
  })
</code>```

Maybe someone have even a better solution.

答:
You can do it in the following way

let arr = [{recordID:'123'},{recordID:'123-opp'},{recordID:'456'},{recordID:'456-opp'},{recordID:'789'}, {recordID:'980'}];

let cleanVariable = (str) => +str.replace(/\-opp|\-ref/,'');
let matchVariable = (str1, str2) => cleanVariable(str1) == cleanVariable(str2);
let result = arr.sort((a, b) => cleanVariable(a.recordID) - cleanVariable(b.recordID)).reduce((a, b) => {
    if(a.length == 0) a.push([]);
    if(a[a.length-1].length == 0) a[a.length-1].push(b);
    else if(matchVariable(a[a.length-1][a[a.length-1].length-1].recordID, b.recordID)) a[a.length-1].push(b);
    else a.push([b]);
    return a;
}, []);

console.log(result);```

Title: Group array objects

Body:
I have a array with objects like this:

[{recordID:'123'},{recordID:'123-opp'},{recordsID:'456'},{recordID:'456-opp'},{recordID:'789'}, {recordID:'980'},...]

So there are some objects with the same recordID just added a -opp and some are single ones and there is no -opp
What I want to do is to combine the corresponding objects in a array. and the other one alone in a array. For example:

[[{recordID:'123'},{recordID:'123-opp'}], [{recordID:'456'},{recordID:'456-opp'}],[{recordID:'789'}],[{recordID:'980'}],...]

To mention: sometimes it could be -opp at the end and sometimes -ref.

I tried multiple ways but don't get the right result. This is my Code:

.then(function(dbResult){ //sort and filter the corresponding records
    var records = [];
    var indexToDelete;
    dbResult.forEach(function(item, index){
      var recordPair = dbResult.filter(function(element, i){
        if(element.recordId.includes(item.recordId)){
          indexToDelete = i;
          return true;
        }else{
          return false;
        }
      })
      records.splice(indexToDelete,1);
      records.push(recordPair);
    })
    console.log(records)
    return records;
  })

Maybe someone have even a better solution.


答:
You could group the result by using a part of the id with a hash table for same groups.

var array = [{ recordID: '123' }, { recordID: '123-opp' }, { recordID: '456' }, { recordID: '456-opp' }, { recordID: '789' }, { recordID: '980' }],
    hash = Object.create(null),
    result = [];

array.forEach(function (o) {
    var key = o.recordID.match(/^\d+/);
    if (!hash[key]) {
        hash[key] = [];
        result.push(hash[key]);
    }
    hash[key].push(o);
});

console.log(result);
console.log(hash);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Group array objects

Body:
You could group the result by using a part of the id with a hash table for same groups.

var array = [{ recordID: '123' }, { recordID: '123-opp' }, { recordID: '456' }, { recordID: '456-opp' }, { recordID: '789' }, { recordID: '980' }],
    hash = Object.create(null),
    result = [];

array.forEach(function (o) {
    var key = o.recordID.match(/^\d+/);
    if (!hash[key]) {
        hash[key] = [];
        result.push(hash[key]);
    }
    hash[key].push(o);
});

console.log(result);
console.log(hash);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Is it possible to add mutiple headers with same key to NSMutableURLRequest?
Is it possible to add mutiple headers with same key to NSMutableURLRequest?

I just come to a request that multiple headers with same key should be present in the headers, as I know , the NSMutableURLRequest's setHTTPHeaderField would only set some field, but not able to add duplicated item into the headers, is there anyway to achieve this? thanks.

答:
There is no -setHTTPHeaderField method, you likely mean -setValue:forHTTPHeaderField:. This method always replaces an existing value. But you can do it. First of all, you have to know, that multiple header fields with the same name are only allowed under some circumstances:

Multiple message-header fields with the same field-name MAY be
present in a message if and only if the entire field-value for that
header field is defined as a comma-separated list [i.e., #(values)].
It MUST be possible to combine the multiple header fields into one
"field-name: field-value" pair, without changing the semantics of the
message, by appending each subsequent field-value to the first, each
separated by a comma.

RFC2616, 4.2

So, a: 1, a: 2 has to have the equivalent a: 1, 2. This is, what
-addValue:forHTTPHeaderField: does:

This method provides the ability to add values to header fields incrementally. If a value was previously set for the specified field, the supplied value is appended to the existing value using the appropriate field delimiter. In the case of HTTP, the delimiter is a comma.

So you can do:

```<code>[request addValue:@1 forHTTPHeaderField:@"a"];
[request addValue:@2 forHTTPHeaderField:@"a"];
</code>```

Body:
There is no -setHTTPHeaderField method, you likely mean -setValue:forHTTPHeaderField:. This method always replaces an existing value. But you can do it. First of all, you have to know, that multiple header fields with the same name are only allowed under some circumstances:

Multiple message-header fields with the same field-name MAY be
present in a message if and only if the entire field-value for that
header field is defined as a comma-separated list [i.e., #(values)].
It MUST be possible to combine the multiple header fields into one
"field-name: field-value" pair, without changing the semantics of the
message, by appending each subsequent field-value to the first, each
separated by a comma.

RFC2616, 4.2

So, a: 1, a: 2 has to have the equivalent a: 1, 2. This is, what
-addValue:forHTTPHeaderField: does:

This method provides the ability to add values to header fields incrementally. If a value was previously set for the specified field, the supplied value is appended to the existing value using the appropriate field delimiter. In the case of HTTP, the delimiter is a comma.

So you can do:

[request addValue:@1 forHTTPHeaderField:@"a"];
[request addValue:@2 forHTTPHeaderField:@"a"];


答:
Use following automated tools:

https://developers.google.com/speed/pagespeed/

https://gtmetrix.com/

Chrome's lighthouse

Optimize image sizes and quality. (Automated tools above provide You with the optimized images)

Place Your CSS file at the beginning of your bootstrapping file such as index.html

Compress CSS files (remove the formatting)

Place Your JS file at the bottom of the file.

Compress JS files (remove the formatting)

Title: How to minimize load time of a landing page

Body:
I'm honestly confused about where to start with minimizing the load time of a website i'm building - https://projectrhea.herokuapp.com/ . Currently takes around 9 seconds to load the website which I want to try and bring down to sub 3 seconds.

I've done a diagnostic test, shown here https://www.webpagetest.org/result/171113_T2_851758db144ac117ab4e986a3798b1b5/1/details/#waterfall_view_step1 .

From what I can see there are three main reasons it would be taking awhile to load.

The first is the javascript.

I only need a small amount of it to run the site but I am very
confused about how to separate the code I need from the code I don't
need. I use it for the banner to show multiple phrases underneath the
banner that I would rather keep.

The second part is the shear amount of CSS files I'm drawing from.

I used a template to begin the site (it was a good way for me to learn
how to design the site). Now I think this has meant there is way too
many css and other files connected to this landing page.

The third part is the video file I have.

I would love to keep this
video as I just like how it fits in the site. I'll try and minimize
the file size after I have worked out the above issues.

This is my first real time trying to solve an issue like this and I would really appreciate the knowledge a more experienced coder could bring to this. Thanks!


问:
Self tracking entities return Unchanged in my WCF service
I've set up a little n-tier web application using MVP (Model View Presenter) in the front-end, a WCF service on the backend, which communicates with the BLL an behind that the DAL, which communicates with the EF4.0.
This is all working quite nicely, I've created several Get and Add methods which all work.
Now I wanted to create several Update methods. Since I'm using the Self-Tracking Entities (STE) of the EF4.0, I thought everything would work out quite fine and implementation would be rather easy.

This doesn't seem to be the case.
When changing my items in the web front-end, they keep having the status Unchanged when moving back to the WCF-service. Because the entity is unchanged, nothing gets updated in the database.
Through this question on SO: EF 4 Self Tracking Entities does not work as expected
I came accross the article telling something more in detail about implementing the STE's with in an n-tier application. (http://msdn.microsoft.com/en-us/magazine/ee335715.aspx)
I quote:

Make certain to reuse the Self-Tracking Entity template’s
  generated entity code on your
  client.  If you use proxy code
  generated by Add Service Reference in
  Visual Studio or some other tool,
  things look right for the most part,
  but you will discover that the
  entities don’t actually keep track of
  their changes on the client.

Well, I've managed to create a client to the service using this code:

```<code>var svc = new ChannelFactory<INorthwindSTEService>(
    "INorthwindSTEService")
    .CreateChannel();
</code>```

This appears to work quite alright.
The thing is, how do I get the serialized entities on the client?
In the code example I'm seeing the writer uses this code:

```<code>var products = new List<Product>(svc.GetProducts());
var customer = svc.GetCustomer("ALFKI");
</code>```

But I fail to see where those objects/entities/??? are defined (I'm talking about a Customer and a Product)

I've tested it using the entities which were created using the Add Service Reference, but that doesn't seem to work. The returned entities still have the status Unchanged.

I'd rather not reference the EF entities in my front-end, because I'd like to keep them separated and only have serialized objects on my front-end. Though, if it is really necessary, I might just have to do that.

Oh, using the MarkAsModified() method on the entity object does work nicely though, but that's more of a hack as the entity should check his status by itself.

Any advice on how to proceed?
My guess is using the MarkAsModiefied() method or referencing the entity models project in my web application could be viable work-around, but if there's something better, I'd like to try that first.

答:
You need to move the self tracking entities out of the entity frameowrk project

if you look in the .tt file you will see that there is a path to to .edmx file that you ahve to fill in.

This will aloow you to have them in a project seperate to the entity framework.

you can then reference this project from your front end and have access to the tracking entities as you expect.

As for performing the update ... well im looking myself ;p
(I don't really want to sieve them out into their different states myself)

you say this
'Make certain to reuse the Self-Tracking Entity template’s generated entity code on your client'

and then you say that you do not want to do this lower down.

That is your problem.

Body:
I've set up a little n-tier web application using MVP (Model View Presenter) in the front-end, a WCF service on the backend, which communicates with the BLL an behind that the DAL, which communicates with the EF4.0.
This is all working quite nicely, I've created several Get and Add methods which all work.
Now I wanted to create several Update methods. Since I'm using the Self-Tracking Entities (STE) of the EF4.0, I thought everything would work out quite fine and implementation would be rather easy.

This doesn't seem to be the case.
When changing my items in the web front-end, they keep having the status Unchanged when moving back to the WCF-service. Because the entity is unchanged, nothing gets updated in the database.
Through this question on SO: EF 4 Self Tracking Entities does not work as expected
I came accross the article telling something more in detail about implementing the STE's with in an n-tier application. (http://msdn.microsoft.com/en-us/magazine/ee335715.aspx)
I quote:

Make certain to reuse the Self-Tracking Entity template’s
  generated entity code on your
  client.  If you use proxy code
  generated by Add Service Reference in
  Visual Studio or some other tool,
  things look right for the most part,
  but you will discover that the
  entities don’t actually keep track of
  their changes on the client.

Well, I've managed to create a client to the service using this code:

var svc = new ChannelFactory<INorthwindSTEService>(
    "INorthwindSTEService")
    .CreateChannel();

This appears to work quite alright.
The thing is, how do I get the serialized entities on the client?
In the code example I'm seeing the writer uses this code:

var products = new List<Product>(svc.GetProducts());
var customer = svc.GetCustomer("ALFKI");

But I fail to see where those objects/entities/??? are defined (I'm talking about a Customer and a Product)

I've tested it using the entities which were created using the Add Service Reference, but that doesn't seem to work. The returned entities still have the status Unchanged.

I'd rather not reference the EF entities in my front-end, because I'd like to keep them separated and only have serialized objects on my front-end. Though, if it is really necessary, I might just have to do that.

Oh, using the MarkAsModified() method on the entity object does work nicely though, but that's more of a hack as the entity should check his status by itself.

Any advice on how to proceed?
My guess is using the MarkAsModiefied() method or referencing the entity models project in my web application could be viable work-around, but if there's something better, I'd like to try that first.


答:
The bigger your css, the longer the page takes to load. So try to reduce/minify css and try to use css in a single file. Same with JS also

Use Lazy load for images so webpage displays quickly without calling images.

Make sure server is using keep-alive as it can truly affect how your server fulfills requests.

Enable gzip compression

Minimize page redirects because it affect page speed

Enable browser caching so your browser can load the page without having to send another HTTP request to the server.


答: It's not working as ' works for literals, so you probably getting what you typed literaly, on the other hand other kind of quotes let you develope a custom spresion</p>

Title: what is the difference between ` ` and ' '?


问:
Can I change H2 embedded DB dialect to Sybase?
I need to write some test on my project which use Sybase DB. These tests closely related to running some SQL requests. For this purpose we must use myBatis and DBunit approach with h2 embedded DB. But issue is that some Sybase and h2 has a little bit different syntax for same functions.

Example:

```<code>    Sybase: CONVERT(data_type, expression [, format_style])
    H2: CONVERT(value, data_type)
</code>```

So as you can see if I will write SQL's based on H2 dialect tests will be passed but code in application which will run it on Sybase will fail for sure.

Questions:

Is there any way how make H2 DB understand Sybase dialect?

Is there any way how to make SQL's to be compatible on different DB's and this is exactly what I need bcos there is a chance that in future we can move to another DB and rewrite all SQL's will be a very bad and time consuming?

答:
in the worse case scenario, you may make use of databaseIdProvider and provide a different SQL for each of the different database.

Ensure the following configuration is in place:

```<code><databaseIdProvider type="DB_VENDOR">
    <property name="HSQL Database Engine" value="hsql" />
    <property name="Adaptive Server Enterprise" value="sybase"/>
</databaseIdProvider>
</code>```

then in the mapper.xml, you can do as follows:

to be use by both:

```<code><select id="select1" resultType="string" parameterType="int">
    select
    name from common where id=#{value}
</select>
</code>```

to use by hsql only:

```<code><select id="select1" resultType="string" parameterType="int" databaseId="hsql">
    ...
</select>
</code>```

to use by sybase only

```<code><select id="select1" resultType="string" parameterType="int" databaseId="sybase">
    ...
</select>
</code>```

Body:
I need to write some test on my project which use Sybase DB. These tests closely related to running some SQL requests. For this purpose we must use myBatis and DBunit approach with h2 embedded DB. But issue is that some Sybase and h2 has a little bit different syntax for same functions.

Example:

    Sybase: CONVERT(data_type, expression [, format_style])
    H2: CONVERT(value, data_type)

So as you can see if I will write SQL's based on H2 dialect tests will be passed but code in application which will run it on Sybase will fail for sure.

Questions:

Is there any way how make H2 DB understand Sybase dialect?

Is there any way how to make SQL's to be compatible on different DB's and this is exactly what I need bcos there is a chance that in future we can move to another DB and rewrite all SQL's will be a very bad and time consuming?

Body:
in the worse case scenario, you may make use of databaseIdProvider and provide a different SQL for each of the different database.

Ensure the following configuration is in place:

<databaseIdProvider type="DB_VENDOR">
    <property name="HSQL Database Engine" value="hsql" />
    <property name="Adaptive Server Enterprise" value="sybase"/>
</databaseIdProvider>

then in the mapper.xml, you can do as follows:

to be use by both:

<select id="select1" resultType="string" parameterType="int">
    select
    name from common where id=#{value}
</select>

to use by hsql only:

<select id="select1" resultType="string" parameterType="int" databaseId="hsql">
    ...
</select>

to use by sybase only

<select id="select1" resultType="string" parameterType="int" databaseId="sybase">
    ...
</select>


问:
MobX action transfer to function as callback
Question:

if I have store (pseudo code)

```<code>export default class MainStore {
  @observable someObservable = [];

  someFuncWithApi(actionFuncFromComponent) {
    apiCall.then(res => actionFuncFromComponent(res.loadPercentage)).then(() => ....)
  }
}

const mainStore = new MainStore;

....

@inject('mainStore')
@observer
export default class SomeComponent extends Component {
  @observable percentage = null;

  @action
  setPercentage(percentage) {
    this.percentage = percentage
  }

  someHandle() {
    this.props.mainStore.someFuncWithApi(this.setPercentage)
  }
}
</code>```

This need for changing load percentage, someFuncWithApi is called but not change percentage or rerender in component. Please, tell me the right way for this.

答:
this.props.mainStore.someFuncWithApi(this.setPercentage)

calls an unbound this.setPercentage. Either pass (x) => this.setPercentage(x) or bind the function to this

Body:
Question:

if I have store (pseudo code)

export default class MainStore {
  @observable someObservable = [];

  someFuncWithApi(actionFuncFromComponent) {
    apiCall.then(res => actionFuncFromComponent(res.loadPercentage)).then(() => ....)
  }
}

const mainStore = new MainStore;

....

@inject('mainStore')
@observer
export default class SomeComponent extends Component {
  @observable percentage = null;

  @action
  setPercentage(percentage) {
    this.percentage = percentage
  }

  someHandle() {
    this.props.mainStore.someFuncWithApi(this.setPercentage)
  }
}

This need for changing load percentage, someFuncWithApi is called but not change percentage or rerender in component. Please, tell me the right way for this.


问:
Converting a result of Integer to String or Word in C
so i have a problem here. I am working on my class assignment which is create a calculator but every result must be in a word, example :

```<code>int a,b,c;
printf("Input first number:");
scanf("%d", &a);
printf("Input second number:"):
scanf("%d", &b);
c=a+b;
printf("The result are: %d", c);
printf("If in words, it is  = ");
switch(c){
case 0:printf("abcdef");break;
case 1:printf("bc");break;
case 2:printf("abged");break;
case 3:printf("abgcd");break;
case 4:printf("fbgc");break;
case 5:printf("afgod");break;
case 6:printf("fgcde");break;
case 7:printf("abc");break;
case 8:printf("abcdefg");break;
case 9:printf("abcdfg");break;
default :printf("error");break;
</code>```

So the result from this when im running it is :

Input first number : 12

input second number : 12

The result are: 24

If in words, it is = error

so what I'm confused here is how I did print the c result as a word? so what i want from my output is

Input first number : 12

input second number : 12

The result are : 24

If in words, it is = abged fbcg

so far I'm searching for answers but I cannot find it. If anyone here can help me, please do.

Thanks in advance

*edited

答:
Use a lookup for all the options of this word and then print the relevant according to the index without all the switch case mess

```<code>char* lookup = {
                {"abcdef\n"},
                {"bc\n"},
                {"abged\n"},
                {"abgcd\n"},
                {"fbgc\n"},
                {"afgod\n"},
                {"fgcde\n"},
                {"abc\n"},
                {"abcdefg\n"},
                {"abcdfg\n"},
};
</code>```

then==>

```<code>c=a+b;
if (c>9)
{
printf("error\n");
}
else
{
printf(lookup[c]);
}
</code>```

Body:
so i have a problem here. I am working on my class assignment which is create a calculator but every result must be in a word, example :

int a,b,c;
printf("Input first number:");
scanf("%d", &a);
printf("Input second number:"):
scanf("%d", &b);
c=a+b;
printf("The result are: %d", c);
printf("If in words, it is  = ");
switch(c){
case 0:printf("abcdef");break;
case 1:printf("bc");break;
case 2:printf("abged");break;
case 3:printf("abgcd");break;
case 4:printf("fbgc");break;
case 5:printf("afgod");break;
case 6:printf("fgcde");break;
case 7:printf("abc");break;
case 8:printf("abcdefg");break;
case 9:printf("abcdfg");break;
default :printf("error");break;

So the result from this when im running it is :

Input first number : 12

input second number : 12

The result are: 24

If in words, it is = error

so what I'm confused here is how I did print the c result as a word? so what i want from my output is

Input first number : 12

input second number : 12

The result are : 24

If in words, it is = abged fbcg

so far I'm searching for answers but I cannot find it. If anyone here can help me, please do.

Thanks in advance

*edited

Body:
Use a lookup for all the options of this word and then print the relevant according to the index without all the switch case mess

char* lookup = {
                {"abcdef\n"},
                {"bc\n"},
                {"abged\n"},
                {"abgcd\n"},
                {"fbgc\n"},
                {"afgod\n"},
                {"fgcde\n"},
                {"abc\n"},
                {"abcdefg\n"},
                {"abcdfg\n"},
};

then==>

c=a+b;
if (c>9)
{
printf("error\n");
}
else
{
printf(lookup[c]);
}


问:
Pre populated value is not being removed in react-select@1.0.0-rc.5 when clicking on cross button of the selected option
I am currently building a react app where I need a form with the pre-populated values in it when a user wants to update his/her profile. In the add new user form, It's fine to have the drop-down in its default state. But when a user wants to update profile then there is a project and a group dropdown that needs to have a default value i.e. the value when the user was created. Means the drop-down should be populated with the project and the group associated with it.

```<code><Select
    multi={true}
    simpleValue
    required
    value={value}
    options={[{value:'One', label:'PROJECTONE'},{value:'Two', label:'PROJECTTWO'}]}
    onChange={handleInputChange}
/>
</code>```

So I need a dropdown with the prepopulated projects i.e. PROJECTONE and PROJECTTWO both.

This is the ScreenShot of my update profile. I have the value which I want to set in the dropdown but if I set comma separated string then when I want to remove that option it is not being affected i.e. I am not able to remove that option.

Question Update 1:

So here is my full component

```<code>export interface IInputProps {
    required?: boolean;
    type: string;
    placeholder?: string;
    menuItems?: Object[];
    isDisabled?: boolean;
    onSelect?: (value) => void;
    defaultValue?: string;
    id?: string;
    multi?: boolean;
    searchable?: boolean;
}

export interface IInputState {
    value: string;
}

export class Input extends React.PureComponent<IInputProps, IInputState> {

  constructor({ defaultValue }) {
      super();
      this.state = { value: (defaultValue || '')};
  }

  componentWillReceiveProps(nextProps) {
      if (!nextProps.defaultValue) {
          return;
      }

      const { state: { value } } = this;
      if (nextProps.defaultValue !== value) {
          this.setState({
              value: nextProps.defaultValue
          });
      }
  }

  handleInputChange = (selectedValue) => {
      this.setState({
          value: selectedValue,
      });
  }

  get value() {
      return this.state.value;
  }

  render() {
        const { props: { searchable, multi, id, menuItems, required, isDisabled, placeholder, type, defaultValue },
            state: { value, dropDownValue }, handleInputChange } = this;
            return (
                <Select
                    multi={multi ? multi : false}
                    simpleValue
                    searchable={searchable ? searchable : false}
                    disabled={isDisabled ? isDisabled : false}
                    required
                    value={value}
                    placeholder={placeholder ? placeholder : 'Select...'}
                    options={menuItems}
                    onChange={handleInputChange}
                />
            );
        }
    }
  }
</code>```

I am using this input component whereever I need a Select Input and passing the props.
When I use this component as..

```<code><Input
    multi={true}
    defaultValue="PROJECTONE,PROJECTTWO"
    ref="myProjects"
    id="myProjects"
    menuItems={[{value:'One', label:'PROJECTONE'},{value:'Two', label:'PROJECTTWO'}]}
/>
</code>```

Then nothing is being set in it's value.
I am using component will recieve props to check if there is any default value passed if it is passed then I am setting the value.

And Once the value is being set on the dropdown I can not remove it using it's cross button that's the main problem here.

答:
There is a problem in your componentWillReceiveProps function:

```</p>

```componentWillReceiveProps(nextProps) {
  if (!nextProps.defaultValue) {
      return;
  }

  const { state: { value } } = this;
  if (nextProps.defaultValue !== value) {
      this.setState({
          value: nextProps.defaultValue
      });
  }
  }
```

<p>```

This function can be caused by changes to props or state.

You check nextProps.defaultValue !== value in here, once you check an option of the select, it's value may not be equal to the nextProps.defaultValue, then you always set the value state to the defaultValue, so you can not get the right value of the option.

You need also check whether the nextProps.defaultValue and the this.props.defaultValue is same or not, so that you will get the right changed value:

```</p>

```componentWillReceiveProps(nextProps) {
  if (!nextProps.defaultValue) {
      return;
  }

  const { state: { value } } = this;
  if (nextProps.defaultValue !== value && nextProps.defaultValue !== this.props.defaultValue) {
      this.setState({
          value: nextProps.defaultValue
      });
  }
  }
```

<p>```

Body:
I am currently building a react app where I need a form with the pre-populated values in it when a user wants to update his/her profile. In the add new user form, It's fine to have the drop-down in its default state. But when a user wants to update profile then there is a project and a group dropdown that needs to have a default value i.e. the value when the user was created. Means the drop-down should be populated with the project and the group associated with it.

<Select
    multi={true}
    simpleValue
    required
    value={value}
    options={[{value:'One', label:'PROJECTONE'},{value:'Two', label:'PROJECTTWO'}]}
    onChange={handleInputChange}
/>

So I need a dropdown with the prepopulated projects i.e. PROJECTONE and PROJECTTWO both.

This is the ScreenShot of my update profile. I have the value which I want to set in the dropdown but if I set comma separated string then when I want to remove that option it is not being affected i.e. I am not able to remove that option.

Question Update 1:

So here is my full component

export interface IInputProps {
    required?: boolean;
    type: string;
    placeholder?: string;
    menuItems?: Object[];
    isDisabled?: boolean;
    onSelect?: (value) => void;
    defaultValue?: string;
    id?: string;
    multi?: boolean;
    searchable?: boolean;
}

export interface IInputState {
    value: string;
}

export class Input extends React.PureComponent<IInputProps, IInputState> {

  constructor({ defaultValue }) {
      super();
      this.state = { value: (defaultValue || '')};
  }

  componentWillReceiveProps(nextProps) {
      if (!nextProps.defaultValue) {
          return;
      }

      const { state: { value } } = this;
      if (nextProps.defaultValue !== value) {
          this.setState({
              value: nextProps.defaultValue
          });
      }
  }

  handleInputChange = (selectedValue) => {
      this.setState({
          value: selectedValue,
      });
  }

  get value() {
      return this.state.value;
  }

  render() {
        const { props: { searchable, multi, id, menuItems, required, isDisabled, placeholder, type, defaultValue },
            state: { value, dropDownValue }, handleInputChange } = this;
            return (
                <Select
                    multi={multi ? multi : false}
                    simpleValue
                    searchable={searchable ? searchable : false}
                    disabled={isDisabled ? isDisabled : false}
                    required
                    value={value}
                    placeholder={placeholder ? placeholder : 'Select...'}
                    options={menuItems}
                    onChange={handleInputChange}
                />
            );
        }
    }
  }

I am using this input component whereever I need a Select Input and passing the props.
When I use this component as..

<Input
    multi={true}
    defaultValue="PROJECTONE,PROJECTTWO"
    ref="myProjects"
    id="myProjects"
    menuItems={[{value:'One', label:'PROJECTONE'},{value:'Two', label:'PROJECTTWO'}]}
/>

Then nothing is being set in it's value.
I am using component will recieve props to check if there is any default value passed if it is passed then I am setting the value.

And Once the value is being set on the dropdown I can not remove it using it's cross button that's the main problem here.

Body:
There is a problem in your componentWillReceiveProps function:

```</p>

<pre><code>componentWillReceiveProps(nextProps) {
  if (!nextProps.defaultValue) {
      return;
  }

  const { state: { value } } = this;
  if (nextProps.defaultValue !== value) {
      this.setState({
          value: nextProps.defaultValue
      });
  }
  }
</code></pre>

<p>```

This function can be caused by changes to props or state.

You check nextProps.defaultValue !== value in here, once you check an option of the select, it's value may not be equal to the nextProps.defaultValue, then you always set the value state to the defaultValue, so you can not get the right value of the option.

You need also check whether the nextProps.defaultValue and the this.props.defaultValue is same or not, so that you will get the right changed value:

```</p>

<pre><code>componentWillReceiveProps(nextProps) {
  if (!nextProps.defaultValue) {
      return;
  }

  const { state: { value } } = this;
  if (nextProps.defaultValue !== value && nextProps.defaultValue !== this.props.defaultValue) {
      this.setState({
          value: nextProps.defaultValue
      });
  }
  }
</code></pre>

<p>```


问:
Find and Add multiple values in ArrayList
I want to add programPercentTotalViewed from the given sample data where programId is same from the ArrayList for example programId= 59554.
How can I do that.</p>

```<code>1- programId=59554, programPercentTotalViewed=50
2- programId=30583, programPercentTotalViewed=15
3- programId=59554, programPercentTotalViewed=5
4- programId=30583, programPercentTotalViewed=5
5- programId=59554, programPercentTotalViewed=5
6- programId=30583, programPercentTotalViewed=5
7- programId=59554, programPercentTotalViewed=5

    List<LiveEventsDto> eventsList = liveEvents;
        Set<String> names = new HashSet<String>();
        for (LiveEventsDto singleEvent : eventsList) {
            if (names.contains(singleEvent.getProgramId())) {
                System.out.println("Because same programId exists: " + singleEvent.getProgramId());
                System.out.println("ProgramPercentTotalViewed: " + singleEvent.getProgramPercentTotalViewed());

            } else {
                System.out.println("Because same programId  DOES NOT exists: " + singleEvent.getProgramId());
            }
        }
</code>```

答:
Typically like this:</p>

```<code>Map<Integer, Integer> sums = new HashMap<>();
for (LiveEventsDto car: cars) {
    int key = car.getProgramId();
    int count = car.getProgramPercentTotalViewed();
    if (sums.containsKey(key) {
        count += sums.get(key);
    }
    sums.put(key, count);
}
</code>```

Body:
I want to add programPercentTotalViewed from the given sample data where programId is same from the ArrayList for example programId= 59554.
How can I do that.

1- programId=59554, programPercentTotalViewed=50
2- programId=30583, programPercentTotalViewed=15
3- programId=59554, programPercentTotalViewed=5
4- programId=30583, programPercentTotalViewed=5
5- programId=59554, programPercentTotalViewed=5
6- programId=30583, programPercentTotalViewed=5
7- programId=59554, programPercentTotalViewed=5

    List<LiveEventsDto> eventsList = liveEvents;
        Set<String> names = new HashSet<String>();
        for (LiveEventsDto singleEvent : eventsList) {
            if (names.contains(singleEvent.getProgramId())) {
                System.out.println("Because same programId exists: " + singleEvent.getProgramId());
                System.out.println("ProgramPercentTotalViewed: " + singleEvent.getProgramPercentTotalViewed());

            } else {
                System.out.println("Because same programId  DOES NOT exists: " + singleEvent.getProgramId());
            }
        }

Body:
Typically like this:

Map<Integer, Integer> sums = new HashMap<>();
for (LiveEventsDto car: cars) {
    int key = car.getProgramId();
    int count = car.getProgramPercentTotalViewed();
    if (sums.containsKey(key) {
        count += sums.get(key);
    }
    sums.put(key, count);
}


问:
How to: create .doc files using templates with django/python
I am writing a django application and there is something I don't know how to do. Say you have a database with users and several .doc files you might want to send to those users (postal letters, not electronicaly). I am wondering if there is a way to automatically create those letters from templates using my user database to fill in some markers? (i.e. name, address, etc.)

I've heard of the "pod" python library but I've never used it. The documentation seems to say to use openoffice templates, but mine are in MS Word format. Since they are often updated by people who only use MS Office, I'm stuck.

Any help would be appreciated.

J.

答:
Using mailmerge is easy and you can modify the template from a word doc.

http://pbpython.com/python-word-template.html

You can incorporate mail merge with a view as well. Here is an example where my_template1 is my word document template and there are fields called name and title in it.

```<code>def TestDocument2(request):
    template = os.path.join(os.path.dirname(__file__),
    'templates/my_template1.docx')

    document = MailMerge(template)
    document.merge(name='testcoy',
               title = 'My title',
               )
    f = io.BytesIO()
    document.write(f)
    length = f.tell()
    f.seek(0)
    response = HttpResponse(
        f.getvalue(),
        content_type='application/vnd.openxmlformats-
        officedocument.wordprocessingml.document'
         )
    response['Content-Disposition'] = 'attachment; filename=example.docx'
    response['Content-Length'] = length
    return response
</code>```

Body:
Using mailmerge is easy and you can modify the template from a word doc.

http://pbpython.com/python-word-template.html

You can incorporate mail merge with a view as well. Here is an example where my_template1 is my word document template and there are fields called name and title in it.

def TestDocument2(request):
    template = os.path.join(os.path.dirname(__file__),
    'templates/my_template1.docx')

    document = MailMerge(template)
    document.merge(name='testcoy',
               title = 'My title',
               )
    f = io.BytesIO()
    document.write(f)
    length = f.tell()
    f.seek(0)
    response = HttpResponse(
        f.getvalue(),
        content_type='application/vnd.openxmlformats-
        officedocument.wordprocessingml.document'
         )
    response['Content-Disposition'] = 'attachment; filename=example.docx'
    response['Content-Length'] = length
    return response


问:
Using Heroku Scheduler with Node.js
There is literally no tutorial about using Heroku Scheduler with Node.js. Assume that I have a function called sayHello() and I would like to run it every 10 mins. How can I use it in controller. In ruby you write rake function_name() however no explanation made for Node. Can I write '/sayHello' or I should do extra configuration?

答:
Following steps work in my situation.

In the root folder add worker.js file.

In worker.js. Write an simple function, like above.

function sayHello() {
  console.log('Hello');
}
sayHello();

Go to heroku Scheduler add-ons. Click 'add new job' and type 'worker' in the field. Then set time interval and click save.

Here are something should notice

After update works setting.If using above example, you can use heroku run node worker.js to check if it work. It should be show 'Hello' in your terminal.

I use express-babel starter for my node.js project.

Title: Using Heroku Scheduler with Node.js


问:
How to write a switch statement in Ruby
How do I write a switch statement in Ruby?

答:
```<code>$age =  5
case $age
when 0 .. 2
   puts "baby"
when 3 .. 6
   puts "little child"
when 7 .. 12
   puts "child"
when 13 .. 18
   puts "youth"
else
   puts "adult"
end
</code>```

See "Ruby - if...else, case, unless" for more information.

Title: How to write a switch statement in Ruby

Body:
$age =  5
case $age
when 0 .. 2
   puts "baby"
when 3 .. 6
   puts "little child"
when 7 .. 12
   puts "child"
when 13 .. 18
   puts "youth"
else
   puts "adult"
end

See "Ruby - if...else, case, unless" for more information.


问:
Detaching Rows in Pivot Table - Laravel
I have a pivot table country_team with data in this form

country_team

```<code> country_id    team_id
     1            1
     1            2
</code>```

Country

```<code>   id    name
    1    Spain
</code>```

Team

```<code> id     name
  1     Barcelona
  2     Real Madrid
</code>```

In my table, i have it displayed in this form

Table

```<code> Country_id    Team
     1         Barcelona
     1         Real Madrid
</code>```

Now, i want to detach real Madrid from the row but how can get the id of real madrid or get the name Real Madrid to detach it. I cannot delete using country_id since it will delete all teams belonging to that particular country .

Controller

```<code>public function index()
{
    $countries = Country::where('id',Auth::user()->id)->get();

    return view('admin.order.index',compact('orders'));
}

public function deleteTeam()
{
    $get_country_id = Country::findOrFail($id);
    $get_country_id->teams()->detach();
}
</code>```

HTML

```<code><tbody>
    @foreach($countries as $country)
        @foreach($country->teams as $team)
        <tr>
            <td>{{$country->id }}</td>
            <td>{{ $team->name}}</td>
        </tr>
        @endforeach
    @endforeach
</tbody>
</code>```

答:
Use a sub-query:

```<code>DELETE FROM country_team
WHERE team_id = (SELECT id FROM Team WHERE name = 'Real Madrid')
</code>```

The select in () will return the id for team 'Real Madrid', 2.  So it will delete entries in country_team if team_id == 2.

Title: Detaching Rows in Pivot Table - Laravel

Body:
I have a pivot table country_team with data in this form

country_team

 country_id    team_id
     1            1
     1            2

Country

   id    name
    1    Spain

Team

 id     name
  1     Barcelona
  2     Real Madrid

In my table, i have it displayed in this form

Table

 Country_id    Team
     1         Barcelona
     1         Real Madrid

Now, i want to detach real Madrid from the row but how can get the id of real madrid or get the name Real Madrid to detach it. I cannot delete using country_id since it will delete all teams belonging to that particular country .

Controller

public function index()
{
    $countries = Country::where('id',Auth::user()->id)->get();

    return view('admin.order.index',compact('orders'));
}

public function deleteTeam()
{
    $get_country_id = Country::findOrFail($id);
    $get_country_id->teams()->detach();
}

HTML

    @foreach($countries as $country)
        @foreach($country->teams as $team)

            {{$country->id }}
            {{ $team->name}}

        @endforeach
    @endforeach

Body:
Use a sub-query:

DELETE FROM country_team
WHERE team_id = (SELECT id FROM Team WHERE name = 'Real Madrid')

The select in () will return the id for team 'Real Madrid', 2.  So it will delete entries in country_team if team_id == 2.