问:
How can I change the style of a control (CListBox) initialized with DDX_Control, before DDX_Control is called
I'm modifying an existing project and a dialog has controls I am subclassing to theme differently in some cases (in other cases I will leave it entirely alone).  By the time DDX_Control() is called during DoDataExchange(), the hwnd for the ListBox already has styles applied.  Specifically, at this time even if I do SetWindowLongPtr(), the LBS_OWNERDRAWFIXED does not work.  By "does not work," I mean that although the style is applied, owner draw messages are not received by the CListBox.

Conversely, if I avoid the DDX_Control() and simply do a create, the ListBox does receive the messages and can be ownerdrawn.  But if I do this there are now two HWND, only one of which is returned by GetDlgItem().  I believe I can make this work if necessary, but I wondered if there is a secret to intercept the HWND creation of the controls in the dialog (actually a CPropertyPage).

Below is code that doesn't work, with more commented code that "works" but isn't the way I wanted it to work, if possible.

```<code>void CMyPropertySheet::DoDataExchange(CDataExchange* pDX)
{
    HWND hWndCtrl;
    pDX->m_pDlgWnd->GetDlgItem(IDC_LIST1, &hWndCtrl);

    if (themed) {
        DWORD style = GetWindowLongPtr(hWndCtrl, GWL_STYLE) | LBS_OWNERDRAWFIXED;
        SetWindowLongPtr(hWndCtrl, GWL_STYLE, style);
        DDX_Control(pDX, IDC_LIST1, m_listbox);
        //RECT wr;
        //::GetWindowRect(hWndCtrl, &wr);
        //m_listbox.Create(style, wr, this, IDC_LIST1);
    } else {
        DDX_Control(pDX, IDC_LIST1, m_listbox);
    }
</code>```

I should probably add I tried subclassing the window, but it didn't help, and CMyPropertySheet::PreSubclassWindow wasn't soon enough, either.

答:
OK, I'm not sure I recommend this to anyone, but I did find a way to modify the template, finally.  I had to use VirtualProtect to unlock the memory of the template.</p>

```<code>for (int i = 0; i < m_pages.GetSize(); i++) {
    CPropertyPage* pPage = GetPage(i);
    PROPSHEETPAGE* tpsp = &pPage->m_psp;

    const DLGTEMPLATE* pTemplate;
    if (tpsp->dwFlags & PSP_DLGINDIRECT) {
        pTemplate = tpsp->pResource;
    } else {
        HRSRC hResource = ::FindResource(tpsp->hInstance, tpsp->pszTemplate, RT_DIALOG);
        if (hResource == NULL) return false;
        HGLOBAL hTemplate = LoadResource(tpsp->hInstance, hResource);
        if (hTemplate == NULL) return false;
        pTemplate = (LPCDLGTEMPLATE)LockResource(hTemplate);
        if (pTemplate == NULL) return false;
    }

    if (afxOccManager != NULL) {
        DLGITEMTEMPLATE *pItem = _AfxFindFirstDlgItem(pTemplate);
        DLGITEMTEMPLATE *pNextItem;
        BOOL bDialogEx = IsDialogEx(pTemplate);

        int iItem, iItems = DlgTemplateItemCount(pTemplate);

        for (iItem = 0; iItem < iItems; iItem++) {
            pNextItem = _AfxFindNextDlgItem(pItem, bDialogEx);
            DWORD dwOldProtect, tp;
            if (bDialogEx) {
                _DialogSplitHelper::DLGITEMTEMPLATEEX *pItemEx = (_DialogSplitHelper::DLGITEMTEMPLATEEX *)pItem;
                if (pItemEx->id == IDC_LIST1) {
                    if (VirtualProtect(&pItemEx->style, sizeof(pItemEx->style), PAGE_READWRITE, &dwOldProtect)) {
                        pItemEx->style |= LBS_OWNERDRAWFIXED;
                        VirtualProtect(&pItemEx->style, sizeof(pItemEx->style), dwOldProtect, &tp);
                    }
                }
            } else {
                if (pItem->id == IDC_LIST1) {
                    if (VirtualProtect(&pItem->style, sizeof(pItem->style), PAGE_READWRITE, &dwOldProtect)) {
                        pItem->style |= LBS_OWNERDRAWFIXED;
                        VirtualProtect(&pItem->style, sizeof(pItem->style), dwOldProtect, &tp);
                    }
                }
            }
            pItem = pNextItem;
        }
    }
}
return true;
</code>```

Body:
I'm modifying an existing project and a dialog has controls I am subclassing to theme differently in some cases (in other cases I will leave it entirely alone).  By the time DDX_Control() is called during DoDataExchange(), the hwnd for the ListBox already has styles applied.  Specifically, at this time even if I do SetWindowLongPtr(), the LBS_OWNERDRAWFIXED does not work.  By "does not work," I mean that although the style is applied, owner draw messages are not received by the CListBox.

Conversely, if I avoid the DDX_Control() and simply do a create, the ListBox does receive the messages and can be ownerdrawn.  But if I do this there are now two HWND, only one of which is returned by GetDlgItem().  I believe I can make this work if necessary, but I wondered if there is a secret to intercept the HWND creation of the controls in the dialog (actually a CPropertyPage).

Below is code that doesn't work, with more commented code that "works" but isn't the way I wanted it to work, if possible.

