问:
How to Use BufferingClientHttpResponseWrapper with HttpComponentsAsyncClientHttpRequestFactory
Below is the Interceptor code for logging request and response when doing Async Rest Call from Spring's AsyncRestTemplate.
This code is working provided we can use BufferingClientHttpResponseWrapper in some other package.
Here are some details about BufferingClientHttpResponseWrapper and how to add it with AsyncRestTemplate.
My Question is when I am using HttpComponentsAsyncClientHttpRequestFactory in my AsyncRestTemplate. How I can get the Buffered Response. We CAN NOT use BufferingClientHttpResponseWrapper as show below in my code as it is not a public class. Is there any other way to do it?
I know there are wire log available for HttpComponent AsyncHttpClient. But it will have all the logs from all the AsyncResttemplates in whole application. If we want to capture the logs only for one template then Interceptor is the only way I think. Please suggest if there is any other option available.

```<code>public class AsyncRestReqResInterceptor implements AsyncClientHttpRequestInterceptor {
    private static final XLogger REQ_RES_LOGGER = XLoggerFactory.getXLogger("myLogger");

    @Override
        public ListenableFuture<ClientHttpResponse> intercept(HttpRequest request, byte[] body, AsyncClientHttpRequestExecution execution) throws IOException {
            String requestPath = request.getURI().getPath();
            REQ_RES_LOGGER.debug(request.getMethod()+" "+requestPath);

            String requestBody = new String(body);
            REQ_RES_LOGGER.debug(requestBody);
            ListenableFuture<ClientHttpResponse> listenableFuture = execution.executeAsync(request, body);
            ListenableFutureAdapter<ClientHttpResponse,ClientHttpResponse> futureAdapter=
                    new ListenableFutureAdapter<ClientHttpResponse, ClientHttpResponse>(listenableFuture) {
                        @Override
                        protected ClientHttpResponse adapt(ClientHttpResponse adapteeResult) throws ExecutionException {
                            return logResponseBody(adapteeResult);
                        }
                    };
            return  futureAdapter;
        }

    private ClientHttpResponse logResponseBody(ClientHttpResponse response,boolean isImageInResponse){
                try {
                    BufferingClientHttpResponseWrapper responseWrapper = new BufferingClientHttpResponseWrapper(response);
                    REQ_RES_LOGGER.debug("Response Status Code :" + responseWrapper.getStatusCode().value());
                    REQ_RES_LOGGER.debug("Response Status Text :" + responseWrapper.getStatusText());
                    if (response != null && response.getBody() != null) {
                        String responseXml = IOUtils.toString(responseWrapper.getBody(), Charset.defaultCharset());
                        REQ_RES_LOGGER.debug(responseXml);
                    } else {
                        REQ_RES_LOGGER.debug("Empty Response Body");
                    }
                    return responseWrapper;
                }catch (IOException io){
                    REQ_RES_LOGGER.error("Unexpected Error ",io);
                    return response;
                }

        }
    }
</code>```

答:
I finally figured out a way to use this class. As this is a final class it is meant to be used within Springframework only. There was a pull request in springframework for this change. I am not sure when this change will be merged in the framework, but below are the classes which will solve the above problem. These classes would be helpful if we want to intercept the request and response for logging.

BufferingAsyncClientHttpRequestFactory

```<code>public class BufferingAsyncClientHttpRequestFactory extends

BufferingClientHttpRequestFactory
        implements AsyncClientHttpRequestFactory {

    private final AsyncClientHttpRequestFactory requestFactory;
    /**
     * Create a buffering wrapper for the given {@link ClientHttpRequestFactory}.
     * @param requestFactory the target request factory to wrap
     */
    public BufferingAsyncClientHttpRequestFactory(AsyncClientHttpRequestFactory requestFactory) {
        super((ClientHttpRequestFactory) requestFactory);
        this.requestFactory=requestFactory;
    }

    /**
     * Indicates whether the request/response exchange for the given URI and method
     * should be buffered in memory.
     * <p>The default implementation returns {@code true} for all URIs and methods.
     * Subclasses can override this method to change this behavior.
     * @param uri the URI
     * @param httpMethod the method
     * @return {@code true} if the exchange should be buffered; {@code false} otherwise
     */

    @Override
    public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
        AsyncClientHttpRequest request = requestFactory.createAsyncRequest(uri, httpMethod);
        if (shouldBuffer(uri, httpMethod)) {
            return new BufferingAsyncClientHttpRequestWrapper(request);
        }
        else {
            return request;
        }
    }

    protected boolean shouldBuffer(URI uri, HttpMethod httpMethod) {
        return true;
    }

}
</code>```

BufferingAsyncClientHttpRequestWrapper.java

```<code>public class BufferingAsyncClientHttpRequestWrapper extends AbstractBufferingAsyncClientHttpRequest {

    private final AsyncClientHttpRequest request;

    public BufferingAsyncClientHttpRequestWrapper(AsyncClientHttpRequest asyncClientHttpRequest){
        this.request=asyncClientHttpRequest;
    }

    @Override
    public HttpMethod getMethod() {
        return this.request.getMethod();
    }

    @Override
    public URI getURI() {
        return this.request.getURI();
    }

    @Override
    protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
        this.request.getHeaders().putAll(headers);
        if(bufferedOutput.length>0){
            StreamUtils.copy(bufferedOutput,this.request.getBody());
        }
        ListenableFuture<ClientHttpResponse> futureResponse = this.request.executeAsync();
        ListenableFutureAdapter<ClientHttpResponse,ClientHttpResponse> bufferedResponse =
                new ListenableFutureAdapter<ClientHttpResponse, ClientHttpResponse>(futureResponse) {
                    @Override
                    protected ClientHttpResponse adapt(ClientHttpResponse adapteeResult) throws ExecutionException {
                        return new BufferingClientHttpResponseWrapper(adapteeResult);
                    }
                };
        return bufferedResponse;
    }
}
</code>```

Body:
Below is the Interceptor code for logging request and response when doing Async Rest Call from Spring's AsyncRestTemplate.
This code is working provided we can use BufferingClientHttpResponseWrapper in some other package.
Here are some details about BufferingClientHttpResponseWrapper and how to add it with AsyncRestTemplate.
My Question is when I am using HttpComponentsAsyncClientHttpRequestFactory in my AsyncRestTemplate. How I can get the Buffered Response. We CAN NOT use BufferingClientHttpResponseWrapper as show below in my code as it is not a public class. Is there any other way to do it?
I know there are wire log available for HttpComponent AsyncHttpClient. But it will have all the logs from all the AsyncResttemplates in whole application. If we want to capture the logs only for one template then Interceptor is the only way I think. Please suggest if there is any other option available.

public class AsyncRestReqResInterceptor implements AsyncClientHttpRequestInterceptor {
    private static final XLogger REQ_RES_LOGGER = XLoggerFactory.getXLogger("myLogger");

    @Override
        public ListenableFuture<ClientHttpResponse> intercept(HttpRequest request, byte[] body, AsyncClientHttpRequestExecution execution) throws IOException {
            String requestPath = request.getURI().getPath();
            REQ_RES_LOGGER.debug(request.getMethod()+" "+requestPath);

            String requestBody = new String(body);
            REQ_RES_LOGGER.debug(requestBody);
            ListenableFuture<ClientHttpResponse> listenableFuture = execution.executeAsync(request, body);
            ListenableFutureAdapter<ClientHttpResponse,ClientHttpResponse> futureAdapter=
                    new ListenableFutureAdapter<ClientHttpResponse, ClientHttpResponse>(listenableFuture) {
                        @Override
                        protected ClientHttpResponse adapt(ClientHttpResponse adapteeResult) throws ExecutionException {
                            return logResponseBody(adapteeResult);
                        }
                    };
            return  futureAdapter;
        }

    private ClientHttpResponse logResponseBody(ClientHttpResponse response,boolean isImageInResponse){
                try {
                    BufferingClientHttpResponseWrapper responseWrapper = new BufferingClientHttpResponseWrapper(response);
                    REQ_RES_LOGGER.debug("Response Status Code :" + responseWrapper.getStatusCode().value());
                    REQ_RES_LOGGER.debug("Response Status Text :" + responseWrapper.getStatusText());
                    if (response != null && response.getBody() != null) {
                        String responseXml = IOUtils.toString(responseWrapper.getBody(), Charset.defaultCharset());
                        REQ_RES_LOGGER.debug(responseXml);
                    } else {
                        REQ_RES_LOGGER.debug("Empty Response Body");
                    }
                    return responseWrapper;
                }catch (IOException io){
                    REQ_RES_LOGGER.error("Unexpected Error ",io);
                    return response;
                }

        }
    }

Body:
I finally figured out a way to use this class. As this is a final class it is meant to be used within Springframework only. There was a pull request in springframework for this change. I am not sure when this change will be merged in the framework, but below are the classes which will solve the above problem. These classes would be helpful if we want to intercept the request and response for logging.

BufferingAsyncClientHttpRequestFactory

public class BufferingAsyncClientHttpRequestFactory extends

BufferingClientHttpRequestFactory
        implements AsyncClientHttpRequestFactory {

    private final AsyncClientHttpRequestFactory requestFactory;
    /**
     * Create a buffering wrapper for the given {@link ClientHttpRequestFactory}.
     * @param requestFactory the target request factory to wrap
     */
    public BufferingAsyncClientHttpRequestFactory(AsyncClientHttpRequestFactory requestFactory) {
        super((ClientHttpRequestFactory) requestFactory);
        this.requestFactory=requestFactory;
    }

    /**
     * Indicates whether the request/response exchange for the given URI and method
     * should be buffered in memory.
     * <p>The default implementation returns {@code true} for all URIs and methods.
     * Subclasses can override this method to change this behavior.
     * @param uri the URI
     * @param httpMethod the method
     * @return {@code true} if the exchange should be buffered; {@code false} otherwise
     */

    @Override
    public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
        AsyncClientHttpRequest request = requestFactory.createAsyncRequest(uri, httpMethod);
        if (shouldBuffer(uri, httpMethod)) {
            return new BufferingAsyncClientHttpRequestWrapper(request);
        }
        else {
            return request;
        }
    }

    protected boolean shouldBuffer(URI uri, HttpMethod httpMethod) {
        return true;
    }

}

