问:
How to ignore an html tag of a 3rd party component in an angular4 unit test?
I have looked in the docs, checked SO, and tried different solutions/work arounds and I just can't seem to get this to work. I am writing a unit test for an angular4 app with karma/jasmine. It tests a component which makes use of a third party component ckeditor (https://www.npmjs.com/package/ng2-ckeditor). Although when I run the test I get this error...

Failed: Uncaught (in promise): Error: Template parse errors:
  'ckeditor' is not a known element:
  1. If 'ckeditor' is an Angular component, then verify that it is part of this module.
  2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("[ERROR ->]

 "): ng:///DynamicTestModule/CkEditorComponent.html@0:0 Error: Template parse errors: 'ckeditor' is not a known element:
    1. If 'ckeditor' is an Angular component, then verify that it is part of this module.
    2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("[ERROR ->] "): ng:///DynamicTestModule/CkEditorComponent.html@0:0 ...

My unit test file looks like this

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ManageInvanareLoginComponent } from './manage-invanare-login.component';
import {CreateDriftInfoComponent} from "../create-drift-info/create-drift-info.component";
import {CreateLoginTextComponent} from "../create-login-text/create-login-text.component";
import {MdInputContainer, MdInputModule} from "@angular/material";
import {CKEditorModule} from "ng2-ckeditor";
import {CkEditorComponent} from "../ck-editor/ck-editor.component";

