问:
Can't link file resource after updating to gradle 3.0.1
I'm getting the following error after trying to run my project.

```<code>Error:failed linking file resources.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
</code>```

After following what was suggested here (disabling aapt2) I got bunch of new errors.

```<code>Error:com.android.ide.common.process.ProcessException: Error while
executing process DIR/build-tools/27.0.2/aapt with arguments {package -
f --no-crunch -I DIR/platforms/android-27/android.jar -M
DIR/app/build/intermediates/manifests/full/debug/AndroidManifest.xml -S
DIR/app/build/intermediates/res/merged/debug -m -J
DIR/app/build/generated/source/r/debug -F
DIR/app/build/intermediates/res/debug/resources-debug.ap_ --custom-
package com.appname -0 apk --output-text-symbols
DIR/app/build/intermediates/symbols/debug --no-version-vectors}
</code>```

and

```<code>Error:org.gradle.process.internal.ExecException: Process 'command
'DIR/build-tools/27.0.2/aapt''
finished with non-zero exit value 1
</code>```

Gradle file:

```<code>buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.0'
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
buildscript {
    repositories {
        repositories {
            maven { url 'https://maven.google.com' }
        }
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.25.1'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.2'
    defaultConfig {
        applicationId "com.trynagrub.trynagrub"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/signalr-client-sdk.jar')
    compile files('libs/signalr-client-sdk-android.jar')
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
//    compile 'org.zakariya.stickyheaders:stickyheaders:0.7.6'
//    compile 'com.github.stfalcon:chatkit:0.2.2'
//    compile 'com.hbb20:ccp:2.0.3'
    compile 'net.danlew:android.joda:2.9.9'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.xw.repo:bubbleseekbar:3.6'
    compile 'com.github.pavlospt:circleview:1.3'
    compile 'com.facebook.android:facebook-android-sdk:4.29.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:support-compat:27.0.1'
    compile 'de.hdodenhof:circleimageview:2.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-gcm:11.6.2'
    compile 'com.snatik:storage:2.1.0'
    compile 'com.github.tamir7.contacts:contacts:1.1.7'
    compile 'com.google.android.gms:play-services-maps:11.6.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

I don't know why it keeps happening. But all the R references in the app cannot be resolved because of this. Before updating I had a problem with mixing versions of android support libraries, so I disable the libraries that used different version of support library, can that be the cause of this?

Please help.

答:
Try changing all compile terms located in dependencies part to implementation :

```<code>dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
implementation files('libs/signalr-client-sdk.jar')
implementation files('libs/signalr-client-sdk-android.jar')
implementation('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
    transitive = true;
}
implementation('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
    transitive = true;
}
implementation 'net.danlew:android.joda:2.9.9'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.xw.repo:bubbleseekbar:3.6'
implementation 'com.github.pavlospt:circleview:1.3'
implementation 'com.facebook.android:facebook-android-sdk:4.29.0'
implementation 'com.amitshekhar.android:android-networking:1.0.0'
implementation 'com.android.support:support-compat:27.0.1'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.google.android.gms:play-services-gcm:11.6.2'
implementation 'com.snatik:storage:2.1.0'
implementation 'com.github.tamir7.contacts:contacts:1.1.7'
implementation 'com.google.android.gms:play-services-maps:11.6.2'
testCompile 'junit:junit:4.12'
}
</code>```

Body:
I'm getting the following error after trying to run my project.

Error:failed linking file resources.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

After following what was suggested here (disabling aapt2) I got bunch of new errors.

Error:com.android.ide.common.process.ProcessException: Error while
executing process DIR/build-tools/27.0.2/aapt with arguments {package -
f --no-crunch -I DIR/platforms/android-27/android.jar -M
DIR/app/build/intermediates/manifests/full/debug/AndroidManifest.xml -S
DIR/app/build/intermediates/res/merged/debug -m -J
DIR/app/build/generated/source/r/debug -F
DIR/app/build/intermediates/res/debug/resources-debug.ap_ --custom-
package com.appname -0 apk --output-text-symbols
DIR/app/build/intermediates/symbols/debug --no-version-vectors}

and

Error:org.gradle.process.internal.ExecException: Process 'command
'DIR/build-tools/27.0.2/aapt''
finished with non-zero exit value 1

Gradle file:

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.0'
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
buildscript {
    repositories {
        repositories {
            maven { url 'https://maven.google.com' }
        }
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.25.1'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.2'
    defaultConfig {
        applicationId "com.trynagrub.trynagrub"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/signalr-client-sdk.jar')
    compile files('libs/signalr-client-sdk-android.jar')
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
//    compile 'org.zakariya.stickyheaders:stickyheaders:0.7.6'
//    compile 'com.github.stfalcon:chatkit:0.2.2'
//    compile 'com.hbb20:ccp:2.0.3'
    compile 'net.danlew:android.joda:2.9.9'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.xw.repo:bubbleseekbar:3.6'
    compile 'com.github.pavlospt:circleview:1.3'
    compile 'com.facebook.android:facebook-android-sdk:4.29.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:support-compat:27.0.1'
    compile 'de.hdodenhof:circleimageview:2.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-gcm:11.6.2'
    compile 'com.snatik:storage:2.1.0'
    compile 'com.github.tamir7.contacts:contacts:1.1.7'
    compile 'com.google.android.gms:play-services-maps:11.6.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

I don't know why it keeps happening. But all the R references in the app cannot be resolved because of this. Before updating I had a problem with mixing versions of android support libraries, so I disable the libraries that used different version of support library, can that be the cause of this?

Please help.

Body:
Try changing all compile terms located in dependencies part to implementation :

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
implementation files('libs/signalr-client-sdk.jar')
implementation files('libs/signalr-client-sdk-android.jar')
implementation('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
    transitive = true;
}
implementation('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
    transitive = true;
}
implementation 'net.danlew:android.joda:2.9.9'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.xw.repo:bubbleseekbar:3.6'
implementation 'com.github.pavlospt:circleview:1.3'
implementation 'com.facebook.android:facebook-android-sdk:4.29.0'
implementation 'com.amitshekhar.android:android-networking:1.0.0'
implementation 'com.android.support:support-compat:27.0.1'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.google.android.gms:play-services-gcm:11.6.2'
implementation 'com.snatik:storage:2.1.0'
implementation 'com.github.tamir7.contacts:contacts:1.1.7'
implementation 'com.google.android.gms:play-services-maps:11.6.2'
testCompile 'junit:junit:4.12'
}


来源: stackexchange

问:
Removing the clicked item from menu list using angular 4

Hi,

I have a notification menu list in which i am binding the data which is coming from the REST API. My notification menu will look like this. See below image for clarity.

In the notifications, when ever i click on any of the list item then it should be removed from the list and on the above also there is notification bubble in red color with some count that how many notifications i have received. What i want to achieve is when i click on the notification menu list then the clicked list item should be removed from it also the count should decrease in red color bubble above the bell icon. For example, when i click on notification list item of first item the it should be removed as well as the count should be decreased.

notification.component.ts

```<code>try {

      this.currentUser = JSON.parse(this.cookieService.get('user-is-logged-in-details'));
      console.log(this.currentUser.uid);
      this._userService.getBellNotification(this.currentUser.uid)
      .subscribe(data => this.cookieData = data);
      } catch (e) {
          console.log("Catch Block Error from Notification.Component.ts");
          //console.log("currentUser", this.currentUser.uid);
      }
</code>```

apiservice.service.ts

```<code>getBellNotification(uid: any){
        const urlBell = this.config.apiUrl+'api/supplier-notification/'+uid+'?_format=json';
        let headers = new Headers();
        headers.append("Content-Type", 'application/json');
        headers.append('Authorization', 'Basic ' + btoa('apiuser:@piUser@2017Supplier'));
        let requestoptions = new RequestOptions({headers: headers});
        return this.http.get(urlBell, requestoptions)
        .map(response => response.json())
        .catch(this.handleErrorObservable);
    }
</code>```

notification.component.html

```<code><span
    class="notification"
    dropdown (onShown)="onShown()"
    (onHidden)="onHidden()"
    (isOpenChange)="isOpenChange()">
    <a
        href dropdownToggle
        (click)="false">
        <i
        class="glyphicon glyphicon-bell"
        [ngClass]="cookieData?.search_unread_count != 0 ? 'notification-icon': ' '">
    <span *ngIf="cookieData?.search_unread_count != 0">{{cookieData.search_unread_count}}</span>
    </i>
    </a>
      <ul
        *dropdownMenu
        class="dropdown-menu notify-drop">
          <div
            class="notify-drop-title">Notifications</div>
            <div
                class="drop-content"
                *ngFor="let item of cookieData.search_result">
                <li
                    data-id="{{item.id}}"
                    class="notification-items unread">
                    <i
                        class="fa fa-dot-circle-o"
                        aria-hidden="true">
                    </i>
                    <a
                        data-link="admin-invoice-list"
                        href="javascript:;">{{item.message}}
                    </a>
                </li>
            </div>
      </ul>
</span>
</code>```

Can anyone please suggest me how it can be achieved?

答:
have youtried to attach a (click) function on each
 so to remove (or do the action you want) on the click of
 item?...something like:

```<code> <div
                class="drop-content"
                *ngFor="let item of cookieData.search_result">
                <li (click)="remove(item)"
                    data-id="{{item.id}}"
                    class="notification-items unread">
                    <i
                        class="fa fa-dot-circle-o"
                        aria-hidden="true">
                    </i>
                    <a
                        data-link="admin-invoice-list"
                        href="javascript:;">{{item.message}}
                    </a>
                </li>
</code>```

then in your ts file:

```<code>   remove(item:any){
    //ALSO CALL A BACKEND API... TO REMOVE THEM .. THIS IS ONLY FRONT END
    this.cookieData = this.cookieData.filter(xx=>xx.id != item.id);
      this.cookieData.search_unread_count=this.cookieData.search_result.length;
    }