BufferingAsyncClientHttpRequestWrapper.java

public class BufferingAsyncClientHttpRequestWrapper extends AbstractBufferingAsyncClientHttpRequest {

    private final AsyncClientHttpRequest request;

    public BufferingAsyncClientHttpRequestWrapper(AsyncClientHttpRequest asyncClientHttpRequest){
        this.request=asyncClientHttpRequest;
    }

    @Override
    public HttpMethod getMethod() {
        return this.request.getMethod();
    }

    @Override
    public URI getURI() {
        return this.request.getURI();
    }

    @Override
    protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
        this.request.getHeaders().putAll(headers);
        if(bufferedOutput.length>0){
            StreamUtils.copy(bufferedOutput,this.request.getBody());
        }
        ListenableFuture<ClientHttpResponse> futureResponse = this.request.executeAsync();
        ListenableFutureAdapter<ClientHttpResponse,ClientHttpResponse> bufferedResponse =
                new ListenableFutureAdapter<ClientHttpResponse, ClientHttpResponse>(futureResponse) {
                    @Override
                    protected ClientHttpResponse adapt(ClientHttpResponse adapteeResult) throws ExecutionException {
                        return new BufferingClientHttpResponseWrapper(adapteeResult);
                    }
                };
        return bufferedResponse;
    }
}


来源: stackexchange

问:
Golang: Error while make test: signal: killed
I am getting this error while running make test on a Golang project:

```<code>signal: killed
FAIL <package name>
make: *** [test] Error 1
</code>```

The same code was running perfectly fine until yesterday.
Note: I tried doing make test on other branches also but same result.

答:
Thanks a lot @JimB

I uninstalled the Xcode and it runs fine now. Weird !

ContentLicense: CC BY-SA 3.0

Body:
I am getting this error while running make test on a Golang project:

signal: killed
FAIL <package name>
make: *** [test] Error 1

The same code was running perfectly fine until yesterday.
Note: I tried doing make test on other branches also but same result.


问:
injection of service is failed
I m trying to send an email using a service class, but I always receive null .I can't see my mistake

here is my code
this my notification service

```<code>@Autowired
private JavaMailSender javaMailSender;
/*
@Autowired
public  NotificationService(JavaMailSender javaMailSender){
    this.javaMailSender = javaMailSender;

}
*/
@Async
public void sendNotificaitoin(String msg) throws MailException, InterruptedException {

    System.out.println("Sleeping now...");
    Thread.sleep(10000);

    System.out.println("Sending email...");

    SimpleMailMessage mail = new SimpleMailMessage();
    mail.setTo("ghanem.dhafer@gmail.com");
    mail.setFrom("ulquiorra.cifer19924@gmail.com");
    mail.setSubject("NOTIFICATION");
    mail.setText(msg);
    javaMailSender.send(mail);

    System.out.println("Email Sent!");
</code>```

this is where I invoke the service:

```<code>@Autowired
private NotificationService notificationService;
try {

    notificationService.sendNotificaitoin(msg);
    }catch( Exception e ){
        // catch error
        System.out.println("Error Sending Email: " + e.getMessage());
    }
</code>```

i also create beans, all tuto shows sending email in controller but i need to send in a service(class).
any ideas?

答:
Put the JavaMailSender in a class and annotate it with @Service like

```<code>@Service
JavaMailSender {
        void sendNotification();
}
</code>```

Then use it in another class like

```<code>@Autowired
JavaMailSender notificationService;

// use the service in a method
void somewhere(){
        notificationService.sendNotification(yourArguments);
}
</code>```

Title: injection of service is failed

Body:
I m trying to send an email using a service class, but I always receive null .I can't see my mistake

here is my code
this my notification service

@Autowired
private JavaMailSender javaMailSender;
/*
@Autowired
public  NotificationService(JavaMailSender javaMailSender){
    this.javaMailSender = javaMailSender;

}
*/
@Async
public void sendNotificaitoin(String msg) throws MailException, InterruptedException {

    System.out.println("Sleeping now...");
    Thread.sleep(10000);

    System.out.println("Sending email...");

    SimpleMailMessage mail = new SimpleMailMessage();
    mail.setTo("ghanem.dhafer@gmail.com");
    mail.setFrom("ulquiorra.cifer19924@gmail.com");
    mail.setSubject("NOTIFICATION");
    mail.setText(msg);
    javaMailSender.send(mail);

    System.out.println("Email Sent!");

this is where I invoke the service:

@Autowired
private NotificationService notificationService;
try {

    notificationService.sendNotificaitoin(msg);
    }catch( Exception e ){
        // catch error
        System.out.println("Error Sending Email: " + e.getMessage());
    }

i also create beans, all tuto shows sending email in controller but i need to send in a service(class).
any ideas?

Body:
Put the JavaMailSender in a class and annotate it with @Service like

@Service
JavaMailSender {
        void sendNotification();
}

Then use it in another class like

@Autowired
JavaMailSender notificationService;

// use the service in a method
void somewhere(){
        notificationService.sendNotification(yourArguments);
}


问:
dynamic definition of macro
I need to define function and macro dynamically, for dynamic function the followinf code work fine, but it fail when I try to add macro inside the first one.
Is there a manner to get the needed behavior</p>

```<code>#define INIT_PATH_FUNCTION(UCI_PATH, DPATH) \
struct ctx *ctx_##_PATH; \
int print##_PATH(char *package) \
{\
    print("package %s \n", package); \
    return 0; \
}\
#define foreach_file_##PATH(path) \
    for (section = print##_PATH(path); \
        section != NULL; \
        section = print##_PATH(path))\

#define PRINT(UCI_PATH, path) print##_PATH(path)

INIT_PATH_FUNCTION(test, "/etc/")
INIT_PATH_FUNCTION(test2, "/root/")
</code>```

答:
I need to define function and macro dynamically

Then I'm afraid you are destined for dissatisfaction.  You can write a macro whose replacement text contains macro invocations, but you cannot produce a macro definition by expanding a macro.  Ultimately, it comes down to paragraph 6.10/2 of the standard, which says, in part

A preprocessing directive consists of a sequence of preprocessing
  tokens that satisfies the following constraints: The first token in
  the sequence is a # preprocessing token that (at the start of
  translation phase 4) is either the first character in the source file
  (optionally after white space containing no new-line characters) or
  that follows white space containing at least one new-line character.

(Emphasis added.)

Although you can give a macro replacement text that has the form of a macro definition, the replacement text does not satisfy the requirements for being a preprocessing directive of any kind at the start of translation phase 4 (wherein preprocessing directives are executed).  That expansion of the macro produces text of such a form is irrelevant, because it comes too late.

Function definitions (and declarations) are another matter, however.  You certainly can produce these via macros if you wish, and this is a reasonable thing to do if you need several distinct functions with a lot of boilerplate code.

Title: dynamic definition of macro

Body:
I need to define function and macro dynamically, for dynamic function the followinf code work fine, but it fail when I try to add macro inside the first one.
Is there a manner to get the needed behavior