describe('ManageInvanareLoginComponent', () => {
  let component: ManageInvanareLoginComponent;
  let fixture: ComponentFixture<ManageInvanareLoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        CkEditorComponent,
        CreateDriftInfoComponent,
        CreateLoginTextComponent,
        ManageInvanareLoginComponent,
        MdInputContainer
      ],
      providers:[
        CKEditorModule,
        MdInputModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ManageInvanareLoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

My app.module.ts file looks like this...

```<code>    ...
           import { NO_ERRORS_SCHEMA } from "@angular/core";
        import { CKEditorModule } from 'ng2-ckeditor';

            @NgModule({   declarations: [
                AppComponent,
                WelcomeComponent,
                DriftInfoDisplayComponent,
                LoginInfoComponent,
                SideBarComponent,
                CkEditorComponent,
                ManageInvanareLoginComponent,
                CreateDriftInfoComponent,
                CreateLoginTextComponent   ],   exports:[
                CkEditorComponent   ],   imports: [
                CKEditorModule,
                BrowserModule,
                FormsModule,
                HttpModule,
                AppRoutingModule,
                BrowserAnimationsModule,
                MdGridListModule,
                MdButtonModule,
                MdInputModule   ],   providers: [
                PathsService,
                DriftInfoDisplayComponent,
                DriftInfoService
                ],
            schemas:[NO_ERRORS_SCHEMA],
            bootstrap: [AppComponent] })
            export class AppModule { }
</code>```

I dont event want to test the ckeditor element but I do want to test other functions in the component which contains this creditor element tag.

Is there a way that I can tell the test to just ignore this tag?

答:
You should also add schemas:[NO_ERRORS_SCHEMA] to your test configuration

```<code>TestBed.configureTestingModule({
  ...
  schemas:[NO_ERRORS_SCHEMA],
});
</code>```

See also

https://blog.nrwl.io/essential-angular-testing-192315f8be9b

Body:
I have looked in the docs, checked SO, and tried different solutions/work arounds and I just can't seem to get this to work. I am writing a unit test for an angular4 app with karma/jasmine. It tests a component which makes use of a third party component ckeditor (https://www.npmjs.com/package/ng2-ckeditor). Although when I run the test I get this error...

Failed: Uncaught (in promise): Error: Template parse errors:
  'ckeditor' is not a known element:
  1. If 'ckeditor' is an Angular component, then verify that it is part of this module.
  2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("[ERROR ->]

 "): ng:///DynamicTestModule/CkEditorComponent.html@0:0 Error: Template parse errors: 'ckeditor' is not a known element:
    1. If 'ckeditor' is an Angular component, then verify that it is part of this module.
    2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("[ERROR ->] "): ng:///DynamicTestModule/CkEditorComponent.html@0:0 ...

My unit test file looks like this

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ManageInvanareLoginComponent } from './manage-invanare-login.component';
import {CreateDriftInfoComponent} from "../create-drift-info/create-drift-info.component";
import {CreateLoginTextComponent} from "../create-login-text/create-login-text.component";
import {MdInputContainer, MdInputModule} from "@angular/material";
import {CKEditorModule} from "ng2-ckeditor";
import {CkEditorComponent} from "../ck-editor/ck-editor.component";

describe('ManageInvanareLoginComponent', () => {
  let component: ManageInvanareLoginComponent;
  let fixture: ComponentFixture<ManageInvanareLoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        CkEditorComponent,
        CreateDriftInfoComponent,
        CreateLoginTextComponent,
        ManageInvanareLoginComponent,
        MdInputContainer
      ],
      providers:[
        CKEditorModule,
        MdInputModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ManageInvanareLoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

My app.module.ts file looks like this...

    ...
           import { NO_ERRORS_SCHEMA } from "@angular/core";
        import { CKEditorModule } from 'ng2-ckeditor';

            @NgModule({   declarations: [
                AppComponent,
                WelcomeComponent,
                DriftInfoDisplayComponent,
                LoginInfoComponent,
                SideBarComponent,
                CkEditorComponent,
                ManageInvanareLoginComponent,
                CreateDriftInfoComponent,
                CreateLoginTextComponent   ],   exports:[
                CkEditorComponent   ],   imports: [
                CKEditorModule,
                BrowserModule,
                FormsModule,
                HttpModule,
                AppRoutingModule,
                BrowserAnimationsModule,
                MdGridListModule,
                MdButtonModule,
                MdInputModule   ],   providers: [
                PathsService,
                DriftInfoDisplayComponent,
                DriftInfoService
                ],
            schemas:[NO_ERRORS_SCHEMA],
            bootstrap: [AppComponent] })
            export class AppModule { }

I dont event want to test the ckeditor element but I do want to test other functions in the component which contains this creditor element tag.

Is there a way that I can tell the test to just ignore this tag?

Body:
You should also add schemas:[NO_ERRORS_SCHEMA] to your test configuration

TestBed.configureTestingModule({
  ...
  schemas:[NO_ERRORS_SCHEMA],
});

See also

https://blog.nrwl.io/essential-angular-testing-192315f8be9b


来源: stackexchange

问:
QT auto save screenshot with naming template
I want to save multiple screenshot every 10 second with different name,

i want to save like this

here my current code

```<code>      QScreen *screen = QGuiApplication::primaryScreen();
      QPixmap pic  = screen->grabWindow(0);
      pic.save("C:/Users/Coding/Desktop/img/desktop_1.png");
</code>```

答:
You can format a QString to your file name and append a counter at the end, like this:</p>

```<code>int counter = 1;
auto fileName = QString("C:/Users/Coding/Desktop/img/desktop_%1.png").arg(counter);
counter++;
pic.save(fileName);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to save multiple screenshot every 10 second with different name,

i want to save like this

here my current code

      QScreen *screen = QGuiApplication::primaryScreen();
      QPixmap pic  = screen->grabWindow(0);
      pic.save("C:/Users/Coding/Desktop/img/desktop_1.png");

Body:
You can format a QString to your file name and append a counter at the end, like this:

int counter = 1;
auto fileName = QString("C:/Users/Coding/Desktop/img/desktop_%1.png").arg(counter);
counter++;
pic.save(fileName);


问:
Cannot install bmon using opkg under Openwrt?
After running opkg install bmon, I got this error:

```<code>root@OpenWrt:~# opkg install bmon
Installing bmon (4.0-1) to root...
Downloading http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/packages/bmon_4.0-1_ar71xx.ipk.
Multiple packages (libpthread and libpthread) providing same name marked HOLD or PREFER. Using latest.
Installing libncursesw (5.9-3) to root...
Downloading http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/base/libncursesw_5.9-3_ar71xx.ipk.
Configuring iftop.
//usr/lib/opkg/info/iftop.postinst: line 4: default_postinst: not found
Collected errors:
 * check_data_file_clashes: Package libncursesw wants to install file /usr/lib/libform.so
    But that file is already provided by package  * libncurses
 * check_data_file_clashes: Package libncursesw wants to install file /usr/lib/libmenu.so
    But that file is already provided by package  * libncurses
 * check_data_file_clashes: Package libncursesw wants to install file /usr/lib/libncurses.so
    But that file is already provided by package  * libncurses
 * check_data_file_clashes: Package libncursesw wants to install file /usr/lib/libpanel.so
    But that file is already provided by package  * libncurses
 * opkg_install_cmd: Cannot install package bmon.
 * pkg_run_script: package "iftop" postinst script returned status 127.
 * opkg_configure: iftop.postinst returned 127.
</code>```

I have searched for quite a while, but there is few info about bmon.

And this is my opkg.conf

```<code>root@OpenWrt:~# cat /etc/opkg.conf
#src/gz attitude_adjustment http://downloads.openwrt.org/attitude_adjustment/12.09/ar71xx/generic/packages
dest root /
dest ram /tmp
lists_dir ext /var/opkg-lists
option overlay_root /overlay
src/gz chaos_calmer_base http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/base
src/gz chaos_calmer_packages http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/packages
src/gz chaos_calmer_luci http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/luci
src/gz chaos_calmer_routing http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/routing
src/gz chaos_calmer_telephony http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/telephony
src/gz chaos_calmer_management http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/management
</code>```

答:
From the logs it seems like bmon has dependency on libncursesw which tries to install some files which were already available from libncurses.
Since both the packages has similar functionalities, you can force the installation by

opkg --nodeps install bmon

This will install the required package but leave the dependencies.

Body:
After running opkg install bmon, I got this error:

root@OpenWrt:~# opkg install bmon
Installing bmon (4.0-1) to root...
Downloading http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/packages/bmon_4.0-1_ar71xx.ipk.
Multiple packages (libpthread and libpthread) providing same name marked HOLD or PREFER. Using latest.
Installing libncursesw (5.9-3) to root...
Downloading http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/base/libncursesw_5.9-3_ar71xx.ipk.
Configuring iftop.
//usr/lib/opkg/info/iftop.postinst: line 4: default_postinst: not found
Collected errors:
 * check_data_file_clashes: Package libncursesw wants to install file /usr/lib/libform.so
    But that file is already provided by package  * libncurses
 * check_data_file_clashes: Package libncursesw wants to install file /usr/lib/libmenu.so
    But that file is already provided by package  * libncurses
 * check_data_file_clashes: Package libncursesw wants to install file /usr/lib/libncurses.so
    But that file is already provided by package  * libncurses
 * check_data_file_clashes: Package libncursesw wants to install file /usr/lib/libpanel.so
    But that file is already provided by package  * libncurses
 * opkg_install_cmd: Cannot install package bmon.
 * pkg_run_script: package "iftop" postinst script returned status 127.
 * opkg_configure: iftop.postinst returned 127.

I have searched for quite a while, but there is few info about bmon.

And this is my opkg.conf

root@OpenWrt:~# cat /etc/opkg.conf
#src/gz attitude_adjustment http://downloads.openwrt.org/attitude_adjustment/12.09/ar71xx/generic/packages
dest root /
dest ram /tmp
lists_dir ext /var/opkg-lists
option overlay_root /overlay
src/gz chaos_calmer_base http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/base
src/gz chaos_calmer_packages http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/packages
src/gz chaos_calmer_luci http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/luci
src/gz chaos_calmer_routing http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/routing
src/gz chaos_calmer_telephony http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/telephony
src/gz chaos_calmer_management http://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/packages/management


问:
Is there any alternate similar to NameValueCollection collection in C#
NameValueCollection can hold multiple string values under a single key.

Is there any collection where I can hold multiple OBJECT (not string) under a single key?

答:
You can have a look at the MultiDictionary in the corefxlab repository. Install the  Microsoft.Experimental.Collections Nuget:

```<code>MultiDictionary<string, int> myDictionary = new MultiDictionary<string, int>();
myDictionary.Add("key", 1);
myDictionary.Add("key", 2);
myDictionary.Add("key", 3);
//myDictionary["key"] now contains the values 1, 2, and 3
</code>```

You can read the following post about the MultiDictionary: https://blogs.msdn.microsoft.com/dotnet/2014/06/20/would-you-like-a-multidictionary/

Body:
You can have a look at the MultiDictionary in the corefxlab repository. Install the  Microsoft.Experimental.Collections Nuget:

MultiDictionary<string, int> myDictionary = new MultiDictionary<string, int>();
myDictionary.Add("key", 1);
myDictionary.Add("key", 2);
myDictionary.Add("key", 3);
//myDictionary["key"] now contains the values 1, 2, and 3

You can read the following post about the MultiDictionary: https://blogs.msdn.microsoft.com/dotnet/2014/06/20/would-you-like-a-multidictionary/


问:
Find if two strings are same in an array?
I have an array of objects. Each object has an property called title , I want to know if two object has the same title. How to do that in swift?</p>

答:
```<code>let s = Set(arr.map{$0.title})
print("found duplicate title?", arr.count != s.count)
</code>```

in case your title doesn't conform to Hashable protocol, simply use

```<code>let s1 = Set(arr1.map{"\($0.title)"})
print("found duplicate title?", arr1.count != s1.count)
</code>```

Body:
let s = Set(arr.map{$0.title})
print("found duplicate title?", arr.count != s.count)

in case your title doesn't conform to Hashable protocol, simply use

let s1 = Set(arr1.map{"\($0.title)"})
print("found duplicate title?", arr1.count != s1.count)


问:
Function is returning Undefined
I need small help in a small code. The function is returning undefined and i want to return the console.log of the sum. The code is here http://jsbin.com/jedigigigo/edit?js,console

var addDigits = function a(num) {
  var length = num.toString().length;
  var value = num.toString();
  var sum = 0;
  for (var i = 0; i < value.length; i++) {
    sum += Number(value[i]);
  }
  if (sum > 9) {
    a(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(addDigits(38));```

答:
Add return in if statement :-

```<code>/**
* @param {number} num
* @return {number}
*/
</code>```

var addDigits = function a(num) {
  var length = num.toString().length;
  var value = num.toString();
  var sum = 0;
  for (var i = 0; i < value.length; i++) {
    sum += Number(value[i]);
  }
  if (sum > 9) {
    return a(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(addDigits(38));```

Title: Function is returning Undefined

Body:
Add return in if statement :-

/**
* @param {number} num
* @return {number}
*/

var addDigits = function a(num) {
  var length = num.toString().length;
  var value = num.toString();
  var sum = 0;
  for (var i = 0; i < value.length; i++) {
    sum += Number(value[i]);
  }
  if (sum > 9) {
    return a(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(addDigits(38));


问:
How does CouchDB handle data?
How is authentication handled in CouchDB?  Say I create Admin users and Readers, and assign them roles.  Say also that I assign them to an individual database.  On the file system level, is there a way for someone who is not authenticating, to look at the data that is stored in the database?  Is the data stored as plain text in a file?  How is this handled in CouchDB?</p>

答:
Through the database interface, roles are just as strong as they are in any other database. As long as they can't get hold of the files, it's absolutely as secure as your permissions and passwords. However, if they do, there's absolutely no compression or encryption built into CouchDB. Encrypt the data in your code (or your abstraction layer if you use one) if file system access control is a concern - of course anyone who gets hold of your DB filesystem could probably find your code's decryption keys, as well.

It's not a plain text file, it's a binary file that combines the data and indices, but you could copy it to a local CouchDB install and view it that way, or just open it in a good text editor. The data chunks are stored in plain text (JSON, actually) and isn't hard to read, though binary attachments remain binary.

ContentLicense: CC BY-SA 2.5

Title: How does CouchDB handle data?


问:
How to disable button onclick in Reactjs?
I had a condition if the two textfield are the same it will proceed, if not then the button is disabled. I know I'm doing this wrong.</p>

```<code>onSubmit() {
        debugger
        if  (this.state.password == this.state.password2)
            alert('same');
        else
            alert('error');
            this.disable;
}
</code>```

答:
You can do that in your render function:

```<code>render() {
  const submitDisabled = this.state.password !== this.state.password2

  return (
    // ...
      <button disabled={submitDisabled}>Submit</button>
    // ...
  )
}
</code>```

Body:
I had a condition if the two textfield are the same it will proceed, if not then the button is disabled. I know I'm doing this wrong.

onSubmit() {
        debugger
        if  (this.state.password == this.state.password2)
            alert('same');
        else
            alert('error');
            this.disable;
}

Body:
You can do that in your render function:

render() {
  const submitDisabled = this.state.password !== this.state.password2

  return (
    // ...
      <button disabled={submitDisabled}>Submit</button>
    // ...
  )
}


问:
Pattern substitution in Python
Looking for some alternative to clean a tabular file containing informations between parenthesis.
It will be the first step to include in a pipeline and I need to remove every value inside parenthesis (parenthesis included).

What I have

```<code>> Otu00467  Bacteria(100);Gracilibacteria(99);unclassified(99);unclassified(99);unclassified(99);unclassified(99);
> Otu00469  Bacteria(100);Proteobacteria(96);unclassified(96);unclassified(96);unclassified(96);unclassified(96);
> Otu00470  Bacteria(100);Proteobacteria(100);Alphaproteobacteria(100);Rhodospirillales(100);Rhodospirillaceae(100);Azospirillum(54);
</code>```

What I desire:

```<code> Otu00467   Bacteria;Gracilibacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00469   Bacteria;Proteobacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00470   Bacteria;Proteobacteria;Alphaproteobacteria;Rhodospirillales;Rhodospirillaceae;Azospirillum;
</code>```

My first approach was to split the second column by ";" , "("  , ")" and further join everything. Not bad but too ugly.

Thank you.

答:
```<code>import re
new_string = re.sub(r'\(.*?\)', '', your_string)
</code>```

Title: Pattern substitution in Python

Body:
Looking for some alternative to clean a tabular file containing informations between parenthesis.
It will be the first step to include in a pipeline and I need to remove every value inside parenthesis (parenthesis included).

What I have

> Otu00467  Bacteria(100);Gracilibacteria(99);unclassified(99);unclassified(99);unclassified(99);unclassified(99);
> Otu00469  Bacteria(100);Proteobacteria(96);unclassified(96);unclassified(96);unclassified(96);unclassified(96);
> Otu00470  Bacteria(100);Proteobacteria(100);Alphaproteobacteria(100);Rhodospirillales(100);Rhodospirillaceae(100);Azospirillum(54);

What I desire:

 Otu00467   Bacteria;Gracilibacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00469   Bacteria;Proteobacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00470   Bacteria;Proteobacteria;Alphaproteobacteria;Rhodospirillales;Rhodospirillaceae;Azospirillum;

My first approach was to split the second column by ";" , "("  , ")" and further join everything. Not bad but too ugly.

Thank you.


问:
How to write a simple generic Core Data function for all Entities
EDIT: Specifically using Swift Generics

I want a countAll() function for all of my entities and I'm hoping to achieve this by writing one generic function.

The following handles an entity called 'Event', but I want to handle an entity named 'T'.

I'm not sure how to write a generic function like this. Could someone help please?

```<code>func countAll() -> Int {
    let request: NSFetchRequest<Event> = Event.fetchRequest()
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}
</code>```

This is the closest I can get before I hit an error:

```<code>func count<T: NSFetchRequestResult>(entityName: String) -> Int {
    let request = NSFetchRequest<T>(entityName: entityName)
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}
</code>```

答:
You can pass the managed object class instead of NSFetchRequestResult
to the generic function:

```<code>func countAll<T: NSManagedObject>(entity: T.Type) -> Int {
    let entityName = String(describing: entity)
    let request = NSFetchRequest<T>(entityName: entityName)
    do {
        return try thePersistentContainer.viewContext.count(for: request)
    } catch {
        print(error.localizedDescription)
        return 0
    }
}

let count = countAll(entity: YourEntity.self)
</code>```

An alternative is to define an extension method on NSManagedObject
(similarly as in How can I create instances of managed object subclasses in a NSManagedObject Swift extension?):

```<code>extension NSManagedObject {

    class func countAll() -> Int {
        let eName = String(describing: self)
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: eName)
        do {
            return try thePersistentContainer.viewContext.count(for: request)
        } catch {
            print(error.localizedDescription)
            return 0
        }
    }
}

let count = YourEntity.countAll()
</code>```

Body:
EDIT: Specifically using Swift Generics

I want a countAll() function for all of my entities and I'm hoping to achieve this by writing one generic function.

The following handles an entity called 'Event', but I want to handle an entity named 'T'.

I'm not sure how to write a generic function like this. Could someone help please?

func countAll() -> Int {
    let request: NSFetchRequest<Event> = Event.fetchRequest()
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}

This is the closest I can get before I hit an error:

func count<T: NSFetchRequestResult>(entityName: String) -> Int {
    let request = NSFetchRequest<T>(entityName: entityName)
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}

Body:
You can pass the managed object class instead of NSFetchRequestResult
to the generic function:

func countAll<T: NSManagedObject>(entity: T.Type) -> Int {
    let entityName = String(describing: entity)
    let request = NSFetchRequest<T>(entityName: entityName)
    do {
        return try thePersistentContainer.viewContext.count(for: request)
    } catch {
        print(error.localizedDescription)
        return 0
    }
}

let count = countAll(entity: YourEntity.self)

An alternative is to define an extension method on NSManagedObject
(similarly as in How can I create instances of managed object subclasses in a NSManagedObject Swift extension?):

extension NSManagedObject {

    class func countAll() -> Int {
        let eName = String(describing: self)
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: eName)
        do {
            return try thePersistentContainer.viewContext.count(for: request)
        } catch {
            print(error.localizedDescription)
            return 0
        }
    }
}

let count = YourEntity.countAll()


答:
```<code> if(sum>9) {
     return a(sum); // You forgot to return a value from recursive call.
 }
</code>```

Although the code looks really weird :)

Title: Function is returning Undefined

Body:
I need small help in a small code. The function is returning undefined and i want to return the console.log of the sum. The code is here http://jsbin.com/jedigigigo/edit?js,console

var addDigits = function a(num) {
  var length = num.toString().length;
  var value = num.toString();
  var sum = 0;
  for (var i = 0; i < value.length; i++) {
    sum += Number(value[i]);
  }
  if (sum > 9) {
    a(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(addDigits(38));

Body:
 if(sum>9) {
     return a(sum); // You forgot to return a value from recursive call.
 }

Although the code looks really weird :)


答:
First, dont check onSubmit but on change (you dont want to disable it AFTER it was submitted) for both your input.
Add a state value for your disabledButton, and set it to false only if both input are the same (in the onChange event).

You can set disabled button inside your JSX like this

```<code><button disabled={this.state.disabledButton} />
</code>```

Title: How to disable button onclick in Reactjs?

Body:
First, dont check onSubmit but on change (you dont want to disable it AFTER it was submitted) for both your input.
Add a state value for your disabledButton, and set it to false only if both input are the same (in the onChange event).

You can set disabled button inside your JSX like this

<button disabled={this.state.disabledButton} />


问:
How to generate a random, unique, alphanumeric string?
How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends you an email with a link, and you have to click that link in order to verify your account

How can I generate one of those using PHP?

答:
I'm here with some good research data based on the functions provided by Scott's answer. So I set up a Digital Ocean droplet just for this 5-day long automated test and stored the generated unique strings in a MySQL database.

During this test period, I used 5 different lengths (5, 10, 15, 20, 50) and +/-0.5 million records were inserted for each length. During my test, only the length 5 generated +/-3K duplicates out of 0.5 million and the remaining lengths didn't generate any duplicates. So we can say that if we use a length of 15 or above with Scott's functions, then we can generate highly reliable unique strings. Here is the table showing my research data:

Update

I created a simple Heroku app using these functions that returns the token as a JSON response. The app can be accessed at https://uniquestrings.herokuapp.com/api/token?length=15

ContentLicense: CC BY-SA 4.0


问:
How can I update NodeJS and NPM to their latest versions?

I just installed Node.js & NPM (Node Package Manager)

I installed NPM for access to additional Node.js Modules.

After I installed Node.js & NPM I noticed that neither were the latest versions available.

I would like to know: How do I upgrade Node.js, NPM, and my Node.js Modules to their latest versions?

Do I need to uninstall Node.js & NPM and reinstall the latest versions?

Here is the link to what I have tried so far. This link is a section from npm.

答:
To update npm :

```<code>npm install npm@{version} -g
</code>```

to update npm to the latest version:

```<code>npm install npm@latest -g
</code>```

and to check the version :

```<code>npm -v
</code>```

to update node js :

```<code>sudo npm cache clean -f
sudo npm install -g n
sudo n stable
</code>```

to check :

```<code>node -v
</code>```

Body:
To update npm :

npm install npm@{version} -g

to update npm to the latest version:

npm install npm@latest -g

and to check the version :

npm -v

to update node js :

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

to check :

node -v


问:
SQL multiples select and group by using "first 1"
Despite the confusing title, I think it's pretty simple
I have a database in the following format:
(EXAMPLE)

```<code>---------------------------------
| X101| X102      | X103 | X104 |
---------------------------------
| COD | PROD_NAME | TYPE | INFO |

| 05  | PROD A1   | 05   | ABC  |
| 019 | TAPE 01   | 05   | ABC  |
| 052 | MASTER 0  | 03   | ABC  |
| 111 | APPLE     | 03   | ABC  |
| 150 | RANDOM0   | 05   | ABC  |
| 235 | ITEM661   | 03   | ABC  |
| 290 | ITEM874   | 03   | ABC  |
---------------------------------
</code>```

I've tried in many ways, but I have not come up with a result. The database has a little more than 20 thousand products, I wanted to know how to
'select first 1' of each TYPE('group by TYPE' and show only the 'first 1' of each type)

Database is Firebird 1.5.

答:
One might use stored procedures.

```<code>CREATE PROCEDURE SelectFirstOfTypes()
         RETURNS (COD INT, PROD_NAME VARCHAR(15), TYPE INT, INFO VARCHAR(15)) AS
BEGIN
  FOR SELECT DISTINCT TYPE FROM EXAMPLE INTO :TYPE DO BEGIN
    FOR SELECT FIRST 1 e.COD, e.PROD_NAME, e.INFO FROM EXAMPLE e
    WHERE :TYPE = e.TYPE  INTO :COD, :PROD_NAME, :INFO DO BEGIN
       SUSPEND;
    END
  END
END;

GRANT SELECT ON EXAMPLE TO SelectFirstOfTypes;

SELECT * FROM SelectFirstOfTypes();
</code>```

Note, that both SELECT statements are wrapped in FOR-loop.

outer one - because it can return multiple rows,

inner one - because it can return zero rows for specific types

Some links

http://www.ibexpert.net/ibe/index.php?n=Doc.WritingStoredProceduresAndTriggers

http://www.destructor.de/firebird/storedproc.htm

How to SELECT a PROCEDURE in Firebird 2.5

http://www.pp4s.co.uk/main/tu-db-firebird-demo4.html

Body:
Despite the confusing title, I think it's pretty simple
I have a database in the following format:
(EXAMPLE)

---------------------------------
| X101| X102      | X103 | X104 |
---------------------------------
| COD | PROD_NAME | TYPE | INFO |

| 05  | PROD A1   | 05   | ABC  |
| 019 | TAPE 01   | 05   | ABC  |
| 052 | MASTER 0  | 03   | ABC  |
| 111 | APPLE     | 03   | ABC  |
| 150 | RANDOM0   | 05   | ABC  |
| 235 | ITEM661   | 03   | ABC  |
| 290 | ITEM874   | 03   | ABC  |
---------------------------------

I've tried in many ways, but I have not come up with a result. The database has a little more than 20 thousand products, I wanted to know how to
'select first 1' of each TYPE('group by TYPE' and show only the 'first 1' of each type)

Database is Firebird 1.5.

Body:
One might use stored procedures.

CREATE PROCEDURE SelectFirstOfTypes()
         RETURNS (COD INT, PROD_NAME VARCHAR(15), TYPE INT, INFO VARCHAR(15)) AS
BEGIN
  FOR SELECT DISTINCT TYPE FROM EXAMPLE INTO :TYPE DO BEGIN
    FOR SELECT FIRST 1 e.COD, e.PROD_NAME, e.INFO FROM EXAMPLE e
    WHERE :TYPE = e.TYPE  INTO :COD, :PROD_NAME, :INFO DO BEGIN
       SUSPEND;
    END
  END
END;

GRANT SELECT ON EXAMPLE TO SelectFirstOfTypes;

SELECT * FROM SelectFirstOfTypes();

Note, that both SELECT statements are wrapped in FOR-loop.

outer one - because it can return multiple rows,

inner one - because it can return zero rows for specific types

Some links

http://www.ibexpert.net/ibe/index.php?n=Doc.WritingStoredProceduresAndTriggers

http://www.destructor.de/firebird/storedproc.htm

How to SELECT a PROCEDURE in Firebird 2.5

http://www.pp4s.co.uk/main/tu-db-firebird-demo4.html


问:
How to set a fixed size for Canvas on Chart.js
This is my first time posting a question so I hope this is written according to the rules.

So, I'm using Chart.js to create efficiency charts regarding a fleet of vehicles. I get the values I need through AJAX (Making a request to a PHP file and accessing the database (PostgreSQL)).

Then, through javascript I create the charts (See the code bellow).

My problem is in the first line of code where I set the width and height values but they are not applied to the canvas. I've tried doing it through the style attribute or through the width and height attributes, but neither works.

I've also tried to change these parameters through jQuery after the function is executed, but that didn't work either.

$("#info_content").html("<canvas id=chartdiv0 style='width:600px;height:150px'></canvas><canvas id=chartdiv1 width='600' height='150'></canvas><canvas id=chartdiv2 width='600' height='150'></canvas>");
 //If fuel is selected
if(imei[1]=='comb')
  c=3;
//If Kilometers is selected
if(imei[1]=='km')
{
  c=1;
  tituloefi[0]="Kilometros Precorridos";
}
for(var i=0;i<c;i++)
{
  var ctx = document.getElementById("chartdiv"+i).getContext('2d');
  for(var k=0;k<datajson[i].length;k++)
      datajson[i][k]['valor']=datajson[i][k]['valor']/h[i];
    datajson[i].reverse();
    if(datajson[i][0]==undefined)
    {
      $("#chartdiv"+i).remove();
      continue;
    }
    //Values are being generated by getting a database value and adding a random value
    var myChart = new Chart(ctx, {
      type: 'line',
      data: {
          labels: [datajson[i][0]['data'], datajson[i][1]['data'], datajson[i][2]['data'], datajson[i][3]['data'], datajson[i][4]['data'], datajson[i][5]['data'],datajson[i][6]['data']],
          datasets: [{
              label: false,
              data: [datajson[i][0]['valor'], (datajson[i][1]['valor']+Math.random()*40000), datajson[i][2]['valor']+Math.random()*40000, datajson[i][3]['valor']+Math.random()*40000, datajson[i][4]['valor']+Math.random()*40000, datajson[i][5]['valor']+Math.random()*40000,datajson[i][6]['valor']+Math.random()*40000],
              backgroundColor: [
                  'rgb(61, 135, 255)'
              ],
              borderColor: [
                  'rgb(0, 74, 196)'
              ],
              borderWidth: 3
          }]
      },
      options: {
          title: {display:true,text:tituloefi[i],fontSize:20},
          legend: {display:false},
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero:true
                  }
              }]
          },
          tooltips: {
            displayColors:false,
            callbacks: {
                label: function(tooltipItem, chart) {
                    return "Média: "+Math.round(tooltipItem.yLabel*100)/100+(c==1?" Km":" Litros");
                }
            }
        }
      }
  });
}
if(c==1)
{
  $("#chartdiv1").remove();
  $("#chartdiv2").remove();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="info_content"></div></code>```

I've also tried to change the values with the Javascript console on Chrome and it WORKED (It only worked if changed the style attribute, changing width or height attribute erased the canvas). I really don't understand.

I think that the problem is that I'm creating the canvas dynamically, but if that's the problem I'm not seeing the answer (Maybe adding the canvas in the original HTML with display:none , but I really didn't want to do that).

Here is what I'm displaying in the page, as you can see, there are 3 charts and I can only see 2 without scrolling.

Oddly enough when I open the Chrome Javascript console I get the display I wanted. Here is the view with the console open.

Any help would be greatly appreciated.

Thank you in advance.

答:
I found out the solution. I'll leave the answer to my problem here in case anybody has the same problem.

It wasn't working because I hadn't set the options responsive:false, so the chart was adjusting to the size of the data.

Thank you anyway.

Body:
This is my first time posting a question so I hope this is written according to the rules.

So, I'm using Chart.js to create efficiency charts regarding a fleet of vehicles. I get the values I need through AJAX (Making a request to a PHP file and accessing the database (PostgreSQL)).

Then, through javascript I create the charts (See the code bellow).

My problem is in the first line of code where I set the width and height values but they are not applied to the canvas. I've tried doing it through the style attribute or through the width and height attributes, but neither works.

I've also tried to change these parameters through jQuery after the function is executed, but that didn't work either.

$("#info_content").html("<canvas id=chartdiv0 style='width:600px;height:150px'></canvas><canvas id=chartdiv1 width='600' height='150'></canvas><canvas id=chartdiv2 width='600' height='150'></canvas>");
 //If fuel is selected
if(imei[1]=='comb')
  c=3;
//If Kilometers is selected
if(imei[1]=='km')
{
  c=1;
  tituloefi[0]="Kilometros Precorridos";
}
for(var i=0;i<c;i++)
{
  var ctx = document.getElementById("chartdiv"+i).getContext('2d');
  for(var k=0;k<datajson[i].length;k++)
      datajson[i][k]['valor']=datajson[i][k]['valor']/h[i];
    datajson[i].reverse();
    if(datajson[i][0]==undefined)
    {
      $("#chartdiv"+i).remove();
      continue;
    }
    //Values are being generated by getting a database value and adding a random value
    var myChart = new Chart(ctx, {
      type: 'line',
      data: {
          labels: [datajson[i][0]['data'], datajson[i][1]['data'], datajson[i][2]['data'], datajson[i][3]['data'], datajson[i][4]['data'], datajson[i][5]['data'],datajson[i][6]['data']],
          datasets: [{
              label: false,
              data: [datajson[i][0]['valor'], (datajson[i][1]['valor']+Math.random()*40000), datajson[i][2]['valor']+Math.random()*40000, datajson[i][3]['valor']+Math.random()*40000, datajson[i][4]['valor']+Math.random()*40000, datajson[i][5]['valor']+Math.random()*40000,datajson[i][6]['valor']+Math.random()*40000],
              backgroundColor: [
                  'rgb(61, 135, 255)'
              ],
              borderColor: [
                  'rgb(0, 74, 196)'
              ],
              borderWidth: 3
          }]
      },
      options: {
          title: {display:true,text:tituloefi[i],fontSize:20},
          legend: {display:false},
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero:true
                  }
              }]
          },
          tooltips: {
            displayColors:false,
            callbacks: {
                label: function(tooltipItem, chart) {
                    return "Média: "+Math.round(tooltipItem.yLabel*100)/100+(c==1?" Km":" Litros");
                }
            }
        }
      }
  });
}
if(c==1)
{
  $("#chartdiv1").remove();
  $("#chartdiv2").remove();
}

I've also tried to change the values with the Javascript console on Chrome and it WORKED (It only worked if changed the style attribute, changing width or height attribute erased the canvas). I really don't understand.

I think that the problem is that I'm creating the canvas dynamically, but if that's the problem I'm not seeing the answer (Maybe adding the canvas in the original HTML with display:none , but I really didn't want to do that).