</code>```

Hope it helps you!!

ContentLicense: CC BY-SA 3.0

Body:
Hi,

I have a notification menu list in which i am binding the data which is coming from the REST API. My notification menu will look like this. See below image for clarity.

In the notifications, when ever i click on any of the list item then it should be removed from the list and on the above also there is notification bubble in red color with some count that how many notifications i have received. What i want to achieve is when i click on the notification menu list then the clicked list item should be removed from it also the count should decrease in red color bubble above the bell icon. For example, when i click on notification list item of first item the it should be removed as well as the count should be decreased.

notification.component.ts

try {

      this.currentUser = JSON.parse(this.cookieService.get('user-is-logged-in-details'));
      console.log(this.currentUser.uid);
      this._userService.getBellNotification(this.currentUser.uid)
      .subscribe(data => this.cookieData = data);
      } catch (e) {
          console.log("Catch Block Error from Notification.Component.ts");
          //console.log("currentUser", this.currentUser.uid);
      }

apiservice.service.ts

getBellNotification(uid: any){
        const urlBell = this.config.apiUrl+'api/supplier-notification/'+uid+'?_format=json';
        let headers = new Headers();
        headers.append("Content-Type", 'application/json');
        headers.append('Authorization', 'Basic ' + btoa('apiuser:@piUser@2017Supplier'));
        let requestoptions = new RequestOptions({headers: headers});
        return this.http.get(urlBell, requestoptions)
        .map(response => response.json())
        .catch(this.handleErrorObservable);
    }

notification.component.html

    {{cookieData.search_unread_count}}

Notifications

                    {{item.message}}

Can anyone please suggest me how it can be achieved?

Body:
have youtried to attach a (click) function on each
 so to remove (or do the action you want) on the click of
 item?...something like:

 <div
                class="drop-content"
                *ngFor="let item of cookieData.search_result">
                <li (click)="remove(item)"
                    data-id="{{item.id}}"
                    class="notification-items unread">
                    <i
                        class="fa fa-dot-circle-o"
                        aria-hidden="true">
                    </i>
                    <a
                        data-link="admin-invoice-list"
                        href="javascript:;">{{item.message}}
                    </a>
                </li>

then in your ts file:

   remove(item:any){
    //ALSO CALL A BACKEND API... TO REMOVE THEM .. THIS IS ONLY FRONT END
    this.cookieData = this.cookieData.filter(xx=>xx.id != item.id);
      this.cookieData.search_unread_count=this.cookieData.search_result.length;
    }

Hope it helps you!!


问:
NativeScript's Intellisense (Android) - is not showing some methods?
Using WebStorm, I have a Progress element :

```<code><Progress  id="prgressid" ></Progress>
</code>```

I want to increase its height. It can be done via scaleY=".." attribute or via native code :

```<code>mProgressBar.setScaleY(3);
</code>```

I've decided to do it via code but the intellisene shows me :

Another try without .android.

It doesn't have the setScaleY method.

(if I try to use setScale method - it fails at runtime - But if I try setScaleY - it does work.)

Question:

Why isn't the method shown ? And what should I see in order to see all accessible methods ?

tns info :

Sdk manager

答:
EDIT: the initial snippet had an error - in fact, you can access the public methods setScaleY and setScaleX but you will need the typings (via tns-platform-declarations) and also we would need to cast the native component to android.widget.ProgressBar (otherwise it would be of type any)

For example:

```<code><Progress value="50" loaded="onPbLoaded" />
</code>```

TypeScript

```<code>export function onPbLoaded(args) {
    let pb = <Progress>args.object;

    if(isAndroid) {
        let nativeProgress = <android.widget.ProgressBar>pb.android; // android.widget.ProgressBar{d26eea9 V.ED..... ......ID 0,0-0,0}
        console.log("nativeProgress Android: " + nativeProgress);

        nativeProgress.setScaleX(3);
        nativeProgress.setScaleY(5);
    }
}
</code>```

Body:
Using WebStorm, I have a Progress element :

<Progress  id="prgressid" ></Progress>

I want to increase its height. It can be done via scaleY=".." attribute or via native code :

mProgressBar.setScaleY(3);

I've decided to do it via code but the intellisene shows me :

Another try without .android.

It doesn't have the setScaleY method.

(if I try to use setScale method - it fails at runtime - But if I try setScaleY - it does work.)

Question:

Why isn't the method shown ? And what should I see in order to see all accessible methods ?

tns info :

Sdk manager

Body:
EDIT: the initial snippet had an error - in fact, you can access the public methods setScaleY and setScaleX but you will need the typings (via tns-platform-declarations) and also we would need to cast the native component to android.widget.ProgressBar (otherwise it would be of type any)

For example:

<Progress value="50" loaded="onPbLoaded" />

TypeScript

export function onPbLoaded(args) {
    let pb = <Progress>args.object;

    if(isAndroid) {
        let nativeProgress = <android.widget.ProgressBar>pb.android; // android.widget.ProgressBar{d26eea9 V.ED..... ......ID 0,0-0,0}
        console.log("nativeProgress Android: " + nativeProgress);

        nativeProgress.setScaleX(3);
        nativeProgress.setScaleY(5);
    }
}


问:
How can I make ajax parameters dynamic?
Here is a part of my code:

```<code>if ( external_link ) {
   data = {external_link : external_link};
} else {
   data = form_data;
}

