问:
jquery UI draggable with live
this is a draggable sortable example on the jqueryui website, i need to use live() with this (I think) because the elements are created through ajax, does anybody know how to apply the live event to the following?  </p>

```<code><script>
    $(function() {
        $( "#sortable" ).sortable({
            revert: true
        });
        $( "#draggable" ).draggable({
            connectToSortable: "#sortable",
            helper: "clone",
            revert: "invalid"
        });
        $( "ul, li" ).disableSelection();
    });
    </script>
</code>```

答:
I had the exact same problem and I think that it is a much better idea to solve this problem using a JQuery addin method:

```<code>//Add draggable feature:
//Define a setup method for the draggable config so we can reuse it for dynamic elements
$(function() {
    jQuery.fn.draggableSetup = function draggableSetup() {
        this.draggable(
        {
            // enter your custom draggable code here...
        });
        return this;
    }
});

//Apply the draggable config your dynamic elements after adding them
$("#dynamic_element_id").draggableSetup();
</code>```

Thanks to this post for the answer.

This gives you a reusable solution and you don't have to repeat your implementation for each ajax
method.

ContentLicense: CC BY-SA 2.5

Title: jquery UI draggable with live

Body:
I had the exact same problem and I think that it is a much better idea to solve this problem using a JQuery addin method:

//Add draggable feature:
//Define a setup method for the draggable config so we can reuse it for dynamic elements
$(function() {
    jQuery.fn.draggableSetup = function draggableSetup() {
        this.draggable(
        {
            // enter your custom draggable code here...
        });
        return this;
    }
});

//Apply the draggable config your dynamic elements after adding them
$("#dynamic_element_id").draggableSetup();

Thanks to this post for the answer.

This gives you a reusable solution and you don't have to repeat your implementation for each ajax
method.


来源: stackexchange

问:
Python-docx module not overwriting same file name
I have been using python-docx to create and save .docx files automatically. It works to create a single uniquely named .docx file, but if I want to overwrite that file it doesn't do anything.

I have tried doing os.remove, or deleting the file before running my program again, and still nothing.

The only thing which allows it to work is to go into the Recycle Bin and delete it permanently.

def writeDocx():
    # os.remove(client+' Invoice.docx')
    ###heading at top###
    document.add_heading(client+" Invoice", 0)
    document.add_paragraph("").add_run("This Invoice was generated automatically").italic = True
    table = document.add_table(rows=1, cols=3)
    t = table.rows[0].cells
    t[0].text = 'TEST'
    t[1].text = 'TEST'
    t[2].text = 'TEST'
    for i in range(6):
        row_cells = table.add_row().cells
        row_cells[0].text = str(i)
        row_cells[1].text = str(i)
        row_cells[2].text = str(i)
    document.save(client+' Invoice.docx')
```

It should overwrite already saved  Invoice.docx file with the newly generated file, but it does not.

It shows no error messages.

答:
From the official documentation of Python-Docx

The document.save("file.docx") function will not replace the
  existing file until it is opened as document object (document = Document("file.docx"))

But if you want a workaround, you can do something like this

```<code>is_present = False
document = Document()
try:
  document = Document("Invoice.docx")
  is_present =True
except:
  pass

if is_present:
  document.save("old-Invoice.docx") # or you can delete it.
  document = Document()
document.add_heading("Invoice", 0)
document.add_paragraph("").add_run("This Invoice was generated automatically").italic = True
table = document.add_table(rows=1, cols=3)
t = table.rows[0].cells
t[0].text = 'TEST1'
t[1].text = 'TEST2'
t[2].text = 'TEST3'
for i in range(6):
    row_cells = table.add_row().cells
    row_cells[0].text = str(i)
    row_cells[1].text = str(i)
    row_cells[2].text = str(i)
document.save('Invoice.docx')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have been using python-docx to create and save .docx files automatically. It works to create a single uniquely named .docx file, but if I want to overwrite that file it doesn't do anything.

I have tried doing os.remove, or deleting the file before running my program again, and still nothing.

The only thing which allows it to work is to go into the Recycle Bin and delete it permanently.

def writeDocx():
    # os.remove(client+' Invoice.docx')
    ###heading at top###
    document.add_heading(client+" Invoice", 0)
    document.add_paragraph("").add_run("This Invoice was generated automatically").italic = True
    table = document.add_table(rows=1, cols=3)
    t = table.rows[0].cells
    t[0].text = 'TEST'
    t[1].text = 'TEST'
    t[2].text = 'TEST'
    for i in range(6):
        row_cells = table.add_row().cells
        row_cells[0].text = str(i)
        row_cells[1].text = str(i)
        row_cells[2].text = str(i)
    document.save(client+' Invoice.docx')

It should overwrite already saved  Invoice.docx file with the newly generated file, but it does not.

It shows no error messages.

Body:
From the official documentation of Python-Docx

The document.save("file.docx") function will not replace the
  existing file until it is opened as document object (document = Document("file.docx"))

But if you want a workaround, you can do something like this

is_present = False
document = Document()
try:
  document = Document("Invoice.docx")
  is_present =True
except:
  pass

if is_present:
  document.save("old-Invoice.docx") # or you can delete it.
  document = Document()
document.add_heading("Invoice", 0)
document.add_paragraph("").add_run("This Invoice was generated automatically").italic = True
table = document.add_table(rows=1, cols=3)
t = table.rows[0].cells
t[0].text = 'TEST1'
t[1].text = 'TEST2'
t[2].text = 'TEST3'
for i in range(6):
    row_cells = table.add_row().cells
    row_cells[0].text = str(i)
    row_cells[1].text = str(i)
    row_cells[2].text = str(i)
document.save('Invoice.docx')


问:
Throwing an exception from within a signal handler
We have a library that deals with many aspects of error reporting.  I have been tasked to port this library to Linux.   When running though my little test suite, one of the tests failed.   A simplified version of the test appears below.

```<code>// Compiler: 4.1.1 20070105 RedHat 4.1.1-52
// Output: Terminate called after throwing an instance of 'int' abort

#include <iostream>
#include <csignal>
using namespace std;

void catch_signal(int signalNumber)
{
    signal(SIGINT, SIG_DFL);
    throw(signalNumber);
}

int test_signal()
{
    signal(SIGINT, catch_signal);

    try
    {
        raise(SIGINT);
    }
    catch (int &z)
    {
        cerr << "Caught exception: " << z << endl;
    }
    return 0;
}

int main()
{
    try
    {
        test_signal();
    }
    catch (int &z)
    {
        cerr << "Caught unexpected exception: " << z << endl;
    }
    return 0;
}
</code>```

My expectation is that the Caught exception: message will be displayed.   What actually happens is that the program terminates as no catch handler appears to be present for the thrown int.

There are a few questions on SO that seem related.
I found a number of Google pages that were related.
The 'wisdom' seems to boil down to.

Ya can't throw exceptions from signal handlers, cause the signal
handler runs with its own stack, so there are no handlers defined on it.

Ya can throw exceptions from signal handlers, just reconstruct a fake
frame on the stack, and you are good to go.

Ya, we do it all the time. It works for me on platform X

Ya, that used to be available with gcc, but doesn't seem to work any
more. Try the -fnon-call-exceptions option, maybe that will work

The code works as expected on our AIX/TRU64/MSVC compiler/environments. It fails in our Linux environment.

  **I am looking for suggestions to help resolve this issue so the library behavior on Linux will match my other platforms, or some sort or workaround that might achieve the same sort of functionality.

Letting the program core dump on signal, is not a viable option.**

EDIT: Possibly related - Throwing C++ exceptions from a hardware exception handler. Why does -fnon-call-exceptions not behave as expected?

答:
At least in Ubuntu 16.04 x86-64, throwing out of a signal handler seems to work fine. Whether this is by design (i.e. guaranteed to work, rather than working accidentally somehow), I have not researched. I compiled the program below using g++ -o sig-throw sig-throw.cpp:

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

extern "C" void handler(int sig, siginfo_t *info, void *xxx)
{
    throw "Foo";
}

int main(int argc, char **argv)
{
    struct sigaction sa = {0};

    sa.sa_sigaction = handler;
#if 0
    // To ensure SIGALRM doesn't remain blocked once the signal handler raises
    // an exception, either enable the following, or add enable the sigprocmask
    // logic in the exception handler below.
    sa.sa_flags = SA_NODEFER;
#endif
    sigaction(SIGALRM, &sa, NULL);

    alarm(3);

    try {
        printf("Sleeping...\n");
        sleep(10);
        printf("Awoke\n"); // syscall interrupted
    }
    catch (...) {
        printf("Exception!\n");
#if 1
        // To ensure SIGALRM doesn't remain blocked once the signal handler
        // raises an exception, either enable the following, or add enable
        // SA_NODEFER when registering the signal handler.
        sigset_t sigs_alarm;
        sigemptyset(&sigs_alarm);
        sigaddset(&sigs_alarm, SIGALRM);
        sigprocmask(SIG_UNBLOCK, &sigs_alarm, NULL);
#endif
    }

    alarm(3);

    try {
        printf("Sleeping...\n");
        sleep(10);
        printf("Awoke\n"); // syscall interrupted
    }
    catch (...) {
        printf("Exception!\n");
    }

    return 0;
}
</code>```

Here's it running:

```<code>[swarren@swarren-lx1 sig-throw]$ ./sig-throw
Sleeping...
Exception!
</code>```

For reference:

```<code>[swarren@swarren-lx1 sig-throw]$ lsb_release -a
...
Description:    Ubuntu 16.04.6 LTS
...

[swarren@swarren-lx1 sig-throw]$ dpkg -l libc6
...
ii  libc6:amd64  2.23-0ubuntu11  amd64  GNU C Library: Shared libraries