Here is what I'm displaying in the page, as you can see, there are 3 charts and I can only see 2 without scrolling.

Oddly enough when I open the Chrome Javascript console I get the display I wanted. Here is the view with the console open.

Any help would be greatly appreciated.

Thank you in advance.


答:
Use re.sub:

```<code>import re

with open open('file.txt') as file:
    text = re.sub(r'\(.*?\)', '', file.read(), flags=re.M)
</code>```

This removes all occurrences of the text enclosed in parentheses. The re.M flag is the multiline specifier, which is useful when your string has newlines within the matching pattern.

Title: Pattern substitution in Python

Body:
Use re.sub:

import re

with open open('file.txt') as file:
    text = re.sub(r'\(.*?\)', '', file.read(), flags=re.M)

This removes all occurrences of the text enclosed in parentheses. The re.M flag is the multiline specifier, which is useful when your string has newlines within the matching pattern.


问:
Write list of objects to text file
I've got a class Dish like this:

```<code>public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}
</code>```

In the main form the user can enter the previous data.
Then I create a list of "Dish":

```<code>public static List<Piatto> List = new List<Piatto>();
</code>```

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

```<code>public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }
</code>```

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

答:
If you just want to write, the quickest way without too many code changes is to override your ToString method.</p>

```<code>public class Dish
{
    public Dish(int cost, string name)
    {
       Cost = cost;
       Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }

    public override string ToString(){
        return "Name: "+Name+" cost: "+cost;
    }
}
</code>```