$.ajax({
    url: base_url + frm.attr('action'),
    type: frm.attr('method'),
    data: data,
    cache: false,
    contentType: false, // this
    processData: false, // and this should be removed when external_link isn't false
    success: function (imageUpload) {
</code>```

All I'm trying to do is making contentType: false and processData: false parameters dynamic. I mean, if the condition above was true, then those two mentioned parameters should be removed. How can I do that?

答:
```<code>var ajaxParams = {
  url: base_url + frm.attr('action'),
  data: data
  // contentType not here
};

if (something) {
  ajaxParams.contentType = false; // add new parameter
}

$.ajax(ajaxParams);
</code>```

Title: How can I make ajax parameters dynamic?

Body:
Here is a part of my code:

if ( external_link ) {
   data = {external_link : external_link};
} else {
   data = form_data;
}

$.ajax({
    url: base_url + frm.attr('action'),
    type: frm.attr('method'),
    data: data,
    cache: false,
    contentType: false, // this
    processData: false, // and this should be removed when external_link isn't false
    success: function (imageUpload) {

All I'm trying to do is making contentType: false and processData: false parameters dynamic. I mean, if the condition above was true, then those two mentioned parameters should be removed. How can I do that?


问:
Cache coherence- MESI protocol
Can there be a case in a cache employing a MESI protocol (has l1 and l2 inclusivity employed) where l2 can send an invalid instruction to an already invalid line in l1. </p>

答:
There could be a scenario where the L2 simply does not know if the L1 has the line, because the L1 is allowed to silently drop it.

In fact, if the L2 is inclusive, there's hardly any reason to waste bandwidth when evicting a non-modified line from the L1 (capacity eviction), because the L2 already has a copy and there's no change. It is therefore likely that many lines in the L2 are still there long after they were evicted from the L1. An eviction from the L2 when it finally arrives (later, since it's bigger) would have to send back a snoop to enforce inclusiveness, because it can't be sure if the line is still in the L1 or not.

Title: Cache coherence- MESI protocol


问:
Regex to extract multiple fields from multiple pattern of data
I have to extract multiple fields from data. Some times data pattern is slightly different so I want that it should work with all those patterns.

I have written regex but its not perfect.

My regex is saved at:
https://regex101.com/r/V1gWZW/1

Here is the fields which I am looking to extract.

PS: Regex is not specific to any language. I will use it in Splunk Tool.

答:
I have solved it by myself.

final working regex:
https://regex101.com/r/V1gWZW/4

```<code>((?P<TIME_GC_TIMESTAMP>[^ ]*?):\s*)?(?P<relative_time>\d+\.\d+):.*(?P<Name>ParNew|P.*ParNew|PSYoungGen|DefNew):?\s?(?P<ParNew_before_1>\d+)K->(?P<ParNew_after_1>\d+)K\((?P<young_heap_size>\d+)K\)]?\s?(?P<ParNew_before_2>\d+)K\->(?P<ParNew_after_2>\d+)K\((?P<total_heap_size>\d+)K\),\s*(?P<par_new_duration>\d+\.\d+) secs\]
</code>```

Thanks

Body:
I have solved it by myself.

final working regex:
https://regex101.com/r/V1gWZW/4

((?P<TIME_GC_TIMESTAMP>[^ ]*?):\s*)?(?P<relative_time>\d+\.\d+):.*(?P<Name>ParNew|P.*ParNew|PSYoungGen|DefNew):?\s?(?P<ParNew_before_1>\d+)K->(?P<ParNew_after_1>\d+)K\((?P<young_heap_size>\d+)K\)]?\s?(?P<ParNew_before_2>\d+)K\->(?P<ParNew_after_2>\d+)K\((?P<total_heap_size>\d+)K\),\s*(?P<par_new_duration>\d+\.\d+) secs\]

Thanks


问:
How do I become "test infected" with TDD?
I keep reading about people who are "test infected", meaning that they don't just "get" TDD but also can't live without it.  They've "had the makeover" as it were.  The question is, how do I get like that?</p>

答:
Learn about TDD to start, and then begin integrating it into your workflow. If you use the methodologies enough, you'll find that they become second nature and you'll start framing all of your development tasks within that framework.

Also, start using the J-Unit (or X-Unit) framework for your language of choice.

OwnerDisplayName: Andrew Harmel-Law

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Zxaos


问:
How to show custom post type column before date column
I am using the following code to output columns pertaining to a CPT:

```<code>//set up new column to show custom meta theme_color
function pr_testimonials_column($column) {
    $column['testimonial_person_tagline'] = 'Person Tagline';

    return $column;
}

add_filter('manage_testimonials_posts_columns', 'pr_testimonials_column');

//show custom column data
function pr_show_testimonials_column($name) {
    global $post;
    switch ($name) {
        case 'testimonial_person_tagline':
            $testimonial_person_tagline = get_post_meta($post->ID, '_testimonial_person_tagline', true);
            echo $testimonial_person_tagline;
    }
}

add_action('manage_testimonials_posts_custom_column',  'pr_show_testimonials_column');
</code>```

The result is this, with the date first and the columns second. How can I modify my code to show all of my custom columns first, and date column last?

答:
Find the key for the Date column, next step to unset it and then set after adding your custom column,

```<code>function pr_testimonials_column($column) {

    // Remove Date
    unset($column['date']);

    $column['testimonial_person_tagline'] = 'Person Tagline';
    $column['date'] = 'Date';

    return $column;
}
add_filter('manage_testimonials_posts_columns', 'pr_testimonials_column');
</code>```

Hope this one helps.

Body:
I am using the following code to output columns pertaining to a CPT:

//set up new column to show custom meta theme_color
function pr_testimonials_column($column) {
    $column['testimonial_person_tagline'] = 'Person Tagline';

    return $column;
}

add_filter('manage_testimonials_posts_columns', 'pr_testimonials_column');

//show custom column data
function pr_show_testimonials_column($name) {
    global $post;
    switch ($name) {
        case 'testimonial_person_tagline':
            $testimonial_person_tagline = get_post_meta($post->ID, '_testimonial_person_tagline', true);
            echo $testimonial_person_tagline;
    }
}

add_action('manage_testimonials_posts_custom_column',  'pr_show_testimonials_column');

The result is this, with the date first and the columns second. How can I modify my code to show all of my custom columns first, and date column last?

Body:
Find the key for the Date column, next step to unset it and then set after adding your custom column,

function pr_testimonials_column($column) {

    // Remove Date
    unset($column['date']);

    $column['testimonial_person_tagline'] = 'Person Tagline';
    $column['date'] = 'Date';

    return $column;
}
add_filter('manage_testimonials_posts_columns', 'pr_testimonials_column');

Hope this one helps.


问:
How to add Zeppelin to CDH 'by the book'?
There are many tools You can instal via Cloudera Manager, but Zeppelin in missing on the list. What is a best way to add Zeppelin to Cloudera CDH stack? I found some docs in internet, but they are a bit manual. I'm looking for a managed solution. </p>

答:
CDH supports Hue for the notebook environment.

Cloudera Manager has no Zeppelin Parcel support, as far as I know.

I'm not sure what you mean by "managed solution", but automating an install of Zeppelin (and Spark), configuring to point at an external YARN master for job submission isn't too complicated, and can be written in Puppet, Chef, or Ansible fairly easily if you know those tools.

ContentLicense: CC BY-SA 4.0


问:
Getting class not found Exception when running in eclipse
I am running the following code in eclipse but getting a class not found exception:

```<code>         import org.eclipse.jface.window.Window;
         import org.eclipse.swt.SWT;
         import org.eclipse.swt.widgets.Display;
         import org.eclipse.swt.widgets.Shell;

        public class DialogClass {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("TEst");
    Shell frame = new Shell(SWT.SHELL_TRIM);

    PublishGenericArtefactDialog publishGenericArtefactDialog =
                       new PublishGenericArtefactDialog(frame);

    publishGenericArtefactDialog.setTitle("Test");

    if (publishGenericArtefactDialog.open() == Window.CANCEL){
        try {
            throw new Exception("Cancelled");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      }
       }

       }
</code>```

and error i am getting is

```<code>    TEst
    Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/core/runtime/IStatus
at DialogClass.main(DialogClass.java:19)
     Caused by: java.lang.ClassNotFoundException: org.eclipse.core.runtime.IStatus
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 1 more
</code>```

need help

答:
When you run your exported product, if you see something like,

```<code>org.osgi.framework.BundleException:
The activator org.eclipse.ui.internal.WorkbenchPlugin
for bundle org.eclipse.ui.workbench is invalid

...

Caused by: java.lang.ClassNotFoundException: org.eclipse.swt.SWTError
</code>```

It may be fixed via:

Open the product configuration editor on your product file

Click the "Launching" tab

clear out the "Program Arguments" and "VM Arguments" fields.

Re-export the product

Body:
I am running the following code in eclipse but getting a class not found exception:

         import org.eclipse.jface.window.Window;
         import org.eclipse.swt.SWT;
         import org.eclipse.swt.widgets.Display;
         import org.eclipse.swt.widgets.Shell;

        public class DialogClass {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("TEst");
    Shell frame = new Shell(SWT.SHELL_TRIM);

    PublishGenericArtefactDialog publishGenericArtefactDialog =
                       new PublishGenericArtefactDialog(frame);

    publishGenericArtefactDialog.setTitle("Test");

    if (publishGenericArtefactDialog.open() == Window.CANCEL){
        try {
            throw new Exception("Cancelled");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      }
       }

       }

and error i am getting is

    TEst
    Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/core/runtime/IStatus
at DialogClass.main(DialogClass.java:19)
     Caused by: java.lang.ClassNotFoundException: org.eclipse.core.runtime.IStatus
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 1 more

need help

Body:
When you run your exported product, if you see something like,

org.osgi.framework.BundleException:
The activator org.eclipse.ui.internal.WorkbenchPlugin
for bundle org.eclipse.ui.workbench is invalid

...

Caused by: java.lang.ClassNotFoundException: org.eclipse.swt.SWTError

It may be fixed via:

Open the product configuration editor on your product file

Click the "Launching" tab

clear out the "Program Arguments" and "VM Arguments" fields.

Re-export the product


问:
JDBC insertin String,Date and duration values to table
I've been trying to insert String, Date(now) and duration to the table.

Here is my code: At the args section (at the end) "app.insert("name", "date_added","path", "duration");" those values I mentioned as " date_added and duration" it wants me to convert them into String with an error. How can I prevent this happening and let the code enter date(now) and duration to app.insert section?

```<code>package xxxxx;

import java.sql.*;

public class SAMPLE_SOUND {

    private Connection connect() {

        String url = "jdbc:sqlite:neural.db";
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }
    public void insert(String name,Date date_added, String path, Time duration){
        String sql= " INSERT INTO SAMPLE_SOUND(name,date_added,path,duration) VALUES(?,?,?,?)";

        try(Connection conn = this.connect();
            PreparedStatement pstmt = conn.prepareStatement(sql)){
            pstmt.setString(1,name);
            pstmt.setDate(2, date_added);
            pstmt.setString(3,path);
            pstmt.setTime(4, duration);

            pstmt.executeUpdate();
        } catch (SQLException e){
            System.out.println(e.getMessage());
        }
    }

    public static void main(String[] args) {
        SAMPLE_SOUND app = new SAMPLE_SOUND();
        app.insert("name", "date_added","path", "duration");
    }
}
</code>```

答:
it wants me to convert them into String with an error

No, not at all. It signals that you're trying to pass strings as arguments, elthough the method expects a Date and a Time. The correct fix is of course to pass a Date and a Time. But IntelliJ doesn't know that, and it suggests that maybe you actually do want to pass Strings, and the arguments types should then be changed to String.

Remember, you are the smart developer. It's up to you to decide what to do.

Please respect the Java naming conventions.

Body:
I've been trying to insert String, Date(now) and duration to the table.

Here is my code: At the args section (at the end) "app.insert("name", "date_added","path", "duration");" those values I mentioned as " date_added and duration" it wants me to convert them into String with an error. How can I prevent this happening and let the code enter date(now) and duration to app.insert section?

package xxxxx;

import java.sql.*;

public class SAMPLE_SOUND {

    private Connection connect() {

        String url = "jdbc:sqlite:neural.db";
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }
    public void insert(String name,Date date_added, String path, Time duration){
        String sql= " INSERT INTO SAMPLE_SOUND(name,date_added,path,duration) VALUES(?,?,?,?)";

        try(Connection conn = this.connect();
            PreparedStatement pstmt = conn.prepareStatement(sql)){
            pstmt.setString(1,name);
            pstmt.setDate(2, date_added);
            pstmt.setString(3,path);
            pstmt.setTime(4, duration);

            pstmt.executeUpdate();
        } catch (SQLException e){
            System.out.println(e.getMessage());
        }
    }

    public static void main(String[] args) {
        SAMPLE_SOUND app = new SAMPLE_SOUND();
        app.insert("name", "date_added","path", "duration");
    }
}


问:
global variables typescript not defined
I have a problem with typescript global variable.

I'm writing a piece of code to login with facebook in my ionic 3 app.

I have a global variable declared, but when the app runs, got me the error *.*FB is not defined** at the function FB.init({})

The code:

```<code>//all needed imports

declare const FB;

@Injectable()
export class AuthenticationProvider implements OnInit{

  //properties

  //constructor

   ngOnInit() {
     debugger
     if( FB != null && FB != 'undefined')
     {
       FB.init({
         appId: '***',
         cookie: false,access
         status: true,
         xfbml: true,
         version: 'v2.11'
       });
     }
   }

   //FB.login(){} inside an observable function
   //FB.getLoginStatus(){} inside an observable function
   //FB.api(){} inside an observable function

 }
</code>```

Can someone help me?

答:
Your FB api has not been correctly imported in your application.

this must be something similar as

import * as FB from 'fb_api';

Title: global variables typescript not defined

Body:
I have a problem with typescript global variable.

I'm writing a piece of code to login with facebook in my ionic 3 app.

I have a global variable declared, but when the app runs, got me the error *.*FB is not defined** at the function FB.init({})

The code:

//all needed imports

declare const FB;

@Injectable()
export class AuthenticationProvider implements OnInit{

  //properties

  //constructor

   ngOnInit() {
     debugger
     if( FB != null && FB != 'undefined')
     {
       FB.init({
         appId: '***',
         cookie: false,access
         status: true,
         xfbml: true,
         version: 'v2.11'
       });
     }
   }

   //FB.login(){} inside an observable function
   //FB.getLoginStatus(){} inside an observable function
   //FB.api(){} inside an observable function

 }

Can someone help me?


问:
Can the intmax_t hold size_t?
Can the intmax_t hold size_t maximum decimal number?
And what size type in printf  have a biggest priority uintmax_t/intmax_t or size_t (ex. if i write printf("%zjd", x))? </p>

答:
Most likely not

Both are implementation specific, so it's not really possible to answer.

size_t is (usually) an unsigned integer holding the largest possible number of bits that will fit in a register on a given CPU. That's not exactly guaranteed in reality though, but I still haven't found an example where this isn't true.

intmax_t is a signed integer, meaning it will probably have the bits required to store any value that a size_t can hold, but large values will not mean the same; the largest value that a size_t can hold, is likely going to be a negative integer when interpreted as an intmax_t.

Title: Can the intmax_t hold size_t?


问:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your server version for the right syntax to use near ' ' at line 2
I'm trying to create a table in my database on phpMyAdmin with this code:

```<code>CREATE TABLE usuarios (
    nombre VARCHAR NOT NULL,
    passwd VARCHAR NOT NULL,
    correo VARCHAR NOT NULL,
    sexo VARCHAR(1) NOT NULL,
    edad DATE NOT NULL,
    rango INTEGER NOT NULL,
    tipo VARCHAR(1) NOT NULL,
    imagen VARCHAR NOT NULL,
    txt VARCHAR NOT NULL,
    CONSTRAINT nombre_pk PRIMARY KEY (nombre)
);
</code>```

And I get this problem:

MySQL said:

#1064 - You have an error in your SQL syntax; check the manual that corresponds
  to your server version for the right syntax to use near 'NOT NULL,
     passwd VARCHAR NOT NULL,
     correo VARCHAR NOT NULL,
     sexo ' at line 2

答:
You need lengths for VARCHAR declarations in MySQL.  For instance:

```<code>CREATE TABLE usuarios (
    nombre VARCHAR(255) NOT NULL,
    passwd VARCHAR(255) NOT NULL,
    correo VARCHAR(255) NOT NULL,
    sexo CHAR(1) NOT NULL,
    edad DATE NOT NULL,
    rango INTEGER NOT NULL,
    tipo VARCHAR(1) NOT NULL,
    imagen VARCHAR(255) NOT NULL,
    txt VARCHAR(255) NOT NULL,
    CONSTRAINT nombre_pk PRIMARY KEY (nombre)
);
</code>```

Body:
I'm trying to create a table in my database on phpMyAdmin with this code:

CREATE TABLE usuarios (
    nombre VARCHAR NOT NULL,
    passwd VARCHAR NOT NULL,
    correo VARCHAR NOT NULL,
    sexo VARCHAR(1) NOT NULL,
    edad DATE NOT NULL,
    rango INTEGER NOT NULL,
    tipo VARCHAR(1) NOT NULL,
    imagen VARCHAR NOT NULL,
    txt VARCHAR NOT NULL,
    CONSTRAINT nombre_pk PRIMARY KEY (nombre)
);

And I get this problem:

MySQL said:

#1064 - You have an error in your SQL syntax; check the manual that corresponds
  to your server version for the right syntax to use near 'NOT NULL,
     passwd VARCHAR NOT NULL,
     correo VARCHAR NOT NULL,
     sexo ' at line 2

Body:
You need lengths for VARCHAR declarations in MySQL.  For instance:

CREATE TABLE usuarios (
    nombre VARCHAR(255) NOT NULL,
    passwd VARCHAR(255) NOT NULL,
    correo VARCHAR(255) NOT NULL,
    sexo CHAR(1) NOT NULL,
    edad DATE NOT NULL,
    rango INTEGER NOT NULL,
    tipo VARCHAR(1) NOT NULL,
    imagen VARCHAR(255) NOT NULL,
    txt VARCHAR(255) NOT NULL,
    CONSTRAINT nombre_pk PRIMARY KEY (nombre)
);


问:
$http request does not execute after a day or 2 on RHC
We have a Node JS - Express application running on a Openshift RHC v2 and an api is being called to a third party SMS gateway server whenever a user requests for an OTP. For this we have added a simple $http call which will trigger an SMS to the mentioned number with the message.

The request looks something like this :

```<code>$http.get("http://example.com/?user=userid:password&number=9876543210&message='Hi your OTP is 18276'")
    .success(function(error, response){
        if (!error && response.statusCode == 200) {
              console.log('STATUS: ' + response.statusCode)
              console.log('HEADERS: ' + JSON.stringify(response.headers));
        } else {
              console.log('STATUS : '+ error.statusCode);
              console.log(error);
        }

     });
</code>```

This works as soon as the RHC Server starts running. After a few days or sometimes a few hours we observe that this API is never called. We have added console logs before and after the requests and still the API is never called. It is very very surprising and shocking how can it not execute this request (which is working for a few days and then goes down completely).

What could be the issue here? Will re-share what we have :

```<code>console.log("Generated OTP : " + otp);   // ... Where OTP is what we have generated... Console 1
var number = 9876543210;
var message = 'Hi your OTP is : '+otp;

console.log('Number : ' + number + ', Message : ' + message);  // ... Console 2
$http.get("http://example.com/?user=userid:password&number="+number+"&message="+message)
        .success(function(error, response){
            if (!error && response.statusCode == 200) {
                  console.log('STATUS: ' + response.statusCode) ... Console 3
                  console.log('HEADERS: ' + JSON.stringify(response.headers));  // ... Console 4
            } else {
                  console.log('STATUS : '+ error.statusCode);   // ... Console 5
                  console.log(error);   // ... Console 6
            }

         });

  console.log("callback - Post - /sellers/phone/:number/:email"); // ...Console 7
  res.json({"otp":otp});
</code>```

When this is down, Consoles 1, 2 and 7 can be seen but not 3, 4 or 5 and 6.

Is there any way we can debug either on the Openshift or on the Node application?

If I do a server restart using rhc app-restart <app> the other consoles will be seen and we receive the SMS / Messages.

Please help. Any additional information needed, please let us know.
Thank you.

EDIT : I have also tried using request as below :

```<code>request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
               console.log('STATUS: ' + response.statusCode);
               console.log('HEADERS: ' + JSON.stringify(response.headers));
        } else {
               console.log('STATUS : ' + error.statusCode);
               console.log(error);
        }
  });