[swarren@swarren-lx1 sig-throw]$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609
</code>```

Body:
We have a library that deals with many aspects of error reporting.  I have been tasked to port this library to Linux.   When running though my little test suite, one of the tests failed.   A simplified version of the test appears below.

// Compiler: 4.1.1 20070105 RedHat 4.1.1-52
// Output: Terminate called after throwing an instance of 'int' abort

#include <iostream>
#include <csignal>
using namespace std;

void catch_signal(int signalNumber)
{
    signal(SIGINT, SIG_DFL);
    throw(signalNumber);
}

int test_signal()
{
    signal(SIGINT, catch_signal);

    try
    {
        raise(SIGINT);
    }
    catch (int &z)
    {
        cerr << "Caught exception: " << z << endl;
    }
    return 0;
}

int main()
{
    try
    {
        test_signal();
    }
    catch (int &z)
    {
        cerr << "Caught unexpected exception: " << z << endl;
    }
    return 0;
}

My expectation is that the Caught exception: message will be displayed.   What actually happens is that the program terminates as no catch handler appears to be present for the thrown int.

There are a few questions on SO that seem related.
I found a number of Google pages that were related.
The 'wisdom' seems to boil down to.

Ya can't throw exceptions from signal handlers, cause the signal
handler runs with its own stack, so there are no handlers defined on it.

Ya can throw exceptions from signal handlers, just reconstruct a fake
frame on the stack, and you are good to go.

Ya, we do it all the time. It works for me on platform X

Ya, that used to be available with gcc, but doesn't seem to work any
more. Try the -fnon-call-exceptions option, maybe that will work

The code works as expected on our AIX/TRU64/MSVC compiler/environments. It fails in our Linux environment.

  **I am looking for suggestions to help resolve this issue so the library behavior on Linux will match my other platforms, or some sort or workaround that might achieve the same sort of functionality.

Letting the program core dump on signal, is not a viable option.**

EDIT: Possibly related - Throwing C++ exceptions from a hardware exception handler. Why does -fnon-call-exceptions not behave as expected?

Body:
At least in Ubuntu 16.04 x86-64, throwing out of a signal handler seems to work fine. Whether this is by design (i.e. guaranteed to work, rather than working accidentally somehow), I have not researched. I compiled the program below using g++ -o sig-throw sig-throw.cpp:

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

extern "C" void handler(int sig, siginfo_t *info, void *xxx)
{
    throw "Foo";
}

int main(int argc, char **argv)
{
    struct sigaction sa = {0};

    sa.sa_sigaction = handler;
#if 0
    // To ensure SIGALRM doesn't remain blocked once the signal handler raises
    // an exception, either enable the following, or add enable the sigprocmask
    // logic in the exception handler below.
    sa.sa_flags = SA_NODEFER;
#endif
    sigaction(SIGALRM, &sa, NULL);

    alarm(3);

    try {
        printf("Sleeping...\n");
        sleep(10);
        printf("Awoke\n"); // syscall interrupted
    }
    catch (...) {
        printf("Exception!\n");
#if 1
        // To ensure SIGALRM doesn't remain blocked once the signal handler
        // raises an exception, either enable the following, or add enable
        // SA_NODEFER when registering the signal handler.
        sigset_t sigs_alarm;
        sigemptyset(&sigs_alarm);
        sigaddset(&sigs_alarm, SIGALRM);
        sigprocmask(SIG_UNBLOCK, &sigs_alarm, NULL);
#endif
    }

    alarm(3);

    try {
        printf("Sleeping...\n");
        sleep(10);
        printf("Awoke\n"); // syscall interrupted
    }
    catch (...) {
        printf("Exception!\n");
    }

    return 0;
}

Here's it running:

[swarren@swarren-lx1 sig-throw]$ ./sig-throw
Sleeping...
Exception!

For reference:

[swarren@swarren-lx1 sig-throw]$ lsb_release -a
...
Description:    Ubuntu 16.04.6 LTS
...

[swarren@swarren-lx1 sig-throw]$ dpkg -l libc6
...
ii  libc6:amd64  2.23-0ubuntu11  amd64  GNU C Library: Shared libraries

[swarren@swarren-lx1 sig-throw]$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609


问:
MSVC 1 bit enum type equals -1 and equality test fails
I have defined a bitfield of enum types to match a set of bits in an embedded system. I'm trying to write a test harness in MSVC for the code, but comparing what should be equal values fails.

The definition looks like this:

typedef enum { SERIAL, PARALLEL } MODE_e;
typedef union {
    struct {
        TYPE_e      Type    : 1;    // 1
        POSITION_e  1Pos    : 1;    // 2
        POSITION_e  2Pos    : 1;    // 3
        bool        Enable  : 1;    // 4
        NET_e       Net     : 1;    // 5
        TYPE_e      Type    : 1;    // 6
        bool        En      : 1;    // 7
        TIME_e      Time    : 3;    // 8-10
        MODE_e      Mode    : 1;    // 11
        bool        TestEn  : 1;    // 12
        bool        DelayEn : 1;    // 13
        MODE_e      Mode    : 1;    // 14
        bool        xEn     : 1;    // 15
        MODE_e      yMode   : 1;    // 16
        bool        zEnable : 1;    // 17
    } Bits;
    uint32_t Word;
} BITS_t;
```
<p>Later the following comparison fails:</p>
<pre class="lang-none prettyprint-override"><code>Store.Bits.Mode = PARALLEL;
if (store.Bits.Mode == PARALLEL)
    ...
</code>```

I examined the Mode bool in the debugger, and it looked odd. The value of Mode is -1.

It's as if MSVC considers the value to be a two's complement number, but 1 bit wide, so 0b1 is decimal -1. The enum sets PARALLEL to 1, so the two do not match.

The comparison works fine on the embedded side using LLVM or GCC.

Which behavior is correct? I assume GCC and LLVM have better support for the C standards than MSVC in areas such as bit fields. More importantly, can I work around this difference without making major changes to the embedded code?

答:
A simple fix I came up with, which is only valid for MSVC and GCC/LLVM, is:</p>
```<code>#ifdef  _WIN32
#define JOFF        0
#define JON         -1
#else
#define JOFF        0
#define JON         1
#endif

typedef enum { SERIAL = JOFF, PARALLEL = JON } TEST_MODE_e;
</code>```

Body:
I have defined a bitfield of enum types to match a set of bits in an embedded system. I'm trying to write a test harness in MSVC for the code, but comparing what should be equal values fails.

The definition looks like this:

typedef enum { SERIAL, PARALLEL } MODE_e;
typedef union {
    struct {
        TYPE_e      Type    : 1;    // 1
        POSITION_e  1Pos    : 1;    // 2
        POSITION_e  2Pos    : 1;    // 3
        bool        Enable  : 1;    // 4
        NET_e       Net     : 1;    // 5
        TYPE_e      Type    : 1;    // 6
        bool        En      : 1;    // 7
        TIME_e      Time    : 3;    // 8-10
        MODE_e      Mode    : 1;    // 11
        bool        TestEn  : 1;    // 12
        bool        DelayEn : 1;    // 13
        MODE_e      Mode    : 1;    // 14
        bool        xEn     : 1;    // 15
        MODE_e      yMode   : 1;    // 16
        bool        zEnable : 1;    // 17
    } Bits;
    uint32_t Word;
} BITS_t;

Later the following comparison fails:

Store.Bits.Mode = PARALLEL;
if (store.Bits.Mode == PARALLEL)
    ...

I examined the Mode bool in the debugger, and it looked odd. The value of Mode is -1.

It's as if MSVC considers the value to be a two's complement number, but 1 bit wide, so 0b1 is decimal -1. The enum sets PARALLEL to 1, so the two do not match.

The comparison works fine on the embedded side using LLVM or GCC.

Which behavior is correct? I assume GCC and LLVM have better support for the C standards than MSVC in areas such as bit fields. More importantly, can I work around this difference without making major changes to the embedded code?

Body:
A simple fix I came up with, which is only valid for MSVC and GCC/LLVM, is:

#ifdef  _WIN32
#define JOFF        0
#define JON         -1
#else
#define JOFF        0
#define JON         1
#endif

typedef enum { SERIAL = JOFF, PARALLEL = JON } TEST_MODE_e;


问:
Stateful FeignClient (session between client and server)
I've been struggling with @FeignClient for Spring Cloud.
We have root "Gateway" WAR that calls "backend" services WARs where we cache user-role specific metadata (this data is supposed to be big enough to request it on every call and small enough to store it in RAM memory).

I need the client to be able to handle Set-Cookie and then put the JSESSIONID to the server side while client session is alive. So that I believe that I need to store all server's side sessionIds in some session-scoped bean for particular Gateway User. Like

```<code>"client1" => "8D06349922CD77D1CE68F78F4FAE04C5"
"client2" => "another session id"
</code>```

Having surfed the Internet I found solutions for ApacheHttpClient and for Spring RestTemplate. The only thing about Feign is that there's the ability to obtain @RequestHeader("Cookie") as an argument for remote function.

Well, I wrote some rude code that did the trick:

```<code>HttpMessageConverter httpMessageConverter = new HttpMessageConverter() {
            @Override
            public Object read(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
                HttpHeaders headers = inputMessage.getHeaders();
                logger.info("headers: {}", headers);
                List<String> setCookie = headers.get("Set-Cookie");
                logger.info("setCookie: {}", setCookie);
                if(setCookie != null){
                    String jsId = setCookie.get(0).split(";")[0].split("=")[1];
                    logger.info("jsId Object read: {}", jsId);
                    cookies.setSessionId("key", jsId);
                }
                return delegate.read(clazz,inputMessage);
            }
};
</code>```

.....

```<code>RequestInterceptor jsessionFeignRequestInterceptor = new RequestInterceptor() {
    @Override
    public void apply(RequestTemplate template) {
        String sessionId = cookies.getSessionId("key");
        logger.info("THE JSESSIONID: {}", sessionId);
        if(sessionId != null) {
            template.header("Cookie", "JSESSIONID=" + sessionId);
        }
    }
};
</code>```

....

```<code> Feign.builder()
    .encoder(new SpringEncoder(new HttpMessageConverters(httpMessageConverter)))
    .requestInterceptor(jsessionFeignRequestInterceptor)
    .requestInterceptor(oauth2FeignRequestInterceptor)........
</code>```

However it looks odd in my opinion.

Is there maybe some other "suitable option" to achieve similar functionality?

NOTE: we are using OAuth2 Spring Auth Server.

Thanks.

答:
I have done something similar by using OkHttpClient with a custom Interceptor.

Builder builder = Feign
    .builder()
    .client(new OkHttpClient(new okhttp3.OkHttpClient.Builder().addInterceptor(new SessionIdRequestInterceptor()).build()));
```

<p>OkHttpClient also supports an Authenticator interface, but that is called only on 401 http status. Since my authentication server redirects to a login page with a 200 or 302, I had to make a custom validation of the authentication, hence the interceptor. Here's my implementation:</p>