#define INIT_PATH_FUNCTION(UCI_PATH, DPATH) \
struct ctx *ctx_##_PATH; \
int print##_PATH(char *package) \
{\
    print("package %s \n", package); \
    return 0; \
}\
#define foreach_file_##PATH(path) \
    for (section = print##_PATH(path); \
        section != NULL; \
        section = print##_PATH(path))\

#define PRINT(UCI_PATH, path) print##_PATH(path)

INIT_PATH_FUNCTION(test, "/etc/")
INIT_PATH_FUNCTION(test2, "/root/")


问:
Having two views/panes in a view controller
Here image from AliExpress iphone app.Kindly view this first

I had to implement it. Now that i have implemented the custom segmented control programmatically(not the default segmented control interface builder component), i am unable to perform some action once it's clicked. The situation is:   As i posted below, i have that code in a class. and i have two container views linked to another class. What i want is that once i click these, the container views data gets changed. I have implementing it by creating instance of other class and accessing the methods but i am getting nil value errors and app is crashing. Can you please tell me how to do that? I can't directly link those as outlets to containers views classes as they are not interface components but programmatically implemented segmented controls.

Please help. thanks

答: The answer is that you are looking for a segmented control using containers.</p>


问:
How to change background color of days before today in FullCalendar...?
I want to change the background color of Days in my FullCalendar

How can i do this..?

答:
Do it in css, as simple as
</p>

```<code>.fc-past {
  background-color: #F5F5F6
}
</code>```

Body:
Do it in css, as simple as

.fc-past {
  background-color: #F5F5F6
}


问:
How to select files from a grid using a checkbox to add to a zip to download
I have a directory viewer that generates rows based on the files present in the directory that are  displayed on the grid. I'm trying to add checkboxes that, when checked, will add the selected files to a zip archive. Currently my code is this

```<code><div id="directory-list-header">
            <div class="row">
                <div class="col-md-7 col-sm-6 col-xs-10">File</div>
                <div class="col-md-1 col-sm-2 col-xs-2 text-right">Size</div>
                <div class="col-md-2 col-sm-2 hidden-xs text-right">Last Modified</div>
                <div class="col-md-2 col-sm-2 col-xs-2 text-right">Select</div>
            </div>
        </div>

        <ul id="directory-listing" class="nav nav-pills nav-stacked">

            <?php foreach($dirArray as $name => $fileInfo): ?>
                <li data-name="<?php echo $name; ?>" data-href="<?php echo $fileInfo['url_path']; ?>">
                    <a href="<?php echo $fileInfo['url_path']; ?>" class="clearfix" data-name="<?php echo $name; ?>">

                        <div class="row">
                            <span class="file-name col-md-7 col-sm-6 col-xs-9">
                                <i class="fa <?php echo $fileInfo['icon_class']; ?> fa-fw"></i>
                                <?php echo $name; ?>
                            </span>

                            <span class="file-size col-md-1 col-sm-2 col-xs-3 text-right">
                                <?php echo $fileInfo['file_size']; ?>
                            </span>

                            <span class="file-modified col-md-2 col-sm-2 hidden-xs text-right">
                                <?php echo $fileInfo['mod_time']; ?>
                            </span>

                            <span class="selected col-md-2 col-sm-2 col-xs-1 text-right">
                                <form method="get">
                                    <input type="checkbox" name="selected[]" value="<?php echo $fileInfo['url_path']; ?>">
                                </form>
                            </span>
                        </div>
</code>```

I added the  tag and I was thinking that I should add any files that are checked to an array, then send that array to a zip using ZipArchive() and serving it to the client via a stream, however I'm not sure how the code would look for the checkbox logic since this is my first foray into HTML/PHP. Any help would be appreciated, I have the user interface squared away, it's just a matter of getting the background working

答:
php has a class that does it.

Learn about it here http://php.net/manual/en/class.ziparchive.php.

The code bellow can solve your issue;

```<code><?php
  $zip = new ZipArchive;

  function addFileToZip($aFileZipName, $aFileName, $fileContent){

    if ($zip->open($aFileZipName) === TRUE) {

      $zip->addFromString($aFileName, $fileContent);

      $zip->close();

      return true;
    } else {

      return false;

    }
  }
?>
</code>```

if this explanation couldn't help you, please, post your complete code.
By the way, consider use a more elegant way to produce your HTML code, like angular or jquery.

Body:
I have a directory viewer that generates rows based on the files present in the directory that are  displayed on the grid. I'm trying to add checkboxes that, when checked, will add the selected files to a zip archive. Currently my code is this

File

Size

Last Modified

Select

            <?php foreach($dirArray as $name => $fileInfo): ?>
                <li data-name="<?php echo $name; ?>" data-href="<?php echo $fileInfo['url_path']; ?>">
                    <a href="<?php echo $fileInfo['url_path']; ?>" class="clearfix" data-name="<?php echo $name; ?>">

                                <i class="fa <?php echo $fileInfo['icon_class']; ?> fa-fw">
                                <?php echo $name; ?>

                                <?php echo $fileInfo['file_size']; ?>

                                <?php echo $fileInfo['mod_time']; ?>

                                <form method="get">
                                    <input type="checkbox" name="selected[]" value="<?php echo $fileInfo['url_path']; ?>">
                                </form>

I added the  tag and I was thinking that I should add any files that are checked to an array, then send that array to a zip using ZipArchive() and serving it to the client via a stream, however I'm not sure how the code would look for the checkbox logic since this is my first foray into HTML/PHP. Any help would be appreciated, I have the user interface squared away, it's just a matter of getting the background working

Body:
php has a class that does it.

Learn about it here http://php.net/manual/en/class.ziparchive.php.

The code bellow can solve your issue;

<?php
  $zip = new ZipArchive;

  function addFileToZip($aFileZipName, $aFileName, $fileContent){

    if ($zip->open($aFileZipName) === TRUE) {

      $zip->addFromString($aFileName, $fileContent);

      $zip->close();

      return true;
    } else {

      return false;

    }
  }
?>

if this explanation couldn't help you, please, post your complete code.
By the way, consider use a more elegant way to produce your HTML code, like angular or jquery.


问:
ANTLR4: extraneous input caused by a rule not being tested
The actual grammar I'm working with is much larger but this snippet illustrates my problem.

```<code>grammar test ;

word: CHAR(CHAR|DIGIT)* ;

DIGIT: [0-9] ;
CHAR: [a-z] ;
OR: 'or' ;
</code>```

When testing the rule word, any words containing a sub string of "or" produce an extraneous input error. For example:

hello : FINE

antidisestablishmentarianism : FINE

horse : ERROR

Why is ANTLR picking this up? The or isn't even used.

I'm fairly sure that this is the same problem this person had but I'm having trouble making sense of it.

答:
The CHAR rule matches text with a length=1; the OR rule with a length=2. So, the lexer will choose the OR rule to match any or text sequence in preference to the CHAR rule.

That is, the lexer will choose rules based first on longest match, and then on grammar order.

Body:
The actual grammar I'm working with is much larger but this snippet illustrates my problem.

grammar test ;

word: CHAR(CHAR|DIGIT)* ;

DIGIT: [0-9] ;
CHAR: [a-z] ;
OR: 'or' ;

When testing the rule word, any words containing a sub string of "or" produce an extraneous input error. For example:

hello : FINE

antidisestablishmentarianism : FINE

horse : ERROR

Why is ANTLR picking this up? The or isn't even used.

I'm fairly sure that this is the same problem this person had but I'm having trouble making sense of it.


问:
iOS MVVM: Is Delegation Pattern a Requirement?
First of, researching MVVM for iOS is a headache as there are multiple varying implementations floating around online. So far I found 3 categories of MVVM:

MVVM that uses Delegation / Protocols to update the ViewController / View

MVVM with KVO binding like ReactiveCocoa

MVVM as a simple helper / wrapper class for the model (no protocols, no KVO)

Is Delegation Pattern or KVO a requirement for implementing MVVM in iOS?

I've seen a number of MVVM examples online that do not make use of Protocols / Delegation, and instead just use MVVM as a helper class to encapsulate the Model and provide state to the ViewController.

Is that still considered MVVM?

答:
It my opinion of MVVM.

MVVM or MV-whatever is just a architecture try to separate the view and logic. It have some benefits like enhance your code testability and follow SRP let your debug much easier... etc.

Another key point, MVVM communicate between View-Model and View use data binding, when user update the value from UI, and the value directly update to View-Model.

As you say, there have several choice to implement MVVM. But if you choice the option 3, how to binding the value from View-Model to View and Model to View-Model?

If using KVO View can observed View-Model's
 propertys but View-Model didn't need to know anything about View.

If using delegate pattern, View-Model just need to implement what View needed and nothing more need to know about View.

Using KVO or delegate pattern is just try to decoupling between View-Model and View, and data binding between them.

So I think the option 3 didn't considered MVVM. Maybe it still strong coupling between View and View-Model.


问:
How do I reset axis 1 in pandas?
I want to reset my column headers in pandas.  I want my column names to be my top row and then my column headers to be reset to 0,1,2,3 in pandas dataframe.  How do i perform this operation?</p>

答:
You can change the column header names with .columns property of pandas dataframe.
To reset it to 0,1,2,3.. use the following code</p>

```<code>>>> df.columns = list(range(len(df.columns)))
</code>```

Title: How do I reset axis 1 in pandas?

Body:
You can change the column header names with .columns property of pandas dataframe.
To reset it to 0,1,2,3.. use the following code

>>> df.columns = list(range(len(df.columns)))


问:
Cannot find module 'meteor-promise'
I am using Meteor 1.4.3.2 on a windows7 dev environment.
I've ran into a problem with an application after attempting to remove a failed demeteorizer attempt. After removal of demeteorizer folders/files now receiving error:

```<code>module.js:327
    throw err;
    ^
Error: Cannot find module 'meteor-promise'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\Users\muser\AppData\Local\.meteor\packages\meteor-
tool\1.4.0-1\mt-os.windows.x86_32\tools\tool-env\install-promise.js:6:1)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
</code>```

I believe this meteor-promise is related to the Fibers module used in demeteorizer.
Seems that files were inadvertently removed from outside of application folders due to sym-link to somewhere in \AppData\Local.meteor....  I think.

My other applications are still working fine, so a meteor reinstall seems unlikely to fix issue.

Adding to the excitement none of my saved versions (including fresh clones from repo) will work either. This I think adds evidence to the sym-link theory.

Any suggestions on best approach to fix the application?

Thanks very much for your time and expertise.

答:
Thanks for your input @jordanwillis!

Absolutely a mess. Points out that while I've been happily coding along with Meteor I've neglected understanding what's under the hood.
Turns out this app was using 1.4.0, not 1.4.3 as I previously stated.

Here are the actions I took which fixed my problem.

Remove folders:

```<code>C:\Users\muser\testApp\.meteor\local\dev_bundle*\*
C:\Users\muser\AppData\Local\.meteor\packages\meteor-tool\1.4.0-1\*
</code>```

Ran:

```<code>C:\Users\muser\testApp> meteor run
</code>```

Meteor re-installed 1.4.0-1 and did not try to recreate the dev_bundle folder which I assume was only needed for demeteorizer.
The application started up and all seems good.

Thanks again.

Title: Cannot find module 'meteor-promise'

Body:
I am using Meteor 1.4.3.2 on a windows7 dev environment.
I've ran into a problem with an application after attempting to remove a failed demeteorizer attempt. After removal of demeteorizer folders/files now receiving error:

module.js:327
    throw err;
    ^
Error: Cannot find module 'meteor-promise'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\Users\muser\AppData\Local\.meteor\packages\meteor-
tool\1.4.0-1\mt-os.windows.x86_32\tools\tool-env\install-promise.js:6:1)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)

I believe this meteor-promise is related to the Fibers module used in demeteorizer.
Seems that files were inadvertently removed from outside of application folders due to sym-link to somewhere in \AppData\Local.meteor....  I think.

My other applications are still working fine, so a meteor reinstall seems unlikely to fix issue.

Adding to the excitement none of my saved versions (including fresh clones from repo) will work either. This I think adds evidence to the sym-link theory.