void CMyPropertySheet::DoDataExchange(CDataExchange* pDX)
{
    HWND hWndCtrl;
    pDX->m_pDlgWnd->GetDlgItem(IDC_LIST1, &hWndCtrl);

    if (themed) {
        DWORD style = GetWindowLongPtr(hWndCtrl, GWL_STYLE) | LBS_OWNERDRAWFIXED;
        SetWindowLongPtr(hWndCtrl, GWL_STYLE, style);
        DDX_Control(pDX, IDC_LIST1, m_listbox);
        //RECT wr;
        //::GetWindowRect(hWndCtrl, &wr);
        //m_listbox.Create(style, wr, this, IDC_LIST1);
    } else {
        DDX_Control(pDX, IDC_LIST1, m_listbox);
    }

I should probably add I tried subclassing the window, but it didn't help, and CMyPropertySheet::PreSubclassWindow wasn't soon enough, either.

Body:
OK, I'm not sure I recommend this to anyone, but I did find a way to modify the template, finally.  I had to use VirtualProtect to unlock the memory of the template.

for (int i = 0; i < m_pages.GetSize(); i++) {
    CPropertyPage* pPage = GetPage(i);
    PROPSHEETPAGE* tpsp = &pPage->m_psp;

    const DLGTEMPLATE* pTemplate;
    if (tpsp->dwFlags & PSP_DLGINDIRECT) {
        pTemplate = tpsp->pResource;
    } else {
        HRSRC hResource = ::FindResource(tpsp->hInstance, tpsp->pszTemplate, RT_DIALOG);
        if (hResource == NULL) return false;
        HGLOBAL hTemplate = LoadResource(tpsp->hInstance, hResource);
        if (hTemplate == NULL) return false;
        pTemplate = (LPCDLGTEMPLATE)LockResource(hTemplate);
        if (pTemplate == NULL) return false;
    }

    if (afxOccManager != NULL) {
        DLGITEMTEMPLATE *pItem = _AfxFindFirstDlgItem(pTemplate);
        DLGITEMTEMPLATE *pNextItem;
        BOOL bDialogEx = IsDialogEx(pTemplate);

        int iItem, iItems = DlgTemplateItemCount(pTemplate);

        for (iItem = 0; iItem < iItems; iItem++) {
            pNextItem = _AfxFindNextDlgItem(pItem, bDialogEx);
            DWORD dwOldProtect, tp;
            if (bDialogEx) {
                _DialogSplitHelper::DLGITEMTEMPLATEEX *pItemEx = (_DialogSplitHelper::DLGITEMTEMPLATEEX *)pItem;
                if (pItemEx->id == IDC_LIST1) {
                    if (VirtualProtect(&pItemEx->style, sizeof(pItemEx->style), PAGE_READWRITE, &dwOldProtect)) {
                        pItemEx->style |= LBS_OWNERDRAWFIXED;
                        VirtualProtect(&pItemEx->style, sizeof(pItemEx->style), dwOldProtect, &tp);
                    }
                }
            } else {
                if (pItem->id == IDC_LIST1) {
                    if (VirtualProtect(&pItem->style, sizeof(pItem->style), PAGE_READWRITE, &dwOldProtect)) {
                        pItem->style |= LBS_OWNERDRAWFIXED;
                        VirtualProtect(&pItem->style, sizeof(pItem->style), dwOldProtect, &tp);
                    }
                }
            }
            pItem = pNextItem;
        }
    }
}
return true;


来源: stackexchange

问:
Selecting multiple columns in a Pandas dataframe
How do I select columns a and b from df, and save them into a new dataframe df1?

index  a   b   c
1      2   3   4
2      3   4   5
```
<p>Unsuccessful attempt:</p>
<pre class="lang-py prettyprint-override"><code>df1 = df['a':'b']
df1 = df.ix[:, 'a':'b']
</code>```

答:
I've seen several answers on that, but one remained unclear to me. How would you select those columns of interest?

The answer to that is that if you have them gathered in a list, you can just reference the columns using the list.

Example

```<code>print(extracted_features.shape)
print(extracted_features)

(63,)
['f000004' 'f000005' 'f000006' 'f000014' 'f000039' 'f000040' 'f000043'
 'f000047' 'f000048' 'f000049' 'f000050' 'f000051' 'f000052' 'f000053'
 'f000054' 'f000055' 'f000056' 'f000057' 'f000058' 'f000059' 'f000060'
 'f000061' 'f000062' 'f000063' 'f000064' 'f000065' 'f000066' 'f000067'
 'f000068' 'f000069' 'f000070' 'f000071' 'f000072' 'f000073' 'f000074'
 'f000075' 'f000076' 'f000077' 'f000078' 'f000079' 'f000080' 'f000081'
 'f000082' 'f000083' 'f000084' 'f000085' 'f000086' 'f000087' 'f000088'
 'f000089' 'f000090' 'f000091' 'f000092' 'f000093' 'f000094' 'f000095'
 'f000096' 'f000097' 'f000098' 'f000099' 'f000100' 'f000101' 'f000103']
</code>```

I have the following list/NumPy array extracted_features, specifying 63 columns. The original dataset has 103 columns, and I would like to extract exactly those, then I would use

```<code>dataset[extracted_features]
</code>```

And you will end up with this

This something you would use quite often in machine learning (more specifically, in feature selection). I would like to discuss other ways too, but I think that has already been covered by other Stack Overflower users.

ContentLicense: CC BY-SA 4.0

Body:
How do I select columns a and b from df, and save them into a new dataframe df1?

index  a   b   c
1      2   3   4
2      3   4   5

Unsuccessful attempt:

df1 = df['a':'b']
df1 = df.ix[:, 'a':'b']

Body:
I've seen several answers on that, but one remained unclear to me. How would you select those columns of interest?

The answer to that is that if you have them gathered in a list, you can just reference the columns using the list.

Example

print(extracted_features.shape)
print(extracted_features)

(63,)
['f000004' 'f000005' 'f000006' 'f000014' 'f000039' 'f000040' 'f000043'
 'f000047' 'f000048' 'f000049' 'f000050' 'f000051' 'f000052' 'f000053'
 'f000054' 'f000055' 'f000056' 'f000057' 'f000058' 'f000059' 'f000060'
 'f000061' 'f000062' 'f000063' 'f000064' 'f000065' 'f000066' 'f000067'
 'f000068' 'f000069' 'f000070' 'f000071' 'f000072' 'f000073' 'f000074'
 'f000075' 'f000076' 'f000077' 'f000078' 'f000079' 'f000080' 'f000081'
 'f000082' 'f000083' 'f000084' 'f000085' 'f000086' 'f000087' 'f000088'
 'f000089' 'f000090' 'f000091' 'f000092' 'f000093' 'f000094' 'f000095'
 'f000096' 'f000097' 'f000098' 'f000099' 'f000100' 'f000101' 'f000103']

I have the following list/NumPy array extracted_features, specifying 63 columns. The original dataset has 103 columns, and I would like to extract exactly those, then I would use

dataset[extracted_features]

And you will end up with this

This something you would use quite often in machine learning (more specifically, in feature selection). I would like to discuss other ways too, but I think that has already been covered by other Stack Overflower users.


问:
Chrome headless print-to-pdf doesn't render images
I am trying to write a script to output a lot of markdown pages to PDF using Chrome's headless mode.   My current command is:

```<code>/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome  --headless
  --run-all-compositor-stages-before-draw  --disable-gpu
  --print-to-pdf="index.pdf" http://localhost:8080/#!index.md
</code>```

The resulting PDF file seems to render as it would be shown except for the images.   What I get in the PDF file is a link to the image instead of the image itself.

When I run the --screenshot option I do get the pictures you would expect in the resulting image file.

I think the reason is that it has something to do with the page being rendered with MDwiki, which does a lot of client-side work to convert markdown to HTML.   But when I try to use the --virtual-time-budget option Chrome errors out with a message about multiple tables only allowed if debugger is enabled.

Any suggestions for what next to try?

答:
It turns out that there is an node package that takes care of this: chrome-headless-render-pdf.  There isn't much documentation but it works.  Check out:</p>

```<code>npm docs chrome-headless-render-pdf
</code>```

Body:
I am trying to write a script to output a lot of markdown pages to PDF using Chrome's headless mode.   My current command is:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome  --headless
  --run-all-compositor-stages-before-draw  --disable-gpu
  --print-to-pdf="index.pdf" http://localhost:8080/#!index.md

The resulting PDF file seems to render as it would be shown except for the images.   What I get in the PDF file is a link to the image instead of the image itself.

When I run the --screenshot option I do get the pictures you would expect in the resulting image file.

I think the reason is that it has something to do with the page being rendered with MDwiki, which does a lot of client-side work to convert markdown to HTML.   But when I try to use the --virtual-time-budget option Chrome errors out with a message about multiple tables only allowed if debugger is enabled.

Any suggestions for what next to try?

Body:
It turns out that there is an node package that takes care of this: chrome-headless-render-pdf.  There isn't much documentation but it works.  Check out:

npm docs chrome-headless-render-pdf


问:
Executing unix shell commands using PHP
A text box will be used to capture the command. I've been told that I have to use the exec() function to execute UNIX shell commands.

Something like this, user types ls in the text box. The exec() function will execute the UNIX command and the command will be displayed on the web page.

What I want to know how will I get the output of the shell command and display in the web browser using PHP.

I don't know where to start since I'm very new to PHP.

I'm using Ubuntu.

答:
You can use the backticks for this purpose. Like:

```<code>$output = `command-executable -switches`
</code>```

In addition, some applications echo their output to the STD_ERR stream so you might not see output. On linux, you can redirect the error input to the 'normal' input by appending 2>&1 to the command string.

ContentLicense: CC BY-SA 3.0

Title: Executing unix shell commands using PHP

Body:
You can use the backticks for this purpose. Like:

$output = `command-executable -switches`

In addition, some applications echo their output to the STD_ERR stream so you might not see output. On linux, you can redirect the error input to the 'normal' input by appending 2>&1 to the command string.


问:
Using cnn models trained on different datasets
I am having 3 different datasets, 3 of them were all blood smear image stained with the same chemical substance. Blood smear images are images that capture your blood, include Red, White blood cells inside.

The first dataset contain 2 classes : normal vs blood cancer
The second dataset contain 2 classes: normal vs blood infection
The third dataset contain 2 classes: normal vs sickle cell disease

So, what i want to do is : when i input a blood smear image, the AI system will tell me whether it was : normal , or blood cancer or blood infection or sickle cell disease (4 classes classification task)

What should i do?

Should i mix these 3 datasets and train only 1 model to detect 4 classes ?

Or should i train 3 different models and them combine them? If yes, what method should i use to combine?

Update : i searched for a while. Can this task called "Learning without forgetting?"

答: As @Peter said it is totally data dependent. If the images of the 4 classes, namely  normal ,blood cancer ,blood infection ,sickle cell disease are easily distinguishable with your naked eyes and there is no scope of confusion among all the classes then you should simply go for 1 model which gives out probabilities  of all the 4 classes(as mentioned by @maxi marufo). If there is confusion between classes and the images are NOT distinguishable with naked eyes or there is a lot of scope of confusion between the classes then you should use 3 different models but then you'll need. You simply get the predicted probabilities from all the 3 models suppose p1(normal) and p1(c1), p2(normal) and p2(c2), p3(normal) and p3(c3). Now you can average(p1(normal),p2(normal),p3(normal)) and the use a softmax for p(normal), p1(c1), p2(c2), p3(c3) . Out of multiple ways you could try, the above could be one. </p>


问:
Build failed with an exception. while generating a signed apk
I am trying to build an application. I can able to build the application properly. Also, I can able to generate the application with debug mode. But when I try to generate the signed apk with release mode, I got the below error.

Please help me what went wrong.

The error is as below

```<code>:app:validateSigningRelease UP-TO-DATE
:app:packageRelease FAILED

 FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:packageRelease'.
> C:\Users\Baba\Project\Application\Artharakshak\Code\Artharakshak\app\release\app-release.apk

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s
30 actionable tasks: 29 executed, 1 up-to-date
</code>```

Below is my progourd file

```<code># Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in C:\Users\Baba\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# Add any project specific keep options here:

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
-ignorewarnings
</code>```

Build Version is

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
</code>```

答:
Maybe you put an incorrect password

you need to add this code inside gradle.properties

```<code>MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=my-key-alias
MYAPP_RELEASE_STORE_PASSWORD=your_password
MYAPP_RELEASE_KEY_PASSWORD=your_password
</code>```

Body:
I am trying to build an application. I can able to build the application properly. Also, I can able to generate the application with debug mode. But when I try to generate the signed apk with release mode, I got the below error.

Please help me what went wrong.

The error is as below

:app:validateSigningRelease UP-TO-DATE
:app:packageRelease FAILED

 FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:packageRelease'.
> C:\Users\Baba\Project\Application\Artharakshak\Code\Artharakshak\app\release\app-release.apk

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s
30 actionable tasks: 29 executed, 1 up-to-date

Below is my progourd file

# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in C:\Users\Baba\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# Add any project specific keep options here:

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
-ignorewarnings

Build Version is

dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

Body:
Maybe you put an incorrect password

you need to add this code inside gradle.properties

MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=my-key-alias
MYAPP_RELEASE_STORE_PASSWORD=your_password
MYAPP_RELEASE_KEY_PASSWORD=your_password


问:
Dispatcher has no subscribers for channel 'unknown.channel.name
I am trying to run the publisher and subscriber, using spring binding.

made sure the destination(exchange) is created locally on the rabbit-mq.

publisher (app.yml)

```<code>spring:
  cloud:
    stream:
      bindings:
        output:
          destination: HelloDestination
  rabbitmq:
    addresses: xxx.xxx.xx.xxx
</code>```

Subscriber(app.yml)

```<code>spring:
  cloud:
    stream:
      bindings:
        input:
          destination: HelloDestination
  rabbitmq:
    addresses: xxx.xxx.xx.xxx
server:
  port: 8081
</code>```

publisher (pom.yml)

```<code>    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>
</code>```

Subscriber (pom.yml)

```<code>        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>
</code>```

publisher (source java file)

```<code>@SpringBootApplication
@EnableBinding(Source.class)
public class Demo1Application {

    //@Autowired
    //private static MessageChannel output;

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);

        String sampleMessage = "Hello";
        Message<String> message =
                MessageBuilder.withPayload("Hello World").build();

        MessageChannel output = new DirectChannel();

        output.send(message);

    }

}
</code>```

//consumer (source file)

```<code>@SpringBootApplication
@EnableBinding(Sink.class)
public class Demo2Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo2Application.class, args);
    }

    @StreamListener(Sink.INPUT)
    public void listenerMethod(Message<String> message)
    {
        System.out.println("The Message is :"+message);
    }
}
</code>```

//----

After doing all, I see the exchange created and also the message on exchange. The consumer starts up just fine. but the producer chokes when trying to send the message with the error message

```<code>Exception in thread "main" org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'unknown.channel.name'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=Hello World, headers={id=ccf86001-5dba-6c64-bc76-e1f58782de42, timestamp=1558883876384}], failedMessage=GenericMessage [payload=Hello World, headers={id=ccf86001-5dba-6c64-bc76-e1f58782de42, timestamp=1558883876384}]
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:461)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:401)
    at com.example.demo.Demo1Application.main(Demo1Application.java:29)
Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=Hello World, headers={id=ccf86001-5dba-6c64-bc76-e1f58782de42, timestamp=1558883876384}]
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:138)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:105)
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscri
</code>```

I expected the message to be read.

答: You need to get channel 'output' from the application context returned by the run() method instead of creating your own DirectChannel.</p>

Body:
I am trying to run the publisher and subscriber, using spring binding.

made sure the destination(exchange) is created locally on the rabbit-mq.

publisher (app.yml)

spring:
  cloud:
    stream:
      bindings:
        output:
          destination: HelloDestination
  rabbitmq:
    addresses: xxx.xxx.xx.xxx

Subscriber(app.yml)

spring:
  cloud:
    stream:
      bindings:
        input:
          destination: HelloDestination
  rabbitmq:
    addresses: xxx.xxx.xx.xxx
server:
  port: 8081

publisher (pom.yml)

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>

Subscriber (pom.yml)

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>

publisher (source java file)

@SpringBootApplication
@EnableBinding(Source.class)
public class Demo1Application {

    //@Autowired
    //private static MessageChannel output;

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);

        String sampleMessage = "Hello";
        Message<String> message =
                MessageBuilder.withPayload("Hello World").build();

        MessageChannel output = new DirectChannel();

        output.send(message);

    }

}

//consumer (source file)

@SpringBootApplication
@EnableBinding(Sink.class)
public class Demo2Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo2Application.class, args);
    }

    @StreamListener(Sink.INPUT)
    public void listenerMethod(Message<String> message)
    {
        System.out.println("The Message is :"+message);
    }
}

//----

After doing all, I see the exchange created and also the message on exchange. The consumer starts up just fine. but the producer chokes when trying to send the message with the error message

Exception in thread "main" org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'unknown.channel.name'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=Hello World, headers={id=ccf86001-5dba-6c64-bc76-e1f58782de42, timestamp=1558883876384}], failedMessage=GenericMessage [payload=Hello World, headers={id=ccf86001-5dba-6c64-bc76-e1f58782de42, timestamp=1558883876384}]
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:461)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:401)
    at com.example.demo.Demo1Application.main(Demo1Application.java:29)
Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=Hello World, headers={id=ccf86001-5dba-6c64-bc76-e1f58782de42, timestamp=1558883876384}]
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:138)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:105)
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscri

I expected the message to be read.


问:
reinterpret_cast from rvalue to rvalue reference
Just a simple does it compile test.
gcc accepts the following while clang and msvc reject it: https://godbolt.org/z/DlUasL

```<code>float test()
{
    return reinterpret_cast<float&&>(0x7F800000);
}
</code>```

Which one is right according to the standard?

答: The conversion this reinterpret_cast expression seeks to perform is not among the list of conversions [expr.reinterpret.cast] that a reinterpret_cast can perform [expr.reinterpret.cast]/1. 0x7F800000 is a literal of integral type. The only conversion reinterpret_cast could perform that converts from a value of integral type to some other type is that of turning such a value into a pointer type [expr.reinterpret.cast]/5. float&& is a reference type, not a pointer type. The only conversion reinterpret_cast can perform that converts to a reference type is that of converting a glvalue expression [expr.reinterpret.cast]/11. 0x7F800000 is not a glvalue. Thus, this code is ill-formed. The fact that GCC would accept this is quite surprising to me and, I would say, definitely a bug that should be reported…

Body:
Just a simple does it compile test.
gcc accepts the following while clang and msvc reject it: https://godbolt.org/z/DlUasL

float test()
{
    return reinterpret_cast<float&&>(0x7F800000);
}

Which one is right according to the standard?


答:
As long as it is one line you can just echo the return value of exec.

Like so:

echo exec('ls');

But it only displays the first line.

Title: Executing unix shell commands using PHP

Body:
A text box will be used to capture the command. I've been told that I have to use the exec() function to execute UNIX shell commands.

Something like this, user types ls in the text box. The exec() function will execute the UNIX command and the command will be displayed on the web page.

What I want to know how will I get the output of the shell command and display in the web browser using PHP.

I don't know where to start since I'm very new to PHP.

I'm using Ubuntu.


问:
Using JavaScript to display Laravel's Variable
In my code I am using typeahead.js. I use Laravel 5 and I need to replace the var states with my {{ $jobs }} variable. I need to list all Job Titles as an array.

In my controller I have

```<code>$jobs = Job::all(['job_title']);
</code>```

I know the loop method in javascript but I dont know how to "link" my blade's variable in the javascript. Anyone knows how to?

I have tried, in my.js

```<code>var jobs = {{ $jobs }}
</code>```

But that wont work.

答:
I just solved this by placing a reference on the window Object in the  of my layout file, and then picking that reference up with a mixin that can be injected into any component.

TLDR SOLUTION

.env

```<code>GEODATA_URL="https://geo.some-domain.com"
</code>```

config/geodata.php

```<code><?php