<pre class="lang-java prettyprint-override"><code>class SessionIdRequestInterceptor implements okhttp3.Interceptor {

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        okhttp3.Request authenticatedRequest = authenticateRequest(chain.request());
        okhttp3.Response response = chain.proceed(authenticatedRequest);
        if (isAuthenticated(response)) {
            saveSessionId(response);
        } else if (jSessionId != null) {
            jSessionId = null;
            response.body().close();
            authenticatedRequest = authenticateRequest(authenticatedRequest);
            response = chain.proceed(authenticatedRequest);
        }
        if (!isAuthenticated(response)) {
            throw new PermissionDeniedException("Failed Authentication");
        }
        return response;
    }

    private void saveSessionId(okhttp3.Response response) {
        String setCookie = response.header("Set-Cookie");
        if (setCookie != null) {
            jSessionId = setCookie.split(";")[0].split("=")[1];
        }
    }

    private boolean isAuthenticated(okhttp3.Response response) {
        return !response.request().url().encodedPath().contains("/cas-server/login");
    }

    private okhttp3.Request authenticateRequest(okhttp3.Request request) {
        okhttp3.Request.Builder builder = request.newBuilder();
        if (jSessionId != null) {
            builder.addHeader("Cookie", "JSESSIONID=" + jSessionId);
        } else {
            builder
                .addHeader("Authorization", "Basic " + Base64
                    .getEncoder()
                    .encodeToString((configuration.getUser() + ":" + configuration.getClearPassword()).getBytes()));
        }
        return builder.build();
    }
}
</code>```

Body:
I've been struggling with @FeignClient for Spring Cloud.
We have root "Gateway" WAR that calls "backend" services WARs where we cache user-role specific metadata (this data is supposed to be big enough to request it on every call and small enough to store it in RAM memory).

I need the client to be able to handle Set-Cookie and then put the JSESSIONID to the server side while client session is alive. So that I believe that I need to store all server's side sessionIds in some session-scoped bean for particular Gateway User. Like

"client1" => "8D06349922CD77D1CE68F78F4FAE04C5"
"client2" => "another session id"

Having surfed the Internet I found solutions for ApacheHttpClient and for Spring RestTemplate. The only thing about Feign is that there's the ability to obtain @RequestHeader("Cookie") as an argument for remote function.

Well, I wrote some rude code that did the trick:

HttpMessageConverter httpMessageConverter = new HttpMessageConverter() {
            @Override
            public Object read(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
                HttpHeaders headers = inputMessage.getHeaders();
                logger.info("headers: {}", headers);
                List<String> setCookie = headers.get("Set-Cookie");
                logger.info("setCookie: {}", setCookie);
                if(setCookie != null){
                    String jsId = setCookie.get(0).split(";")[0].split("=")[1];
                    logger.info("jsId Object read: {}", jsId);
                    cookies.setSessionId("key", jsId);
                }
                return delegate.read(clazz,inputMessage);
            }
};

.....

RequestInterceptor jsessionFeignRequestInterceptor = new RequestInterceptor() {
    @Override
    public void apply(RequestTemplate template) {
        String sessionId = cookies.getSessionId("key");
        logger.info("THE JSESSIONID: {}", sessionId);
        if(sessionId != null) {
            template.header("Cookie", "JSESSIONID=" + sessionId);
        }
    }
};

....

 Feign.builder()
    .encoder(new SpringEncoder(new HttpMessageConverters(httpMessageConverter)))
    .requestInterceptor(jsessionFeignRequestInterceptor)
    .requestInterceptor(oauth2FeignRequestInterceptor)........

However it looks odd in my opinion.

Is there maybe some other "suitable option" to achieve similar functionality?

NOTE: we are using OAuth2 Spring Auth Server.

Thanks.

Body:
I have done something similar by using OkHttpClient with a custom Interceptor.

Builder builder = Feign
    .builder()
    .client(new OkHttpClient(new okhttp3.OkHttpClient.Builder().addInterceptor(new SessionIdRequestInterceptor()).build()));

OkHttpClient also supports an Authenticator interface, but that is called only on 401 http status. Since my authentication server redirects to a login page with a 200 or 302, I had to make a custom validation of the authentication, hence the interceptor. Here's my implementation:

class SessionIdRequestInterceptor implements okhttp3.Interceptor {

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        okhttp3.Request authenticatedRequest = authenticateRequest(chain.request());
        okhttp3.Response response = chain.proceed(authenticatedRequest);
        if (isAuthenticated(response)) {
            saveSessionId(response);
        } else if (jSessionId != null) {
            jSessionId = null;
            response.body().close();
            authenticatedRequest = authenticateRequest(authenticatedRequest);
            response = chain.proceed(authenticatedRequest);
        }
        if (!isAuthenticated(response)) {
            throw new PermissionDeniedException("Failed Authentication");
        }
        return response;
    }

    private void saveSessionId(okhttp3.Response response) {
        String setCookie = response.header("Set-Cookie");
        if (setCookie != null) {
            jSessionId = setCookie.split(";")[0].split("=")[1];
        }
    }

    private boolean isAuthenticated(okhttp3.Response response) {
        return !response.request().url().encodedPath().contains("/cas-server/login");
    }

    private okhttp3.Request authenticateRequest(okhttp3.Request request) {
        okhttp3.Request.Builder builder = request.newBuilder();
        if (jSessionId != null) {
            builder.addHeader("Cookie", "JSESSIONID=" + jSessionId);
        } else {
            builder
                .addHeader("Authorization", "Basic " + Base64
                    .getEncoder()
                    .encodeToString((configuration.getUser() + ":" + configuration.getClearPassword()).getBytes()));
        }
        return builder.build();
    }
}


问:
Change the image of a label from radio input
I'm trying to change the label images by input of a radio button with JavaScript or CSS.

I've tried "input[type="radio"]:not(:checked) + label" within CSS and
also tried to change it by JavaScript.

What I currently have:

var service1 = document.getElementById('service1');
var service2 = document.getElementById('service2');
var service3 = document.getElementById('service3');

if(service1 == document.getElementById('service1').checked){
 document.getElementById('service2').src = "decent_rate_unchecked.png";
 document.getElementById('service3').src = "good_rate_unchecked.png";
}else if(service2 == document.getElementById('service2').checked){
 document.getElementById('service1').src = "bad_rate_unchecked.png";
 document.getElementById('service3').src = "good_rate_unchecked.png";
}else{
 document.getElementById('service2').src = "bad_rate_unchecked.png";
 document.getElementById('service3').src = "decent_rate_unchecked.png";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#service1 input[type="radio"]:not(:checked) + label{
 border: 5px solid black;
 border-radius: 25px;
}</code>```

<form action="Sources/form.php" method="post" id="container">

<input type="radio" checked="checked" id="service1" name="service" value="1" required="required"/>

<input type="radio" id="service2" name="service" value="5,5" required="required"/>

<input type="radio" id="service3" name="service" value="10" required="required"/>

</form>```

Expected result would be that the images change into the pre-made "unchecked" states of the images, actual results is that nothing happens except for the fact that it gets a black round border if it's selected

答:
You don't need js here, I see a lot of issues with HTML markup attributes, but to solve your problem just use this code,

form.service__rate label{
  display: inline-block;
  width: 42px;
  height: 42px;
}

#service1 + label{
/*background: url("./Sources/bad-rate.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/1/") center/cover no-repeat;
}
#service2 + label{
/*background: url("./Sources/decent-rate.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/1/") center/cover no-repeat;
}
#service3 + label{
/*background: url("./Sources/good-rate.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/1/") center/cover no-repeat;
}

#service1:checked + label {
/*background: url("./Sources/bad_rate_unchecked.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/2/") center/cover no-repeat;
}
#service2:checked + label {
/*background: url("./Sources/decent_rate_unchecked.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/2/") center/cover no-repeat;
}
#service3:checked + label {
/*background: url("./Sources/good_rate_unchecked.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/2/") center/cover no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- HTML -->
<form action="Sources/form.php" method="post" id="container" class="service__rate">
<fieldset>
  <legend>Service rate:</legend>
  <input type="radio" checked="checked" id="service1" name="service" value="1" required="required"/>
  <label for="service1">
  </label>
  <input type="radio" id="service2" name="service" value="5,5" required="required"/>
  <label for="service2">
  </label>
  <input type="radio" id="service3" name="service" value="10" required="required"/>
  <label for="service3">
</label>
</fieldset>
</form></code>```

Body:
I'm trying to change the label images by input of a radio button with JavaScript or CSS.

I've tried "input[type="radio"]:not(:checked) + label" within CSS and
also tried to change it by JavaScript.

What I currently have:

var service1 = document.getElementById('service1');
var service2 = document.getElementById('service2');
var service3 = document.getElementById('service3');

if(service1 == document.getElementById('service1').checked){
 document.getElementById('service2').src = "decent_rate_unchecked.png";
 document.getElementById('service3').src = "good_rate_unchecked.png";
}else if(service2 == document.getElementById('service2').checked){
 document.getElementById('service1').src = "bad_rate_unchecked.png";
 document.getElementById('service3').src = "good_rate_unchecked.png";
}else{
 document.getElementById('service2').src = "bad_rate_unchecked.png";
 document.getElementById('service3').src = "decent_rate_unchecked.png";
}

#service1 input[type="radio"]:not(:checked) + label{
 border: 5px solid black;
 border-radius: 25px;
}

<form action="Sources/form.php" method="post" id="container">

<input type="radio" checked="checked" id="service1" name="service" value="1" required="required"/>

<input type="radio" id="service2" name="service" value="5,5" required="required"/>

<input type="radio" id="service3" name="service" value="10" required="required"/>

</form>

Expected result would be that the images change into the pre-made "unchecked" states of the images, actual results is that nothing happens except for the fact that it gets a black round border if it's selected

Body:
You don't need js here, I see a lot of issues with HTML markup attributes, but to solve your problem just use this code,

form.service__rate label{
  display: inline-block;
  width: 42px;
  height: 42px;
}

#service1 + label{
/*background: url("./Sources/bad-rate.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/1/") center/cover no-repeat;
}
#service2 + label{
/*background: url("./Sources/decent-rate.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/1/") center/cover no-repeat;
}
#service3 + label{
/*background: url("./Sources/good-rate.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/1/") center/cover no-repeat;
}

#service1:checked + label {
/*background: url("./Sources/bad_rate_unchecked.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/2/") center/cover no-repeat;
}
#service2:checked + label {
/*background: url("./Sources/decent_rate_unchecked.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/2/") center/cover no-repeat;
}
#service3:checked + label {
/*background: url("./Sources/good_rate_unchecked.png") center/cover no-repeat;*/
background: url("http://lorempixel.com/50/50/technics/2/") center/cover no-repeat;
}

<!-- HTML -->
<form action="Sources/form.php" method="post" id="container" class="service__rate">
<fieldset>
  <legend>Service rate:</legend>
  <input type="radio" checked="checked" id="service1" name="service" value="1" required="required"/>
  <label for="service1">
  </label>
  <input type="radio" id="service2" name="service" value="5,5" required="required"/>
  <label for="service2">
  </label>
  <input type="radio" id="service3" name="service" value="10" required="required"/>
  <label for="service3">
</label>
</fieldset>
</form>


问:
How to do append insertion in sparksql?
I have a api endpoint written by sparksql with the following sample code. Every time api accept a request it will run sparkSession.sql(sql_to_hive) which would create a single file in HDFS. Is there any way to do insert by appending data to existing file in HDFS ? Thanks.</p>

```<code>    sqlContext = SQLContext(sparkSession.sparkContext)
    df = sqlContext.createDataFrame(ziped_tuple_list, schema=schema)
    df.registerTempTable('TMP_TABLE')
    sql_to_hive = 'insert into log.%(table_name)s partition%(partition)s select %(title_str)s from TMP_TABLE'%{
        'table_name': table_name,
        'partition': partition_day,
        'title_str': title_str
    }
    sparkSession.sql(sql_to_hive)
</code>```

答:
I don't think this is possible case to append data to the existing file.

But you can work around this case by using either of these ways

Approach1

Using Spark, write to intermediate temporary table and then insert overwrite to final table:

```<code>existing_df=spark.table("existing_hive_table") //get the current data from hive
current_df //new dataframe
union_df=existing_df.union(current_df)
union_df.write.mode("overwrite").saveAsTable("temp_table") //write the data to temp table
temp_df=spark.table("temp_table") //get data from temp table
temp_df.repartition(<number>).write.mode("overwrite").saveAsTable("existing_hive_table") //overwrite to final table
</code>```

Approach2:

Hive(not spark) offers overwriting and select same table .i.e

```<code>insert overwrite table default.t1 partition(partiton_column)
select * from default.t1; //overwrite and select from same t1 table
</code>```

If you are following this way then there needs to be hive job triggered once your spark job finishes.

Hive will acquire lock while running overwrite/select the same table so if any job which is writing to table will wait.

In Addition: Orc format will offer alter table concatenate which will merge small ORC files to create a new larger file.