Any suggestions on best approach to fix the application?

Thanks very much for your time and expertise.

Body:
Thanks for your input @jordanwillis!

Absolutely a mess. Points out that while I've been happily coding along with Meteor I've neglected understanding what's under the hood.
Turns out this app was using 1.4.0, not 1.4.3 as I previously stated.

Here are the actions I took which fixed my problem.

Remove folders:

C:\Users\muser\testApp\.meteor\local\dev_bundle*\*
C:\Users\muser\AppData\Local\.meteor\packages\meteor-tool\1.4.0-1\*

Ran:

C:\Users\muser\testApp> meteor run

Meteor re-installed 1.4.0-1 and did not try to recreate the dev_bundle folder which I assume was only needed for demeteorizer.
The application started up and all seems good.

Thanks again.


问:
In-built Sorting in C++
How do use vector or in-built sort function in C++ with most of the language in C? I am trying to just sort an array for a C program. Can it explained with a simple code with sort implementation? I am very new to C++.</p>

答:
This method used built in sorting algorithm and changes its time complexity based on the input array.</p>

```<code> 1. #include <bits/stdc++.h>
        using namespace std;

        int main()
        {
            int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
            int n = sizeof(arr)/sizeof(arr[0]);
           sort(arr, arr+n); //sort(arr, arr+n, greater<int>()); for descending

            cout << "\nArray after sorting

 using "
             "default sort is : \n";
        for (int i = 0; i < n; ++i)
            cout << arr[i] << " ";

        return 0;
    }
</code>```

Title: In-built Sorting in C++

Body:
This method used built in sorting algorithm and changes its time complexity based on the input array.

 1. #include <bits/stdc++.h>
        using namespace std;

        int main()
        {
            int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
            int n = sizeof(arr)/sizeof(arr[0]);
           sort(arr, arr+n); //sort(arr, arr+n, greater<int>()); for descending

            cout << "\nArray after sorting

 using "
             "default sort is : \n";
        for (int i = 0; i < n; ++i)
            cout << arr[i] << " ";

        return 0;
    }


问:
Unresponsive application after launched with JNLP
I'm looking into the JNLP stuff and I decided to try to run a small application that I made with JNLP. I created a simple java program and the jnlp file. I upload both the jar file and the jnlp file to my apache server, along with an html file to display the Launch button. This is the jnlp file (I'm not 100% sure if it's correct):

```<code><?xml version="1.0" encoding="UTF-8"?>
  <jnlp spec="1.0+" codebase="http://localhost:8080/" href="example.jnlp">
  <information>
      <title>Example</title>
      <vendor>Dev</vendor>
  </information>
  <resources>
      <!-- Application Resources -->
      <j2se version="1.6+"
            href="http://java.sun.com/products/autodl/j2se"/>
      <jar href="Example.jar" main="true" />

  </resources>
  <application-desc name="Example"
       main-class="main.Example"
       width="600"
       height="600">
   </application-desc>
   <update check="background"/>
  </jnlp>
</code>```

The following is my html file on my apache server:

```<code><html>
  <head>
    <title>Example</title>
  </head>
  <body>
    <script src="http://www.java.com/js/deployJava.js"></script>
    <script>
      // using JavaScript to get location of JNLP file relative to HTML page
      var dir = location.href.substring(0, location.href.lastIndexOf('/')+1);
      var url = dir + "example.jnlp";
  document.alert(dir);
      deployJava.createWebStartLaunchButton(url, '1.6.0');
    </script>
  </body>
</html>
</code>```

The problem is, when I click the Launch button it asks if I want to run example.jnlp. Then after a bit the application just opens up but when I click any the buttons they do nothing. It's as if the GUI is showing but all over the under lying logic is not there. Any idea what may be the issue?

答:
..This is the jnlp file (I'm not 100% sure if it's correct): ..

It is not 100% correct.  Check it using JaNeLA.  Of most concern is the HREF of "examp.jnlp", which does not seem to match the actual name.

..The following is my html ..

Which is also over complicated, and quite probably invalid, though I doubt that is the problem here.  For the moment, launch the JNLP from a plain old HTML link.  I am guessing you are testing from a machine running 1.6+ Java, so the deployJava.js is not necessary at this stage.

..after a bit the application just opens up but when I click any the buttons they do nothing. It's as if the GUI is showing but all over the under lying logic is not there. Any idea what may be the issue?

Without code it is a little hard to say.  But some preliminary questions are:

Does the code swallow
exceptions at any stage?  (If
so, fix that immediately!)

What is reported in the Java Console when the application launches?  When debugging, it is essential to ensure the console pops open for every launch of a Java applet or JWS app.  Console visibility is configured via the Java Control Panel.

ContentLicense: CC BY-SA 2.5

Body:
I'm looking into the JNLP stuff and I decided to try to run a small application that I made with JNLP. I created a simple java program and the jnlp file. I upload both the jar file and the jnlp file to my apache server, along with an html file to display the Launch button. This is the jnlp file (I'm not 100% sure if it's correct):

<?xml version="1.0" encoding="UTF-8"?>
  <jnlp spec="1.0+" codebase="http://localhost:8080/" href="example.jnlp">
  <information>
      <title>Example</title>
      <vendor>Dev</vendor>
  </information>
  <resources>

      <j2se version="1.6+"
            href="http://java.sun.com/products/autodl/j2se"/>
      <jar href="Example.jar" main="true" />

  </resources>
  <application-desc name="Example"
       main-class="main.Example"
       width="600"
       height="600">
   </application-desc>
   <update check="background"/>
  </jnlp>

The following is my html file on my apache server:

    <title>Example</title>

The problem is, when I click the Launch button it asks if I want to run example.jnlp. Then after a bit the application just opens up but when I click any the buttons they do nothing. It's as if the GUI is showing but all over the under lying logic is not there. Any idea what may be the issue?


问:
Material-UI app bar comes with a margin
I used  Material-UI 's AppBar component and it works well, but comes with a margin, anyone got a workaround. I need to get rid of the margin.</p>

答:
If you use default React Web template to create the project, you can edit the index.html file in public folder, add below style in body:

...
```
</div>
</div>
</p>

<p>Or add it in you css file like below:</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-css lang-css prettyprint-override"><code>body {
    margin: 0;
}</code>```

Title: Material-UI app bar comes with a margin

Body:
If you use default React Web template to create the project, you can edit the index.html file in public folder, add below style in body:

<body style="margin: 0">
...
</body>

Or add it in you css file like below:

body {
    margin: 0;
}


问:
How do ldap search for email address in contacts' 2nd/3rd alternate email addresses?
I have an LDAP server with my email contacts so that I can lookup contacts by name/email, etc. However, it only seems to search and find the first email address for any contact.

For example, if I have a person:

```<code>LastName: Doe
FirstName: John
Email: jdoe@work.com
Email2: johndoe@home.com
Email3: johndoe@fun.com
</code>```

It only searches through or returns the first email. For example, if I search for "John", it will return only the "jdoe@work.com" even though the other two email addresses have "john" in them. The search filters I've tried are:

```<code>//This one will both look through and match the first email but ignores the 2nd/3rd
(|(displayName=*%v*)(mail=*%v*)(uid=*%v*)(givenname=*%v*)(sn=*%v*)(cn=*%v*))

//This one throws an error saying "mail2" and "mail3" are invalid filters.
(|(displayName=*%v*)(mail=*%v*)(mail2=*%v*)(mail3=*%v*)(uid=*%v*)(givenname=*%v*)(sn=*%v*)(cn=*%v*))
</code>```

What should I be using?

Also, does anyone have a link to some page that lists all the possible filters I can put in an ldap person search?

答:
Active Directory was released with some schema choices that are questionable. Now it is hard to fix them.

One of those is that mail, was flagged as single valued. This should have been a multivalued attribute. Thus the use of proxyAddresses, where it tries to overload a string syntax attribute with more information by using smtp: or x500: or SIP: to indicate a protocol for the address. Then upper case (SMTP) means primary and lower case (smtp) means secondary.

This also occured for telephoneNumber being single valued, and extra values now overflow into the attribute otherPhone.

Same for:

facsimileTelephoneNumber and otherFacsimileTelephoneNumber

labelledUri and url

homePhone and otherHomePhone

pager and otherPager

mobile and otherMobile

Body:
I have an LDAP server with my email contacts so that I can lookup contacts by name/email, etc. However, it only seems to search and find the first email address for any contact.

For example, if I have a person:

LastName: Doe
FirstName: John
Email: jdoe@work.com
Email2: johndoe@home.com
Email3: johndoe@fun.com

It only searches through or returns the first email. For example, if I search for "John", it will return only the "jdoe@work.com" even though the other two email addresses have "john" in them. The search filters I've tried are:

//This one will both look through and match the first email but ignores the 2nd/3rd
(|(displayName=*%v*)(mail=*%v*)(uid=*%v*)(givenname=*%v*)(sn=*%v*)(cn=*%v*))

//This one throws an error saying "mail2" and "mail3" are invalid filters.
(|(displayName=*%v*)(mail=*%v*)(mail2=*%v*)(mail3=*%v*)(uid=*%v*)(givenname=*%v*)(sn=*%v*)(cn=*%v*))

What should I be using?

Also, does anyone have a link to some page that lists all the possible filters I can put in an ldap person search?


问:
Can't connect to MySQL server on 'internal-db.xxxxx.gridserver.com' (4)
I'm trying to connect to mySQL via Sequel Pro, but continue to receive the "MySQL said: Can't connect to MySQL server on 'internal-db.xxxx.gridserver.com' (4)" error message.

mySQL is hosted via mediatemple.

I'm on macOS Sierra v 10.12.2

I've increased connection time to 30secs.

right before this error I couldn't connect with error code 61.  I've changed port from 3306 to 3307 which has bought me here.