</code>```

答:
Since AngularJS v1.6 the .success() and .error() methods on promises are removed.

Instead use the .then() method. All the data for the success, errors and headers  are moved to the .then(response) response data.

So:

```<code>response.config, // Contains an object of configurations, like `Method`, `params`, `URL`
response.data, // Contains the data the request returned
response.status,  // Contains the status code, Eg 200 which is success
response.statusText, // Text of the status, Eg. Ok on success or Error on error
</code>```

So check whether the $http method succeeded like so:

```<code>$http.get("http://example.com/?user=userid:password&number="+number+"&message="+message)
// Use .then instead of .success
.then(function (response) {
    if(response.status === 200) {

        // Successfull

    } else {

        // Error occurred

    }
});
</code>```

Just incase you wonder why they are removed. Check out this topic:

Why are angular $http success/error methods deprecated? Removed from v1.6?

Body:
We have a Node JS - Express application running on a Openshift RHC v2 and an api is being called to a third party SMS gateway server whenever a user requests for an OTP. For this we have added a simple $http call which will trigger an SMS to the mentioned number with the message.

The request looks something like this :

$http.get("http://example.com/?user=userid:password&number=9876543210&message='Hi your OTP is 18276'")
    .success(function(error, response){
        if (!error && response.statusCode == 200) {
              console.log('STATUS: ' + response.statusCode)
              console.log('HEADERS: ' + JSON.stringify(response.headers));
        } else {
              console.log('STATUS : '+ error.statusCode);
              console.log(error);
        }

     });

This works as soon as the RHC Server starts running. After a few days or sometimes a few hours we observe that this API is never called. We have added console logs before and after the requests and still the API is never called. It is very very surprising and shocking how can it not execute this request (which is working for a few days and then goes down completely).

What could be the issue here? Will re-share what we have :

console.log("Generated OTP : " + otp);   // ... Where OTP is what we have generated... Console 1
var number = 9876543210;
var message = 'Hi your OTP is : '+otp;

console.log('Number : ' + number + ', Message : ' + message);  // ... Console 2
$http.get("http://example.com/?user=userid:password&number="+number+"&message="+message)
        .success(function(error, response){
            if (!error && response.statusCode == 200) {
                  console.log('STATUS: ' + response.statusCode) ... Console 3
                  console.log('HEADERS: ' + JSON.stringify(response.headers));  // ... Console 4
            } else {
                  console.log('STATUS : '+ error.statusCode);   // ... Console 5
                  console.log(error);   // ... Console 6
            }

         });

  console.log("callback - Post - /sellers/phone/:number/:email"); // ...Console 7
  res.json({"otp":otp});

When this is down, Consoles 1, 2 and 7 can be seen but not 3, 4 or 5 and 6.

Is there any way we can debug either on the Openshift or on the Node application?

If I do a server restart using rhc app-restart <app> the other consoles will be seen and we receive the SMS / Messages.

Please help. Any additional information needed, please let us know.
Thank you.

EDIT : I have also tried using request as below :

request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
               console.log('STATUS: ' + response.statusCode);
               console.log('HEADERS: ' + JSON.stringify(response.headers));
        } else {
               console.log('STATUS : ' + error.statusCode);
               console.log(error);
        }
  });

Body:
Since AngularJS v1.6 the .success() and .error() methods on promises are removed.

Instead use the .then() method. All the data for the success, errors and headers  are moved to the .then(response) response data.

So:

response.config, // Contains an object of configurations, like `Method`, `params`, `URL`
response.data, // Contains the data the request returned
response.status,  // Contains the status code, Eg 200 which is success
response.statusText, // Text of the status, Eg. Ok on success or Error on error

So check whether the $http method succeeded like so:

$http.get("http://example.com/?user=userid:password&number="+number+"&message="+message)
// Use .then instead of .success
.then(function (response) {
    if(response.status === 200) {

        // Successfull

    } else {

        // Error occurred

    }
});

Just incase you wonder why they are removed. Check out this topic:

Why are angular $http success/error methods deprecated? Removed from v1.6?


问:
How to change markup cell font color in Jupyter notebook
I am using a customized theme for jupyter notebook and the font color for markup cells while it is active and I am typing is black and has barely enough contrast.  I was not able to locate the section in custom.css that dictate the font color. When I inspect the font color, Iit points to codemirror.css, a file that I am not able to locate on my machine. The black fonr is the case for nbextension page. I left some pictures below.

link to the custom.css file

markup cell:

nbextension page:

答:
That's strange, this line of your custom.css should affect all cells in your notebook.

Perhaps put an !important declaration on the colour line so as to override any other styles in place? e.g. change color: white; to color: white !important;

It's odd that this is only affecting your markdown cells though, as things like brackets and equals signs in your code cells are coloured by the exact same mechanism.


问:
How do you scrape AJAX pages?
Please advise how to scrape AJAX pages.</p>

答:
Selenium WebDriver is a good solution: you program a browser and you automate what needs to be done in the browser. Browsers (Chrome, Firefox, etc) provide their own drivers that work with Selenium. Since it works as an automated REAL browser, the pages (including javascript and Ajax) get loaded as they do with a human using that browser.

The downside is that it is slow (since you would most probably like to wait for all images and scripts to load before you do your scraping on that single page).

Title: How do you scrape AJAX pages?

Body: Please advise how to scrape AJAX pages.

LastEditorDisplayName: swilliams


问:
How to convert a Boost::make_recursive_variant Object into a string?

Been playing with Boost:make_recursive_variant and I'm quite stump on how to create a string from a given Variant and return it.

I can output easily using cout, but my goal was to create a C++ Version of Arrays.deeptoString from java to return a string. Kept running into compile issues trying to work around recursive_variant. Here my Current Code for Arrays.deeptoString.

```<code>typedef boost::make_recursive_variant<string, int, vector<boost::recursive_variant_ > >::type ObjectE;
class deepToString : public boost::static_visitor<std::string> {
public:
    string operator()(const int i) const {
        storedString += i;
        storedString += ",";
        return storedString;
    }
    string operator()(std::vector<ObjectE> const &v) const {
        storedString += "[";
        for (std::size_t i = 0; i < v.size() - 1; i++) {
            storedString += boost::apply_visitor(create_string(), v[i]);
            storedString += ",";
        }
        storedString += boost::apply_visitor(create_string(), v[v.size() - 1]);
        storedString += "]";
        return storedString;
    }
    string operator()(std::string const &s) const {
        storedString += s;
        storedString += ",";
    }
    mutable string storedString = "";
};
</code>```

I was hoping I could return the string, but instead it just crashes on me. I... both love and hate recursive variants atm. Ideally if there was a given

```<code>ObjectE t = ["string" , [1, 2] , ["str2", "str3"], [1,3,6], [[1,2], [1,4]]]
</code>```

I should be able to do the following line to get

```<code>string output = boost::apply_visitor(deepToString(), t);
</code>```

output get

```<code> "["string" , [1, 2] , ["str2", "str3"], [1,3,6], [[1,2], [1,4]]]"
</code>```

At the start, I tried not using const methods since we are changing the values inside the method, but I got a large series of compiles errors. This current style compiles for me, but will crash on me. I should have prob look into why it crashing first.

Any ideas on how I should approach this problem

答:
There are a number of problems:

doing storedString += i; (where i is int) doesn't do what you think it does

You fail to return a value from operator()(std::string const&) const

You recurse into create_string() which is a temporary; this is the reason you couldn't make things const properly

Fixing all that and doing it right with the mutable/const:

Live On Coliru

```<code>#include <boost/variant.hpp>
#include <vector>
#include <iostream>