```<code> alter table <db_name>.<orc_table_name> [partition_column="val"] concatenate;
</code>```

We can also use distributeby,sortby clauses to control number of files, refer this and this link for more details.

Another Approach3 is by using hadoop fs -getMerge to merge all small files into one (this method works for text files and i haven't tried for orc,avro ..etc formats).

Title: How to do append insertion in sparksql?

Body:
I have a api endpoint written by sparksql with the following sample code. Every time api accept a request it will run sparkSession.sql(sql_to_hive) which would create a single file in HDFS. Is there any way to do insert by appending data to existing file in HDFS ? Thanks.

    sqlContext = SQLContext(sparkSession.sparkContext)
    df = sqlContext.createDataFrame(ziped_tuple_list, schema=schema)
    df.registerTempTable('TMP_TABLE')
    sql_to_hive = 'insert into log.%(table_name)s partition%(partition)s select %(title_str)s from TMP_TABLE'%{
        'table_name': table_name,
        'partition': partition_day,
        'title_str': title_str
    }
    sparkSession.sql(sql_to_hive)

Body:
I don't think this is possible case to append data to the existing file.

But you can work around this case by using either of these ways

Approach1

Using Spark, write to intermediate temporary table and then insert overwrite to final table:

existing_df=spark.table("existing_hive_table") //get the current data from hive
current_df //new dataframe
union_df=existing_df.union(current_df)
union_df.write.mode("overwrite").saveAsTable("temp_table") //write the data to temp table
temp_df=spark.table("temp_table") //get data from temp table
temp_df.repartition(<number>).write.mode("overwrite").saveAsTable("existing_hive_table") //overwrite to final table

Approach2:

Hive(not spark) offers overwriting and select same table .i.e

insert overwrite table default.t1 partition(partiton_column)
select * from default.t1; //overwrite and select from same t1 table

If you are following this way then there needs to be hive job triggered once your spark job finishes.

Hive will acquire lock while running overwrite/select the same table so if any job which is writing to table will wait.

In Addition: Orc format will offer alter table concatenate which will merge small ORC files to create a new larger file.

 alter table <db_name>.<orc_table_name> [partition_column="val"] concatenate;

We can also use distributeby,sortby clauses to control number of files, refer <a href="http://I%20don't%20think%20this%20is%20possible%20case.%20%20But%20you%20can%20work%20around%20this%20case%20by%20using%20either%20of%20these%20ways%20%20***Approach1***%20%20**%60Using%20Spark,%20write%20to%20intermediate%20temporary%20table%20and%20then%20insert%20overwrite%20to%20final%20table:%60**%20%20%20%20%20%20existing_df=spark.table(%22existing_hive_table%22)%20//get%20the%20current%20data%20from%20hive%20%20%20%20%20current_df%20//new%20dataframe%20%20%20%20%20union_df=existing_df.union(current_df)%20%20%20%20%20%20union_df.write.mode(%22overwrite%22).saveAsTable(%22temp_table%22)%20//write%20the%20data%20to%20temp%20table%20%20%20%20%20temp_df=spark.table(%22temp_table%22)%20//get%20data%20from%20temp%20table%20%20%20%20%20temp_df.repartition(%3Cnumber%3E).write.mode(%22overwrite%22).saveAsTable(%22existing_hive_table%22)%20//overwrite%20to%20final%20table%20%20%20%20***Approach2:***%20%20**%60Hive(not%20spark)%60**%20offers%20overwriting%20and%20select%20same%20table%20.i.e%20%20%20%20%20%20insert%20overwrite%20table%20default.t1%20partition(partiton_column)%20%20%20%20%20%20select%20*%20from%20default.t1;%20//overwrite%20and%20select%20from%20same%20t1%20table%20%20If%20you%20are%20following%20this%20way%20then%20there%20needs%20to%20be%20hive%20job%20triggered%20once%20your%20spark%20job%20finishes.%20%20Hive%20will%20acquire%20lock%20while%20running%20overwrite/select%20the%20same%20table%20so%20if%20any%20job%20which%20is%20writing%20to%20table%20will%20wait.%20%20**%60In%20Addition:%60**%20%60Orc%20format%60%20will%20offer%20[alter%20table%20concatenate][1]%20which%20will%20merge%20small%20ORC%20files%20to%20create%20a%20new%20larger%20file.%20%20%20%20%20%20%20alter%20table%20%3Cdb_name%3E.%3Corc_table_name%3E%20[partition_column=%22val%22]%20concatenate;%20%20%20%20In%20addition%20we%20can%20also%20use%20distributeby%20sortby%20to%20control%20number%20of%20files,%20refer%20this%20and%20[this][2]%20link%20for%20more%20details.%20%20%20%20%20[1]:%20https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-AlterTable/PartitionConcatenate%20%20%20[2]:%20https://stackoverflow.com/questions/32096347/hive-create-multi-small-files-for-each-insert-in-hdfs" rel="nofollow noreferrer">this and this link for more details.

Another Approach3 is by using hadoop fs -getMerge to merge all small files into one (this method works for text files and i haven't tried for orc,avro ..etc formats).


问:
Github V4 GraphQL API - audit log query
i'm trying to interact with github api v4, i want to query audit log events based on schemas available in the api. I can found a documentary about the github api here and I can see the schemas available here but there are no working examples of how to query the different schemas.

If there is someone here experience with this API, specially with the audit log schemas,  I need a working example to start interacting with the audit log schemas...

for example i want to query all organization add member to team events, suppose to be in the schema TeamAddMemberAuditEntry, or remove member from org OrgRemoveMemberAuditEntry

So far I've tried to query it with node.js:

```<code>require('isomorphic-fetch');

fetch('https://api.github.com/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json',
             'Authorization': 'bearer <token>',
             'Accept': 'application/vnd.github.audit-log- preview+json'},
  body: JSON.stringify({ query: '{ TeamAddMemberAuditEntry }' }),
})
  .then(res => res.json())
  .then(res => console.log(res.data));
</code>```

答:
If someone here will look for solution, after viewing the public schema this is how the query looks for getting audit-log objects, this is without the headers and the query prefix of course.

The auditLog is a union type, you can get multiple audit events by adding another "...on" block. for example here i'm getting all the orginvitemembers events

```<code>{
  organization(login:"<your-org>") {
    auditLog(first:2) {
      edges {
        node {
          __typename
          ... on OrgInviteMemberAuditEntry {
            action
            actorIp
            actorLogin
            createdAt
            userLogin
            actorLocation{
              country
              city
            }
          }
        }
      }
    }
  }
}
</code>```

Title: Github V4 GraphQL API - audit log query

Body:
i'm trying to interact with github api v4, i want to query audit log events based on schemas available in the api. I can found a documentary about the github api here and I can see the schemas available here but there are no working examples of how to query the different schemas.

If there is someone here experience with this API, specially with the audit log schemas,  I need a working example to start interacting with the audit log schemas...

for example i want to query all organization add member to team events, suppose to be in the schema TeamAddMemberAuditEntry, or remove member from org OrgRemoveMemberAuditEntry

So far I've tried to query it with node.js:

require('isomorphic-fetch');

fetch('https://api.github.com/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json',
             'Authorization': 'bearer <token>',
             'Accept': 'application/vnd.github.audit-log- preview+json'},
  body: JSON.stringify({ query: '{ TeamAddMemberAuditEntry }' }),
})
  .then(res => res.json())
  .then(res => console.log(res.data));

Body:
If someone here will look for solution, after viewing the public schema this is how the query looks for getting audit-log objects, this is without the headers and the query prefix of course.

The auditLog is a union type, you can get multiple audit events by adding another "...on" block. for example here i'm getting all the orginvitemembers events

{
  organization(login:"<your-org>") {
    auditLog(first:2) {
      edges {
        node {
          __typename
          ... on OrgInviteMemberAuditEntry {
            action
            actorIp
            actorLogin
            createdAt
            userLogin
            actorLocation{
              country
              city
            }
          }
        }
      }
    }
  }
}


问:
Updating column value based on multiple conditions across multiple dataframes
I have two dataframes and am trying to update Name in DF1 based on two conditions Tool and Location-

Dataframes -

first one

```<code>DF1

NAME    Tool    Location
-       tool_1  location_1
-       tool_15 location_2
-       tool_19 location_3
</code>```

and second one -

```<code>DF2

NAME    Tool    Location
name51  tool_1  location_1
name42  tool_15 location_2
name33  tool_19 location_3
</code>```

I've tried using a numpy where condition checking for both values however am getting error that states -

ValueError: Can only compare identically-labeled Series objects

I understand the problem is different row numbers in both of my dataframes. I've tried some solutions with resetting indexes without any success.

Here is my attempted query -

```<code>DF1['NAME'] = np.where((DF1.Tool == DF2.Tool) & (DF1.Location== DF2.Location), DF2.Name)
</code>```

What could be a work around for this problem ? I am unable to match both dataframes with the exact length of rows.

Expected result for DF1 would be -

```<code>DF1

NAME    Tool    Location
name51  tool_1  location_1
name42  tool_15 location_2
name33  tool_19 location_3
</code>```

thank you,

答:
Merge and reindex():

```<code>DF1=DF1.merge(DF2,on=['Tool','Location'],suffixes=('_x','')).reindex(DF1.columns,axis=1)
</code>```

```<code>     NAME     Tool    Location
0  name51   tool_1  location_1
1  name42  tool_15  location_2
2  name33  tool_19  location_3
</code>```

Body:
I have two dataframes and am trying to update Name in DF1 based on two conditions Tool and Location-

Dataframes -

first one

DF1

NAME    Tool    Location
-       tool_1  location_1
-       tool_15 location_2
-       tool_19 location_3

and second one -

DF2

NAME    Tool    Location
name51  tool_1  location_1
name42  tool_15 location_2
name33  tool_19 location_3

I've tried using a numpy where condition checking for both values however am getting error that states -

ValueError: Can only compare identically-labeled Series objects

I understand the problem is different row numbers in both of my dataframes. I've tried some solutions with resetting indexes without any success.

Here is my attempted query -

DF1['NAME'] = np.where((DF1.Tool == DF2.Tool) & (DF1.Location== DF2.Location), DF2.Name)

What could be a work around for this problem ? I am unable to match both dataframes with the exact length of rows.

Expected result for DF1 would be -

DF1

NAME    Tool    Location
name51  tool_1  location_1
name42  tool_15 location_2
name33  tool_19 location_3

thank you,

Body:
Merge and reindex():

DF1=DF1.merge(DF2,on=['Tool','Location'],suffixes=('_x','')).reindex(DF1.columns,axis=1)

     NAME     Tool    Location
0  name51   tool_1  location_1
1  name42  tool_15  location_2
2  name33  tool_19  location_3


问:
Implementing 3D Secure using CyberSource REST API
I'm adding a support of CyberSource to our system and just got new requirement about 3D Secure support.

I've already implemented some flows using CyberSource REST API:

Payments

Card tokenisation via Flexible token

I'm a little bit confused, because I can't find any information about implementation of Payer Authentication in conjunction with the REST integration. All I found is the documentation for Simple Order API and SCMP API.

Am I missing something? Am I supposed to use any of the aforementioned docs or there is some separate document for REST API? Or I should use different integration method instead of REST?