答: Solved: Turns out I needed to refresh my allowed remote IP list with the host.</p>


问:
Update multiple columns in table with SET command
I don't necessarily have an error, mainly curious as to what is going on behind the scenes with an UPDATE I am trying to perform on multiple columns of the same table on a single record, using the value of one column and some math to set the value in the other column. Basically a two for one is what I am trying to accomplish.
I have this row in a table named pipe_tally3:

```<code> id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    0 |      0 | na  | na    | 2017-03-27
</code>```

I try to UPDATE it like this:

```<code>UPDATE pipe_tally3
SET cuts = 2.0, new_lt = lt - cuts
WHERE jt_id = 'Asset-33';
UPDATE 1
</code>```

Then when I check that row again:

```<code> id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    2 |     74 | na  | na    | 2017-03-27
</code>```

The cuts column did get updated and is now showing the value 2 but the new_lt columns shows the value 74. But it should be (or I want it set to) the value of 72, which would be the value of the lt column 74 subtracted from the cuts column of 2. Why does this not work like this is my main question?
But if I update the cuts column by itself with

```<code>UPDATE pipe_tally3
SET cuts = 3.0 WHERE jt_id = 'Asset-33';
UPDATE 1
</code>```

And it does get updated.

```<code>id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    3 |     72 | na  | na    | 2017-03-27
</code>```

I can then use

```<code>UPDATE pipe_tally3
SET new_lt = lt - cuts WHERE jt_id = 'Asset-33';
UPDATE 1
</code>```

And it works as desired by using the values from the lt and cuts columns when it sets the new_lt:

```<code>id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    3 |     71 | na  | na    | 2017-03-27
</code>```

Is there a way I can accomplish this in PostgreSQL? Thanks in advance.

Edit
I realize I can always do this by hard coding the value in as well:

```<code>UPDATE pipe_tally3
SET cuts = 3.5, new_lt = lt - 3.5
WHERE jt_id = 'Asset-33';
UPDATE 1
</code>```

And that works

```<code>id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |  3.5 |   70.5 | na  | na    | 2017-03-27
</code>```

Just wanted to know why it does not work (or I am not doing something correctly) the other way as specified above.

答:
```<code>update pipe_tally3
set cuts = s.cuts, new_lt = lt - s.cuts
from (
    select 2.0 as cuts
) s
where jt_id = 'asset-33';
</code>```

Body:
I don't necessarily have an error, mainly curious as to what is going on behind the scenes with an UPDATE I am trying to perform on multiple columns of the same table on a single record, using the value of one column and some math to set the value in the other column. Basically a two for one is what I am trying to accomplish.
I have this row in a table named pipe_tally3:

 id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    0 |      0 | na  | na    | 2017-03-27

I try to UPDATE it like this:

UPDATE pipe_tally3
SET cuts = 2.0, new_lt = lt - cuts
WHERE jt_id = 'Asset-33';
UPDATE 1

Then when I check that row again:

 id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    2 |     74 | na  | na    | 2017-03-27

The cuts column did get updated and is now showing the value 2 but the new_lt columns shows the value 74. But it should be (or I want it set to) the value of 72, which would be the value of the lt column 74 subtracted from the cuts column of 2. Why does this not work like this is my main question?
But if I update the cuts column by itself with

UPDATE pipe_tally3
SET cuts = 3.0 WHERE jt_id = 'Asset-33';
UPDATE 1

And it does get updated.

id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    3 |     72 | na  | na    | 2017-03-27

I can then use

UPDATE pipe_tally3
SET new_lt = lt - cuts WHERE jt_id = 'Asset-33';
UPDATE 1

And it works as desired by using the values from the lt and cuts columns when it sets the new_lt:

id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    3 |     71 | na  | na    | 2017-03-27

Is there a way I can accomplish this in PostgreSQL? Thanks in advance.

Edit
I realize I can always do this by hard coding the value in as well:

UPDATE pipe_tally3
SET cuts = 3.5, new_lt = lt - 3.5
WHERE jt_id = 'Asset-33';
UPDATE 1

And that works

id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |  3.5 |   70.5 | na  | na    | 2017-03-27

Just wanted to know why it does not work (or I am not doing something correctly) the other way as specified above.


问:
CSS overlay with scrolling content
I am trying to get a content panel inside a fixed-position overlay to scroll vertically, but it does not scroll, it is forced into its container.

Can you spot the mistake?
fiddle

Only the green bottom should scroll the header should stay where it is.

```<code><html>
<head>
    <style>
        * {
            box-sizing: border-box;
        }
    </style>
</head>
<body style="background-color: #502074;">
    <div style="position: fixed; width:100%; height: 100%;">
        <div style="height: 80px; width: 100%; background-color: yellow;">Top</div>
        <div style="height: 10000px; width: 100%; background-color: green; overflow: scroll;">Bottom</div>
    </div>

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

答:
Thanks @driconmax, it was nearly what I need, worked it out now:

```<code><body style="background-color: #502074;">
    <div style="position: fixed; width:100%; height: 100%; ">
        <div style="height: 80px; width: 100%; background-color: yellow;">Top</div>
        <div style="height:calc(100% - 80px);overflow: scroll;">
          <div style="height: 10000px;  width: 100%; background-color: green; ">Bottom</div>
        </div>
    </div>

</body>
</code>```

Updated fiddle

Title: CSS overlay with scrolling content

Body:
I am trying to get a content panel inside a fixed-position overlay to scroll vertically, but it does not scroll, it is forced into its container.

Can you spot the mistake?
fiddle

Only the green bottom should scroll the header should stay where it is.

Top

Bottom

Body:
Thanks @driconmax, it was nearly what I need, worked it out now:

<body style="background-color: #502074;">
    <div style="position: fixed; width:100%; height: 100%; ">
        <div style="height: 80px; width: 100%; background-color: yellow;">Top</div>
        <div style="height:calc(100% - 80px);overflow: scroll;">
          <div style="height: 10000px;  width: 100%; background-color: green; ">Bottom</div>
        </div>
    </div>

</body>

Updated fiddle


问:
Corresponding Vector to TRUE/FALSE Vector in R
I have two vectors

```<code>> filename
[1] "10021978_1909-07-21_ed-1_seq-4"  "10021978_1910-01-19_ed-1_seq-31"
[3] "10021978_1910-01-19_ed-1_seq-31" "10021978_1910-01-19_ed-1_seq-31"
[5] "10021978_1910-01-19_ed-1_seq-31" "10021978_1911-06-07_ed-1_seq-12"
[7] "10021978_1911-07-05_ed-1_seq-11" "10021978_1911-07-12_ed-1_seq-11"
[9] "10021978_1911-07-12_ed-1_seq-11" "10021978_1911-09-27_ed-1_seq-4"
</code>```

AND

```<code>> dups = duplicated(filename)
> dups
[1] FALSE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE FALSE
</code>```

I am dealing with exporting files but not overwriting files with duplicate file names. I have a few that are duplicates in this set of 10. What I need to do is make those filenames unique.

How can I create a new vector that would have nothing wherever the vector dups is FALSE, and then nonzero wherever TRUE? The tricky thing is that I need it to begin incrementing starting with 2 when there is a series of TRUE next to each other then reset when there is a FALSE. The vector I need for this set would be:

ans = c("", "", 2, 3, 4, "", "", "", 2, "")

so that I can append it to the filenames to deal with duplicates. The final filename vector I need would be:

```<code>[1] "10021978_1909-07-21_ed-1_seq-4"  "10021978_1910-01-19_ed-1_seq-31"
[3] "10021978_1910-01-19_ed-1_seq-31-2" "10021978_1910-01-19_ed-1_seq-31-3"
[5] "10021978_1910-01-19_ed-1_seq-31-4" "10021978_1911-06-07_ed-1_seq-12"
[7] "10021978_1911-07-05_ed-1_seq-11" "10021978_1911-07-12_ed-1_seq-11"
[9] "10021978_1911-07-12_ed-1_seq-11-2" "10021978_1911-09-27_ed-1_seq-4"
</code>```

Thank you very much in advance.

答:
make.unique should be good enough, but if you need the numbering to start at 2, perhaps it is easier to use ave.

Here is an example of both so you can see the difference between the two approaches:

```<code>a <- c("a", "a", "a", "b", "c", "d", "b", "d", "e")
make.unique(a, sep = "-")
# [1] "a"   "a-1" "a-2" "b"   "c"   "d"   "b-1" "d-1" "e"