Title: Write list of objects to text file

Body:
I've got a class Dish like this:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}

In the main form the user can enter the previous data.
Then I create a list of "Dish":

public static List<Piatto> List = new List<Piatto>();

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

Body:
If you just want to write, the quickest way without too many code changes is to override your ToString method.

public class Dish
{
    public Dish(int cost, string name)
    {
       Cost = cost;
       Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }

    public override string ToString(){
        return "Name: "+Name+" cost: "+cost;
    }
}


问:
force windows to have case sensitive for development
Today I spent hours to figure out what's wrong in my production environment (linux) when my project in my local (windows) is fine. I found this culprit:

```<code>import 'something' from '../App/myComponent'
</code>```

above code is running fine although my App folder is in lower case, during my development I didn't see any error, but in my product, stuffs are breaking.

How to force windows to have strict mode?

答: If you're using Webpack, use CaseSensitivePathsPlugin  to enforce that the path of imported modules matches the case of the path on disk.

Body:
Today I spent hours to figure out what's wrong in my production environment (linux) when my project in my local (windows) is fine. I found this culprit:

import 'something' from '../App/myComponent'

above code is running fine although my App folder is in lower case, during my development I didn't see any error, but in my product, stuffs are breaking.

How to force windows to have strict mode?


问:
Generate a pandas dataframe from ordereddict?
I am trying to create a pandas dataframe from an ordereddict to preserve the order of the values. But for some reason after creating the dataframe the fields are messed up again.

Here's the list of ordereddicts:

```<code>[OrderedDict([
  ('key_a',
  'value_a'),
  ('key_b',
  'value_b'),
]),
OrderedDict([
  ('key_a',
  'value_c'),
  ('key_b',
  'value_d'),
])
]
</code>```

Now how should I create a pandas DataFrame from these? What I am looking for is something like that (the important thing is the key_a and key_b etc column name order):

```<code>  key_a    key_b
0 value_a  value_b
1 value_c  value_d
</code>```

I have tried:

```<code>pd.DataFrame.from_records(orderedDictList)
pd.DataFrame.from_dict(orderedDictList)
</code>```

Feel free to ask any additional questions.

答:
You can do something like this using Counter from collections module:

```<code>from collections import OrderedDict, Counter
import pandas as pd

a = {'key_a': 'value_a', 'key_b':'value_b'}
b = {'key_a': 'value_c', 'key_b':'value_d'}

ord_list = [OrderedDict(a), OrderedDict(b)]

col = Counter()
for k in ord_list:
    col.update(k)

df = pd.DataFrame([k.values() for k in ord_list], columns = col.keys())

print(df)
</code>```

Output:

```<code>     key_b    key_a
0  value_b  value_a
1  value_d  value_c
</code>```

Body:
I am trying to create a pandas dataframe from an ordereddict to preserve the order of the values. But for some reason after creating the dataframe the fields are messed up again.

Here's the list of ordereddicts:

[OrderedDict([
  ('key_a',
  'value_a'),
  ('key_b',
  'value_b'),
]),
OrderedDict([
  ('key_a',
  'value_c'),
  ('key_b',
  'value_d'),
])
]

Now how should I create a pandas DataFrame from these? What I am looking for is something like that (the important thing is the key_a and key_b etc column name order):

  key_a    key_b
0 value_a  value_b
1 value_c  value_d

I have tried:

pd.DataFrame.from_records(orderedDictList)
pd.DataFrame.from_dict(orderedDictList)

Feel free to ask any additional questions.

Body:
You can do something like this using Counter from collections module:

from collections import OrderedDict, Counter
import pandas as pd

a = {'key_a': 'value_a', 'key_b':'value_b'}
b = {'key_a': 'value_c', 'key_b':'value_d'}

ord_list = [OrderedDict(a), OrderedDict(b)]

col = Counter()
for k in ord_list:
    col.update(k)

df = pd.DataFrame([k.values() for k in ord_list], columns = col.keys())

print(df)

Output:

     key_b    key_a
0  value_b  value_a
1  value_d  value_c


问:
Error TokenMismatchException in VerifyCsrfToken.php line 68:
I want to do multiple edit, I want to edit from the data I checked following script .blade, I found the TokenMismatchException error in VerifyCsrfToken.php line 68: when updating.

```<code><form name="form" action="{{url('/update-kb')}}" method="post" onsubmit="return deleteConfirm();"/>
<div class="table table-responsive">
    <table id="example1" class="table table-bordered">
        <thead>
        <tr class="info">
            <th width="3%"><input type="checkbox" name="select_all" id="select_all" value=""/></th>
            <th>No</th>
            <th>Data lengkap</th>
            <th>Aksi</th>
        </tr>
        </thead>
        <tbody>
        <?php $i = 1; ?>
        @foreach( $datasiswa as $row )
            <tr>
                <td>
                    <label class="checkbox-inline"><input type="checkbox" name="checked_id[]" class="checkbox" value="{{$row->id}}"/>
                    </label>
                </td>
                <td width="5%">{{ $i }}</td>
                <td width="95%">
                    <table class="table">
                        <tr>
                            <td class="info">Nama panggilan</td>
                            <td>{{$row->nm_panggilan}}</td>
                            <td class="warning">Pekerjaan ibu</td>
                            <td>{{$row->pekerjaan_ibu}}</td>
                        </tr>
                        <tr>
                            <td class="info">Jenis kelamin</td>
                            <td>{{$row->jenis_kelamin}}</td>
                            <td class="warning">No. Handphone</td>
                            <td>{{$row->hp_ibu}}</td>
                        </tr>
                        <tr>
                            <td class="info">Tempat, Tanggal lahir</td>
                            <td>{{$row->tempat}}, {{$row->tanggal_lahir}}</td>
                            <td class="warning">Alamat</td>
                            <td>{{$row->alamat}}</td>
                        </tr>
                        <tr>
                            <td class="info">Status anak</td>
                            <td>{{$row->status_anak}}</td>
                            <td class="warning">Golongan darah</td>
                            <td>{{$row->goldar}}</td>
                        </tr>
                        <tr>
                            <td class="info">Agama</td>
                            <td>{{$row->agama}}</td>
                            <td class="warning">Nama wali</td>
                            <td>{{$row->nm_wali}}</td>
                        </tr>
                        <tr>
                            <td class="info">Kewarganegaraan</td>
                            <td>{{$row->kewarganegaraan}}</td>
                        </tr>
                        <tr>
                            <td class="info">Anak ke-</td>
                            <td>{{$row->anak_ke}}</td>
                        </tr>
                        <tr>
                            <td class="info">Kelas</td>
                            <td>{{$row->kelas}}</td>
                        </tr>
                    </table>
                </td>
                <td>
                    <a href="{!! url('/'.$row->id.'/edit-siswa') !!}">
                        <button class="btn btn-default btn-block"><i class="fa fa-edit"></i></button><br>
                    </a>
                    <a href="{!! url('/'.$row->id.'/delete-siswa') !!}">
                        <button class="btn btn-danger btn-block"><i class="fa fa-trash"></i></button>
                    </a>
                </td>
                </td>
            </tr>
            <?php $i++; ?>
        @endforeach
        </tbody>
    </table>
    <div class="col-md-3">
        <input type="submit" class="btn btn-danger" name="delete_submit" value="Hapus"/>
    </div>
</div>
</form>
</code>```

But I still have error, what causes it?

```<code>public function updatekb($id, Request $request)
{
    $data = Datasiswa::find($id);
    if (isset($request->delete_submit)) {
        $idArr = $request->checked_id;
        foreach ($idArr as $id) {
            DB::update('update tb_siswa, tb_pernyataan set tb_pernyataan.kelas = "cekcek" where tb_pernyataan.kelas = "TK A" and tb_siswa.sekolah = "KB TK KHALIFAH 25" and id = "' . $id . '" ');
        }

        return back();
        Session::flash('sukses', 'Data berhasil di update', compact('data'));
    }
}
</code>```

答:
Laravel use CSRF token to verify user request. so you have to use it on yevery request if you want to disable it then you can disable it from See here how to disable it or you can use it as

```<code> {{ csrf_field() }}
</code>```

or

```<code><input type="hidden" name="_token" value="{{ csrf_token() }}"/>
</code>```

Body:
I want to do multiple edit, I want to edit from the data I checked following script .blade, I found the TokenMismatchException error in VerifyCsrfToken.php line 68: when updating.

<form name="form" action="{{url('/update-kb')}}" method="post" onsubmit="return deleteConfirm();"/>

            <input type="checkbox" name="select_all" id="select_all" value=""/>
            No
            Data lengkap
            Aksi

        <?php $i = 1; ?>
        @foreach( $datasiswa as $row )

                    <input type="checkbox" name="checked_id[]" class="checkbox" value="{{$row->id}}"/>

                {{ $i }}

                            Nama panggilan
                            {{$row->nm_panggilan}}
                            Pekerjaan ibu
                            {{$row->pekerjaan_ibu}}

                            Jenis kelamin
                            {{$row->jenis_kelamin}}
                            No. Handphone
                            {{$row->hp_ibu}}

                            Tempat, Tanggal lahir
                            {{$row->tempat}}, {{$row->tanggal_lahir}}
                            Alamat
                            {{$row->alamat}}

                            Status anak
                            {{$row->status_anak}}
                            Golongan darah
                            {{$row->goldar}}

                            Agama
                            {{$row->agama}}
                            Nama wali
                            {{$row->nm_wali}}

                            Kewarganegaraan
                            {{$row->kewarganegaraan}}

                            Anak ke-
                            {{$row->anak_ke}}

                            Kelas
                            {{$row->kelas}}

                    id.'/edit-siswa') !!}">
                        <button class="btn btn-default btn-block"></button>

                    id.'/delete-siswa') !!}">
                        <button class="btn btn-danger btn-block"></button>

            <?php $i++; ?>
        @endforeach

        <input type="submit" class="btn btn-danger" name="delete_submit" value="Hapus"/>

</form>

But I still have error, what causes it?

public function updatekb($id, Request $request)
{
    $data = Datasiswa::find($id);
    if (isset($request->delete_submit)) {
        $idArr = $request->checked_id;
        foreach ($idArr as $id) {
            DB::update('update tb_siswa, tb_pernyataan set tb_pernyataan.kelas = "cekcek" where tb_pernyataan.kelas = "TK A" and tb_siswa.sekolah = "KB TK KHALIFAH 25" and id = "' . $id . '" ');
        }

        return back();
        Session::flash('sukses', 'Data berhasil di update', compact('data'));
    }
}

Body:
Laravel use CSRF token to verify user request. so you have to use it on yevery request if you want to disable it then you can disable it from See here how to disable it or you can use it as

 {{ csrf_field() }}

or

<input type="hidden" name="_token" value="{{ csrf_token() }}"/>


问:
TPL force higher parallelism
When queuing Tasks to the ThreadPool, the code relies on the default TaskScheduler to execute them. In my code example, I can see that 7 Tasks maximum get executed in parallel on separate threads.

```<code>new Thread(() =>
{
    while (true)
    {
        ThreadPool.GetAvailableThreads(out var wt, out var cpt);
        Console.WriteLine($"WT:{wt} CPT:{cpt}");
        Thread.Sleep(500);
    }
}).Start();

var stopwatch = new Stopwatch();
stopwatch.Start();
var tasks = Enumerable.Range(0, 100).Select(async i => { await Task.Yield(); Thread.Sleep(10000); }).ToArray();
Task.WaitAll(tasks);
Console.WriteLine(stopwatch.Elapsed.TotalSeconds);
Console.ReadKey();
</code>```

Is there a way to force the scheduler to fire up more Tasks on other threads? Or is there a more "generous" scheduler in the framework without implementing a custom one?

EDIT:

Adding ThreadPool.SetMinThreads(100, X) seems to do the trick, I presume awaiting frees up the thread so the pool think it can fire up another one and then it immediately resumes.

By default, the minimum number of threads is set to the number of processors on a system. You can use the SetMinThreads method to increase the minimum number ofthreads. However, unnecessarily increasing these values can cause performance problems. If too many tasks start at the same time, all of them might appear to be slow. In most cases, the thread pool will perform better with its own algorithm for allocating threads. Reducing the minimum to less than the number of processors can also hurt performance.