typedef boost::make_recursive_variant<std::string, int, std::vector<boost::recursive_variant_> >::type ObjectE;
typedef std::vector<ObjectE> ObjectV;

struct create_string : boost::static_visitor<std::string const&> {
    std::string const& operator()(const int i) {
        return storedString += std::to_string(i) + ", ";
    }
    std::string const& operator()(ObjectV const &v) {
        storedString += "[ ";
        for (std::size_t i = 0; i < v.size() - 1; i++) {
            create_string nest;
            storedString += boost::apply_visitor(nest, v[i]) + ", ";
        }
        create_string nest;
        storedString += boost::apply_visitor(nest, v[v.size() - 1]);
        return storedString += " ]";
    }
    std::string const& operator()(std::string const &s) {
        return storedString += s + ", ";
    }

    std::string storedString = "";
};

int main() {
    ObjectE obj = ObjectV {
        1,
        "hello world",
        ObjectV {
            42, ObjectV { "some more" }, -42
        },
    };

    create_string vis;

    std::cout << "Result '" << boost::apply_visitor(vis, obj) << "'\n";
}
</code>```

Prints:

```<code>Result '[ 1, , hello world, , [ 42, , [ some more,  ], -42,  ] ]'
</code>```

Improving

You can do a lot better.

First you can reduce allocations by using a stream instead of copying strings. This could also be made to make the visitor stateless.

You can also make the visitor apply directly to variants, so you don't have to invoke apply_visitor anymore.

You can avoid the redundant commas and use std::quoted to properly escape the string values (in case they contain ", [, ], ,)

You can make everything generic so it works with a lot more variants

Here's the implementation of these bullets:

Live On Coliru

```<code>#include <boost/variant.hpp>
#include <vector>
#include <iostream>
#include <iomanip>

typedef boost::make_recursive_variant<std::string, int, std::vector<boost::recursive_variant_> >::type ObjectE;
typedef std::vector<ObjectE> ObjectV;

struct printer {
    using result_type = void;
    std::ostream& _os;

    // forwards for `operator()`
    template <typename T> void call(T const& v) const { return operator()(v); }

    // dispatch for variants
    template <typename... Ts> void operator()(boost::variant<Ts...> const& v) const {
        return boost::apply_visitor(*this, v);
    }

    void operator()(int i) const                { _os << i;              }
    void operator()(std::string const &s) const { _os << std::quoted(s); }

    template <typename... Ts> void operator()(std::vector<Ts...> const& v) const {
        _os << "[ ";
        bool first = true;
        for (auto& el : v) {
            if (first) first = false;
            else       _os << ", ";
            call(el);
        }
        _os << " ]";
    }
};

int main() {
    ObjectE obj = ObjectV {
        1,
        "hello world",
        ObjectV {
            42, ObjectV { "some more" }, -42
        },
    };

    printer print{std::cout};
    print(obj);
}
</code>```

Printing

```<code>[ 1, "hello world", [ 42, [ "some more" ], -42 ] ]
</code>```

Even More: Pretty Indenting

Now that we've lost the baggage of the string, we can add some state to the visitor again. Let's make it pretty print with indentation.

Live On Coliru

```<code>struct printer {
    using result_type = void;
    std::ostream& _os;
    std::string _indent = "";

    template <typename... Ts> void operator()(boost::variant<Ts...> const& v) const {
        return boost::apply_visitor(*this, v);
    }

    void operator()(int i) const                { _os << i;              }
    void operator()(std::string const &s) const { _os << std::quoted(s); }

    template <typename... Ts> void operator()(std::vector<Ts...> const& v) const {
        _os << "[";
        auto indent = _indent + "    ";

        bool first = true;
        for (auto& el : v) {
            if (first) first = false;
            else _os << ",";
            _os << "\n" << indent;
            printer{_os, indent}(el);
        }

        if (!v.empty())
            _os << "\n" << _indent;
        _os << "]";
    }
};
</code>```

Prints

```<code>[
    1,
    "hello world",
    [],
    [
        42,
        [
            "some more"
        ],
        -42
    ]
]
</code>```

For The Win: Without Recursive Variant, Neat Literals

I noticed you wrote your pseudo-code more like JSON:

```<code>ObjectE t = ["string" , [1, 2] , ["str2", "str3"], [1,3,6], [[1,2], [1,4]]]
</code>```

That's not C++. However, I can make it work like this:

```<code>ObjectE t = {"string" , {1, 2} , {"str2", "str3"}, {1,3,6}, {{1,2}, {1,4}}};
</code>```

You do so by making a type derived from variant, and adding a constructor that takes an initializer list for the vector element:

```<code>struct ObjectE : boost::variant<std::string, int, std::vector<ObjectE> > {
    using Base = boost::variant<std::string, int, std::vector<ObjectE> >;

    using Base::variant;
    using Base::operator=;

    ObjectE(std::initializer_list<ObjectE> init) : Base(std::vector<ObjectE>(init)) {}
};
</code>```

That's all. The improved visitor above was generic enough from the start, so we don't need to change another line of code:

Live On Coliru

```<code>printer print{std::cout};
print(ObjectE { 1, "hello world", {}, { 42, { "some more" }, -42 } });

std::cout << "\nt: ";