dups <- ave(a, a, FUN = seq_along)
a[duplicated(a)] <- paste(a[duplicated(a)], dups[duplicated(a)], sep = "-")
a
# [1] "a"   "a-2" "a-3" "b"   "c"   "d"   "b-2" "d-2" "e"
</code>```

Body:
I have two vectors

> filename
[1] "10021978_1909-07-21_ed-1_seq-4"  "10021978_1910-01-19_ed-1_seq-31"
[3] "10021978_1910-01-19_ed-1_seq-31" "10021978_1910-01-19_ed-1_seq-31"
[5] "10021978_1910-01-19_ed-1_seq-31" "10021978_1911-06-07_ed-1_seq-12"
[7] "10021978_1911-07-05_ed-1_seq-11" "10021978_1911-07-12_ed-1_seq-11"
[9] "10021978_1911-07-12_ed-1_seq-11" "10021978_1911-09-27_ed-1_seq-4"

AND

> dups = duplicated(filename)
> dups
[1] FALSE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE FALSE

I am dealing with exporting files but not overwriting files with duplicate file names. I have a few that are duplicates in this set of 10. What I need to do is make those filenames unique.

How can I create a new vector that would have nothing wherever the vector dups is FALSE, and then nonzero wherever TRUE? The tricky thing is that I need it to begin incrementing starting with 2 when there is a series of TRUE next to each other then reset when there is a FALSE. The vector I need for this set would be:

ans = c("", "", 2, 3, 4, "", "", "", 2, "")

so that I can append it to the filenames to deal with duplicates. The final filename vector I need would be:

[1] "10021978_1909-07-21_ed-1_seq-4"  "10021978_1910-01-19_ed-1_seq-31"
[3] "10021978_1910-01-19_ed-1_seq-31-2" "10021978_1910-01-19_ed-1_seq-31-3"
[5] "10021978_1910-01-19_ed-1_seq-31-4" "10021978_1911-06-07_ed-1_seq-12"
[7] "10021978_1911-07-05_ed-1_seq-11" "10021978_1911-07-12_ed-1_seq-11"
[9] "10021978_1911-07-12_ed-1_seq-11-2" "10021978_1911-09-27_ed-1_seq-4"

Thank you very much in advance.

Body:
make.unique should be good enough, but if you need the numbering to start at 2, perhaps it is easier to use ave.

Here is an example of both so you can see the difference between the two approaches:

a <- c("a", "a", "a", "b", "c", "d", "b", "d", "e")
make.unique(a, sep = "-")
# [1] "a"   "a-1" "a-2" "b"   "c"   "d"   "b-1" "d-1" "e"

dups <- ave(a, a, FUN = seq_along)
a[duplicated(a)] <- paste(a[duplicated(a)], dups[duplicated(a)], sep = "-")
a
# [1] "a"   "a-2" "a-3" "b"   "c"   "d"   "b-2" "d-2" "e"


问:
CSS: Why is vertical-align: baseline stop working on Firefox when using overflow: hidden?
You can reproduce this by running this test case. The results are shown in the screenshot below. The issue is that on Firefox, when adding a overflow: hidden on the "block" (with grey background in the screenshot), the block stop being aligned as I'd like it to be: instead of the baseline of the text in the block being align to the the baseline of the parent box, it is as if the bottom of the block was aligned on the baseline of the parent box. As you can see in the screenshot, this doesn't happen with Chrome.

Is this a Firefox bug?

How to get the expected result on Firefox (baseline alignment with overflow: hidden)?

Note: Using vertical-align: middle on "block" doesn't cut it, as what I really want is baseline alignment. You can see more clearly that vertical-align: middle doesn't do baseline alignment by setting padding: 1em 0 .1em 0 (more padding at the top of the box), which give you:

答:
try adding vertical-align: text-bottom; to .block

you can also try to set equal line-heights for .label and .block


问:
How to fadeIn and fadeOut paths once a class has been added or removed to them?
I am adding a class to some paths and I would like to fade theese one after the other once the class has been added to each. This is what I have tried

$(".home button").on("click", function() {

  $("#hiButtons .btn-default").removeClass("active");
  $(this).addClass("active");
  var periodClass = $(this).parent().attr("class");
  var gapBetweenEach = 10;
  var speedOfFade = 150;

  $("svg path").each(function(i, path) {
    var cl = $(this).attr('class');
    $(this).attr('class', cl.includes(periodClass) ? cl + ' fadeIn' : cl.replace(/fadeIn/g, '')).delay(gapBetweenEach * i).fadeIn(speedOfFade, function() {});
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg>
       <path class="fadeIn"></path>
       <path class="fadeIn"></path>
       <path class="fadeIn"></path>
    </svg></code>```

答:
This is how i resolved it, I first add the class and then I apply the delay to it, also changed the gap in between the fadings and the speed to better notice it.</p>

```<code>$(".home button").on("click", function() {
  $("#hiButtons .btn-default").removeClass("active");
  $(this).addClass("active");
  var periodClass = $(this).parent().attr("class");
  var gapBetweenEach = 200;
  var speedOfFade = 400;
  $("svg path").each(function(i, path) {
    var cl = $(this).attr('class');
    $(this).attr('class', cl.includes(periodClass) ? cl + ' fadeIn' : cl.replace(/fadeIn/g, ''))
    $(".fadeIn").delay(gapBetweenEach * i).fadeIn(speedOfFade);
  });
});
</code>```

Body:
I am adding a class to some paths and I would like to fade theese one after the other once the class has been added to each. This is what I have tried

$(".home button").on("click", function() {

  $("#hiButtons .btn-default").removeClass("active");
  $(this).addClass("active");
  var periodClass = $(this).parent().attr("class");
  var gapBetweenEach = 10;
  var speedOfFade = 150;

  $("svg path").each(function(i, path) {
    var cl = $(this).attr('class');
    $(this).attr('class', cl.includes(periodClass) ? cl + ' fadeIn' : cl.replace(/fadeIn/g, '')).delay(gapBetweenEach * i).fadeIn(speedOfFade, function() {});
  });
});

<svg>
       <path class="fadeIn"></path>
       <path class="fadeIn"></path>
       <path class="fadeIn"></path>
    </svg>

Body:
This is how i resolved it, I first add the class and then I apply the delay to it, also changed the gap in between the fadings and the speed to better notice it.

$(".home button").on("click", function() {
  $("#hiButtons .btn-default").removeClass("active");
  $(this).addClass("active");
  var periodClass = $(this).parent().attr("class");
  var gapBetweenEach = 200;
  var speedOfFade = 400;
  $("svg path").each(function(i, path) {
    var cl = $(this).attr('class');
    $(this).attr('class', cl.includes(periodClass) ? cl + ' fadeIn' : cl.replace(/fadeIn/g, ''))
    $(".fadeIn").delay(gapBetweenEach * i).fadeIn(speedOfFade);
  });
});


问:
Android Emulators not Working after Updating Android Studio
I normally use Android Studio and after updating from 2.2.3 to 2.3 my emulators are no longer working. It's also difficult since Google decided to deprecated the Standalone SDK Manager:

https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Status%20Priority%20Owner%20Summary%20Stars%20Reporter%20Opened&groupby=&sort=&id=235625

I found that I can check/select "Show Package Details" but still I had no luck making my Google Android Emulators to work. They seem to run fine, but I can't see the emulators.

答:
It happened to me too. Seems that there's a package called Intel HAXM no properly installed when you do this upgrade. Try this workaround:

Go to the Tools -> Android -> SDK Manager

Tap on SDK Tools and uncheck "Intel x86 Emulator Accelerator (HAXM installer)"

After uninstall HAXM, install it again

Restart Android Studio

A new update will appear called "Android Emulators". Just install it and restart Android Studio again.


问:
How to count the number of zeros at the start of a string
I have a string:

```<code>"0011HelloWor00ld001"
</code>```

How do I count the number of zeros in the starting of the string?
For example, the above string should return 2.

I tried .match(/^[0]+/).size but it doesn't work.

答:
I like @Wiktor's middle answer best, but here are three more.

#1

```<code>def nbr_leading_zeros(str)
  str.split(/[^0]/).first.size
end

nbr_leading_zeros '0011Hello00'    #=> 2
nbr_leading_zeros '101'            #=> 0
nbr_leading_zeros '000'            #=> 3
</code>```

#2

```<code>def nbr_leading_zeros(str)
  str.each_char.take_while { |c| c=='0' }.size
end
</code>```

#3

```<code>def nbr_leading_zeros(str)
  str.match(/\A0*/)&.end(0).to_i
end
</code>```

Body:
I have a string:

"0011HelloWor00ld001"

How do I count the number of zeros in the starting of the string?
For example, the above string should return 2.

I tried .match(/^[0]+/).size but it doesn't work.

Body:
I like @Wiktor's middle answer best, but here are three more.

#1

def nbr_leading_zeros(str)
  str.split(/[^0]/).first.size
end

nbr_leading_zeros '0011Hello00'    #=> 2
nbr_leading_zeros '101'            #=> 0
nbr_leading_zeros '000'            #=> 3

#2

def nbr_leading_zeros(str)
  str.each_char.take_while { |c| c=='0' }.size
end

#3

def nbr_leading_zeros(str)
  str.match(/\A0*/)&.end(0).to_i
end


问:
Using variable to TSQL + XQuery
All,

I have the following code:

```<code>--xml is already declared and populated with an xml document

SELECT
ent.query('TradeId').value('.','VARCHAR(10)') TradeId
FROM
@xml.nodes('//table/trade[1]') Col(ent)
</code>```

How can I have the expression //table/trade[1] as a variable so I can increase the [1] in a loop ? For example I would like something like the below which is not working:

```<code>DECLARE @KLM varchar(100)
SET @KLM= '//table/trade[1]'
SELECT
ent.query('TradeId').value('.','VARCHAR(10)') TradeId
FROM
@xml.nodes(@KLM) Col(ent)
</code>```

Any ideas?

Thanks,

M

答:
If you remove the positional reference from your .nodes() method, you should get a resultset containing all of the TradeId values.

```<code>SELECT
ent.query('TradeID').value('.','VARCHAR(10)') TradeId
FROM
@xml.nodes('//table/trade') Col(ent)
</code>```

You should then be able to iterate through that resultset, although I would like to add the standard caveat about "iteration in a relational model is generally a bad idea".

Does that help?  If not, is there more to the story?

Title: Using variable to TSQL + XQuery

Body:
All,

I have the following code:

--xml is already declared and populated with an xml document

SELECT
ent.query('TradeId').value('.','VARCHAR(10)') TradeId
FROM
@xml.nodes('//table/trade[1]') Col(ent)

How can I have the expression //table/trade[1] as a variable so I can increase the [1] in a loop ? For example I would like something like the below which is not working:

DECLARE @KLM varchar(100)
SET @KLM= '//table/trade[1]'
SELECT
ent.query('TradeId').value('.','VARCHAR(10)') TradeId
FROM
@xml.nodes(@KLM) Col(ent)

Any ideas?

Thanks,

M

Body:
If you remove the positional reference from your .nodes() method, you should get a resultset containing all of the TradeId values.