From here: https://msdn.microsoft.com/en-us/library/system.threading.threadpool.setminthreads(v=vs.110).aspx

I removed AsParallel as it is not relevant and it just seems to confuse readers.

答:
Useful link that explains it can be done with ThreadPool.SetMinThread:

https://gist.github.com/JonCole/e65411214030f0d823cb#file-threadpool-md

Title: TPL force higher parallelism

Body:
When queuing Tasks to the ThreadPool, the code relies on the default TaskScheduler to execute them. In my code example, I can see that 7 Tasks maximum get executed in parallel on separate threads.

new Thread(() =>
{
    while (true)
    {
        ThreadPool.GetAvailableThreads(out var wt, out var cpt);
        Console.WriteLine($"WT:{wt} CPT:{cpt}");
        Thread.Sleep(500);
    }
}).Start();

var stopwatch = new Stopwatch();
stopwatch.Start();
var tasks = Enumerable.Range(0, 100).Select(async i => { await Task.Yield(); Thread.Sleep(10000); }).ToArray();
Task.WaitAll(tasks);
Console.WriteLine(stopwatch.Elapsed.TotalSeconds);
Console.ReadKey();

Is there a way to force the scheduler to fire up more Tasks on other threads? Or is there a more "generous" scheduler in the framework without implementing a custom one?

EDIT:

Adding ThreadPool.SetMinThreads(100, X) seems to do the trick, I presume awaiting frees up the thread so the pool think it can fire up another one and then it immediately resumes.

By default, the minimum number of threads is set to the number of processors on a system. You can use the SetMinThreads method to increase the minimum number ofthreads. However, unnecessarily increasing these values can cause performance problems. If too many tasks start at the same time, all of them might appear to be slow. In most cases, the thread pool will perform better with its own algorithm for allocating threads. Reducing the minimum to less than the number of processors can also hurt performance.

From here: https://msdn.microsoft.com/en-us/library/system.threading.threadpool.setminthreads(v=vs.110).aspx

I removed AsParallel as it is not relevant and it just seems to confuse readers.


问:
Django search in multiple field with multiple value
I have a model which stores login logout time and date for users

```<code>class LoginLogout(models.Model):
    username = models.CharField(max_length=30, unique=True)
    date = models.DateField(auto_now_add=True)
    login_time = models.TimeField()
    logout_time = models.TimeField(null=True, blank=True)
</code>```

Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset.

答:
This should do the work :</p>

```<code>if not username:
    return LoginLogout.objects.all()
else:
    return LoginLogout.objects.filter(date__gte=date_from,
                                      date__lte=date_to,
                                      username=username)
</code>```

Body:
I have a model which stores login logout time and date for users

class LoginLogout(models.Model):
    username = models.CharField(max_length=30, unique=True)
    date = models.DateField(auto_now_add=True)
    login_time = models.TimeField()
    logout_time = models.TimeField(null=True, blank=True)

Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset.

Body:
This should do the work :

if not username:
    return LoginLogout.objects.all()
else:
    return LoginLogout.objects.filter(date__gte=date_from,
                                      date__lte=date_to,
                                      username=username)


问:
specify rows number in every item in bootstrap carousel
I'm using bootstrap carousel, where it's devided to items.
The first item should always be with active class and the others only class=item.

I'm requesting data, and getting response  using angularjs, trying to fill the items with ng-repeat

now my problem is the first item should be class=item active, and get only 4 rows.
The other items should be with class=item and every item get only 4 rows.

The request response has more than 70 rows. i'm stuck here, how can I devide the 70 rows to 4 in the first active class, and the rest in the other items (4 rows in each item)

Carousel code :

```<code><div id="myCarousel" class="carousel slide">

    <div class="carousel-inner">
        <div class="item active">
            <div class="row">
                <div class="col-sm-3"><a href="#x"><img src="images/restaurants/kababji.jpg" alt="Image" class="img-responsive"><Br><center>Kababji</center></a>
                </div>
                <div class="col-sm-3"><a href="#x"><img src="images/restaurants/alsaniour.jpg" alt="Image" class="img-responsive"><Br><center>Al Saniour</center></a>
                </div>
                <div class="col-sm-3"><a href="#x"><img src="images/restaurants/pizzahut.jpg" alt="Image" class="img-responsive"><Br><center>Pizza Hut</center></a>
                </div>
                <div class="col-sm-3"><a href="#x"><img src="images/restaurants/tabliyetmassaad.jpg" alt="Image" class="img-responsive"><Br><center>Tabiliyet Massaad</center></a>
                </div>
            </div>

        </div>

        <div class="item">
        <div class="row">
                <div class="col-sm-3"><a href="#x"><img src="images/restaurants/burgerking.png" alt="Image" class="img-responsive"><Br><center>Burger King</center></a>
                </div>
                <div class="col-sm-3"><a href="#x"><img src="images/restaurants/malektaouk.jpg" alt="Image" class="img-responsive"><Br><center>Malek Taouk</center></a>
                </div>
                <div class="col-sm-3"><a href="#x"><img src="images/restaurants/pizzahut.jpg" alt="Image" class="img-responsive"><Br><center>Pizza Hut</center></a>
                </div>
                <div class="col-sm-3"><a href="#x"><img src="images/restaurants/tabliyetmassaad.jpg" alt="Image" class="img-responsive"><Br><center>Tabiliyet Massaad</center></a>
                </div>
            </div>

        </div>

    </div>
</code>```

答:
Since you need to show 4 response array items in one carousel item, you can loop through your response array using ng-repeat and show only those items whose index is completely divisible by 4.For example you have 20 items in an array that you want to loop through.You can put a condition in your ng-repeat using ng-if to show only 0th,4th,8th,etc.. items i.e. ($index % 4 == 0) and inside that you can can show 0th,1st,2nd and 3rd items for first row , 4th,5th,6th and 7th for 2nd row ...and so on..

Here is a fiddle demonstrating the same.

Body:
I'm using bootstrap carousel, where it's devided to items.
The first item should always be with active class and the others only class=item.

I'm requesting data, and getting response  using angularjs, trying to fill the items with ng-repeat

now my problem is the first item should be class=item active, and get only 4 rows.
The other items should be with class=item and every item get only 4 rows.

The request response has more than 70 rows. i'm stuck here, how can I devide the 70 rows to 4 in the first active class, and the rest in the other items (4 rows in each item)

Carousel code :

Kababji

Al Saniour

Pizza Hut

Tabiliyet Massaad

Burger King

Malek Taouk

Pizza Hut

Tabiliyet Massaad


问:
Custom Dialog pops up unwantedly
I'm working on an Android App, recently I found out a small bug. Thing is, even If I don't call the Custom Alert Dialogbox function, The Alert Dialog is popping up unwantedly. What must be the reason ?

Providing the code I'm using:-

```<code>if (booking.isPayable()) {

                        goToActivity(PaymentActivity.class);
                        postModelSticky(booking);
                        finish();
                    }
                    getBookingConfirmation();
</code>```

If the condition is true, then go to a activity, else show the dialogBox.
getBookingConfirmation() is a function which opens the Alert
DialogBox. But Even if the condition is true, The dialog is popped up before the transition happens.

答:
You need to put an else in your code

```<code>                   if (booking.isPayable())
                   {

                        goToActivity(PaymentActivity.class);
                        postModelSticky(booking);
                        finish();
                    }
                    else
                    getBookingConfirmation();
</code>```

Title: Custom Dialog pops up unwantedly

Body:
I'm working on an Android App, recently I found out a small bug. Thing is, even If I don't call the Custom Alert Dialogbox function, The Alert Dialog is popping up unwantedly. What must be the reason ?

Providing the code I'm using:-

if (booking.isPayable()) {

                        goToActivity(PaymentActivity.class);
                        postModelSticky(booking);
                        finish();
                    }
                    getBookingConfirmation();

If the condition is true, then go to a activity, else show the dialogBox.
getBookingConfirmation() is a function which opens the Alert
DialogBox. But Even if the condition is true, The dialog is popped up before the transition happens.

Body:
You need to put an else in your code

                   if (booking.isPayable())
                   {

                        goToActivity(PaymentActivity.class);
                        postModelSticky(booking);
                        finish();
                    }
                    else
                    getBookingConfirmation();


问:
Logging daily check results with changing requirements
I apologize for the title, but I couldn't think of a better way to ask this question.

Basically, I need to create a database model for logging daily checks and parameters on various pieces of equipment. Every day the user will open up a form, it will list a number of tasks to check as well ask for operating parameters to be recorded (for example, temperature). The user then enters the parameters and flags any item that has an issue.

The issue I have with modeling this is the fact that the items to check can change as operational requirements change. We may need to add or remove things to check to keep things relevant.

I don't really have much example data to show as I am stumped about which way to go. One thing I can think of is keeping some sort of version number but I'm not sure how that would look in a database. The only other thing I could think to do is generate a hard copy PDF of the results and save that, rather than saving the results in the database. That way I don't have to worry about adding/removing items because previous daily checks will not be stored in the database and therefore won't be impacted. This would probably work fine for our needs as we don't have to go back and change anything after it's done, but I can't help to think there is a better way.

Let me know if you need any clarification and thanks for any help you can provide.

Edit (More Information)

Right now we have a blank excel sheet for each device, it's got a list of checks... one is say "General cleanup of hydraulic fluid", or "Check for abnormal noise/vibration" then there are a couple that wily say "Hydraulic Pressure (psi)" and you have to enter the pressure you recorded... there's probably about 20 tasks on average. You then put your name on the sheet, date it, print it and sign it.. it gets filled probably to never be seen again....

答:
Cam,

Here is the model/ the list of tables and data that I came up with. I think it covers most of the scnerios/queries that you might use for getting data out of the application.

Equipment table and check tables are two independent entities having the master list of equipment and checks respectively.

Setup