答:
Update 6-14-18:  The payer authentication (3-D Secure) is now available with the REST API.

The payer authentication services are not available through the REST API at this time. I know they will be, but don't know when.

The only other option is using the SOAP API (SOAP Toolkit) or pre-built client (Simple Order API). SCMP is a legacy API and should not be used.


问:
Clion: setting up remote Makefile project

Context

I have a remote server with C++ code and Makefile, and I want to use Clion's remote development + Makefile plugin to develop a Makefile project in remote.

I have mostly been following this guide from Jetbrains to set up remote development.

I have followed all the instructions:

install Makefile plugin

set up Remote Host in Build, Execution, Deployment | Toolchains ( there was no problem setting up the remote host )

create corresponding CMake profile in Build, Execution, Deployment | CMake and selected the created Remote Host in the Toolchain

set mapping to my newly created C++ Cmake project to the remote directory under Build, Execution, Deployment | Deployment | Mappings.

Problems with setup

After following all the instructions, I have two issues:

My local project and remote repository are out of sync. My local contains dummy files created on project initialization: cmake-build-debug directory, CMakeLists.txt, and main.cpp, while my remote contains code and Makefile.

There is no configuration created for me to run and build. In the top-right corner where there is run, debug and build buttons, no pre-created configuration is shown:

Instead, there is Add Configuration button. When I click Add Configuration and navigate to create new Makefile configuration, there is no option for me to set up project in remote.

Question

So my question is:

Do I need cmake-build-debug directory and CMakeLists.txt even if I am only going to use the Makefile plugin to build and run? If not, how should I sink my files with remote?

How can I create debug and run configuration with Makefile s.t. it will only build and run on the remote host I have set up?

答:
Several things here:

Full remote mode in CLion works only with CMake projects for now.

Makefile plugin doesn't provide Makefiles project model support in CLion (and you can't work w/o a project model in CLion, the code won't be resolved), it's for syntax highlighting in such files mostly and for Makefiles run/debug configuration. To work with makefiles in CLion, you need a workaround through the compilation database. Please check here: https://www.jetbrains.com/help/clion/managing-makefile-projects.html. But again this works only for local projects.


问:
Cannot call this.displayMaps() in for each loop
I am not sure why I can't call my class method in forEach loop. Is there a way to fix this?

This works:

```<code>this.displayMaps()
</code>```

But, this doesn't work:

```<code>this.state.floors.forEach(function(floor) {
  this.displayMaps(floor)
})
</code>```

答:
The scope of this changes inside the forEach callback function.Instead use arrow function

```<code>{
  this.state.floors.forEach((floor) => {
    this.displayMaps()
  })
}
</code>```

Body:
I am not sure why I can't call my class method in forEach loop. Is there a way to fix this?

This works:

this.displayMaps()

But, this doesn't work:

this.state.floors.forEach(function(floor) {
  this.displayMaps(floor)
})

Body:
The scope of this changes inside the forEach callback function.Instead use arrow function

{
  this.state.floors.forEach((floor) => {
    this.displayMaps()
  })
}


问:
NSClassFromString using a Swift File
I have written a class in Swift in my existing Objective-C project. So far, the bridging has worked very well. I do have a method however, where I generate a class at runtime using NSClassFromString(). When the string is my Swift class name, it returns nil.

```<code>class MySwiftClass : NSObject {}
</code>```

and in Objective-C:

```<code>Class myClass = NSClassFromString(@"MySwiftClass");
</code>```

and myClass would be nil every time. I've also tried:

```<code>Class myClass = NSClassFromString(@"MyAppName.MySwiftClass");
</code>```

and still nil.

答:
A way to compatible Objective-C and Swift:</p>

```<code>CQBaseViewController *detailVC = [[NSClassFromString(controller_name) alloc] init];

// if nil,check as Swift file
if (!detailVC) {
    NSString *prefix = [[NSBundle mainBundle] infoDictionary][@"CFBundleExecutable"];
    NSString *swiftClassName = [NSString stringWithFormat:@"%@.%@", prefix, controller_name];
    detailVC = [[NSClassFromString(swiftClassName) alloc] init];
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: NSClassFromString using a Swift File

Body:
I have written a class in Swift in my existing Objective-C project. So far, the bridging has worked very well. I do have a method however, where I generate a class at runtime using NSClassFromString(). When the string is my Swift class name, it returns nil.

class MySwiftClass : NSObject {}

and in Objective-C:

Class myClass = NSClassFromString(@"MySwiftClass");

and myClass would be nil every time. I've also tried:

Class myClass = NSClassFromString(@"MyAppName.MySwiftClass");

and still nil.

Body:
A way to compatible Objective-C and Swift:

CQBaseViewController *detailVC = [[NSClassFromString(controller_name) alloc] init];

// if nil,check as Swift file
if (!detailVC) {
    NSString *prefix = [[NSBundle mainBundle] infoDictionary][@"CFBundleExecutable"];
    NSString *swiftClassName = [NSString stringWithFormat:@"%@.%@", prefix, controller_name];
    detailVC = [[NSClassFromString(swiftClassName) alloc] init];
}


问:
ScrollViewer control template breaks textboxes
I copied ScrollViewer template from MSDN (link) and it breaks textbox behavior. Scroll now doesn't follow selection when I select text using mouse. Why? How to fix it?

Here's my code

```<code><Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">
  <Window.Resources>
    <Style TargetType="{x:Type ScrollViewer}">
      <Setter Property="OverridesDefaultStyle"
              Value="True" />
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type ScrollViewer}">
            <Grid>
              <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition />
              </Grid.ColumnDefinitions>
              <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition Height="Auto" />
              </Grid.RowDefinitions>
              <Border Grid.Column="1"
                      BorderThickness="0,1,1,1">
                <Border.BorderBrush>
                  <SolidColorBrush Color="{DynamicResource BorderMediumColor}" />
                </Border.BorderBrush>
                <ScrollContentPresenter />
              </Border>
              <ScrollBar x:Name="PART_VerticalScrollBar"
                         Value="{TemplateBinding VerticalOffset}"
                         Maximum="{TemplateBinding ScrollableHeight}"
                         ViewportSize="{TemplateBinding ViewportHeight}"
                         Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" />
              <ScrollBar x:Name="PART_HorizontalScrollBar"
                         Orientation="Horizontal"
                         Grid.Row="1"
                         Grid.Column="1"
                         Value="{TemplateBinding HorizontalOffset}"
                         Maximum="{TemplateBinding ScrollableWidth}"
                         ViewportSize="{TemplateBinding ViewportWidth}"
                         Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" />
            </Grid>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </Window.Resources>
  <StackPanel>
    <TextBox Margin="20"
             Width="100"
             Text="sdjkfhsdjkfhjkdshxcmvnm,xcnv,mxcnv, mxcnv,mxcngjklsdjkfh jkdfghjkfhgjkdfhgkjdfghkjdfhgbkjcvhbkcvjbh" />
  </StackPanel>
</Window>
</code>```

I use .NET 4

Body:
I copied ScrollViewer template from MSDN (link) and it breaks textbox behavior. Scroll now doesn't follow selection when I select text using mouse. Why? How to fix it?

Here's my code

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">
  <Window.Resources>

  </Window.Resources>
  <StackPanel>
    <TextBox Margin="20"
             Width="100"
             Text="sdjkfhsdjkfhjkdshxcmvnm,xcnv,mxcnv, mxcnv,mxcngjklsdjkfh jkdfghjkfhgjkdfhgkjdfghkjdfhgbkjcvhbkcvjbh" />
  </StackPanel>
</Window>

I use .NET 4

Body:
Your style is targeting ALL controls of type ScrollViewer in the Window as the style does not have a key (x:Key) set - This is a problem since TextBox actually uses a ScrollViewer in its template.

Try using <Style x:Key="MyScrollViewerStyle" TargetType="{x:Type ScrollViewer}">. You can then reference this style on your ScrollViewer like so: <ScrollViewer Style="{StaticResource MyScrollViewerStyle}">


问:
Using Findstr to find some string with non-ASCII character by batch
I'm trying to use the findstr in the Testing_Results1 to find the string Conexão falhou.. But's not working because the ã.
I tried to replace Conexão for ConexÆo but not worked. Also tried to skip the ã by this way ^ã but also not working.

```<code>:Testing_Results1
    findstr /I /C:"Conexão falhou." WinSCP.log >nul && (
              echo Sem conexÆo com a internet.
              echo Verifique o problema e tente novamente.
              pause
              goto End
    ) || (
              goto Testing_Results2
    )

    :Testing_Results2

    findstr /I /C:"Conexão perdida" WinSCP.log >nul && (
              echo ConexÆo com o servidor perdida. Tente novamente.
              pause
              goto end
    ) || (
              goto Success
    )

    :Success
    echo Arquivo(s) Exportado(s) com sucesso.
    echo/ &echo/ &echo/
    pause
    goto End

    :Error
    echo Erro desconhecido ocorrido.
    pause
    goto End

    :End
    del /f /s /q %temp%\ftpsend.dat >nul 2>nul
    del /f /s /q WinSCP.log >nul 2>nul
    exit