return [
    'url' => env('GEODATA_URL')
];
</code>```

resources/views/layouts/root.blade.php

```<code><head>
    <script>
        window.geodataUrl = "{{ config('geodata.url') }}";
    </script>
</head>
</code>```

resources/js/components/mixins/geodataUrl.js

```<code>const geodataUrl = {
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
};

export default geodataUrl;
</code>```

usage

```<code><template>
    <div>
        <a :href="geodataUrl">YOLO</a>
    </div>
</template>

<script>
import geodataUrl from '../mixins/geodataUrl';

export default {
    name: 'v-foo',

    mixins: [geodataUrl],

    data() {
        return {};
    },

    computed: {},

    methods: {},
};
</script>
</code>```

END TLDR SOLUTION

If you want, you can use a global mixin instead by adding this to your app.js entrypoint:

```<code>Vue.mixin({
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
});
</code>```

I would not recommend using this pattern, however, for any sensitive data because it is sitting on the window Object.

I like this solution because it doesn't use any extra libraries, and the chain of code is very clear. It passes the grep test, in that you can search your code for "window.geodataUrl" and see everything you need to understand how and why the code is working.

That consideration is important if the code may live for a long time and another developer may come across it.

However, JavaScript::put([]) is in my opinion, a decent utility that can be worth having, but in the past I have disliked how it can be extremely difficult to debug if a problem happens, because you cannot see where in the codebase the data comes from.

Imagine you have some Vue code that is consuming window.chartData that came from JavaScript::put([ 'chartData' => $user->chartStuff ]). Depending on the number of references to chartData in your code base, it could take you a very long time to discover which PHP file was responsible for making window.chartData work, especially if you didn't write that code and the next person has no idea JavaScript::put() is being used.

In that case, I recommend putting a comment in the code like:

```<code>/* data comes from poop.php via JavaScript::put */
</code>```

Then the person can search the code for "JavaScript::put" and quickly find it. Keep in mind "the person" could be yourself in 6 months after you forget the implementation details.

It is always a good idea to use Vue component prop declarations like this:

```<code>props: {
    chartData: {
        type: Array,
        required: true,
    },
},
</code>```

My point is, if you use JavaScript::put(), then Vue cannot detect as easily if the component fails to receive the data. Vue must assume the data is there on the window Object at the moment in time it refers to it. Your best bet may be to instead create a GET endpoint and make a fetch call in your created/mounted lifecycle method.

I think it is important to have an explicit contract between Laravel and Vue when it comes to getting/setting data.

In the interest of helping you as much as possible by giving you options, here is an example of making a fetch call using ES6 syntax sugar:

routes/web.php

```<code>Route::get('/charts/{user}/coolchart', 'UserController@getChart')->name('user.chart');
</code>```

app/Http/Controllers/UserController.php

```<code>public function getChart(Request $request, User $user)
{
    // do stuff
    $data = $user->chart;

    return response()->json([
        'chartData' => $data,
    ]);
}
</code>```

Anywhere in Vue, especially a created lifecycle method:

```<code><?php