SELECT
ent.query('TradeID').value('.','VARCHAR(10)') TradeId
FROM
@xml.nodes('//table/trade') Col(ent)

You should then be able to iterate through that resultset, although I would like to add the standard caveat about "iteration in a relational model is generally a bad idea".

Does that help?  If not, is there more to the story?


问:
Getting the total documents that is relevant to a value in MongoDB
I'm quite new to mongodb so please pardon my obliviousness.
A sample of my database is provided below :

```<code>{
    "_id" : ObjectId("58db82583d5b9f0a47c3db6f"),
    "People" : [
            "Ivar Zapp"
    ],
    "Link" : [
            "https://wikileaks.org/gifiles/docs/19/1971280_panama-costa-rica-cuba-111104-.html"
    ]
}
{
    "_id" : ObjectId("58db82583d5b9f0a47c3db70"),
    "People" : [
            "Ivar Zapp"
    ],
    "Link" : [
            "https://wikileaks.org/gifiles/docs/87/872609_panama-costa-rica-cuba-111104-.html"
    ]
}
{
    "_id" : ObjectId("58db82583d5b9f0a47c3db71"),
    "People" : [
            "Ivar Zapp"
    ],
    "Link" : [
            "https://wikileaks.org/gifiles/docs/19/1964024_-latam-centam-brief-111104-.html"
    ]
}
</code>```

My question now is, according to the snippet above, how do I get the count of the link relevant to a person's name? Example output below :

```<code>{
    "People" : "Ivar Zapp",
    "link_Count" : "3"
}
</code>```

I've thought of aggregation, but I can't really seem to figure out a solution using aggregation for quite a while now. I'm open to any solutions or feedback as long as it helps me progress just a tad bit. Any solutions or feedback provided is most appreciated! Thanks in advance!

答:
You need to use $group operations:
You try following command,

```<code>db.collection.aggregate([
    { $group: {
        _id: '$People',
        count: { $sum: 1 }
    }},
    { $project: {
        _id: 0,
        People: '$_id',
        count: 1
    }}
    ]);
</code>```

Output :

```<code>{
    "count": 3,
    "People": ["Ivar Zapp"]
}
</code>```

Body:
I'm quite new to mongodb so please pardon my obliviousness.
A sample of my database is provided below :

{
    "_id" : ObjectId("58db82583d5b9f0a47c3db6f"),
    "People" : [
            "Ivar Zapp"
    ],
    "Link" : [
            "https://wikileaks.org/gifiles/docs/19/1971280_panama-costa-rica-cuba-111104-.html"
    ]
}
{
    "_id" : ObjectId("58db82583d5b9f0a47c3db70"),
    "People" : [
            "Ivar Zapp"
    ],
    "Link" : [
            "https://wikileaks.org/gifiles/docs/87/872609_panama-costa-rica-cuba-111104-.html"
    ]
}
{
    "_id" : ObjectId("58db82583d5b9f0a47c3db71"),
    "People" : [
            "Ivar Zapp"
    ],
    "Link" : [
            "https://wikileaks.org/gifiles/docs/19/1964024_-latam-centam-brief-111104-.html"
    ]
}

My question now is, according to the snippet above, how do I get the count of the link relevant to a person's name? Example output below :

{
    "People" : "Ivar Zapp",
    "link_Count" : "3"
}

I've thought of aggregation, but I can't really seem to figure out a solution using aggregation for quite a while now. I'm open to any solutions or feedback as long as it helps me progress just a tad bit. Any solutions or feedback provided is most appreciated! Thanks in advance!

Body:
You need to use $group operations:
You try following command,

db.collection.aggregate([
    { $group: {
        _id: '$People',
        count: { $sum: 1 }
    }},
    { $project: {
        _id: 0,
        People: '$_id',
        count: 1
    }}
    ]);

Output :

{
    "count": 3,
    "People": ["Ivar Zapp"]
}


问:
dc.js Scatter Chart with dot color based on counts
I am having a hard time trying to accomplish something simple.
I need to display a XY scatter plot in DC js charts. However, I may have several points with the same XY values. In this case, the color of a XY point must change according to a function that receives as input the number of repetitions.

Ex:

X  -   Y

1  -  9

1  -  9

1  -  9

1  -  4

2  -  10

3  -  5

1  -  4

Point 1  -  9 appears 3 times...  Red Color

Is it possible to implement something like this?

答:
Sure, just use the colorAccessor to assign colors based on the value. (By default it is colored based on the series.)

Additionally, you'll probably want to specify the color scale so that you have control about the value to color mapping. Below we map 0-4 to yellow, blue, purple, red, orange.

```<code>scatterPlot
  .colorAccessor(function(kv) { return kv.value; })
  .colors(d3.scale.ordinal().domain(d3.range(5)).range(['yellow', 'blue', 'purple', 'red', 'orange']))
</code>```

Body:
Sure, just use the colorAccessor to assign colors based on the value. (By default it is colored based on the series.)

Additionally, you'll probably want to specify the color scale so that you have control about the value to color mapping. Below we map 0-4 to yellow, blue, purple, red, orange.

scatterPlot
  .colorAccessor(function(kv) { return kv.value; })
  .colors(d3.scale.ordinal().domain(d3.range(5)).range(['yellow', 'blue', 'purple', 'red', 'orange']))


问:
N1QL: Using select directly on arrays
I am having problems on querying objects inside an array.

I have this sample document

```<code>{
  ...
  status: 'active',
  current: { ... },
  history: [
    {
      id: '73bae187-1101-4fb3-a71a-2bbf90026eb3',
      date: '2017-03-28T09:32:22.884Z',
      content: 'This is second content'
    },
    {
      id: 'd6a6c63d-42db-4ef5-88e9-616cfe539a57',
      date: '2017-03-25T09:32:22.884Z',
      content: 'This is first content'
    },
    {
      id: '3fbdb846-2b55-4ff8-8960-86997ef31556',
      schedule: '1970-01-01T00:00:00.000Z',
      content: 'This is a very old content'
    }
  ]
}
</code>```

I want to directly query from the history array sub document in which I want to apply date filters.

Is it possible in n1ql to retrieve the history array that will only contain the objects that satisfies the condition?

Can I apply a limit to which I can control the number of the the returned objects inside the array?

I tried some queries using splicing [0:$1] where limit is an input but doesn't work when the limit is greater than the array size.

Thanks for the help.

答:
Try either of the following approach:

```<code>SELECT h[0:least(ARRAY_LENGTH(h), $arraylimit)] As h FROM default As d
LET h = ARRAY v FOR v IN d.history WHEN v.id  IN  [ 'xyz', 'pqr'] END;
</code>```

Or:

```<code>SELECT h[0:least(ARRAY_LENGTH(h),$limit)] As h (SELECT ARRAY_AGG(h) As h
FROM default As d UNNEST d.history As h WHERE h.id IN  [ 'xyz', 'pqr'] GROUP BY d) As q;
</code>```

Title: N1QL: Using select directly on arrays

Body:
I am having problems on querying objects inside an array.

I have this sample document

{
  ...
  status: 'active',
  current: { ... },
  history: [
    {
      id: '73bae187-1101-4fb3-a71a-2bbf90026eb3',
      date: '2017-03-28T09:32:22.884Z',
      content: 'This is second content'
    },
    {
      id: 'd6a6c63d-42db-4ef5-88e9-616cfe539a57',
      date: '2017-03-25T09:32:22.884Z',
      content: 'This is first content'
    },
    {
      id: '3fbdb846-2b55-4ff8-8960-86997ef31556',
      schedule: '1970-01-01T00:00:00.000Z',
      content: 'This is a very old content'
    }
  ]
}

I want to directly query from the history array sub document in which I want to apply date filters.

Is it possible in n1ql to retrieve the history array that will only contain the objects that satisfies the condition?

Can I apply a limit to which I can control the number of the the returned objects inside the array?

I tried some queries using splicing [0:$1] where limit is an input but doesn't work when the limit is greater than the array size.

Thanks for the help.

Body:
Try either of the following approach:

SELECT h[0:least(ARRAY_LENGTH(h), $arraylimit)] As h FROM default As d
LET h = ARRAY v FOR v IN d.history WHEN v.id  IN  [ 'xyz', 'pqr'] END;

Or:

SELECT h[0:least(ARRAY_LENGTH(h),$limit)] As h (SELECT ARRAY_AGG(h) As h
FROM default As d UNNEST d.history As h WHERE h.id IN  [ 'xyz', 'pqr'] GROUP BY d) As q;


问:
Jackson Serialization
I would like to know how can we serialize the following using Jackson.

I have the following class:

```<code>public Class School{

private Map<Teacher,List<Student>> exampleMap;

//Getter and Setter

}
</code>```

Teacher & Student are two other entities.

If I now want to serialize this into JSON using Jackson, how should I proceed?

答:
Json treats map's key as String and it default implementation simply calls its toString method.

The following post has clear explanantion, this might help you.

Can we make object as key in map when using JSON?

Title: Jackson Serialization

Body:
I would like to know how can we serialize the following using Jackson.

I have the following class:

public Class School{

private Map<Teacher,List<Student>> exampleMap;

//Getter and Setter

}

Teacher & Student are two other entities.

If I now want to serialize this into JSON using Jackson, how should I proceed?

ContentLicense: CC BY-SA 4.0


问:
Select max date in one column based on unique dates in another
I have a data set that is loaded into the database every time the forecast for that particular date is changed.  I need to be able to select the last load_dt for each fore_dt.  An example data set is below:

```<code>load_dt, fore_dt, data,
1/1/2017, 1/14/2017, 5,
1/5/2017, 1/14/2017, 8,
1/5/2017, 1/15/2017, 9,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5
</code>```

Results should look like:

```<code>load_dt, fore_dt, data,
1/5/2017, 1/14/2017, 8,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5
</code>```