</code>```

Maybe this question can be considered duplicated of these:

Question 1

Question 2

But there i didn't found solution for my problem.

Any idea?

Edit 1:

Follow a piece of my WinSCP.log

```<code>. 2019-05-24 14:36:21.725 --------------------------------------------------------------------------
. 2019-05-24 14:36:21.725 Session name: xxxx@ftp.xxxx.com.br (Ad-Hoc site)
. 2019-05-24 14:36:21.725 Host name: ftp.xxxx.com.br (Port: 21)
. 2019-05-24 14:36:21.725 User name: xxxxx(Password: Yes, Key file: No, Passphrase: No)
. 2019-05-24 14:36:21.725 Transfer Protocol: FTP
. 2019-05-24 14:36:21.725 Ping type: Dummy, Ping interval: 30 sec; Timeout: 15 sec
. 2019-05-24 14:36:21.725 Disable Nagle: No
. 2019-05-24 14:36:21.725 Proxy: None
. 2019-05-24 14:36:21.725 Send buffer: 262144
. 2019-05-24 14:36:21.725 UTF: Auto
. 2019-05-24 14:36:21.725 FTPS: None [Client certificate: No]
. 2019-05-24 14:36:21.725 FTP: Passive: Yes [Force IP: Auto]; MLSD: Auto [List all: Auto]; HOST: Auto
. 2019-05-24 14:36:21.725 Local directory: default, Remote directory: home, Update: Yes, Cache: Yes
. 2019-05-24 14:36:21.725 Cache directory changes: Yes, Permanent: Yes
. 2019-05-24 14:36:21.725 Recycle bin: Delete to: No, Overwritten to: No, Bin path:
. 2019-05-24 14:36:21.725 Timezone offset: 0h 0m
. 2019-05-24 14:36:21.725 --------------------------------------------------------------------------
. 2019-05-24 14:36:21.725 Conectando a ftp.xxxxx.com.br...
. 2019-05-24 14:36:21.725 Conexão falhou.
</code>```

Edit 2:

Follow an image of my cmd using this code:

```<code>@echo on
findstr /I /C:"Conexão falhou" WinSCP.log
echo %errorlevel%
pause
</code>```

答:
The exact behavior you see depends a bit on what code page your text file is using. Assuming your file uses code page 1252 - Latin (Western European), then ã is 0xE3 (decimal 227).

The reason your FINDSTR fails is explained at What are the undocumented features and limitations of the Windows FINDSTR command? under the section Character limits for command line parameters - Extended ASCII transformation. There it explains how FINDSTR transforms (corrupts) many non-ASCII command line characters into an ASCII value.

If you read the referenced section, you will see that character 227 is transformed into 112, which corresponds to the letter p. So your FINDSTR command is looking for the wrong string.

The only way to use FINDSTR to search for your string is to put the search string in a text file and use the /g:file option. FINDSTR does not corrupt characters when using the /G option.

If the contents of "search.txt" is a single line Conexão falhou, then the following command will match the correct lines:

```<code>findstr /I /L /G:search.txt WinSCP.log
</code>```

That being said, the way the string is displayed may be incorrect, depending on your active code page. My machine defaults to code page 437, so ã is displayed as π on my machine. Either way, the character code is 0xE3. If you pipe the results of the FINDSTR to a file, you should see the correct result.

If you really want to put the search string on the command line, then you can explicitly specify a regular expression search even though you use /C by adding the /R option. You can then use . to match any character at the offending position.

```<code>findstr /I /R /C:"Conex.o falhou" WinSCP.log
</code>```

Another option is to use the FIND command instead:

```<code>find /I "Conexão falhou" <"WinSCP.log"
</code>```

Though on my machine I need the following due to active code page 437

```<code>find /I "Conexπo falhou" <"WinSCP.log
</code>```

Body:
I'm trying to use the findstr in the Testing_Results1 to find the string Conexão falhou.. But's not working because the ã.
I tried to replace Conexão for ConexÆo but not worked. Also tried to skip the ã by this way ^ã but also not working.

:Testing_Results1
    findstr /I /C:"Conexão falhou." WinSCP.log >nul && (
              echo Sem conexÆo com a internet.
              echo Verifique o problema e tente novamente.
              pause
              goto End
    ) || (
              goto Testing_Results2
    )

    :Testing_Results2

    findstr /I /C:"Conexão perdida" WinSCP.log >nul && (
              echo ConexÆo com o servidor perdida. Tente novamente.
              pause
              goto end
    ) || (
              goto Success
    )

    :Success
    echo Arquivo(s) Exportado(s) com sucesso.
    echo/ &echo/ &echo/
    pause
    goto End

    :Error
    echo Erro desconhecido ocorrido.
    pause
    goto End

    :End
    del /f /s /q %temp%\ftpsend.dat >nul 2>nul
    del /f /s /q WinSCP.log >nul 2>nul
    exit

Maybe this question can be considered duplicated of these:

Question 1

Question 2

But there i didn't found solution for my problem.

Any idea?

Edit 1:

Follow a piece of my WinSCP.log

. 2019-05-24 14:36:21.725 --------------------------------------------------------------------------
. 2019-05-24 14:36:21.725 Session name: xxxx@ftp.xxxx.com.br (Ad-Hoc site)
. 2019-05-24 14:36:21.725 Host name: ftp.xxxx.com.br (Port: 21)
. 2019-05-24 14:36:21.725 User name: xxxxx(Password: Yes, Key file: No, Passphrase: No)
. 2019-05-24 14:36:21.725 Transfer Protocol: FTP
. 2019-05-24 14:36:21.725 Ping type: Dummy, Ping interval: 30 sec; Timeout: 15 sec
. 2019-05-24 14:36:21.725 Disable Nagle: No
. 2019-05-24 14:36:21.725 Proxy: None
. 2019-05-24 14:36:21.725 Send buffer: 262144
. 2019-05-24 14:36:21.725 UTF: Auto
. 2019-05-24 14:36:21.725 FTPS: None [Client certificate: No]
. 2019-05-24 14:36:21.725 FTP: Passive: Yes [Force IP: Auto]; MLSD: Auto [List all: Auto]; HOST: Auto
. 2019-05-24 14:36:21.725 Local directory: default, Remote directory: home, Update: Yes, Cache: Yes
. 2019-05-24 14:36:21.725 Cache directory changes: Yes, Permanent: Yes
. 2019-05-24 14:36:21.725 Recycle bin: Delete to: No, Overwritten to: No, Bin path:
. 2019-05-24 14:36:21.725 Timezone offset: 0h 0m
. 2019-05-24 14:36:21.725 --------------------------------------------------------------------------
. 2019-05-24 14:36:21.725 Conectando a ftp.xxxxx.com.br...
. 2019-05-24 14:36:21.725 Conexão falhou.

Edit 2:

Follow an image of my cmd using this code:

@echo on
findstr /I /C:"Conexão falhou" WinSCP.log
echo %errorlevel%
pause

Body:
The exact behavior you see depends a bit on what code page your text file is using. Assuming your file uses code page 1252 - Latin (Western European), then ã is 0xE3 (decimal 227).

The reason your FINDSTR fails is explained at What are the undocumented features and limitations of the Windows FINDSTR command? under the section Character limits for command line parameters - Extended ASCII transformation. There it explains how FINDSTR transforms (corrupts) many non-ASCII command line characters into an ASCII value.

If you read the referenced section, you will see that character 227 is transformed into 112, which corresponds to the letter p. So your FINDSTR command is looking for the wrong string.

The only way to use FINDSTR to search for your string is to put the search string in a text file and use the /g:file option. FINDSTR does not corrupt characters when using the /G option.

If the contents of "search.txt" is a single line Conexão falhou, then the following command will match the correct lines:

findstr /I /L /G:search.txt WinSCP.log

That being said, the way the string is displayed may be incorrect, depending on your active code page. My machine defaults to code page 437, so ã is displayed as π on my machine. Either way, the character code is 0xE3. If you pipe the results of the FINDSTR to a file, you should see the correct result.

If you really want to put the search string on the command line, then you can explicitly specify a regular expression search even though you use /C by adding the /R option. You can then use . to match any character at the offending position.

findstr /I /R /C:"Conex.o falhou" WinSCP.log

Another option is to use the FIND command instead:

find /I "Conexão falhou" <"WinSCP.log"

Though on my machine I need the following due to active code page 437

find /I "Conexπo falhou" <"WinSCP.log


问:
Gnuplot: Plotting from *txt files from different directories by reading column header
My folder structure looks kind of like this

```<code>$ tree
.
├── Original_folder
│   └── cat.txt
├── folder1
│   └── cat.txt
├── folder2
│   └── cat.txt
├── folder3
│
└── cat.txt
</code>```

Each cat.txt file has 5 line before starting the column header.
Sample cat.txt file is like this

```<code>Version LRv1.10.0
Build date 2017-12-06
MOL-calc
PRESSURE
!
      Time[s]     InletT[K]   InletP[Pa]   O2_GasOut     C_GasOut
       100         0.000885   1000000       0.0007       0.2111
and so on....
</code>```

I want to plot first column along with the column which have column header with a keyword "_GasOut". (There are unknown number of header with this keywords, For each column I would like to have a separate graph). Additionally, the graphical results of Original_folder should be plotted in the same graph for all the plots from folder1, folder2, folder3...... and so on.

Corresponding graph should be saved in the corresponding folders.

N.B: folder numbers are not fixed.
I added one of the cat.txt file for reference. https://1drv.ms/t/s!Aoomvi55MLAQh1wMmpnPGnliFmgg

答:
Updated Answer

I don't know enough about gnuplot to understand the syntax of what you want to do as described in your comment. I have added code that saves the column headers and trims all the spaces and also code that derives the folder name from the filename - but I have no idea how you will use them so I just print them out. See the line marked "FIXME" in the code!

```<code>#!/bin/bash

gawk -F $'\t' '                                     # Using TABs as field separators
   /_GasOut/{                                       # On lines containing "_GasOut"
      for(f=1;f<=NF;f++){                           # ... iterate over all fields on line
         hdr=$f                                     # ... picking them up
         colhdr[f]=hdr                              # ... saving the column headers
         if(index(hdr,"_GasOut"))wanted[f]=1        # ... and noting which ones we want to print
      }
   }
   ENDFILE{                                         # As we reaach end of each file
      for(f in wanted){                             # ... iterate over wanted fields
         if(length(cmds)) cmds = cmds ",\n"         # ... adding commas and newlines if needed
         hdr = colhdr[f]                            # ... grabbing column header
         gsub(/^[[:space:]]+|[[:space:]]+$/,"",hdr) # ... trim leading or trailing spaces
         folder = FILENAME
         gsub(/\/cat.txt/,"",folder)                # ... deriving foldername
         print "hdr=", hdr, ", folder=", folder     # FIXME
         cmds = cmds "\"" FILENAME "\" using 1:" f  # ... and adding the "using" statement
      }
      delete wanted                                 # Forget list of wanted fields for next file
   }
   END{                                             # At very end of last file
      print cmds                                    # ... print accumulated gnuplot cmds
   }

   ' folder*/cat.txt
</code>```

Sample Output

```<code>hdr= O2_GasOut , folder= folder1
hdr= H2O_GasOut , folder= folder1
hdr= H2_GasOut , folder= folder1
hdr= N2_GasOut , folder= folder1
hdr= NO_GasOut , folder= folder1
hdr= NO2_GasOut , folder= folder1
hdr= N2O_GasOut , folder= folder1
hdr= O2_GasOut , folder= folder2
hdr= H2O_GasOut , folder= folder2
hdr= H2_GasOut , folder= folder2
hdr= N2_GasOut , folder= folder2
hdr= NO_GasOut , folder= folder2
hdr= NO2_GasOut , folder= folder2
hdr= N2O_GasOut , folder= folder2
"folder1/cat.txt" using 1:22,
"folder1/cat.txt" using 1:23,
"folder1/cat.txt" using 1:24,
"folder1/cat.txt" using 1:25,
"folder1/cat.txt" using 1:26,
"folder1/cat.txt" using 1:27,
"folder1/cat.txt" using 1:28,
"folder2/cat.txt" using 1:22,
"folder2/cat.txt" using 1:23,
"folder2/cat.txt" using 1:24,
"folder2/cat.txt" using 1:25,
"folder2/cat.txt" using 1:26,
"folder2/cat.txt" using 1:27,
"folder2/cat.txt" using 1:28
</code>```

Original Answer

I can't seem to count fields the same way as you do, but here is what I have:

```<code>#!/bin/bash

gawk -F $'\t' '                                     # Using TABs as field separators
   /_GasOut/{                                       # On lines containing "_GasOut"
      for(f=1;f<=NF;f++){                           # ... iterate over all fields on line
         this=$f                                    # ... picking them up
         if(index(this,"_GasOut"))wanted[f]=1       # ... and noting which ones we want to print
      }
   }
   ENDFILE{                                         # As we reaach end of each file
      for(f in wanted){                             # ... iterate over wanted fields
         if(length(cmds)) cmds = cmds ",\n"         # ... adding commas and newlines if needed
         cmds = cmds "\"" FILENAME "\" using 1:" f  # ... and adding the "using" statement
      }
      delete wanted                                 # Forget list of wanted fields for next file
   }
   END{                                             # At very end of last file
      print cmds                                    # ... print accumulated gnuplot cmds
   }

   ' folder*/cat.txt