return [
    'url' => env('GEODATA_URL')
];
</code>```0

That example assumes your Vue component is a Mealy finite state machine, whereby the component can only be in one state at any given time, but it can freely switch between states.

I'd recommend using such states as computed props:

```<code><?php

return [
    'url' => env('GEODATA_URL')
];
</code>```1

With markup such as:

```<code><?php

return [
    'url' => env('GEODATA_URL')
];
</code>```2

Body:
In my code I am using typeahead.js. I use Laravel 5 and I need to replace the var states with my {{ $jobs }} variable. I need to list all Job Titles as an array.

In my controller I have

$jobs = Job::all(['job_title']);

I know the loop method in javascript but I dont know how to "link" my blade's variable in the javascript. Anyone knows how to?

I have tried, in my.js

var jobs = {{ $jobs }}

But that wont work.

Body:
I just solved this by placing a reference on the window Object in the <head> of my layout file, and then picking that reference up with a mixin that can be injected into any component.

TLDR SOLUTION

.env

GEODATA_URL="https://geo.some-domain.com"

config/geodata.php

<?php

return [
    'url' => env('GEODATA_URL')
];

resources/views/layouts/root.blade.php

<head>
    <script>
        window.geodataUrl = "{{ config('geodata.url') }}";
    </script>
</head>

resources/js/components/mixins/geodataUrl.js

const geodataUrl = {
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
};

export default geodataUrl;

usage

<template>
    <div>
        <a :href="geodataUrl">YOLO</a>
    </div>
</template>

<script>
import geodataUrl from '../mixins/geodataUrl';

export default {
    name: 'v-foo',

    mixins: [geodataUrl],

    data() {
        return {};
    },

    computed: {},

    methods: {},
};
</script>

END TLDR SOLUTION

If you want, you can use a global mixin instead by adding this to your app.js entrypoint:

Vue.mixin({
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
});

I would not recommend using this pattern, however, for any sensitive data because it is sitting on the window Object.

I like this solution because it doesn't use any extra libraries, and the chain of code is very clear. It passes the grep test, in that you can search your code for "window.geodataUrl" and see everything you need to understand how and why the code is working.

That consideration is important if the code may live for a long time and another developer may come across it.

However, JavaScript::put([]) is in my opinion, a decent utility that can be worth having, but in the past I have disliked how it can be extremely difficult to debug if a problem happens, because you cannot see where in the codebase the data comes from.

Imagine you have some Vue code that is consuming window.chartData that came from JavaScript::put([ 'chartData' => $user->chartStuff ]). Depending on the number of references to chartData in your code base, it could take you a very long time to discover which PHP file was responsible for making window.chartData work, especially if you didn't write that code and the next person has no idea JavaScript::put() is being used.

In that case, I recommend putting a comment in the code like:

/* data comes from poop.php via JavaScript::put */

Then the person can search the code for "JavaScript::put" and quickly find it. Keep in mind "the person" could be yourself in 6 months after you forget the implementation details.

It is always a good idea to use Vue component prop declarations like this:

props: {
    chartData: {
        type: Array,
        required: true,
    },
},

My point is, if you use JavaScript::put(), then Vue cannot detect as easily if the component fails to receive the data. Vue must assume the data is there on the window Object at the moment in time it refers to it. Your best bet may be to instead create a GET endpoint and make a fetch call in your created/mounted lifecycle method.

I think it is important to have an explicit contract between Laravel and Vue when it comes to getting/setting data.

In the interest of helping you as much as possible by giving you options, here is an example of making a fetch call using ES6 syntax sugar:

routes/web.php

Route::get('/charts/{user}/coolchart', 'UserController@getChart')->name('user.chart');

app/Http/Controllers/UserController.php

public function getChart(Request $request, User $user)
{
    // do stuff
    $data = $user->chart;

    return response()->json([
        'chartData' => $data,
    ]);
}

Anywhere in Vue, especially a created lifecycle method:

created() {
    this.handleGetChart();
},

methods: {
    async handleGetChart() {
        try {
            this.state = LOADING;
            const { data } = await axios.get(`/charts/${this.user.id}/coolchart`);

            if (typeof data !== 'object') {
                throw new Error(`Unexpected server response. Expected object, got: ${data}`);
            }

            this.chartData = data.chartData;
            this.state = DATA_LOADED;
        } catch (err) {
            this.state = DATA_FAILED;
            throw new Error(`Problem getting chart data: ${err}`);
        }
    },
},

That example assumes your Vue component is a Mealy finite state machine, whereby the component can only be in one state at any given time, but it can freely switch between states.

I'd recommend using such states as computed props:

computed: {
    isLoading() { return (this.state === LOADING); },
    isDataLoaded() { return (this.state === DATA_LOADED); },
    isDataFailed() { return (this.state === DATA_FAILED); },
},

With markup such as:

<div v-show="isLoading">Loading...</div>
<v-baller-chart v-if="isDataLoaded" :data="chartData"></v-baller-chart>
<button v-show="isDataFailed" type="button" @click="handleGetChart">TRY AGAIN</button>


问:
bash. How to pick random line from a variable containing numerous lines?
```<code>a=$(find ./ -name "*-*.txt")
</code>```

Now I need to get random line from $a, but shuf yelling at me

```<code>b=$(shuf -n1 $a)
</code>```

shuf: extra operand

What's my issue?
Thank you!

答:
You can use $RANDOM for this.

Notes:

${#array[@]} gives the size of the array

$((min + RANDOM % max)) gives you a random integer, whereas max is not included.

You can access an array item at index index_number like so ${array[index_number]}

# define array
a=()
while read line
do
    # read the file list line by line and add to the array
    a+=("$line")
done < <(find ./files -name '*-*.txt')

random_index=$((0 + RANDOM % ${#a[@]}))

echo ${a[$random_index]}
```

Body:
a=$(find ./ -name "*-*.txt")

Now I need to get random line from $a, but shuf yelling at me

b=$(shuf -n1 $a)

shuf: extra operand

What's my issue?
Thank you!


问:
How to create an additional input method service without changing default selected one?
I want to make a new input method with no actual keyboard.
It should stay active (after being enabled by user) always but not be the default keyboard. Because it will not have any visual keyboard and user will still be able to use the default keyboard as he/she selects.

I will trigger it on demand from a network command. Is this possible ?
It should be possible, because for example Android TV remote or Shield TV remote can do this.

But I couldn't find how to do it. When I create a normal input method, it only works if I select it as the default input method.

```<code>    <service android:name="SoftKeyboard"
        android:permission="android.permission.BIND_INPUT_METHOD">
        <intent-filter>
            <action android:name="android.view.InputMethod" />
        </intent-filter>
        <meta-data android:name="android.view.im" android:resource="@xml/method" />
    </service>
</code>```

This is the part from manifest file. Is it possible to make it work without selecting it as the default input method ?
As a second, additional input method …

答:
I could not find a solution which could live together with the original leanback keyboard.
So, I found an example Leanback keyboard code , injected my rest API in it.
Now I have the leanback keyboard modified to make what I want.</p>

Body:
I want to make a new input method with no actual keyboard.
It should stay active (after being enabled by user) always but not be the default keyboard. Because it will not have any visual keyboard and user will still be able to use the default keyboard as he/she selects.

I will trigger it on demand from a network command. Is this possible ?
It should be possible, because for example Android TV remote or Shield TV remote can do this.

But I couldn't find how to do it. When I create a normal input method, it only works if I select it as the default input method.

    <service android:name="SoftKeyboard"
        android:permission="android.permission.BIND_INPUT_METHOD">
        <intent-filter>
            <action android:name="android.view.InputMethod" />
        </intent-filter>
        <meta-data android:name="android.view.im" android:resource="@xml/method" />
    </service>

This is the part from manifest file. Is it possible to make it work without selecting it as the default input method ?
As a second, additional input method …


问:
JQuery validation on not existing checkbox
I have a JQuery DataTable that has checkboxes to select items in it. I added j
JQuery validation such that you can't submit the form without having at least selected one checkbox. Here is what my validation looks like:

```<code>jQuery.validator.addMethod("noApplicationSelected", function(value, element, params) { return $('.cbDisplay').length != 0; },'{0}');
$('[name="cbDisplay"]').rules('add', { noApplicationSelected: ['No checkbox selected'] });
</code>```