The actual data set is much more complex and has a lot of rows.  In the query, I need to be able to select where fore_dt between date and date.

答:
Are you looking at max()</p>

```<code>select max(load_dt) as load_dt, fore_dt, max(data)
    from yourtable
   group by fore_dt
</code>```

Body:
I have a data set that is loaded into the database every time the forecast for that particular date is changed.  I need to be able to select the last load_dt for each fore_dt.  An example data set is below:

load_dt, fore_dt, data,
1/1/2017, 1/14/2017, 5,
1/5/2017, 1/14/2017, 8,
1/5/2017, 1/15/2017, 9,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5

Results should look like:

load_dt, fore_dt, data,
1/5/2017, 1/14/2017, 8,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5

The actual data set is much more complex and has a lot of rows.  In the query, I need to be able to select where fore_dt between date and date.

Body:
Are you looking at max()

select max(load_dt) as load_dt, fore_dt, max(data)
    from yourtable
   group by fore_dt


问:
Ruby daemon hangs on rails load
I am having issues getting a workling daemon working correctly. When I run:

```<code>ruby script/workling_client run
</code>```

the daemon starts to load rails, but hangs indefintely.  When I kill the process, the stack trace is always the same:

```<code>/Library/Ruby/Gems/1.8/gems/activesupport-2.1.2/lib/active_support/core_ext/load_error.rb:32:in `new': Interrupt
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require'
from /Library/Ruby/Gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:510:in `require'
from /Library/Ruby/Gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:355:in `new_constants_in'
from /Library/Ruby/Gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:510:in `require'
from /Library/Ruby/Gems/1.8/gems/httpclient-2.1.2/lib/httpclient.rb:68
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require'
 ... 81 levels...
from /Library/Ruby/Gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `call'
from /Library/Ruby/Gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `catch_exceptions'
from /Library/Ruby/Gems/1.8/gems/daemons-1.0.10/lib/daemons.rb:138:in `run'
from script/workling_client:18
</code>```

If I run the script without the daemons library, it works as expected.  I have, in fact, had trouble using the daemon gem to load anything that requires my rails environment.  Any ideas?

UPDATE: The workling_client loads worklings listen.rb as a daemon.  Instead of loading rails in listen.rb, I changed it so that it gets loaded in workling_client instead, and the process works without a hitch.  Therefore, there is some reason that I can't load rails in a daemonized script :-(

答:
Try start working without monitor:</p>

```<code>options = {
  :app_name   => "workling",
  :ARGV       => ARGV,
  :dir_mode   => :normal,
  :dir        => File.join(File.dirname(__FILE__), '..', 'log'),
  :log_output => true,
  :multiple   => false,
  :backtrace  => true,
  :monitor    => false
}
</code>```

Title: Ruby daemon hangs on rails load

Body:
I am having issues getting a workling daemon working correctly. When I run:

ruby script/workling_client run

the daemon starts to load rails, but hangs indefintely.  When I kill the process, the stack trace is always the same:

/Library/Ruby/Gems/1.8/gems/activesupport-2.1.2/lib/active_support/core_ext/load_error.rb:32:in `new': Interrupt
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require'
from /Library/Ruby/Gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:510:in `require'
from /Library/Ruby/Gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:355:in `new_constants_in'
from /Library/Ruby/Gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:510:in `require'
from /Library/Ruby/Gems/1.8/gems/httpclient-2.1.2/lib/httpclient.rb:68
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require'
 ... 81 levels...
from /Library/Ruby/Gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `call'
from /Library/Ruby/Gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `catch_exceptions'
from /Library/Ruby/Gems/1.8/gems/daemons-1.0.10/lib/daemons.rb:138:in `run'
from script/workling_client:18

If I run the script without the daemons library, it works as expected.  I have, in fact, had trouble using the daemon gem to load anything that requires my rails environment.  Any ideas?

UPDATE: The workling_client loads worklings listen.rb as a daemon.  Instead of loading rails in listen.rb, I changed it so that it gets loaded in workling_client instead, and the process works without a hitch.  Therefore, there is some reason that I can't load rails in a daemonized script :-(

Body:
Try start working without monitor:

options = {
  :app_name   => "workling",
  :ARGV       => ARGV,
  :dir_mode   => :normal,
  :dir        => File.join(File.dirname(__FILE__), '..', 'log'),
  :log_output => true,
  :multiple   => false,
  :backtrace  => true,
  :monitor    => false
}


问:
How to add ngClass type functionality to a row of Primeng p-datatable
I have been using Primeng for a while.

I have used Primeng Datatable (p-dataTable) in my component. The component what I am trying to do is inbox. I read messages from DB to a model named 'Message' in Angular 2. There is a field in model named Read. Its used as a flag. Its Boolean. My requirement is if Read is false, entire row elements should be in one colour, say color1. If Read is true, entire row elements should be another color, say color2.

I know how to do the same using ngClass.

Can someone please suggest me how I can do the same using p-dataTable. I tried many ways I can by referring many sites & didn't find any. What I want is a functionality similar to ngClass in p-dataTable

Here is my code

In HTML

```<code><p-dataTable [rowStyleClass]="readFlag" [value]="message" >
        <p-column [style]="{'width':'38px'}"  selectionMode="multiple"></p-column>
        <p-column field="SenderUserId"  header="From" [sortable]="true"></p-column>
        <p-column class="icon-mandatory" field="Subject" header="Message"></p-column>
        <p-column field="MessageDate" header="Time" [sortable]="true">
            <template let-col let-message="rowData" pTemplate type="body">
                <span>{{message.MessageDate | date: 'medium'}}</span>
            </template>
        </p-column>
</p-dataTable>
</code>```

In Component

```<code>readFlag(rowData: Message) { return rowData.Read ? 'inbox-Read' : 'inbox-Unread' ; }
</code>```

Message Model

```<code>export class Message
{
    public Subject: string;
    public Body: string;
    public MessageDate: any;
    public Read: boolean;
}
</code>```

答:
You can use rowstyle class attribute. It is there in the primeng docs. It takes a function as argument . The function should return the class to be set or try [attr.class]="condition? 'color1':'color2'"

Refer : https://www.primefaces.org/primeng/#/datatable

Body:
I have been using Primeng for a while.

I have used Primeng Datatable (p-dataTable) in my component. The component what I am trying to do is inbox. I read messages from DB to a model named 'Message' in Angular 2. There is a field in model named Read. Its used as a flag. Its Boolean. My requirement is if Read is false, entire row elements should be in one colour, say color1. If Read is true, entire row elements should be another color, say color2.

I know how to do the same using ngClass.

Can someone please suggest me how I can do the same using p-dataTable. I tried many ways I can by referring many sites & didn't find any. What I want is a functionality similar to ngClass in p-dataTable

Here is my code

In HTML

            <template let-col let-message="rowData" pTemplate type="body">
                {{message.MessageDate | date: 'medium'}}
            </template>

In Component

readFlag(rowData: Message) { return rowData.Read ? 'inbox-Read' : 'inbox-Unread' ; }

Message Model

export class Message
{
    public Subject: string;
    public Body: string;
    public MessageDate: any;
    public Read: boolean;
}


问:
Encoding/Decode shapeless records with circe
Upgrading circe from 0.4.1 to 0.7.0 broke the following code:

```<code>import shapeless._
import syntax.singleton._
import io.circe.generic.auto._

.run[Record.`'transaction_id -> Int`.T](transport)

def run[A](transport: Json => Future[Json])(implicit decoder: Decoder[A], exec: ExecutionContext): Future[A]
</code>```

With the following error:

```<code> could not find implicit value for parameter decoder: io.circe.Decoder[shapeless.::[Int with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("transaction_id")],Int],shapeless.HNil]]
[error]       .run[Record.`'transaction_id -> Int`.T](transport)
[error]                                              ^
</code>```

Am I missing some import here or are these encoders/decoders not available in circe anymore?

答:
Instances for Shapeless's hlists, records, etc. were moved to a separate circe-shapes module in the circe 0.6.0 release. If you add this module to your build, the following should just work:

```<code>import io.circe.jawn.decode, io.circe.shapes._
import shapeless._, record.Record, syntax.singleton._

val doc = """{ "transaction_id": 1 }"""

val res = decode[Record.`'transaction_id -> Int`.T](doc)
</code>```

The motivation for moving these instances was that the improved generic derivation introduced in 0.6 meant that they were no longer necessary, and keeping them out of implicit scope when they're not needed is both cleaner and potentially supports faster compile times. The new circe-shapes module also includes features that were not available in circe-generic, such as instances for coproducts.

Body:
Upgrading circe from 0.4.1 to 0.7.0 broke the following code:

import shapeless._
import syntax.singleton._
import io.circe.generic.auto._

.run[Record.`'transaction_id -> Int`.T](transport)

def run[A](transport: Json => Future[Json])(implicit decoder: Decoder[A], exec: ExecutionContext): Future[A]

With the following error:

 could not find implicit value for parameter decoder: io.circe.Decoder[shapeless.::[Int with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("transaction_id")],Int],shapeless.HNil]]
[error]       .run[Record.`'transaction_id -> Int`.T](transport)
[error]                                              ^

Am I missing some import here or are these encoders/decoders not available in circe anymore?

Body:
Instances for Shapeless's hlists, records, etc. were moved to a separate circe-shapes module in the circe 0.6.0 release. If you add this module to your build, the following should just work:

import io.circe.jawn.decode, io.circe.shapes._
import shapeless._, record.Record, syntax.singleton._

val doc = """{ "transaction_id": 1 }"""

val res = decode[Record.`'transaction_id -> Int`.T](doc)

The motivation for moving these instances was that the improved generic derivation introduced in 0.6 meant that they were no longer necessary, and keeping them out of implicit scope when they're not needed is both cleaner and potentially supports faster compile times. The new circe-shapes module also includes features that were not available in circe-generic, such as instances for coproducts.