Whenever you have to set up a series of checks for a given equipment, you will insert a new record in the equipment_check_asc table. Since these associations/ checks are time-based, we have an effective date and end-date to determine what are the checks needed at a given point in time and also to keep a historical track of what checks were mandated at that point in time.

Actual Logging

The actual checks that are made are done using a child table (equipment_check_audit) that records the checks made for each equipment for a given day (whenever they are made).

You can answer the following queries easily from the below model and these are the ones that I could think of.

a) What are the checks needed for this equipment as of today?

b) What were the checks needed for an equipment as of given date

c) Of the required checks, how many were performed and how many were not ( today and any given day ).

d) Of the checks performed, how many passed / failed.

```<code>create table equipment(
   equipment_id number primary key,
   equipment_name varchar2(200) not null
   );

create table checks(
   checkid number primary key,
   check_name varchar2(100) not null
  );

create table equipment_check_asc(
   equipment_check_asc_id number primary key,
   equipment_id number not null,
   checkid number not null,
   eff_date date not null,
   end_date date ,
   eff_flag varchar2(1) not null, -- kind of redundant, easier to find the checks effective today.
   constraint fk_equipment_id foreign key (equipment_id) references equipment(equipment_id),
   constraint fk_checkid      foreign key (checkid) references checks(checkid),
   constraint unq_check       unique (equipment_id,checkid,eff_date)
);

create table equipment_check_audit(
    audit_id number primary key,
    equipment_check_asc_id number not null,
    pass_fail_ind varchar2(1) not null,
    audit_date date not null,
    constraint fk_check_id foreign key (equipment_check_asc_id ) references
       equipment_check_asc (equipment_check_asc_id)
);
</code>```

There might be other corner cases that you might need to cover and model for, but this should give you a general idea.

Here is the data that I tested with.

```<code>insert into equipment values (1, 'Item 1');
insert into equipment values (2, 'Item 2');
commit;

insert into checks values (100, 'Temperature');
insert into checks values (101, 'Robustness' );
insert into checks values (102, 'Stable'     );
commit;

insert into equipment_check_asc values (1000,1,100,sysdate-10, NULL , 'Y');
insert into equipment_check_asc values (1001,1,101,sysdate-10, NULL , 'Y');
insert into equipment_check_asc values (1002,1,102,sysdate-2 , NULL , 'Y');

insert into equipment_check_asc values (1003,2,100,sysdate-30,  sysdate-1 , 'N');
insert into equipment_check_asc values (1004,2,101,sysdate-30,  NULL    , 'Y');

commit;

delete from equipment_check_audit;

/*** Item A ***/

---checks made on 12/09
insert into equipment_check_audit values (10000, 1000, 'Y', sysdate-5);
---insert into equipment_check_audit(10000, 1000, 'Y', sysdate-5); No checks made on robustness even when it was needed.
-- no check done on stability. (as it was not needed).

---checks made today. (all positives case)
insert into equipment_check_audit values (10001, 1000, 'Y', sysdate);
insert into equipment_check_audit values (10002, 1001, 'N', sysdate);
insert into equipment_check_audit values (10003, 1002, 'Y', sysdate);
commit;

/*** Item B ***/
--checks made on 12/9
insert into equipment_check_audit values (10004, 1003, 'Y', sysdate-5);
--checks made today.
insert into equipment_check_audit values (10005, 1004, 'Y', sysdate);
commit;
</code>```

Body:
Cam,

Here is the model/ the list of tables and data that I came up with. I think it covers most of the scnerios/queries that you might use for getting data out of the application.

Equipment table and check tables are two independent entities having the master list of equipment and checks respectively.

Setup

Whenever you have to set up a series of checks for a given equipment, you will insert a new record in the equipment_check_asc table. Since these associations/ checks are time-based, we have an effective date and end-date to determine what are the checks needed at a given point in time and also to keep a historical track of what checks were mandated at that point in time.

Actual Logging

The actual checks that are made are done using a child table (equipment_check_audit) that records the checks made for each equipment for a given day (whenever they are made).

You can answer the following queries easily from the below model and these are the ones that I could think of.

a) What are the checks needed for this equipment as of today?

b) What were the checks needed for an equipment as of given date

c) Of the required checks, how many were performed and how many were not ( today and any given day ).

d) Of the checks performed, how many passed / failed.

create table equipment(
   equipment_id number primary key,
   equipment_name varchar2(200) not null
   );

create table checks(
   checkid number primary key,
   check_name varchar2(100) not null
  );

create table equipment_check_asc(
   equipment_check_asc_id number primary key,
   equipment_id number not null,
   checkid number not null,
   eff_date date not null,
   end_date date ,
   eff_flag varchar2(1) not null, -- kind of redundant, easier to find the checks effective today.
   constraint fk_equipment_id foreign key (equipment_id) references equipment(equipment_id),
   constraint fk_checkid      foreign key (checkid) references checks(checkid),
   constraint unq_check       unique (equipment_id,checkid,eff_date)
);

create table equipment_check_audit(
    audit_id number primary key,
    equipment_check_asc_id number not null,
    pass_fail_ind varchar2(1) not null,
    audit_date date not null,
    constraint fk_check_id foreign key (equipment_check_asc_id ) references
       equipment_check_asc (equipment_check_asc_id)
);

There might be other corner cases that you might need to cover and model for, but this should give you a general idea.

Here is the data that I tested with.

insert into equipment values (1, 'Item 1');
insert into equipment values (2, 'Item 2');
commit;

insert into checks values (100, 'Temperature');
insert into checks values (101, 'Robustness' );
insert into checks values (102, 'Stable'     );
commit;

insert into equipment_check_asc values (1000,1,100,sysdate-10, NULL , 'Y');
insert into equipment_check_asc values (1001,1,101,sysdate-10, NULL , 'Y');
insert into equipment_check_asc values (1002,1,102,sysdate-2 , NULL , 'Y');

insert into equipment_check_asc values (1003,2,100,sysdate-30,  sysdate-1 , 'N');
insert into equipment_check_asc values (1004,2,101,sysdate-30,  NULL    , 'Y');

commit;

delete from equipment_check_audit;

/*** Item A ***/

---checks made on 12/09
insert into equipment_check_audit values (10000, 1000, 'Y', sysdate-5);
---insert into equipment_check_audit(10000, 1000, 'Y', sysdate-5); No checks made on robustness even when it was needed.
-- no check done on stability. (as it was not needed).

---checks made today. (all positives case)
insert into equipment_check_audit values (10001, 1000, 'Y', sysdate);
insert into equipment_check_audit values (10002, 1001, 'N', sysdate);
insert into equipment_check_audit values (10003, 1002, 'Y', sysdate);
commit;

/*** Item B ***/
--checks made on 12/9
insert into equipment_check_audit values (10004, 1003, 'Y', sysdate-5);
--checks made today.
insert into equipment_check_audit values (10005, 1004, 'Y', sysdate);
commit;


问:
How to import an interface in external ngModule library
I'm new on angular 4

I created a ngModule package named mds.angular.bootstrap.datetimepicker with the following package.json

```<code>{
  "name": "mds.angular.bootstrap.datetimepicker",
  "version": "0.9.8",
  "description": "Persian and gregorian DateTimePicker with angular 4",
  "license": "MIT",
  "main": "./mds-datetimePicker.module.js",
  "types": [
    "./mds-datetimePicker.module.d.ts",
    "./assests/date.interface.d.ts",
    "./assests/day.interface.d.ts",
    "./assests/rangeDate.interface.d.ts"
  ],
  "moduleResolution": "node",
  "author": {
    "email": "mds_soft@yahoo.com",
    "name": "Mohammad Dayyan",
    "url": "https://github.com/Mds92/mds-angular-bootstrap-datetime-picker"
  },
  "repository": {
    "type": "public",
    "url": "https://github.com/Mds92/mds-angular-bootstrap-datetime-picker"
  },
  "homepage": "https://github.com/Mds92/mds-angular-bootstrap-datetime-picker",
  "dependencies": {
    "@angular/animations": "^4.1.2",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "jquery": "^3.2.1",
    "mds.persian.calendar": "^0.9.69",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  }
}
</code>```

I publish it on npm and it's OK

Now I want to consume the package in another angular 4 project.

So I install the package npm install mds.angular.bootstrap.datetimepicker --save