Everything works fine but my problem is that if I for example add a filter in my DataTable search such that no entries are present (empty DataTable), and I try to submit the form, it submits even though I haven't selected any checkboxes.
The reason for that I think is because the validation can't bind the rules on the checkboxes because they do not exist.

How can I fix this problem?

Edit 1:
Would adding some validation that checks for whether the DataTable is empty and a checkbox is selected fix my problem? But the issue I see with that is what do I bind this validation to? I guess I could bind it to the select all/deselect all checkbox but that doesn't make sense

Edit 2:

Demo of the probelm: https://jsfiddle.net/mu79L32w/14/

答:
As you suspected, you cannot bind validation to any input that does not yet exist.

I don't see enough code for a demo, so some generics below:

You do not need to write a custom method for making checkboxes required using this plugin.  If the checkboxes are in a group sharing the same name, then required will make at least one from the group mandatory.  See:  jsfiddle.net/q357zcwy/1/

The whole point of the .rules() method is for dynamically adding removing rules after the plugin has already been initialized on the form.  So if you dynamically add an input, then call .rules() on that input after it's been created.  See:  jsfiddle.net/q357zcwy/2/

If you only want to add required, then the easiest way to handle this is by putting the required="required" attribute on the input and my item #2 above is negated.  You do not have to worry about whether it exists or when to call .rules().  Simply create the input that includes this attribute and the plugin will automatically pick it up.  See:  jsfiddle.net/q357zcwy/3/

```<code><input type="checkbox" name="foo" required="required" ....
</code>```

Hidden or invisible fields are always ignored by default.  If your plugin is hiding any of the fields you are trying to validate, then you'll need to over-ride this behavior using the ignore option.  Set ignore to []("nothing") so that nothing is ignored and everything gets validated.

```<code>ignore: []
</code>```

EDIT:  More notes after seeing your jsFiddle:

The .validate() method gets called once to initialize the plugin on the form.  Typically on page load.  However, you have it within the function that is called by your click handler, which means validation is not initialized until the button is clicked and it's repeatedly called unnecessarily every time the button is clicked.

The DataTables plugin is indeed removing the rows entirely when you search/filter the table.  Although the validation plugin can handle invisible or hidden elements (see item #4 above), there is no way anyone can reasonably expect it to handle elements that no longer exist in the DOM.  I find it strange that DataTables can not merely hide these rows or render them invisible rather than removing entirely.

The solution by Jan is interesting as it iterates through the DataTables object looking for checked items.  However, there does not seem to be a way to properly integrate this function into the operation of the jQuery Validate plugin.  While the validate plugin is normally tied to each input and automatically shows/hides messages based on rules, this "workaround" is clumsily shoved into the submitHandler, which is normally only invoked after the form is valid.  It also cannot leverage the default validation messages, highlight, unhighlight, success, invalidHandler, or any of the other built-in functions.

There might be a way to leverage showErrors to show & hide the default messages programmatically based upon the iteration through the DataTables object.  However, this workaround would get overly complex.  You would also need to gather the name(s) of the checked object from the DataTable object in order to know which messages to toggle. Then if none of the rows exist when you want to validate, you'd have to find another way to trigger validation.  Since nearly all of the default functionality of the jQuery Validation plugin would be over-written anyway, it might actually make more sense to just write your own form validation from scratch.  No off-the-shelf validation plugin is going to be able to handle input elements that don't exist.

Body:
I have a JQuery DataTable that has checkboxes to select items in it. I added j
JQuery validation such that you can't submit the form without having at least selected one checkbox. Here is what my validation looks like:

jQuery.validator.addMethod("noApplicationSelected", function(value, element, params) { return $('.cbDisplay').length != 0; },'{0}');
$('[name="cbDisplay"]').rules('add', { noApplicationSelected: ['No checkbox selected'] });

Everything works fine but my problem is that if I for example add a filter in my DataTable search such that no entries are present (empty DataTable), and I try to submit the form, it submits even though I haven't selected any checkboxes.
The reason for that I think is because the validation can't bind the rules on the checkboxes because they do not exist.

How can I fix this problem?

Edit 1:
Would adding some validation that checks for whether the DataTable is empty and a checkbox is selected fix my problem? But the issue I see with that is what do I bind this validation to? I guess I could bind it to the select all/deselect all checkbox but that doesn't make sense

Edit 2:

Demo of the probelm: https://jsfiddle.net/mu79L32w/14/

Body:
As you suspected, you cannot bind validation to any input that does not yet exist.

I don't see enough code for a demo, so some generics below:

You do not need to write a custom method for making checkboxes required using this plugin.  If the checkboxes are in a group sharing the same name, then required will make at least one from the group mandatory.  See:  jsfiddle.net/q357zcwy/1/

The whole point of the .rules() method is for dynamically adding removing rules after the plugin has already been initialized on the form.  So if you dynamically add an input, then call .rules() on that input after it's been created.  See:  jsfiddle.net/q357zcwy/2/

If you only want to add required, then the easiest way to handle this is by putting the required="required" attribute on the input and my item #2 above is negated.  You do not have to worry about whether it exists or when to call .rules().  Simply create the input that includes this attribute and the plugin will automatically pick it up.  See:  jsfiddle.net/q357zcwy/3/

<input type="checkbox" name="foo" required="required" ....

Hidden or invisible fields are always ignored by default.  If your plugin is hiding any of the fields you are trying to validate, then you'll need to over-ride this behavior using the ignore option.  Set ignore to []("nothing") so that nothing is ignored and everything gets validated.

ignore: []

EDIT:  More notes after seeing your jsFiddle:

The .validate() method gets called once to initialize the plugin on the form.  Typically on page load.  However, you have it within the function that is called by your click handler, which means validation is not initialized until the button is clicked and it's repeatedly called unnecessarily every time the button is clicked.

The DataTables plugin is indeed removing the rows entirely when you search/filter the table.  Although the validation plugin can handle invisible or hidden elements (see item #4 above), there is no way anyone can reasonably expect it to handle elements that no longer exist in the DOM.  I find it strange that DataTables can not merely hide these rows or render them invisible rather than removing entirely.

The solution by Jan is interesting as it iterates through the DataTables object looking for checked items.  However, there does not seem to be a way to properly integrate this function into the operation of the jQuery Validate plugin.  While the validate plugin is normally tied to each input and automatically shows/hides messages based on rules, this "workaround" is clumsily shoved into the submitHandler, which is normally only invoked after the form is valid.  It also cannot leverage the default validation messages, highlight, unhighlight, success, invalidHandler, or any of the other built-in functions.

There might be a way to leverage showErrors to show & hide the default messages programmatically based upon the iteration through the DataTables object.  However, this workaround would get overly complex.  You would also need to gather the name(s) of the checked object from the DataTable object in order to know which messages to toggle. Then if none of the rows exist when you want to validate, you'd have to find another way to trigger validation.  Since nearly all of the default functionality of the jQuery Validation plugin would be over-written anyway, it might actually make more sense to just write your own form validation from scratch.  No off-the-shelf validation plugin is going to be able to handle input elements that don't exist.


问:
Unexpected usage of 'this' es-lint error, what rule to disable?
I am using Nuxt configured with el-lint and prettier but all of a sudden its throwing up an error when I use a 'this' within my template.

```<code> 6:15  error  Unexpected usage of 'this'  vue/this-in-template
 7:15  error  Unexpected usage of 'this'  vue/this-in-template
 11:15  error  Unexpected usage of 'this'  vue/this-in-template
 12:15  error  Unexpected usage of 'this'  vue/this-in-template
</code>```

I am trying to rewrite my .eslintrc.js file but I cannot find the rule that will allow me to bypass this es-lint error.

I know the code is working because I can see the result in the background pass the overlay.

```<code><template>
 <div class="slugWrapper">
    <h1>this is {{ $route.params.slug }}</h1>
     <div class="card">
      <video
       v-if="this.cards[0].type == 'Video'"
       :src="this.cards[0].imageurl"
       class="card__video"
      @click="playPause" />
     <img
       v-if="this.cards[0].type=='Image'|| 'image/jpeg'"
      :src="this.cards[0].imageurl"
      class="card__image"
      alt="Image">
   </div>
 </div>
</code>```

I need a rule or a way to ignore es lint in this area

答:
If you want to disable this rule, you need to ignore the vue/this-in-template rule in your .eslintrc file:

```<code>{
  "plugins": ["vue"],
  "rules": {
      "vue/this-in-template": "off"
  }
}
</code>```

You will probably need eslint-plugin-vue installed as a dependency to ignore this rule.

That being said, this rule is probably there for a reason, so you might want to consider refactoring your code so that you don't need to use this in your Vue templates.

Body:
I am using Nuxt configured with el-lint and prettier but all of a sudden its throwing up an error when I use a 'this' within my template.

 6:15  error  Unexpected usage of 'this'  vue/this-in-template
 7:15  error  Unexpected usage of 'this'  vue/this-in-template
 11:15  error  Unexpected usage of 'this'  vue/this-in-template
 12:15  error  Unexpected usage of 'this'  vue/this-in-template

I am trying to rewrite my .eslintrc.js file but I cannot find the rule that will allow me to bypass this es-lint error.

I know the code is working because I can see the result in the background pass the overlay.

<template>

this is {{ $route.params.slug }}

      <video
       v-if="this.cards[0].type == 'Video'"
       :src="this.cards[0].imageurl"
       class="card__video"
      @click="playPause" />

I need a rule or a way to ignore es lint in this area

Body:
If you want to disable this rule, you need to ignore the vue/this-in-template rule in your .eslintrc file:

{
  "plugins": ["vue"],
  "rules": {
      "vue/this-in-template": "off"
  }
}

You will probably need eslint-plugin-vue installed as a dependency to ignore this rule.

That being said, this rule is probably there for a reason, so you might want to consider refactoring your code so that you don't need to use this in your Vue templates.


问:
How can I increase the speed of string generating in my code?
By searching I could find the following solution to generate all the combination of a given string and calculate their hash values. Now I can  generate 10000000 strings and hash values in 21 seconds. However, I need a faster method. </p>

```<code>import itertools
import hashlib
import time

def pow():
    global cnt
    authdata = "eTSlASZYlLNgKJuYeIQvGVbiAcLEEOVgAQPzSrtCOIwQxQHyFHcfjgRQJBJDlojx";
    l = 'abcdefghij'
    result = itertools.product(*([l] * 7))
    for each in result:
        cnt = cnt + 1
        suffix = ''.join(each)
        authdataSuffix = authdata + suffix
        hashValue = hashlib.sha1(authdataSuffix.encode('utf-8')).hexdigest()
        if  hashValue.startswith("0"*8):
            print (hashValue)

cnt = 0
start = time.time()
pow()
end = time.time()
print(cnt)
print(end - start)
</code>```

答: Multi-threading or multi-processing would be the best way to speed up your program other than changing over to a faster language like C++

Body:
By searching I could find the following solution to generate all the combination of a given string and calculate their hash values. Now I can  generate 10000000 strings and hash values in 21 seconds. However, I need a faster method.

import itertools
import hashlib
import time

def pow():
    global cnt
    authdata = "eTSlASZYlLNgKJuYeIQvGVbiAcLEEOVgAQPzSrtCOIwQxQHyFHcfjgRQJBJDlojx";
    l = 'abcdefghij'
    result = itertools.product(*([l] * 7))
    for each in result:
        cnt = cnt + 1
        suffix = ''.join(each)
        authdataSuffix = authdata + suffix
        hashValue = hashlib.sha1(authdataSuffix.encode('utf-8')).hexdigest()
        if  hashValue.startswith("0"*8):
            print (hashValue)

cnt = 0
start = time.time()
pow()
end = time.time()
print(cnt)
print(end - start)


问:
Log4J - Is there any point in explicitly specifying the class name in the call to LogManager.getLogger()?
I'm working on some legacy code with a lot of code like

```<code>private final Logger logger = LogManager.getLogger(ThisClassName.class);
</code>```

I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to

```<code>LogManager.getLogger(getClass());
</code>```

As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass().  Thanks.

答: getClass() does not work from a static context. ThisClassName.class works for static and instance variables.</p>

OwnerDisplayName: nc

ContentLicense: CC BY-SA 2.5

Body:
I'm working on some legacy code with a lot of code like

private final Logger logger = LogManager.getLogger(ThisClassName.class);

I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to

LogManager.getLogger(getClass());

As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass().  Thanks.

OwnerDisplayName: neesh


问:
Display a headline before order review table in WooCommerce checkout
I am trying to add a simple headline just before the woocommerce checkout order review table. I do not want to add it with a function, but directly in the review-order.php template (I am overriding several things, so it makes sense to just override the template in my child theme). When I insert a -tag into the template, it gets displayed twice instead of just once. What do I need to change? The beginning of the review-order.php template is:

```<code><?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<table class="shop_table woocommerce-checkout-review-order-table">
</code>```

and I tried:

```<code><?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<h3>My headline</h3>
<table class="shop_table woocommerce-checkout-review-order-table">
</code>```

and the headline appears twice...

How to avoid this headline appear twice?

答:
To avoid this headline to appear twice use ! is_ajax() in an IF statement as follow:

```<code>if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! is_ajax() ) {
    echo '<h3>'.__("My headline", "woocommerce").'</h3>';
}

?>
<table class="shop_table woocommerce-checkout-review-order-table">
</code>```

This time it will be displayed once, as your heading will not get ajax refreshed.

Body:
I am trying to add a simple headline just before the woocommerce checkout order review table. I do not want to add it with a function, but directly in the review-order.php template (I am overriding several things, so it makes sense to just override the template in my child theme). When I insert a -tag into the template, it gets displayed twice instead of just once. What do I need to change? The beginning of the review-order.php template is:

<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>

and I tried:

<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>

My headline

and the headline appears twice...

How to avoid this headline appear twice?

Body:
To avoid this headline to appear twice use ! is_ajax() in an IF statement as follow:

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! is_ajax() ) {
    echo '<h3>'.__("My headline", "woocommerce").'</h3>';
}

?>
<table class="shop_table woocommerce-checkout-review-order-table">

This time it will be displayed once, as your heading will not get ajax refreshed.


问:
Check for multiple numbers in an array
I need to create a function that checks all numbers in an array and print them out.
My idea was something similar to this:

```<code>  var array = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99];
  var string = "";
  var len = array.length;
</code>```

After declaring the variables, i start to loop them:

```<code>  for (var i = 0; i < len; i ++) {
     for (var j = 0; j < len; j ++) {
        //console.log(array[i], array[j]);
     }
  }
</code>```

Console prints me value in this order:

```<code>3 3
3 6
3 67
. .
6 3
6 6
6 67
. .
</code>```

I thought to create a if statement checking if array[i] is equal to array[j] then pushing the content in a new string.

答:
You can also use Set with Array.filter and Array.indexOf:

let data = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99]