</code>```

And here is the sample output:

```<code>"folder1/cat.txt" using 1:22,
"folder1/cat.txt" using 1:23,
"folder1/cat.txt" using 1:24,
"folder1/cat.txt" using 1:25,
"folder1/cat.txt" using 1:26,
"folder1/cat.txt" using 1:27,
"folder1/cat.txt" using 1:28,
"folder2/cat.txt" using 1:22,
"folder2/cat.txt" using 1:23,
"folder2/cat.txt" using 1:24,
"folder2/cat.txt" using 1:25,
"folder2/cat.txt" using 1:26,
"folder2/cat.txt" using 1:27,
"folder2/cat.txt" using 1:28
</code>```

Body:
My folder structure looks kind of like this

$ tree
.
├── Original_folder
│   └── cat.txt
├── folder1
│   └── cat.txt
├── folder2
│   └── cat.txt
├── folder3
│
└── cat.txt

Each cat.txt file has 5 line before starting the column header.
Sample cat.txt file is like this

Version LRv1.10.0
Build date 2017-12-06
MOL-calc
PRESSURE
!
      Time[s]     InletT[K]   InletP[Pa]   O2_GasOut     C_GasOut
       100         0.000885   1000000       0.0007       0.2111
and so on....

I want to plot first column along with the column which have column header with a keyword "_GasOut". (There are unknown number of header with this keywords, For each column I would like to have a separate graph). Additionally, the graphical results of Original_folder should be plotted in the same graph for all the plots from folder1, folder2, folder3...... and so on.

Corresponding graph should be saved in the corresponding folders.

N.B: folder numbers are not fixed.
I added one of the cat.txt file for reference. https://1drv.ms/t/s!Aoomvi55MLAQh1wMmpnPGnliFmgg

Body:
Updated Answer

I don't know enough about gnuplot to understand the syntax of what you want to do as described in your comment. I have added code that saves the column headers and trims all the spaces and also code that derives the folder name from the filename - but I have no idea how you will use them so I just print them out. See the line marked "FIXME" in the code!

#!/bin/bash

gawk -F $'\t' '                                     # Using TABs as field separators
   /_GasOut/{                                       # On lines containing "_GasOut"
      for(f=1;f<=NF;f++){                           # ... iterate over all fields on line
         hdr=$f                                     # ... picking them up
         colhdr[f]=hdr                              # ... saving the column headers
         if(index(hdr,"_GasOut"))wanted[f]=1        # ... and noting which ones we want to print
      }
   }
   ENDFILE{                                         # As we reaach end of each file
      for(f in wanted){                             # ... iterate over wanted fields
         if(length(cmds)) cmds = cmds ",\n"         # ... adding commas and newlines if needed
         hdr = colhdr[f]                            # ... grabbing column header
         gsub(/^[[:space:]]+|[[:space:]]+$/,"",hdr) # ... trim leading or trailing spaces
         folder = FILENAME
         gsub(/\/cat.txt/,"",folder)                # ... deriving foldername
         print "hdr=", hdr, ", folder=", folder     # FIXME
         cmds = cmds "\"" FILENAME "\" using 1:" f  # ... and adding the "using" statement
      }
      delete wanted                                 # Forget list of wanted fields for next file
   }
   END{                                             # At very end of last file
      print cmds                                    # ... print accumulated gnuplot cmds
   }

   ' folder*/cat.txt

Sample Output

hdr= O2_GasOut , folder= folder1
hdr= H2O_GasOut , folder= folder1
hdr= H2_GasOut , folder= folder1
hdr= N2_GasOut , folder= folder1
hdr= NO_GasOut , folder= folder1
hdr= NO2_GasOut , folder= folder1
hdr= N2O_GasOut , folder= folder1
hdr= O2_GasOut , folder= folder2
hdr= H2O_GasOut , folder= folder2
hdr= H2_GasOut , folder= folder2
hdr= N2_GasOut , folder= folder2
hdr= NO_GasOut , folder= folder2
hdr= NO2_GasOut , folder= folder2
hdr= N2O_GasOut , folder= folder2
"folder1/cat.txt" using 1:22,
"folder1/cat.txt" using 1:23,
"folder1/cat.txt" using 1:24,
"folder1/cat.txt" using 1:25,
"folder1/cat.txt" using 1:26,
"folder1/cat.txt" using 1:27,
"folder1/cat.txt" using 1:28,
"folder2/cat.txt" using 1:22,
"folder2/cat.txt" using 1:23,
"folder2/cat.txt" using 1:24,
"folder2/cat.txt" using 1:25,
"folder2/cat.txt" using 1:26,
"folder2/cat.txt" using 1:27,
"folder2/cat.txt" using 1:28

Original Answer

I can't seem to count fields the same way as you do, but here is what I have:

#!/bin/bash

gawk -F $'\t' '                                     # Using TABs as field separators
   /_GasOut/{                                       # On lines containing "_GasOut"
      for(f=1;f<=NF;f++){                           # ... iterate over all fields on line
         this=$f                                    # ... picking them up
         if(index(this,"_GasOut"))wanted[f]=1       # ... and noting which ones we want to print
      }
   }
   ENDFILE{                                         # As we reaach end of each file
      for(f in wanted){                             # ... iterate over wanted fields
         if(length(cmds)) cmds = cmds ",\n"         # ... adding commas and newlines if needed
         cmds = cmds "\"" FILENAME "\" using 1:" f  # ... and adding the "using" statement
      }
      delete wanted                                 # Forget list of wanted fields for next file
   }
   END{                                             # At very end of last file
      print cmds                                    # ... print accumulated gnuplot cmds
   }

   ' folder*/cat.txt

And here is the sample output:

"folder1/cat.txt" using 1:22,
"folder1/cat.txt" using 1:23,
"folder1/cat.txt" using 1:24,
"folder1/cat.txt" using 1:25,
"folder1/cat.txt" using 1:26,
"folder1/cat.txt" using 1:27,
"folder1/cat.txt" using 1:28,
"folder2/cat.txt" using 1:22,
"folder2/cat.txt" using 1:23,
"folder2/cat.txt" using 1:24,
"folder2/cat.txt" using 1:25,
"folder2/cat.txt" using 1:26,
"folder2/cat.txt" using 1:27,
"folder2/cat.txt" using 1:28


问:
SQL Server - query to return non-conflicting schedules
I'm trying to write a command to create schedules for employees with varying work addresses. There are a number of locations, each of which has to be visited once (by one employee) during a period.

To start, I've made just two tables, address_availability (columns avail_date and address) and employee_availability (columns avail_date and name)

To get a list of all possible placements, I just select the address and employee names from the two tables and join them on the date. As a sample output I get

```<code>London, Thomas, 27/05/2019
London, Thomas, 28/05/2019
Glasgow, Thomas, 27/05/2019
London, Mary, 27/05/2019
Glasgow, Mary, 27/05/2019
</code>```

I need to make it so that there are no scheduling conflicts, i.e. if Thomas is proposed for London on the 27th he cannot be in Glasgow on the 27th.

I would also like to have the command give a maximum of 5 results per employee and not propose two employees for the same place on the same date.

I'm not really sure I'm using the right tool for the job. Is this doable in SQL ?

答:
If you are happy to take it out into the spreadsheet, I would use a PIVOT query https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017) to get the data in a format

```<code>LOCATION     TIME        Thomas  Mary

London       27/05/2019  1       1
Glasgow      27/05/2019  1       1