ObjectE t = {"string" , {1, 2} , {"str2", "str3"}, {1,3,6}, {{1,2}, {1,4}}};
print(t);
</code>```

Prints

```<code>Result '[ 1, , hello world, , [ 42, , [ some more,  ], -42,  ] ]'
</code>```0

Body:
Been playing with Boost:make_recursive_variant and I'm quite stump on how to create a string from a given Variant and return it.

I can output easily using cout, but my goal was to create a C++ Version of Arrays.deeptoString from java to return a string. Kept running into compile issues trying to work around recursive_variant. Here my Current Code for Arrays.deeptoString.

typedef boost::make_recursive_variant<string, int, vector<boost::recursive_variant_ > >::type ObjectE;
class deepToString : public boost::static_visitor<std::string> {
public:
    string operator()(const int i) const {
        storedString += i;
        storedString += ",";
        return storedString;
    }
    string operator()(std::vector<ObjectE> const &v) const {
        storedString += "[";
        for (std::size_t i = 0; i < v.size() - 1; i++) {
            storedString += boost::apply_visitor(create_string(), v[i]);
            storedString += ",";
        }
        storedString += boost::apply_visitor(create_string(), v[v.size() - 1]);
        storedString += "]";
        return storedString;
    }
    string operator()(std::string const &s) const {
        storedString += s;
        storedString += ",";
    }
    mutable string storedString = "";
};

I was hoping I could return the string, but instead it just crashes on me. I... both love and hate recursive variants atm. Ideally if there was a given

ObjectE t = ["string" , [1, 2] , ["str2", "str3"], [1,3,6], [[1,2], [1,4]]]

I should be able to do the following line to get

string output = boost::apply_visitor(deepToString(), t);

output get

 "["string" , [1, 2] , ["str2", "str3"], [1,3,6], [[1,2], [1,4]]]"

At the start, I tried not using const methods since we are changing the values inside the method, but I got a large series of compiles errors. This current style compiles for me, but will crash on me. I should have prob look into why it crashing first.

Any ideas on how I should approach this problem

Body:
There are a number of problems:

doing storedString += i; (where i is int) doesn't do what you think it does

You fail to return a value from operator()(std::string const&) const

You recurse into create_string() which is a temporary; this is the reason you couldn't make things const properly

Fixing all that and doing it right with the mutable/const:

Live On Coliru

#include <boost/variant.hpp>
#include <vector>
#include <iostream>

typedef boost::make_recursive_variant<std::string, int, std::vector<boost::recursive_variant_> >::type ObjectE;
typedef std::vector<ObjectE> ObjectV;

struct create_string : boost::static_visitor<std::string const&> {
    std::string const& operator()(const int i) {
        return storedString += std::to_string(i) + ", ";
    }
    std::string const& operator()(ObjectV const &v) {
        storedString += "[ ";
        for (std::size_t i = 0; i < v.size() - 1; i++) {
            create_string nest;
            storedString += boost::apply_visitor(nest, v[i]) + ", ";
        }
        create_string nest;
        storedString += boost::apply_visitor(nest, v[v.size() - 1]);
        return storedString += " ]";
    }
    std::string const& operator()(std::string const &s) {
        return storedString += s + ", ";
    }

    std::string storedString = "";
};

int main() {
    ObjectE obj = ObjectV {
        1,
        "hello world",
        ObjectV {
            42, ObjectV { "some more" }, -42
        },
    };

    create_string vis;

    std::cout << "Result '" << boost::apply_visitor(vis, obj) << "'\n";
}

Prints:

Result '[ 1, , hello world, , [ 42, , [ some more,  ], -42,  ] ]'

Improving

You can do a lot better.

First you can reduce allocations by using a stream instead of copying strings. This could also be made to make the visitor stateless.

You can also make the visitor apply directly to variants, so you don't have to invoke apply_visitor anymore.

You can avoid the redundant commas and use std::quoted to properly escape the string values (in case they contain ", [, ], ,)

You can make everything generic so it works with a lot more variants

Here's the implementation of these bullets:

Live On Coliru

#include <boost/variant.hpp>
#include <vector>
#include <iostream>
#include <iomanip>

typedef boost::make_recursive_variant<std::string, int, std::vector<boost::recursive_variant_> >::type ObjectE;
typedef std::vector<ObjectE> ObjectV;

struct printer {
    using result_type = void;
    std::ostream& _os;

    // forwards for `operator()`
    template <typename T> void call(T const& v) const { return operator()(v); }

    // dispatch for variants
    template <typename... Ts> void operator()(boost::variant<Ts...> const& v) const {
        return boost::apply_visitor(*this, v);
    }

    void operator()(int i) const                { _os << i;              }
    void operator()(std::string const &s) const { _os << std::quoted(s); }

    template <typename... Ts> void operator()(std::vector<Ts...> const& v) const {
        _os << "[ ";
        bool first = true;
        for (auto& el : v) {
            if (first) first = false;
            else       _os << ", ";
            call(el);
        }
        _os << " ]";
    }
};

int main() {
    ObjectE obj = ObjectV {
        1,
        "hello world",
        ObjectV {
            42, ObjectV { "some more" }, -42
        },
    };

    printer print{std::cout};
    print(obj);
}

Printing

[ 1, "hello world", [ 42, [ "some more" ], -42 ] ]

Even More: Pretty Indenting

Now that we've lost the baggage of the string, we can add some state to the visitor again. Let's make it pretty print with indentation.

Live On Coliru

struct printer {
    using result_type = void;
    std::ostream& _os;
    std::string _indent = "";

    template <typename... Ts> void operator()(boost::variant<Ts...> const& v) const {
        return boost::apply_visitor(*this, v);
    }

    void operator()(int i) const                { _os << i;              }
    void operator()(std::string const &s) const { _os << std::quoted(s); }

    template <typename... Ts> void operator()(std::vector<Ts...> const& v) const {
        _os << "[";
        auto indent = _indent + "    ";

        bool first = true;
        for (auto& el : v) {
            if (first) first = false;
            else _os << ",";
            _os << "\n" << indent;
            printer{_os, indent}(el);
        }

        if (!v.empty())
            _os << "\n" << _indent;
        _os << "]";
    }
};

Prints

[
    1,
    "hello world",
    [],
    [
        42,
        [
            "some more"
        ],
        -42
    ]
]

For The Win: Without Recursive Variant, Neat Literals

I noticed you wrote your pseudo-code more like JSON:

ObjectE t = ["string" , [1, 2] , ["str2", "str3"], [1,3,6], [[1,2], [1,4]]]

That's not C++. However, I can make it work like this:

ObjectE t = {"string" , {1, 2} , {"str2", "str3"}, {1,3,6}, {{1,2}, {1,4}}};

You do so by making a type derived from variant, and adding a constructor that takes an initializer list for the vector element:

struct ObjectE : boost::variant<std::string, int, std::vector<ObjectE> > {
    using Base = boost::variant<std::string, int, std::vector<ObjectE> >;

    using Base::variant;
    using Base::operator=;

    ObjectE(std::initializer_list<ObjectE> init) : Base(std::vector<ObjectE>(init)) {}
};

That's all. The improved visitor above was generic enough from the start, so we don't need to change another line of code:

Live On Coliru

printer print{std::cout};
print(ObjectE { 1, "hello world", {}, { 42, { "some more" }, -42 } });

std::cout << "\nt: ";

ObjectE t = {"string" , {1, 2} , {"str2", "str3"}, {1,3,6}, {{1,2}, {1,4}}};
print(t);

Prints

[
    1,
    "hello world",
    [],
    [
        42,
        [
            "some more"
        ],
        -42
    ]
]
t: [
    "string",
    [
        1,
        2
    ],
    [
        "str2",
        "str3"
    ],
    [
        1,
        3,
        6
    ],
    [
        [
            1,
            2
        ],
        [
            1,
            4
        ]
    ]
]


问:
Check if string contains a 3 character long substring of another string
I need a regex pattern to check whether characters present in a string consecutively repeats 3 character in another string. Eg:

```<code>var string1 = "HelloWorld";
var string2 = "Work";
</code>```

Here the letters "Wor" in string1 repeats in string2, so it should return true.

Any help on this

答:
Slightly longer than the other answers here, and nothing too clever about it. Will simply go through and find all matches, which returns an array, and will loop through that array and return true when the longer string contains one of the split strings.

function getAllConsecutives(string, number) {
  let matches = [],
    regex = "";

  for (let i = 0; i < (string.length - number); i++) {
    regex = new RegExp(`\\w{${i}}(\\w{${number}})`);
    matches.push(string.match(regex)[1])
  }

  return matches
}

function areThereConsecutives(string1, string2, number) {
  let short = string1.length < string2.length ? string1 : string2,
    long = string1.length < string2.length ? string2 : string1,
    consecutives = getAllConsecutives(short, number);

  for (let i = 0; i < consecutives.length; i++) {
    if (long.includes(consecutives[i])) {
      return true;
    }
  }

  return false
}

let string1 = "HelloWorld",
  string2 = "Work";

console.log(areThereConsecutives(string1, string2, 3))```

Body:
I need a regex pattern to check whether characters present in a string consecutively repeats 3 character in another string. Eg:

var string1 = "HelloWorld";
var string2 = "Work";

Here the letters "Wor" in string1 repeats in string2, so it should return true.

Any help on this


问:
Java / Scala math library with elliptic integrals and bessel functions?
I am looking for a math library for scientific computing to use in Java / Scala. Especially I need complete elliptic integrals und modified Bessel functions. I would be nice if it is open source, but I guess I will have to take whatever is out there. A scipy (python lib for scientific computing) replacment would be great :-)</p>

答:
I know that the GNU Scientific Library contains both elliptic integrals and Bessel functions of many kinds.  Unfortunately, good mathematics libraries are hard to come by; your best bet may be to wrap the GSL using JNI (or JNA if you can get it to work).

If you really must have pure Java/Scala functions, I guess you could translate the portions of the library you need.  It would be a lot of work, but it is GPLed code at least.


问:
How can I include CSS file in freemarker
I'm making a website with spring-boot & spring-security which prefers to supply freemarker as view. I don't know ftl much, and now I need use adminLTE's CSS and JS files in my ftl, but how?

```<code><html lang="en">
<#assign basePath=request.contextPath>
<#macro head>
    ...
    <script src="${basePath}WEB-INF/AdminLTE/dist/js/adminlte.min.js"></script>
    <link src="${basePath}WEB-INF/AdminLTE/plugins/iCheck/line/line.css" rel="stylesheet"></link>
    <script src="${basePath}WEB-INF/AdminLTE/plugins/iCheck/icheck.js"></script>
    ...
<#macro>
</code>```

答:
you can include css file by using <#include > tag,
place the stylesheet in the directory and use the
<#include "/{path to style sheet}/Styles.css">

and make sure your style sheet is inside the styles element:

```<code><style type="text/css">
...
</style>
</code>```

Example of this approach is

Test Template

```<code><html>
<head>
<#include "css/test.css">
</head>
<body>
.......................
</body>
</html>
</code>```

test.css

```<code><style type="text/css">
body{background-color:#C5C5C0;}
*{font-family:Tahoma, Verdana, Helvetica, sans-serif;}
</style>
</code>```

Body:
I'm making a website with spring-boot & spring-security which prefers to supply freemarker as view. I don't know ftl much, and now I need use adminLTE's CSS and JS files in my ftl, but how?

<#assign basePath=request.contextPath>
<#macro head>
    ...

    <link src="${basePath}WEB-INF/AdminLTE/plugins/iCheck/line/line.css" rel="stylesheet"></link>

    ...
<#macro>

Body:
you can include css file by using <#include > tag,
place the stylesheet in the directory and use the
<#include "/{path to style sheet}/Styles.css">

and make sure your style sheet is inside the styles element:

<style type="text/css">
...
</style>

Example of this approach is

Test Template

<html>
<head>
<#include "css/test.css">
</head>
<body>
.......................
</body>
</html>