let r = new Set(data.filter((v, i, a) => a.indexOf(v) !== i))

console.log(Array.from(r))```

The idea is to filter the items to those who have multiple indexes found and then add them to the Set. Since Set stores unique items only it will take care of the duplicates and you get the final result.

We take advantage of the fact that Array.filter provides 3 arguments to the iteratee function - value (v), current index (i) and the actual array (a).

Title: Check for multiple numbers in an array

Body:
I need to create a function that checks all numbers in an array and print them out.
My idea was something similar to this:

  var array = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99];
  var string = "";
  var len = array.length;

After declaring the variables, i start to loop them:

  for (var i = 0; i < len; i ++) {
     for (var j = 0; j < len; j ++) {
        //console.log(array[i], array[j]);
     }
  }

Console prints me value in this order:

3 3
3 6
3 67
. .
6 3
6 6
6 67
. .

I thought to create a if statement checking if array[i] is equal to array[j] then pushing the content in a new string.

Body:
You can also use Set with Array.filter and Array.indexOf:

let data = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99]

let r = new Set(data.filter((v, i, a) => a.indexOf(v) !== i))

console.log(Array.from(r))

The idea is to filter the items to those who have multiple indexes found and then add them to the Set. Since Set stores unique items only it will take care of the duplicates and you get the final result.

We take advantage of the fact that Array.filter provides 3 arguments to the iteratee function - value (v), current index (i) and the actual array (a).


问:
Programming Error: "user_id of relation APP_MODEL does not exist"
I've set User as a foreign key on my Video model. I am using the default django auth User model, and have managed to create a user using the serializer and view that I set up for it. The problem is that whenever I try to create a video entry I hit the title error.

I've tried clearing the database, redoing the migrations, but there aren't any migrations for the app that handles the user serializer.

The Model

```<code>from django.contrib.auth.models import User
class Video(models.Model):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True
    )
    map_marker = models.ForeignKey(MapMarker, on_delete=models.CASCADE)
    created = models.DateTimeField()
    ip_addr = models.TextField()
    file_id = models.TextField()

    class Meta:
        ordering = ('created',)
</code>```

Full traceback:

```<code>Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/videos/

Django Version: 2.2.1
Python Version: 3.7.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'userbase',
 'trickspot',
 'profanity']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