London       28/05/2019  1       0
</code>```

So from the table above you can see that on the 27th Mary and Thomas can both do either but on the 28th Thomas is the only one available.

As for making it produce a list, you can take this script further by looping through and where there is only one option, taking it (and then removing that person for that day) and looping again. Depending on complexity you will soon hit limits where you have 2 options and you just need to take one.

This is also on the understanding that there is always a solution, you didn't layout the full requirements etc to suggest that.

Body:
I'm trying to write a command to create schedules for employees with varying work addresses. There are a number of locations, each of which has to be visited once (by one employee) during a period.

To start, I've made just two tables, address_availability (columns avail_date and address) and employee_availability (columns avail_date and name)

To get a list of all possible placements, I just select the address and employee names from the two tables and join them on the date. As a sample output I get

London, Thomas, 27/05/2019
London, Thomas, 28/05/2019
Glasgow, Thomas, 27/05/2019
London, Mary, 27/05/2019
Glasgow, Mary, 27/05/2019

I need to make it so that there are no scheduling conflicts, i.e. if Thomas is proposed for London on the 27th he cannot be in Glasgow on the 27th.

I would also like to have the command give a maximum of 5 results per employee and not propose two employees for the same place on the same date.

I'm not really sure I'm using the right tool for the job. Is this doable in SQL ?

Body:
If you are happy to take it out into the spreadsheet, I would use a PIVOT query https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017) to get the data in a format

LOCATION     TIME        Thomas  Mary

London       27/05/2019  1       1
Glasgow      27/05/2019  1       1

London       28/05/2019  1       0

So from the table above you can see that on the 27th Mary and Thomas can both do either but on the 28th Thomas is the only one available.

As for making it produce a list, you can take this script further by looping through and where there is only one option, taking it (and then removing that person for that day) and looping again. Depending on complexity you will soon hit limits where you have 2 options and you just need to take one.

This is also on the understanding that there is always a solution, you didn't layout the full requirements etc to suggest that.


问:
Laravel 5.5 Webpack dependency was not found
Related SO question: npm - package.json override main field (I tried to do something like this using the  webpack.mix.js but it didn't work).

I have a Laravel 5.5 application with npm v5.6.0 and node v9.4.0 (I'm thinking that this maybe is an npm/node version issue, but I don't have an environment to test with older versions ATM). Everything is working fine and I'm working this app for a while now and I've installed some node modules and used bootstrap.js and app.js to require/import npm modules, but it seems there is a problem with the bootstrap-treeview; I've spent more than 2 hours to try and make webpack compile with this module with no luck; I always get that error after npm run dev:

ERROR  Failed to compile with 1 errors

This dependency was not found:

bootstrap-treeview in ./resources/assets/js/bootstrap.js

I tried to use both require and import inside bootstrap.js and I have even tried an other available module webpack-bootstrap-treeview which it seems that it doesn't have bower dependency:

```<code>//import "~/node_modules/bootstrap-treeview";
//require("bootstrap-treeview");
//import "bootstrap-treeview";
//import "~/node_modules/webpack-bootstrap-treeview";
//require("webpack-bootstrap-treeview");
import "webpack-bootstrap-treeview";
</code>```

bootstrap-treeview: https://www.npmjs.com/package/bootstrap-treeview

webpack-bootstrap-treeview: https://www.npmjs.com/package/webpack-bootstrap-treeview

I know I can just use laravel-mix to compile the js files directly to the app.js and I will probably do, but I want to have my modules organized and I'd like to find the culprit on this issue.

EDIT

I've also tried to delete the node_modules directory then npm install and even npm cache clear, nothing worked for the webpack to compile without that error.

答: Looks like there are some misnamed files.  Renaming the bootstrap-treeview files in node_modules\bootstrap-treeview-2\dist to bootstrap-treeview-2 allows webpack to successfully complete. Oh, and I installed the bootstrap-treeview-2 package because bootstrap-treeview has been archived.</p>

Body:
Related SO question: npm - package.json override main field (I tried to do something like this using the  webpack.mix.js but it didn't work).

I have a Laravel 5.5 application with npm v5.6.0 and node v9.4.0 (I'm thinking that this maybe is an npm/node version issue, but I don't have an environment to test with older versions ATM). Everything is working fine and I'm working this app for a while now and I've installed some node modules and used bootstrap.js and app.js to require/import npm modules, but it seems there is a problem with the bootstrap-treeview; I've spent more than 2 hours to try and make webpack compile with this module with no luck; I always get that error after npm run dev:

ERROR  Failed to compile with 1 errors

This dependency was not found:

bootstrap-treeview in ./resources/assets/js/bootstrap.js

I tried to use both require and import inside bootstrap.js and I have even tried an other available module webpack-bootstrap-treeview which it seems that it doesn't have bower dependency:

//import "~/node_modules/bootstrap-treeview";
//require("bootstrap-treeview");
//import "bootstrap-treeview";
//import "~/node_modules/webpack-bootstrap-treeview";
//require("webpack-bootstrap-treeview");
import "webpack-bootstrap-treeview";

bootstrap-treeview: https://www.npmjs.com/package/bootstrap-treeview

webpack-bootstrap-treeview: https://www.npmjs.com/package/webpack-bootstrap-treeview

I know I can just use laravel-mix to compile the js files directly to the app.js and I will probably do, but I want to have my modules organized and I'd like to find the culprit on this issue.

EDIT

I've also tried to delete the node_modules directory then npm install and even npm cache clear, nothing worked for the webpack to compile without that error.


问:
Is the memory usage of using one dict half the amount that is needed for two dicts?
Let's say I have 2 dictionaries in Python, like this:

```<code>d1 = {}
d2 = {}
d1[(i, j)] = 10
d2[(i, j)] = 20
</code>```

Instead I could do it like this:

```<code>d = {}
d[(i, j)] = (10, 20)
</code>```

Accessing it could be done with d[(i,j)][0] and d[(i,j)][1].

What I would like to ask is this:

Does the second option need less memory than the first?

If yes, is it half the memory?

I need to use very large dictionaries in a program I am writing and if the second solution is better I would opt for that.

答:
Tested this on Windows 10 machine in 32bit Python 3.7.3 repl:

This took 155MB of memory:

```<code>>>> d1 = {(i, j): 10 for i in range(1000) for j in range(1000)}
>>> d2 = {(i, j): 20 for i in range(1000) for j in range(1000)}
</code>```

And this only 79MB:

```<code>>>> d = {(i, j): (10, 20) for i in range(1000) for j in range(1000)}
</code>```

So the second one is obviously better in terms of memory usage, but they are quite different solutions and it's hard to say which one is 'better' overall. It all depends on the use case.

Edit:

The difference is a lot smaller, but still significant when using random values (with unique ids).

This took 157MB:

```<code>>>> from random import randint
>>> d1 = {(i, j): randint(0, 100) for i in range(1000) for j in range(1000)}
>>> d2 = {(i, j): randint(0, 100) for i in range(1000) for j in range(1000)}
</code>```

And this 119MB:

```<code>>>> from random import randint
>>> d = {(i, j): (randint(0, 100), randint(0, 100)) for i in range(1000) for j in range(1000)}
</code>```

Body:
Let's say I have 2 dictionaries in Python, like this:

d1 = {}
d2 = {}
d1[(i, j)] = 10
d2[(i, j)] = 20

Instead I could do it like this:

d = {}
d[(i, j)] = (10, 20)

Accessing it could be done with d[(i,j)][0] and d[(i,j)][1].

What I would like to ask is this:

Does the second option need less memory than the first?

If yes, is it half the memory?

I need to use very large dictionaries in a program I am writing and if the second solution is better I would opt for that.

Body:
Tested this on Windows 10 machine in 32bit Python 3.7.3 repl:

This took 155MB of memory:

>>> d1 = {(i, j): 10 for i in range(1000) for j in range(1000)}
>>> d2 = {(i, j): 20 for i in range(1000) for j in range(1000)}

And this only 79MB:

>>> d = {(i, j): (10, 20) for i in range(1000) for j in range(1000)}

So the second one is obviously better in terms of memory usage, but they are quite different solutions and it's hard to say which one is 'better' overall. It all depends on the use case.

Edit:

The difference is a lot smaller, but still significant when using random values (with unique ids).

This took 157MB:

>>> from random import randint
>>> d1 = {(i, j): randint(0, 100) for i in range(1000) for j in range(1000)}
>>> d2 = {(i, j): randint(0, 100) for i in range(1000) for j in range(1000)}

And this 119MB:

>>> from random import randint
>>> d = {(i, j): (randint(0, 100), randint(0, 100)) for i in range(1000) for j in range(1000)}


问:
Difference between Constructor and ngOnInit
Angular provides life cycle hook ngOnInit by default.

Why should ngOnInit be used, if we already have a constructor?

答:
Constructor is a function executed when component (or other class) is built.

ngOnInit is a function belonging to a component life-cycle method groups and they are executed in a diffrent moment of our component (that's why name life-cycle). Here is a list of all of them:

Constructor will be executed before any life-cycle function.


问:
highlight a column on table element - CSS
I have a table constructed in the following format:

```<code><thead>
  <th></th>
  <th></th>
  <th></th>
</thead>

<tbody>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</tbody>
</code>```

I'm trying to highlight a column if the header column is hovered.  So let's say if I hovered the second header  from, say blue, then the second  from every
, which makes it a column, will be highlighted in yellow.  How can I achieve this? I've tried many different ways but its not highlighting the
, only the header.  I would like to keep it in a table structure.  Can anybody help with this?

答:
you can do something like this:

```<code><table>
<thead>
  <th>head 1</th>
  <th>head 2</th>
  <th>head 3</th>
</thead>

<tbody>
  <tr>
    <td>row 1 cell 1</td>
    <td>row 1 cell 2</td>
    <td>row 1 cell 3</td>
  </tr>
  <tr>
    <td>row 2 cell 1</td>
    <td>row 2 cell 2</td>
    <td>row 2 cell 3</td>
  </tr>
  <tr>
    <td>row 3 cell 1</td>
    <td>row 3 cell 2</td>
    <td>row 3 cell 3</td>
  </tr>
</tbody>
  </table>
</code>```

and css

```<code>table {
  overflow: hidden;
}

td, th {
  position: relative;
}
th:hover {background-color:blue;}

th:hover::after {
  content: "";
  position: absolute;
  background-color: grey;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}
</code>```

Body:
I have a table constructed in the following format:

I'm trying to highlight a column if the header column is hovered.  So let's say if I hovered the second header  from, say blue, then the second  from every
, which makes it a column, will be highlighted in yellow.  How can I achieve this? I've tried many different ways but its not highlighting the
, only the header.  I would like to keep it in a table structure.  Can anybody help with this?

Body:
you can do something like this:

<table>
<thead>
  <th>head 1</th>
  <th>head 2</th>
  <th>head 3</th>
</thead>

<tbody>
  <tr>
    <td>row 1 cell 1</td>
    <td>row 1 cell 2</td>
    <td>row 1 cell 3</td>
  </tr>
  <tr>
    <td>row 2 cell 1</td>
    <td>row 2 cell 2</td>
    <td>row 2 cell 3</td>
  </tr>
  <tr>
    <td>row 3 cell 1</td>
    <td>row 3 cell 2</td>
    <td>row 3 cell 3</td>
  </tr>
</tbody>
  </table>

and css

table {
  overflow: hidden;
}

td, th {
  position: relative;
}
th:hover {background-color:blue;}

th:hover::after {
  content: "";
  position: absolute;
  background-color: grey;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}


问:
How to create a sinusoidal signal with additive White Gaussian Noise (WGN) and dump the dataset to a text file?

The scripts, first create a sine data set for t = [0:0.1:2] with 1Hz frequency.

Then, it adds a Gaussian random data whose mean is 0 and standard deviation is 0.5 to the sine data.

Plots both dataset on the same figure.

At the end, writes all noisy sinusoidal data to the file called
data.csv using a for loop and fprintf function.

I wrote this but i want to use randn.

```<code>>>frequenciy = [1];
>>curTime = 0;
>>h = 0.01;
>>for i = 1:length(frequenciy)
    endTime = curTime + 2*pi/frequenciy(i);
    t = [0:0.1:2];
    shift = frequenciy(i)*t(1);
    curTime = endTime;
    plot(t,sin(frequenciy(i)*t-shift))
    hold on
>>end
</code>```

答:
You don't need a loop.

Try this:

```<code>t = 0:0.01:4;

f = 1; %Hz
w = 2*pi*f;

s = sin(w*t); % original signal with frequency 1Hz
noise = randn(size(s)); % white noise with mu=0, sigma = 1
noise = noise*0.5; % sigma correction
s_noisy = s + noise;

%plot
figure
plot(t, s);
hold on;
plot(t, s_noisy);
hold off;
grid minor;

% save to file
fileID = fopen('sine.csv','w');
fprintf(fileID, '%6.4f\n', s_noisy);
fclose(fileID);
</code>```

Body:
The scripts, first create a sine data set for t = [0:0.1:2] with 1Hz frequency.

Then, it adds a Gaussian random data whose mean is 0 and standard deviation is 0.5 to the sine data.

Plots both dataset on the same figure.

At the end, writes all noisy sinusoidal data to the file called
data.csv using a for loop and fprintf function.

I wrote this but i want to use randn.

>>frequenciy = [1];
>>curTime = 0;
>>h = 0.01;
>>for i = 1:length(frequenciy)
    endTime = curTime + 2*pi/frequenciy(i);
    t = [0:0.1:2];
    shift = frequenciy(i)*t(1);
    curTime = endTime;
    plot(t,sin(frequenciy(i)*t-shift))
    hold on
>>end

Body:
You don't need a loop.

Try this:

t = 0:0.01:4;

f = 1; %Hz
w = 2*pi*f;

s = sin(w*t); % original signal with frequency 1Hz
noise = randn(size(s)); % white noise with mu=0, sigma = 1
noise = noise*0.5; % sigma correction
s_noisy = s + noise;

%plot
figure
plot(t, s);
hold on;
plot(t, s_noisy);
hold off;
grid minor;

% save to file
fileID = fopen('sine.csv','w');
fprintf(fileID, '%6.4f\n', s_noisy);
fclose(fileID);


问:
Install react-native-community/react-native-video on expo kit
In expo kit projects react-native link doesnt work for react-native-community/react-native-video.  Android app stops running and IOS throws the error when the video component is used.  </p>

答:
Okay a finall worked this out of weeks of fiddling.

npm install --save react-native-video

react-native link react-native-video

cd ios

pod install

open xcode and run project - it should work now on IOS

open android studio

open android/settings.gradle

change the line:

List item

project(':react-native-video').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-video/android-exoplayer')

to

project(':react-native-video').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-video/android')


问:
how to fix that fetchmetadata: sill resolvewithnewmodule react-is@16.8.6 checking installable
I am not able to create new project getting this  fetch meta data : sill resolve with new module react-is@16.8.6 checking install . terminal always got stuck on this </p>

答: Open the command prompt as administrator and it will resolve your problem.</p>