test.css

<style type="text/css">
body{background-color:#C5C5C0;}
*{font-family:Tahoma, Verdana, Helvetica, sans-serif;}
</style>


问:
Cross Table Left Join, Django ORM
I have the following models:

```<code>class TradeDetails(models.Model):
    created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP', primary_key=True)
    trade_name = models.CharField(db_column='TRADE_NAME', max_length=45)
    trade_image = models.CharField(db_column='TRADE_IMAGE', max_length=500, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'TRADE_DETAILS'

class TradeNotifications(models.Model):
    client_id = models.CharField(db_column='CLIENT_ID', primary_key=True, max_length=15)
    created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP')
    updated_timestamp = models.DateTimeField(db_column='UPDATED_TIMESTAMP', blank=True, null=True)
    platform_notification = models.IntegerField(db_column='PLATFORM_NOTIFICATION', blank=True, null=True)
    sms_notification = models.IntegerField(db_column='SMS_NOTIFICATION', blank=True, null=True)
    email_notification = models.IntegerField(db_column='EMAIL_NOTIFICATION', blank=True, null=True)
    caller_notification = models.IntegerField(db_column='CALLER_NOTIFICATION', blank=True, null=True)
    caller_id = models.IntegerField(db_column='CALLER_ID', blank=True, null=True)
    client_confirmation = models.IntegerField(db_column='CLIENT_CONFIRMATION', blank=True, null=True)
    device_id = models.CharField(db_column='DEVICE_ID', max_length=256, blank=True, null=True)
    platform = models.CharField(db_column='PLATFORM', max_length=15, blank=True, null=True)
    ip_address = models.CharField(db_column='IP_ADDRESS', max_length=50, blank=True, null=True)
    expired = models.IntegerField(db_column='EXPIRED', blank=True, null=True)
    trade_sent = models.IntegerField(db_column='TRADE_SENT', blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'TRADE_NOTIFICATIONS'
        unique_together = (('client_id', 'created_timestamp'),)
</code>```

I want to perform a left join on another table on the same db using the following sql query:

SELECT TRADE_DETAILS.TRADE_NAME FROM TRADE_NOTIFICATIONS LEFT JOIN
  TRADE_DETAILS ON TRADE_NOTIFICATIONS.CREATED_TIMESTAMP =
  TRADE_DETAILS.CREATED_TIMESTAMP

Is there a more Django-Like way of doing this or should I just go with raw
sql?

Upon reading some answers I tried to do this :

```<code>TradeNotifications.objects.using('tradenotifications').all().values_list('trade_name', 'trade_details_created_timestamp')
</code>```

but it raised an error :
django.core.exceptions.FieldError: Cannot resolve keyword 'trade_name' into field. Choices are: caller_id, caller_notification,

答:
You can't join tables without some relationship between models such as foreign key with Django ORM. There must be a relationship between the models.

This relationship doesn't have to be in the db, it's enough if it's defined in the models, but I don't think this is possible with your TradeDetails and TradeNotifications models. It could be possible with your client_id field; you'd change it from CharField() to ForeignKey(). This is especially useful in cases when you only read from the database and you reverse engineer it and use them as non-managed models.

Title: Cross Table Left Join, Django ORM

Body:
I have the following models:

class TradeDetails(models.Model):
    created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP', primary_key=True)
    trade_name = models.CharField(db_column='TRADE_NAME', max_length=45)
    trade_image = models.CharField(db_column='TRADE_IMAGE', max_length=500, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'TRADE_DETAILS'

class TradeNotifications(models.Model):
    client_id = models.CharField(db_column='CLIENT_ID', primary_key=True, max_length=15)
    created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP')
    updated_timestamp = models.DateTimeField(db_column='UPDATED_TIMESTAMP', blank=True, null=True)
    platform_notification = models.IntegerField(db_column='PLATFORM_NOTIFICATION', blank=True, null=True)
    sms_notification = models.IntegerField(db_column='SMS_NOTIFICATION', blank=True, null=True)
    email_notification = models.IntegerField(db_column='EMAIL_NOTIFICATION', blank=True, null=True)
    caller_notification = models.IntegerField(db_column='CALLER_NOTIFICATION', blank=True, null=True)
    caller_id = models.IntegerField(db_column='CALLER_ID', blank=True, null=True)
    client_confirmation = models.IntegerField(db_column='CLIENT_CONFIRMATION', blank=True, null=True)
    device_id = models.CharField(db_column='DEVICE_ID', max_length=256, blank=True, null=True)
    platform = models.CharField(db_column='PLATFORM', max_length=15, blank=True, null=True)
    ip_address = models.CharField(db_column='IP_ADDRESS', max_length=50, blank=True, null=True)
    expired = models.IntegerField(db_column='EXPIRED', blank=True, null=True)
    trade_sent = models.IntegerField(db_column='TRADE_SENT', blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'TRADE_NOTIFICATIONS'
        unique_together = (('client_id', 'created_timestamp'),)

I want to perform a left join on another table on the same db using the following sql query:

SELECT TRADE_DETAILS.TRADE_NAME FROM TRADE_NOTIFICATIONS LEFT JOIN
  TRADE_DETAILS ON TRADE_NOTIFICATIONS.CREATED_TIMESTAMP =
  TRADE_DETAILS.CREATED_TIMESTAMP

Is there a more Django-Like way of doing this or should I just go with raw
sql?

Upon reading some answers I tried to do this :

TradeNotifications.objects.using('tradenotifications').all().values_list('trade_name', 'trade_details_created_timestamp')

but it raised an error :
django.core.exceptions.FieldError: Cannot resolve keyword 'trade_name' into field. Choices are: caller_id, caller_notification,


问:
parse "strange" date format
Hi I have trouble have parse date in this format:

```<code>1295716379
</code>```

I don’t what kind of date format is it.

Human readable value of this string is:

```<code>22. 1. 2011, 18.12
</code>```

Also I don’t know that this format is some cowboy coder format or it is some "standard".

And if it is possible parse string on the top to human readable format, for examle in C#, Java, C++.

Thank

答:
Verified, it is a unix timestamp.

The time is Sat Jan 22 17:12:59 2011 in UTC.

It looks like you have a local time value and your timezone is UTC+1.

In C/C++:

```<code>#define  _USE_32BIT_TIME_T
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
    int i = atoi("1295716379");
    time_t t = (time_t)i;
    puts(ctime( &t ));
    tm t_tm = *gmtime(&t);
    puts(asctime( &t_tm ));
    return 0;
}
</code>```

Output:

```<code>Sun Jan 23 02:12:59 2011

Sat Jan 22 17:12:59 2011
</code>```

Note that gmtime return UTC time value, localtime return local time value.

PS: I'm living in UTC+9 timezone

Title: parse "strange" date format

Body:
Hi I have trouble have parse date in this format:

1295716379

I don’t what kind of date format is it.

Human readable value of this string is:

22. 1. 2011, 18.12

Also I don’t know that this format is some cowboy coder format or it is some "standard".

And if it is possible parse string on the top to human readable format, for examle in C#, Java, C++.

Thank

Body:
Verified, it is a unix timestamp.

The time is Sat Jan 22 17:12:59 2011 in UTC.

It looks like you have a local time value and your timezone is UTC+1.

In C/C++:

#define  _USE_32BIT_TIME_T
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
    int i = atoi("1295716379");
    time_t t = (time_t)i;
    puts(ctime( &t ));
    tm t_tm = *gmtime(&t);
    puts(asctime( &t_tm ));
    return 0;
}

Output:

Sun Jan 23 02:12:59 2011

Sat Jan 22 17:12:59 2011

Note that gmtime return UTC time value, localtime return local time value.

PS: I'm living in UTC+9 timezone


问:
Does CDI @RequestScoped prevent concurrency problems?
Let us say we have a class:

```<code>@RequestScoped
public class FooService {
     private NonThreadSafeGenerator generator = new NonThreadSafeGenerator();

     public String generateId() {
          return this.generator.generateId();
     }
}
</code>```

And we run our application under some servlet-container. Will it be thread-safe? In other words, is it guaranteed that RequestScoped's bean is always visible only within single thread?

答:
Your FooService bean instance is guaranteed to be used by only one thread at a time.

However, it's still possible that NonThreadSafeGenerator.generateId() is not thread safe. It could for example be relying on static instance variables for state, or invoking a method on another object or class that does this.

Body:
Let us say we have a class:

@RequestScoped
public class FooService {
     private NonThreadSafeGenerator generator = new NonThreadSafeGenerator();

     public String generateId() {
          return this.generator.generateId();
     }
}

And we run our application under some servlet-container. Will it be thread-safe? In other words, is it guaranteed that RequestScoped's bean is always visible only within single thread?


问:
C++ pointer parameters difference
Consider i have two function headers, where both functions returns array of structs by parameter:

```<code>void FunctionOne(int *count, MyStruct **my_structs);

void FunctionOne(int *&count, MyStruct *&my_structs);
</code>```

What is the difference between these two notation?
I searched but couldn't find these particular options compared and explained.

答: The first one is just pointers which means that you can't do count = new int(4) or assign it to new memory if you wish to return a changed memory location. The second one allows you to assign the pointers to new memory locations. This is because without a reference you can not use the assignment operator on the parameters.

Title: C++ pointer parameters difference

Body:
Consider i have two function headers, where both functions returns array of structs by parameter:

void FunctionOne(int *count, MyStruct **my_structs);

void FunctionOne(int *&count, MyStruct *&my_structs);

What is the difference between these two notation?
I searched but couldn't find these particular options compared and explained.


问:
Not able to type in textfield in iphone simulator using Mac Keyboard?
I'm working on a basic iOS app which supports both portrait and landscape modes. When the iPhone simulator keyboard is open in landscape and I'm switching the app to portrait mode I'm unable to type anything in any text field using my Mac physical keyboard.

Has anyone experienced this before? Is it a known bug?

答:
In Xcode 9 I faced the same problem with the iPhone 8+ simulator. I was able to solve it this way:

Open ~/Library/Preferences/com.apple.iphonesimulator.plist file

Find the problematic simulator identifier (shown in the Devices and Simulator window)

Set CaptureKeyboardInput value to YES

Restart the Simulator


问:
JS Scrolling doesn't seem to work on my website

So I am trying to use the smooth scrolling animation used in this template:

https://blackrockdigital.github.io/startbootstrap-scrolling-nav/

After adding the js files to my directory, including the basic JQuery files, I've seen the custom .js file that adds the scrolling uses the .class parameter in an anchor tag to detect if clicking it should trigger the smoothscrolling. So I added those to my anchor tags.

Below is the relevant code.

I will include a live preview too.

index.html file

```<code><!-- Navigation section -->
<section class="nav" id="nav">
    <div class="container">
        <div class="row" style="width: 100%; text-align: center;">
            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                <a class="js-scroll-trigger btn btn-lg btn-nav" href="#about">About me</a>
            </div>

            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                <a class="js-scroll-trigger btn btn-lg btn-nav" href="#work">My work</a>
            </div>

            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                <a class="js-scroll-trigger btn btn-lg btn-nav" href="#contact">Contact</a>
            </div>
        </div>
    </div>
</section>
</code>```

Script imports in index.html

```<code><!-- Import js -->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="js/scrolling-nav.js"></script>
</code>```

Scrolling-nav.js

```<code>(function($) {
  "use strict"; // Start of use strict

  // Smooth scrolling using jQuery easing
  $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, "easeInOutExpo");
        return false;
      }
    }
  });

})(jQuery); // End of use strict
</code>```

I have nearly no experience with JQuery / JS, so it's hard for me to understand where it might be going wrong.

Here is a live preview of the website with above code in it:

Live preview

Full code:

Github link

If there's any information missing, let me know.

答: jQuery is missing, and you're using jQuery in your click event...

Body:
So I am trying to use the smooth scrolling animation used in this template:

https://blackrockdigital.github.io/startbootstrap-scrolling-nav/

After adding the js files to my directory, including the basic JQuery files, I've seen the custom .js file that adds the scrolling uses the .class parameter in an anchor tag to detect if clicking it should trigger the smoothscrolling. So I added those to my anchor tags.

Below is the relevant code.

I will include a live preview too.

index.html file

                About me

                My work

                Contact

Script imports in index.html

Scrolling-nav.js

(function($) {
  "use strict"; // Start of use strict

  // Smooth scrolling using jQuery easing
  $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, "easeInOutExpo");
        return false;
      }
    }
  });

})(jQuery); // End of use strict