The above exception (column "user_id" of relation "trickspot_video" does not exist
LINE 1: INSERT INTO "trickspot_video" ("user_id", "map_marker_id", "...
                                       ^
) was the direct cause of the following exception:

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\viewsets.py" in view
  116.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\views.py" in dispatch
  495.             response = self.handle_exception(exc)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\views.py" in handle_exception
  455.             self.raise_uncaught_exception(exc)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\views.py" in dispatch
  492.             response = handler(request, *args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\mixins.py" in create
  21.         self.perform_create(serializer)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\mixins.py" in perform_create
  26.         serializer.save()

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\serializers.py" in save
  214.             self.instance = self.create(validated_data)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\serializers.py" in create
  943.             instance = ModelClass._default_manager.create(**validated_data)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\query.py" in create
  422.         obj.save(force_insert=True, using=self.db)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\base.py" in save_base
  779.                 force_update, using, update_fields,

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\base.py" in _save_table
  870.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\base.py" in _do_insert
  908.                                using=using, raw=raw)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\query.py" in _insert
  1186.         return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  1335.                 cursor.execute(sql, params)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in execute
  99.             return super().execute(sql, params)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /videos/
Exception Value: column "user_id" of relation "trickspot_video" does not exist
LINE 1: INSERT INTO "trickspot_video" ("user_id", "map_marker_id", "...
                                       ^

</code>```

The entry should be saved with the key of the user I selected on the API view.

答:
Something got broken along the way and dropping the DB and starting again fixed the problem.

Thanks

Body:
I've set User as a foreign key on my Video model. I am using the default django auth User model, and have managed to create a user using the serializer and view that I set up for it. The problem is that whenever I try to create a video entry I hit the title error.

I've tried clearing the database, redoing the migrations, but there aren't any migrations for the app that handles the user serializer.

The Model

from django.contrib.auth.models import User
class Video(models.Model):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True
    )
    map_marker = models.ForeignKey(MapMarker, on_delete=models.CASCADE)
    created = models.DateTimeField()
    ip_addr = models.TextField()
    file_id = models.TextField()

    class Meta:
        ordering = ('created',)

Full traceback:

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/videos/

Django Version: 2.2.1
Python Version: 3.7.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'userbase',
 'trickspot',
 'profanity']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

The above exception (column "user_id" of relation "trickspot_video" does not exist
LINE 1: INSERT INTO "trickspot_video" ("user_id", "map_marker_id", "...
                                       ^
) was the direct cause of the following exception:

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\viewsets.py" in view
  116.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\views.py" in dispatch
  495.             response = self.handle_exception(exc)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\views.py" in handle_exception
  455.             self.raise_uncaught_exception(exc)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\views.py" in dispatch
  492.             response = handler(request, *args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\mixins.py" in create
  21.         self.perform_create(serializer)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\mixins.py" in perform_create
  26.         serializer.save()

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\serializers.py" in save
  214.             self.instance = self.create(validated_data)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\rest_framework\serializers.py" in create
  943.             instance = ModelClass._default_manager.create(**validated_data)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\query.py" in create
  422.         obj.save(force_insert=True, using=self.db)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\base.py" in save_base
  779.                 force_update, using, update_fields,

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\base.py" in _save_table
  870.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\base.py" in _do_insert
  908.                                using=using, raw=raw)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\query.py" in _insert
  1186.         return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  1335.                 cursor.execute(sql, params)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in execute
  99.             return super().execute(sql, params)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "C:\Users\Zeph\.virtualenvs\SK8M8_API-LRdA6z3-\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /videos/
Exception Value: column "user_id" of relation "trickspot_video" does not exist
LINE 1: INSERT INTO "trickspot_video" ("user_id", "map_marker_id", "...
                                       ^

The entry should be saved with the key of the user I selected on the API view.


问:
How to convert to binary using XS+3?
I'm stuck with an issue on my webpage, I'm trying to convert to binary using the 2^n-1 system and can't work up a solution. I've been fine working with 8, 16 and 32 bits but when I try to convert a long (64 bit) then it doesn't work. Any help will be great!

I'm using Jquery on a HTML webpage. I don't know if it's allowed to post the link, but if there's not a problem then I'll link it in a comment. My Jquery code is this:

```<code>$(document).ready(function(){
 $("#boton").click(function(){
  var var1 = bigInt($("#numero").val());
  var var3 = bigInt($("input[name='bit']:checked").val());
  var var3 = var3 - 1;
  var var4 = bigInt(2).pow(var3);
  var var5 = var1 + var4;
  if (var5!=0){
     var var2 = bigInt(var5).toString(2);
     $("#final").text("El numero es " + var2.match(/.{4}/g));
     $("#final").show();
  } else {
        $("#final").text("El numero es 0");
        $("#final").show();
       };
   });
});
</code>```

If I try to convert for example the number 37 on 8 bits, then it would be 37+(2^8-1=128)=165 and would have to convert 165 to binary, showing 10100101. When I try to convert 37 on 64 bits, then it just shows 1 followed by a great number of zeros

答:
You will need to use the methods that your bigint library exposes:</p>

```<code>var var1 = bigInt($("#numero").val());
var var3 = bigInt($("input[name='bit']:checked").val());
var3 = var3.subtract(1);
//         ^^^^^^^^^
var var4 = bigInt(2).pow(var3);
var var5 = var1.add(var4);
//             ^^^^
if (var5.notEquals(0)) {
//      ^^^^^^^^^^
    var var2 = var5.toString(2);
    $("#final").text("El numero es " + var2.match(/.{4}/g));
} else {
    $("#final").text("El numero es 0");
}
$("#final").show();
</code>```

Title: How to convert to binary using XS+3?

Body:
I'm stuck with an issue on my webpage, I'm trying to convert to binary using the 2^n-1 system and can't work up a solution. I've been fine working with 8, 16 and 32 bits but when I try to convert a long (64 bit) then it doesn't work. Any help will be great!

I'm using Jquery on a HTML webpage. I don't know if it's allowed to post the link, but if there's not a problem then I'll link it in a comment. My Jquery code is this:

$(document).ready(function(){
 $("#boton").click(function(){
  var var1 = bigInt($("#numero").val());
  var var3 = bigInt($("input[name='bit']:checked").val());
  var var3 = var3 - 1;
  var var4 = bigInt(2).pow(var3);
  var var5 = var1 + var4;
  if (var5!=0){
     var var2 = bigInt(var5).toString(2);
     $("#final").text("El numero es " + var2.match(/.{4}/g));
     $("#final").show();
  } else {
        $("#final").text("El numero es 0");
        $("#final").show();
       };
   });
});

If I try to convert for example the number 37 on 8 bits, then it would be 37+(2^8-1=128)=165 and would have to convert 165 to binary, showing 10100101. When I try to convert 37 on 64 bits, then it just shows 1 followed by a great number of zeros

Body:
You will need to use the methods that your bigint library exposes:

var var1 = bigInt($("#numero").val());
var var3 = bigInt($("input[name='bit']:checked").val());
var3 = var3.subtract(1);
//         ^^^^^^^^^
var var4 = bigInt(2).pow(var3);
var var5 = var1.add(var4);
//             ^^^^
if (var5.notEquals(0)) {
//      ^^^^^^^^^^
    var var2 = var5.toString(2);
    $("#final").text("El numero es " + var2.match(/.{4}/g));
} else {
    $("#final").text("El numero es 0");
}
$("#final").show();


问:
Google Finance get year to date spreadsheets
I'm using Google Sheets to get stock data from Google Finance, how can I get Year to day percentage change?</p>

答:
For Google and an entire year please try:

```<code>=100*(googlefinance("GOOG")/index(googlefinance("GOOG","price",today()-365),2,2)-1)
</code>```

Or, for this year-to-date:

```<code>=100*(googlefinance("GOOG","price")/index(googlefinance("GOOG","price",date(2018,12,31)),2,2)-1)
</code>```

Body:
For Google and an entire year please try:

=100*(googlefinance("GOOG")/index(googlefinance("GOOG","price",today()-365),2,2)-1)

Or, for this year-to-date:

=100*(googlefinance("GOOG","price")/index(googlefinance("GOOG","price",date(2018,12,31)),2,2)-1)


问:
IntelliJ cannot find any declarations
I completely uninstalled IntelliJ and have now reinstalled and imported my project. I imported using gradle and can see all of the files in my project present. However, when I open a file I can't find any declaration to go to by doing cmd + click. I have the Java 7 SDK setup, and I can't even go to the declaration of classes in my own project. Going to a Java core class like String or List doesn't work either. How can I enable the IDE to be able to find my classes?

I'm on OSX Yosemite, IntelliJ 2016.1.2 build 145.972.

答:
Most of the times there has been a problem with building the cache of the IDE, or something related.

Most probably, File -> Invalidate Caches / Restart, will resolve this problem, just let the IDE finalize it's caching.

Title: IntelliJ cannot find any declarations


问:
JavaScript algorithm for removing expired dates?
having issue processing future and current dates as "new dates"...and old expired dates as "old dates" with JS

```<code> <!DOCTYPE html>
<html>
<head>
<script>
</code>```

function for codes
    function myFunction() {

```<code>weekday array to store days of the week
var weekday=new Array(7);
var month=new Array(12);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

month array to store months
month[0]="Jan";
month[1]="Feb";
month[2]="Mar";
month[3]="Apr";
month[4]="May";
month[5]="Jun";
month[6]="Jul";
month[7]="Aug";
month[8]="Sep";
month[9]="Oct";
month[10]="Nov";
month[11]="Dec";

current date with year, month and day
var currentDate = new Date();

random date string testing values
var x = new Date("Friday May 24 2019 23:58:09 GMT-0400 (Eastern Daylight Time)");
var getDayInt = " " ;
getDayInt += new Array("Friday May 24 2019 23:58:09 GMT-0400 (Eastern Daylight Time)");
var splitString = " ";
splitString = getDayInt.split(" ");
var day = weekday[x.getDay()];
var getMonth= month[x.getMonth()];
var year = splitString[4];

//values in console log
console.log(year);
console.log(x.getMonth());
console.log(day);
console.log(weekday[currentDate.getDay()] + ' currentDate.getDay()');

//current or future year
if (currentDate.getFullYear() <= year) {
    document.getElementById("t").innerHTML='<div>year</div>';

//current or future month
if (currentDate.getMonth() <= x.getMonth()) {
    document.getElementById("t").innerHTML='<div>month</div>';
</code>```

where the issue starts
   want current or future day

```<code>  if (weekday[currentDate.getDay()] >= day || weekday[currentDate.getDay()] <=day) {

document.getElementById("t").innerHTML='<div>new date</div>';

  }
}
}else{

     document.getElementById("t").innerHTML='<div>old date</div>';
}

}
</script>
</head>

<body onload="myFunction()">
<h1 id= "t">Hello World!</h1>
</body>

</html>
</code>```

i expect "old date" with input "Friday May 24 2019 23:58:09 GMT-0400
 (Eastern Daylight Time)" and not new date..

答:
```<code><!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {

//set date

month[0]="Jan";
month[1]="Feb";
month[2]="Mar";
month[3]="Apr";
month[4]="May";
month[5]="Jun";
month[6]="Jul";
month[7]="Aug";
month[8]="Sep";
month[9]="Oct";
month[10]="Nov";
month[11]="Dec";

// current date
var currentDate = new Date();

//random date testing values
var x = new Date("Friday Jan 20 2020 23:58:09 GMT-0400 (Eastern Daylight Time)");
var getDayInt = " " ;
getDayInt += new Array("Friday Jan 20 2020 23:58:09 GMT-0400 (Eastern Daylight Time)");
var res = " ";
res = getDayInt.split(" ");
var day = res[3];
var getMonth= month[x.getMonth()];
var year = res[4];

//filter year
if (currentDate.getFullYear() <= year) {

//filter months with years
if ((currentDate.getMonth() <= x.getMonth() && currentDate.getFullYear() < year)
    ||(currentDate.getMonth() >= x.getMonth() && currentDate.getFullYear() < year)
    || (currentDate.getMonth()<= x.getMonth())) {

// filter days, months and years
  if ((currentDate.getDate() >= day && year > currentDate.getFullYear())
   ||(currentDate.getDate() >= day && year > currentDate.getFullYear() &&
    currentDate.getMonth() <= x.getMonth()) || (currentDate.getDate() <=day)
   || (year == currentDate.getFullYear() && x.getMonth() > currentDate.getMonth())) {

document.getElementById("t").innerHTML='<div>new date</div>';

  }
}

}else{

     document.getElementById("t").innerHTML='<div>old date</div>';
}

}
</script>
</head>

<body onload="myFunction()">
<h1 id= "t">Hello World!</h1>
</body>

</html>
</code>```

Body:
having issue processing future and current dates as "new dates"...and old expired dates as "old dates" with JS

 <!DOCTYPE html>

Hello World!

i expect "old date" with input "Friday May 24 2019 23:58:09 GMT-0400
 (Eastern Daylight Time)" and not new date..


问:
Recursive List - Computing the sum of all elements up to and including the last occurrence
It´s not only a Java question. It is a question of algorithms in general:

The task is to compute the sum of all the elements up to and including the last occurred value "val", which is a parameter in the method.

Method looks like:

int sumLastOcc (Node n, int val)

// n is the node of the list. Starts with the head when the method will be called.

// val is the value up to which the total sum will be formed

Example: 3 5 2 7 5 1 4

Result: 22 for val = 5 (call: sumLastOcc (head, 5))

Result: 0 for val = 9 (call: sumLastOcc (head, 9))

```<code>public class RecursiveList {
    static Node head;
    static boolean found = false;

    public static void main(String[] args) {
        RecursiveList list = new RecursiveList();

        list.addNumber(3);
        list.addNumber(5);
        list.addNumber(2);
        list.addNumber(7);
        list.addNumber(5);
        list.addNumber(1);
        list.addNumber(4);
        list.printList();

        int result = list.sumLastOcc(head, 5);

        System.out.println();
        System.out.println(result);
    }

    private int sumLastOcc(Node n, int val) {
        // CODE TO IMPLEMENT
        }

        return sum;
    }

    private void addNumber(int number) {
        Node curr = head;
        Node prev = null;

        if (head == null) {
            head = new Node(number, null);
        } else {
            while (curr != null) {
                prev = curr;
                curr = curr.next;
            }

            Node newNode = new Node(number, null);
            prev.next = newNode;
        }
    }

    // inner node class
    private class Node {
        Node next;
        int value;

        Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    }

    private void printList() {
        Node curr = head;
        Node prev = null;

        while (curr != null) {
            System.out.print(curr.value + " ");

            prev = curr;
            curr = curr.next;
        }
    }
}
</code>```

It´s okay to use/add any global static variables like:

static boolean found = false;

as already defined.
We should use no loops (for, while, ...) and we should also use no additional method. Just the method "private int sumLastOcc(Node n, int val)" should do that charm.

答:
Thank you guys for the fast and nice respond. I wrote the method similar according to the explanation of Alexander Pavlov. Think this is a very good way:

```<code>private int sumLastOcc(Node n, int val) {
    int sumUpTo = 0;
    int sumAfter = 0;

    if (n.next != null) {
        sumAfter = sumAfter + n.value + sumLastOcc(n.next, val);

        if (n.value == val) {
            found = true;
        }

        if (found) {
            sumUpTo = sumUpTo + sumAfter;
        }
    } else {
        sumAfter = sumAfter + n.value;

        if (n.value == val) {
            sumUpTo = sumUpTo + sumAfter;
            found = true;
        }
    }

    return sumUpTo;
}
</code>```

So this is solved :-)

Body:
It´s not only a Java question. It is a question of algorithms in general:

The task is to compute the sum of all the elements up to and including the last occurred value "val", which is a parameter in the method.

Method looks like:

int sumLastOcc (Node n, int val)

// n is the node of the list. Starts with the head when the method will be called.

// val is the value up to which the total sum will be formed

Example: 3 5 2 7 5 1 4

Result: 22 for val = 5 (call: sumLastOcc (head, 5))

Result: 0 for val = 9 (call: sumLastOcc (head, 9))

public class RecursiveList {
    static Node head;
    static boolean found = false;

    public static void main(String[] args) {
        RecursiveList list = new RecursiveList();

        list.addNumber(3);
        list.addNumber(5);
        list.addNumber(2);
        list.addNumber(7);
        list.addNumber(5);
        list.addNumber(1);
        list.addNumber(4);
        list.printList();

        int result = list.sumLastOcc(head, 5);

        System.out.println();
        System.out.println(result);
    }

    private int sumLastOcc(Node n, int val) {
        // CODE TO IMPLEMENT
        }

        return sum;
    }

    private void addNumber(int number) {
        Node curr = head;
        Node prev = null;

        if (head == null) {
            head = new Node(number, null);
        } else {
            while (curr != null) {
                prev = curr;
                curr = curr.next;
            }

            Node newNode = new Node(number, null);
            prev.next = newNode;
        }
    }

    // inner node class
    private class Node {
        Node next;
        int value;

        Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    }

    private void printList() {
        Node curr = head;
        Node prev = null;

        while (curr != null) {
            System.out.print(curr.value + " ");

            prev = curr;
            curr = curr.next;
        }
    }
}

It´s okay to use/add any global static variables like:

static boolean found = false;

as already defined.
We should use no loops (for, while, ...) and we should also use no additional method. Just the method "private int sumLastOcc(Node n, int val)" should do that charm.

Body:
Thank you guys for the fast and nice respond. I wrote the method similar according to the explanation of Alexander Pavlov. Think this is a very good way:

private int sumLastOcc(Node n, int val) {
    int sumUpTo = 0;
    int sumAfter = 0;

    if (n.next != null) {
        sumAfter = sumAfter + n.value + sumLastOcc(n.next, val);

        if (n.value == val) {
            found = true;
        }

        if (found) {
            sumUpTo = sumUpTo + sumAfter;
        }
    } else {
        sumAfter = sumAfter + n.value;

        if (n.value == val) {
            sumUpTo = sumUpTo + sumAfter;
            found = true;
        }
    }

    return sumUpTo;
}

So this is solved :-)


问:
Change font width in matplotlib
I trying to use plt.text to plot letters that are variously stretched or squeezed in the horizontal direction. I thought the 'stretch' option would do that, but it doesn't change anything:

```<code>import matplotlib.pyplot as plt

plt.text(1,1, 'A', stretch=100)

plt.show()
</code>```

It doesn't seem to matter what value I use for stretch, the result always looks the same.

答:
I tried specifying the stretch using mpl.rcParams['font.stretch'] = 1000 but as per the official docs, it seems font.stretch is not yet implemented (emphasis mine):

The font.stretch property has 11 values: ultra-condensed, extra-condensed, condensed, semi-condensed, normal, semi-expanded, expanded, extra-expanded, ultra-expanded, wider, and narrower.  This property is not currently implemented.

Title: Change font width in matplotlib

Body:
I trying to use plt.text to plot letters that are variously stretched or squeezed in the horizontal direction. I thought the 'stretch' option would do that, but it doesn't change anything:

import matplotlib.pyplot as plt

plt.text(1,1, 'A', stretch=100)

plt.show()

It doesn't seem to matter what value I use for stretch, the result always looks the same.