I use it as the following

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MdsDatetimePickerModule } from 'mds.angular.bootstrap.datetimepicker';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [ AppComponent ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MdsDatetimePickerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

It's OK until here, But I have to import IDate from mds.angular.bootstrap.datetimepicker package to use it in my component

But it throws exception:

```<code>ERROR in D:/Sources/sample/src/app/app.component.ts (2,23): Cannot find module 'date.interface'.

import { Component } from '@angular/core';
import { IDate } from 'date.interface'; //ERROR

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mds Angular Bootstrap DateTimePicker';
  viewInit = false;

  inLinePersianDateTimePicker = '';
  inlinePersianDatePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.inLinePersianDateTimePicker = selectedDate.formatString;
  }

  inLineGregorianDateTimePicker = '';
  inlineGregorianDatePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.inLineGregorianDateTimePicker = selectedDate.formatString;
  }

  popoverPersianDateTimePicker = '';
  popoverPersianDateTimePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.popoverPersianDateTimePicker = selectedDate.formatString;
  }

  popoverGregorianDateTimePicker = '';
  popoverGregorianDateTimePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.popoverGregorianDateTimePicker = selectedDate.formatString;
  }

  ngAfterViewInit() {
    this.viewInit = true;
  }
}
</code>```

The following is IDate in mds.angular.bootstrap.datetimepicker package

```<code>export interface IDate {
  year: number;
  month: number;
  day: number;
  hour: number;
  minute: number;
  second: number;
  millisecond: number;
  formatString: string;
}
</code>```

How should I use IDate in external applications?

答:
Finally, I found the solution:

First: Creating index.ts (I named it index, you can change the name) and write export for each type we want to use in external libraries.

```<code>export * from "./mds-datetimePicker.module";
export * from "./services/mds-datetime-picker-resources.service";
export * from "./components/mds-datetime-picker.component";
export * from "./components/core/mds-datetime-picker-core.component";
export * from "./assests/date.interface";
export * from "./assests/day.interface";
export * from "./assests/mds-datetime-picker.utility";
export * from "./assests/rangeDate.interface";
</code>```

Second: open command prompt and choose package.json path, then write the following command:

```<code>tsc --declaration
</code>```

you can write tsc -d instead.

This command compiles typescript files and creates *.d.ts files

Finally: In package.json add the following lines:

```<code>"main": "./index.js",
"types": "./index.d.ts"
</code>```

Now, we can import all of types in index.ts as the following:

```<code>import { MdsDatetimePickerModule, IDate } from 'mds.angular.bootstrap.datetimepicker';
</code>```

Body:
I'm new on angular 4

I created a ngModule package named mds.angular.bootstrap.datetimepicker with the following package.json

{
  "name": "mds.angular.bootstrap.datetimepicker",
  "version": "0.9.8",
  "description": "Persian and gregorian DateTimePicker with angular 4",
  "license": "MIT",
  "main": "./mds-datetimePicker.module.js",
  "types": [
    "./mds-datetimePicker.module.d.ts",
    "./assests/date.interface.d.ts",
    "./assests/day.interface.d.ts",
    "./assests/rangeDate.interface.d.ts"
  ],
  "moduleResolution": "node",
  "author": {
    "email": "mds_soft@yahoo.com",
    "name": "Mohammad Dayyan",
    "url": "https://github.com/Mds92/mds-angular-bootstrap-datetime-picker"
  },
  "repository": {
    "type": "public",
    "url": "https://github.com/Mds92/mds-angular-bootstrap-datetime-picker"
  },
  "homepage": "https://github.com/Mds92/mds-angular-bootstrap-datetime-picker",
  "dependencies": {
    "@angular/animations": "^4.1.2",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "jquery": "^3.2.1",
    "mds.persian.calendar": "^0.9.69",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  }
}

I publish it on npm and it's OK

Now I want to consume the package in another angular 4 project.

So I install the package npm install mds.angular.bootstrap.datetimepicker --save

I use it as the following

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MdsDatetimePickerModule } from 'mds.angular.bootstrap.datetimepicker';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [ AppComponent ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MdsDatetimePickerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

It's OK until here, But I have to import IDate from mds.angular.bootstrap.datetimepicker package to use it in my component

But it throws exception:

ERROR in D:/Sources/sample/src/app/app.component.ts (2,23): Cannot find module 'date.interface'.

import { Component } from '@angular/core';
import { IDate } from 'date.interface'; //ERROR

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mds Angular Bootstrap DateTimePicker';
  viewInit = false;

  inLinePersianDateTimePicker = '';
  inlinePersianDatePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.inLinePersianDateTimePicker = selectedDate.formatString;
  }

  inLineGregorianDateTimePicker = '';
  inlineGregorianDatePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.inLineGregorianDateTimePicker = selectedDate.formatString;
  }

  popoverPersianDateTimePicker = '';
  popoverPersianDateTimePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.popoverPersianDateTimePicker = selectedDate.formatString;
  }

  popoverGregorianDateTimePicker = '';
  popoverGregorianDateTimePickerChanged(selectedDate: IDate) {
    if (!this.viewInit) return;
    this.popoverGregorianDateTimePicker = selectedDate.formatString;
  }

  ngAfterViewInit() {
    this.viewInit = true;
  }
}

The following is IDate in mds.angular.bootstrap.datetimepicker package

export interface IDate {
  year: number;
  month: number;
  day: number;
  hour: number;
  minute: number;
  second: number;
  millisecond: number;
  formatString: string;
}

How should I use IDate in external applications?

Body:
Finally, I found the solution:

First: Creating index.ts (I named it index, you can change the name) and write export for each type we want to use in external libraries.

export * from "./mds-datetimePicker.module";
export * from "./services/mds-datetime-picker-resources.service";
export * from "./components/mds-datetime-picker.component";
export * from "./components/core/mds-datetime-picker-core.component";
export * from "./assests/date.interface";
export * from "./assests/day.interface";
export * from "./assests/mds-datetime-picker.utility";
export * from "./assests/rangeDate.interface";

Second: open command prompt and choose package.json path, then write the following command:

tsc --declaration

you can write tsc -d instead.

This command compiles typescript files and creates *.d.ts files

Finally: In package.json add the following lines:

"main": "./index.js",
"types": "./index.d.ts"

Now, we can import all of types in index.ts as the following:

import { MdsDatetimePickerModule, IDate } from 'mds.angular.bootstrap.datetimepicker';


问:
Count no. of tokens after tokenization, stop words removal and stemming
I have the following function:

```<code>def preprocessText (data):
    stemmer = nltk.stem.porter.PorterStemmer()
    preprocessed = []
    for each in data:
        tokens = nltk.word_tokenize(each.lower().translate(string.punctuation))
        filtered = [word for word in tokens if word not in nltk.corpus.stopwords.words('english')]
        preprocessed.append([stemmer.stem(item) for item in filtered])
    print(Counter(tokens).most_common(10))
    return (np.array(preprocessed))
</code>```

which should remove punctuation, tokenize, remove stop words and stem using the Porter Stemmer. However, it doesn't work correctly. For example, when I run this code:

```<code>s = ["The cow and of.", "and of dog the."]
print (Counter(preprocessText(s)))
</code>```

it produces this output:

```<code>[('and', 1), ('.', 1), ('dog', 1), ('the', 1), ('of', 1)]
</code>```

which doesn't remove punctuation or stopwords.

答:
The problem is that you're misusing translate. To use it correctly, you'd need to make a mapping table that (as the help string will tell you) maps "Unicode ordinals to Unicode ordinals, strings, or None.". E.g., like this:

```<code>>>> mapping = dict((ord(x), None) for x in string.punctuation)  # `None` means "delete"
>>> print("This.and.that".translate(mapping))
'Thisandthat'
</code>```

But if you do that to word tokens, you'll just be replacing punctuation tokens with empty strings. You could add a step to get rid of them, but I recommend simply selecting what you do want: namely, alphanumeric words.

```<code>tokens = nltk.word_tokenize(each.lower() if each.isalnum())
</code>```

That's all you need to change in your code.

Body:
I have the following function:

def preprocessText (data):
    stemmer = nltk.stem.porter.PorterStemmer()
    preprocessed = []
    for each in data:
        tokens = nltk.word_tokenize(each.lower().translate(string.punctuation))
        filtered = [word for word in tokens if word not in nltk.corpus.stopwords.words('english')]
        preprocessed.append([stemmer.stem(item) for item in filtered])
    print(Counter(tokens).most_common(10))
    return (np.array(preprocessed))

which should remove punctuation, tokenize, remove stop words and stem using the Porter Stemmer. However, it doesn't work correctly. For example, when I run this code:

s = ["The cow and of.", "and of dog the."]
print (Counter(preprocessText(s)))

it produces this output:

[('and', 1), ('.', 1), ('dog', 1), ('the', 1), ('of', 1)]

which doesn't remove punctuation or stopwords.

Body:
The problem is that you're misusing translate. To use it correctly, you'd need to make a mapping table that (as the help string will tell you) maps "Unicode ordinals to Unicode ordinals, strings, or None.". E.g., like this:

>>> mapping = dict((ord(x), None) for x in string.punctuation)  # `None` means "delete"
>>> print("This.and.that".translate(mapping))
'Thisandthat'

But if you do that to word tokens, you'll just be replacing punctuation tokens with empty strings. You could add a step to get rid of them, but I recommend simply selecting what you do want: namely, alphanumeric words.

tokens = nltk.word_tokenize(each.lower() if each.isalnum())

That's all you need to change in your code.


问:
Didn't find class "com.google.firebase.provider.FirebaseInitProvider"
Before, my program run well. But When I just updated my Android studio to the latest version (2.2 built on 15-sept-16), I am having the following error. When I built it, it says: Built sucessfully, but this error appears when I run my program:

E/AndroidRuntime: FATAL EXCEPTION: main                                                                            Process: com.example.androidtutorial, PID: 28293
  java.lang.RuntimeException: Unable to get provider
  com.google.firebase.provider.FirebaseInitProvider:
  java.lang.ClassNotFoundException: Didn't find class
  "com.google.firebase.provider.FirebaseInitProvider" on path:
  DexPathList[[zip file
  "/data/app/com.example.androidtutorial-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.androidtutorial-2/lib/x86,
  /system/lib, /vendor/lib]]
                                                                               at
  android.app.ActivityThread.installProvider(ActivityThread.java:5814)
                                                                               at
  android.app.ActivityThread.installContentProviders(ActivityThread.java:5403)
                                                                               at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:5342)
                                                                               at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                                               at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                                            Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.google.firebase.provider.FirebaseInitProvider" on path:
  DexPathList[[zip file
  "/data/app/com.example.androidtutorial-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.androidtutorial-2/lib/x86,
  /system/lib, /vendor/lib]]
                                                                               at
  dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                               at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
                                                                               at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                                                                               at
  android.app.ActivityThread.installProvider(ActivityThread.java:5799)
                                                                               at
  android.app.ActivityThread.installContentProviders(ActivityThread.java:5403)
                                                                               at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:5342)
                                                                               at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                                               at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

I already looked at other questions but the problem is not the same.
What am I doing wrong? Please help

答: just remove the google play services dependencies if you are including it. I am able to fix this error everytime using this. If you are using google maps or any other specific google service then include the dependency for that particular service only. Also try to check the version of google play service dependency.</p>


问:
Jenkins Master on Linux to trigger PowerShell script on windows slave
I have a Linux server where I have installed Jenkins and I have a windows slave server too. Just wanted to know is it possible to run powershell task from windows slave as we have Jenkins installed on Linux server? Or do I need to make a windows master to run all these powershell tasks?</p>

答: This is possible. Make sure that you select the appropriate slave (using label expressions) to execute the job.</p>