I have nearly no experience with JQuery / JS, so it's hard for me to understand where it might be going wrong.

Here is a live preview of the website with above code in it:

Live preview

Full code:

Github link

If there's any information missing, let me know.


问:
How can I make ajax parameters dynamic?
Here is a part of my code:

```<code>if ( external_link ) {
   data = {external_link : external_link};
} else {
   data = form_data;
}

$.ajax({
    url: base_url + frm.attr('action'),
    type: frm.attr('method'),
    data: data,
    cache: false,
    contentType: false, // this
    processData: false, // and this should be removed when external_link isn't false
    success: function (imageUpload) {
</code>```

All I'm trying to do is making contentType: false and processData: false parameters dynamic. I mean, if the condition above was true, then those two mentioned parameters should be removed. How can I do that?

答:
Pass an object into ajax call instead creating a literal object there? Preferably by wrapping a function around the call.

Code below is not direct implementation but showcase of principle:

```<code>var makeAjaxAndExecute = function(param1, param2){
  var ajaxObjectInitiate = {object literal here}
  ajaxObjectInitiate.param1 = param1;
  ajaxObjectInitiate.param2 = param2;

  $.ajax(ajaxObjectInitiate //.... rest of your code
}
</code>```

You can further separate configuring the object and actually making the call, you can have general generator of requests elsewhere totally depends what are your needs and how complex do you wanna / need it to be.

If you need to do it on a lot of calls, I would opt for totally isolated builder that holds onto object and has getters and setters for options and possibly internal states and logic. And once object is set simple pass it to ajax call.

Scale-able, maintainable and easy to debug but not needed if you have simple logic as this.

Title: How can I make ajax parameters dynamic?

Body:
Here is a part of my code:

if ( external_link ) {
   data = {external_link : external_link};
} else {
   data = form_data;
}

$.ajax({
    url: base_url + frm.attr('action'),
    type: frm.attr('method'),
    data: data,
    cache: false,
    contentType: false, // this
    processData: false, // and this should be removed when external_link isn't false
    success: function (imageUpload) {

All I'm trying to do is making contentType: false and processData: false parameters dynamic. I mean, if the condition above was true, then those two mentioned parameters should be removed. How can I do that?

Body:
Pass an object into ajax call instead creating a literal object there? Preferably by wrapping a function around the call.

Code below is not direct implementation but showcase of principle:

var makeAjaxAndExecute = function(param1, param2){
  var ajaxObjectInitiate = {object literal here}
  ajaxObjectInitiate.param1 = param1;
  ajaxObjectInitiate.param2 = param2;

  $.ajax(ajaxObjectInitiate //.... rest of your code
}

You can further separate configuring the object and actually making the call, you can have general generator of requests elsewhere totally depends what are your needs and how complex do you wanna / need it to be.

If you need to do it on a lot of calls, I would opt for totally isolated builder that holds onto object and has getters and setters for options and possibly internal states and logic. And once object is set simple pass it to ajax call.

Scale-able, maintainable and easy to debug but not needed if you have simple logic as this.


问:
Why torrent can't download some files via HTTP?
There is a torrent file in which the web seed is configured. Most files are loaded normally, but when downloading some files (text\american.ini) the connection to the server suddenly terminates and the download stops. This can be checked if, when adding a torrent, select only this file to download. At the same time, this file is loaded normally from the browser. Because of what it can be? Tested on uTorrent and libtorrent.

Here you can download the torrent file and check it personally.

Download

答:
There are two different kinds of Web Seeds, BEP 19 and BEP 17, and one assumes that the server is configured to handle working with torrent clients, your torrent has a BEP 19 link that's supposed to point to a file or a directory that has the same name as the torrent and that directory should contain the files in the torrent.

Your torrent name looks like this:

```<code>files/licence.txt
</code>```

and your Web Seed looks like this:

```<code>https://website.com/projects/crmp/
</code>```

It's not working because the Web Seed URL is wrong.

Body:
There are two different kinds of Web Seeds, BEP 19 and BEP 17, and one assumes that the server is configured to handle working with torrent clients, your torrent has a BEP 19 link that's supposed to point to a file or a directory that has the same name as the torrent and that directory should contain the files in the torrent.

Your torrent name looks like this:

files/licence.txt

and your Web Seed looks like this:

https://website.com/projects/crmp/

It's not working because the Web Seed URL is wrong.


问:
Clear File List in Fine Uploader in purpose to reupload just one file
I use fine uploader to upload just one file on 'edit entity' page. Entity should have one file assosiated with it. I should show user a popup message with error if he selects more than 1 file in file browser while uploading. I want to set limit to fineUploader and use this setting:

```<code>itemLimit: 1
</code>```

The issue is that if I load one first file it works ok, but if I try to reload it I have validation error (I have my own code for UI that clears control(link) with uploaded file and writes new link there). I know that error appiars because there is a fileList inside Fine Uploader and for it I upload - not reload - another file.

I tryed some code to clear fine uploader state. For example:

```<code>onComplete: function (id) {
                    qq(this.getItemByFileId(id)).remove();
                },
</code>```

But it works only for UI elements, not for "inside" data.
Actually, after several hours googling this issue it seems to me that my problem doesn't have any solution, but probably someone knows...

答:
ok, so, I found the answer. The function that helped me is reset();
It resets the state of fine uploader and file list, sure, also. Now I have validation for case if user select several files for upload in file browser and at the same time I don't have any erros while uploading ONE file several times. Here is my version of 'onAllComplete' event.

```<code>onAllComplete: function (succeeded, failed) {
                    //some code that saves file on the server
                    this.reset(); // the fix
                },
</code>```

Body:
I use fine uploader to upload just one file on 'edit entity' page. Entity should have one file assosiated with it. I should show user a popup message with error if he selects more than 1 file in file browser while uploading. I want to set limit to fineUploader and use this setting:

itemLimit: 1

The issue is that if I load one first file it works ok, but if I try to reload it I have validation error (I have my own code for UI that clears control(link) with uploaded file and writes new link there). I know that error appiars because there is a fileList inside Fine Uploader and for it I upload - not reload - another file.

I tryed some code to clear fine uploader state. For example:

onComplete: function (id) {
                    qq(this.getItemByFileId(id)).remove();
                },

But it works only for UI elements, not for "inside" data.
Actually, after several hours googling this issue it seems to me that my problem doesn't have any solution, but probably someone knows...

Body:
ok, so, I found the answer. The function that helped me is reset();
It resets the state of fine uploader and file list, sure, also. Now I have validation for case if user select several files for upload in file browser and at the same time I don't have any erros while uploading ONE file several times. Here is my version of 'onAllComplete' event.

onAllComplete: function (succeeded, failed) {
                    //some code that saves file on the server
                    this.reset(); // the fix
                },


答:
What about defining the minimum set of options first, and add the other two if the condition is met?</p>

```<code>var options = {
    url: base_url + frm.attr('action'),
    type: frm.attr('method'),
    data: data,
    cache: false,
    success: function (imageUpload) {
    ...
};

if ( external_link ) { // the external link entered

    options.contentType: false; // this
    options.processData: false; // and this should be removed when external_link isn't false
    options.data = {external_link : external_link};
} else {
   options.data = form_data;
}

$.ajax(options);
</code>```

Title: How can I make ajax parameters dynamic?

Body:
What about defining the minimum set of options first, and add the other two if the condition is met?

var options = {
    url: base_url + frm.attr('action'),
    type: frm.attr('method'),
    data: data,
    cache: false,
    success: function (imageUpload) {
    ...
};

if ( external_link ) { // the external link entered

    options.contentType: false; // this
    options.processData: false; // and this should be removed when external_link isn't false
    options.data = {external_link : external_link};
} else {
   options.data = form_data;
}

$.ajax(options);