问:
Angular2 drag and drop unusable, but fixed if removing an unrelated part of the template
I am using Angular2 to implement drag and drop capabilities. I want to move "windows" that are inside "sessions", and each window has a number of bookmarks on it.

What I see is that when I have a slightly complex structure, let's say 4 sessions each one with 2 windows and each window with 5-10 bookmarks in it, then moving the windows from one session to another is very slow, up to 60seconds waiting (!!)

Then, if I don't include in the template the bookmarks, everything is snappy.

My first solution has been to render the bookmarks in a container outside the sessions, i.e. outside the drag&drop directives, and I then move the bookmarks by javascript (typescript) from the outside container to the session-window again when demanded.

The bookmarks are unrelated to the sessions, they are outside. but still if they are in the template, everything is unusable again. And if I remove them from the template, then everything is snappy again.

Then why is that? How is that they produce this impact? How could I fix it?

EDIT:
quick&dirty plunker, try to move the "title" sections and you will wait seconds
https://plnkr.co/edit/VyKo3BIvThn1BbMt3lCv?p=preview

And the second plunker without the bookmarks loaded (in app.html), it is snappy
https://plnkr.co/edit/ZEG9glXlgzVvapyOwvnE?p=preview

Part of the template

```<code><section id="current_bookmarks">
    <div *ngFor="let session_window_name of session_keys;"
        [bookmark_draggable_target]="{event_type:'moving_sessions',zone:session_window_name}"
        (drop_here)="onDrop($event)">
        <div class="session_window_name">
            <div class="session_window_name_title"><input class="input_session_names title" [id]="sessions[session_window_name].name+'_input'" type="text" value="{{sessions[session_window_name].title}}"></div>
        </div>
        <div *ngFor="let window_name of sessions[session_window_name].windows_keys; let i = index;"
            [bookmark_draggable]="{event_type:'moving_sessions',id:session_window_name+'_'+sessions[session_window_name].windows[window_name].id}">
            <session [index]="i" [from]="'stored'" [session]="session_window_name" [window]="sessions[session_window_name].windows[window_name]"></session>
        </div>
    </div>
</section>
</code>```

And if the part below is removed (within the same template), then the problem is fixed. BUT, there's no bookmark_draggable or bookmark_draggable_target directives here (!)

```<code><section id="bookmarks_pool">

    <ng-container *ngFor="let session_window_name of session_keys;">
        <div *ngFor="let window_name of sessions[session_window_name].windows_keys; let i = index;">
            <div *ngFor="let bookmark of sessions[session_window_name].windows[window_name].bookmarks; let i = index;" >
                <div>
                    <span class="material-icons list_shown" (click)="bookmark_delete(session_window_name+'_'+sessions[session_window_name].windows[window_name].id+'_'+i+'_bookmark')">label</span>
                    <span class="material-icons clear_hidden" (click)="bookmark_delete(session_window_name+'_'+sessions[session_window_name].windows[window_name].id+'_'+i+'_bookmark')">clear</span>
                    <a target="_blank" [href]="sanitize(bookmark.url)">{{bookmark.url}}</a>
                </div>
            </div>
        </div>
    </ng-container>

</section>
</code>```

The directives

```<code>import { Output, EventEmitter, Input, HostListener, Directive, HostBinding } from '@angular/core';

export interface DropTargetOptions {
    zone?: any;
    id?: any;
    event_type?:any;
}

@Directive({
    selector: '[bookmark_draggable_target]'
})

export class DropTargetDirective {
    private options: DropTargetOptions = {};

    @Input() set bookmark_draggable_target(options: DropTargetOptions) {
        if (options)
            this.options = options;
    }

    @Output('drop_here') drop = new EventEmitter();

    @HostListener('dragover', ['$event']) onDragOver(ev:any) {
        const {zone={},id={},event_type='default_event'} = this.options;
        if (ev.dataTransfer.types.indexOf('application/x-$'+event_type) >= 0)
            ev.preventDefault();
        else
            console.log(ev.dataTransfer.types)
    }

    @HostListener('drop', ['$event']) onDrop(ev:any) {
console.log('what')
        const {zone={},event_type='default_event'} = this.options;
        const info = JSON.parse(ev.dataTransfer.getData('application/x-$'+event_type));
        this.drop.next({info,zone});
    }
}
</code>```

and

```<code>import { Input, HostListener, Directive, HostBinding } from '@angular/core';

export interface DraggableOptions {
    id?: any; // ? is for optional
    event_type?:any;
}

@Directive({
    selector: '[bookmark_draggable]'
})

export class DraggableDirective {
    private options: DraggableOptions = {};

    @HostBinding('draggable') get draggable() {
        return true;
    }

    @Input() set bookmark_draggable(options: DraggableOptions) {
        if (options)
            this.options = options;
    }

    @HostListener('dragstart', ['$event']) onDragStart(event:any) {
        const {id={}, event_type='default_event'} = this.options;
//      event.dataTransfer.setDragImage(document.getElementById(id),0,0);
        event.dataTransfer.setData('application/x-$'+event_type, JSON.stringify(this.options));
    }

}
</code>```

EDIT: tab.config.js

```<code>/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
//      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
//      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
//      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
//      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
//      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
//      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
//      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
//      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
//      'rxjs':                      'npm:rxjs',
//      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'

      // chrome extension changes
      '@angular/core': 'lib/core.umd.js',
      '@angular/common': 'lib/common.umd.js',
      '@angular/compiler': 'lib/compiler.umd.js',
      '@angular/platform-browser': 'lib/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'lib/platform-browser-dynamic.umd.js',
      '@angular/http': 'lib/http.umd.js',
      '@angular/router': 'lib/router.umd.js',
      '@angular/forms': 'lib/forms.umd.js',

      'rxjs': 'lib/rxjs',
      'angular-in-memory-web-api': 'lib/in-memory-web-api.umd.js',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './tabs.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

System.import('app').catch(function(err){ console.error(err); });
</code>```

EDIT: package.json dependencies

```<code>  "dependencies": {
    "@angular/common": "^4.0.1",
    "@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",
    "angular-in-memory-web-api": "^0.3.1",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "^5.0.1",
    "systemjs": "^0.20.11",
    "zone.js": "^0.8.5"
  },
  "devDependencies": {
    "@types/jasmine": "^2.5.36",
    "@types/node": "^7.0.12",
    "canonical-path": "0.0.2",
    "concurrently": "^3.1.0",
    "http-server": "^0.9.0",
    "jasmine-core": "^2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "lite-server": "^2.2.2",
    "lodash": "^4.16.4",
    "protractor": "^5.1.1",
    "rimraf": "^2.5.4",
    "tslint": "^5.0.0",
    "typescript": "^2.0.10"
  },
</code>```

答:
1) Instead of using sanitize function i would use custom pure pipe.

```<code>@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url) {
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }
}
</code>```

Angular executes a pure pipe only when it detects a pure change to the input value while your sanitize function is executed during each change detection cycle.

```<code>[href]="bookmark.url | safe">
<img class="bookmark_favicon" [src]="('chrome://favicon/'+bookmark.url) | safe"
</code>```

https://plnkr.co/edit/7Qnxsh2a4OIODgQX13u0?p=preview

2) When you deal with sorting and moving items i would also use trackBy within ngFor

3) Another improvement is subscribing to dragover event outside angular zone:

drop-target.directive.ts

```<code>listener: Function;

constructor(private elRef: ElementRef, private zone: NgZone, private renderer: Renderer2) {
  zone.runOutsideAngular(() => {
    this.listener = this.renderer.listen(this.elRef.nativeElement, 'dragover', (ev) => {
        const { zone = {}, id = {}, event_type = 'default_event' } = this.options; // the one defined in "bookmark_draggable_target"
        if (ev.dataTransfer.types.indexOf('application/x-$' + event_type) >= 0) // the one sent in the event
            ev.preventDefault();
        else
            console.log(ev.dataTransfer.types)
    });
  })
}

ngOnDestroy() {
    this.listener();
}
</code>```

https://plnkr.co/edit/NXOZUk8L5bM2k6ceQUpx?p=preview

or

```<code>import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/fromEvent';
...
zone.runOutsideAngular(() => {
  this.subscription = Observable.fromEvent(this.elRef.nativeElement, 'dragover').subscribe((ev: any) => {
    const { zone = {}, id = {}, event_type = 'default_event' } = this.options; // the one defined in "bookmark_draggable_target"
    if (ev.dataTransfer.types.indexOf('application/x-$' + event_type) >= 0) // the one sent in the event
      ev.preventDefault();
    else
      console.log(ev.dataTransfer.types)
  });
})

ngOnDestroy() {
    this.subscription.unsubscribe();
}
</code>```

https://plnkr.co/edit/HrmPPHJ63WjYC1SHNUQp?p=preview

4) Next step is having component that will render bookmarks and have OnPush change detection strategy

Body:
I am using Angular2 to implement drag and drop capabilities. I want to move "windows" that are inside "sessions", and each window has a number of bookmarks on it.

What I see is that when I have a slightly complex structure, let's say 4 sessions each one with 2 windows and each window with 5-10 bookmarks in it, then moving the windows from one session to another is very slow, up to 60seconds waiting (!!)

Then, if I don't include in the template the bookmarks, everything is snappy.

My first solution has been to render the bookmarks in a container outside the sessions, i.e. outside the drag&drop directives, and I then move the bookmarks by javascript (typescript) from the outside container to the session-window again when demanded.

The bookmarks are unrelated to the sessions, they are outside. but still if they are in the template, everything is unusable again. And if I remove them from the template, then everything is snappy again.

Then why is that? How is that they produce this impact? How could I fix it?

EDIT:
quick&dirty plunker, try to move the "title" sections and you will wait seconds
https://plnkr.co/edit/VyKo3BIvThn1BbMt3lCv?p=preview

And the second plunker without the bookmarks loaded (in app.html), it is snappy
https://plnkr.co/edit/ZEG9glXlgzVvapyOwvnE?p=preview

Part of the template

<input class="input_session_names title" [id]="sessions[session_window_name].name+'_input'" type="text" value="{{sessions[session_window_name].title}}">

            <session [index]="i" [from]="'stored'" [session]="session_window_name" [window]="sessions[session_window_name].windows[window_name]"></session>

And if the part below is removed (within the same template), then the problem is fixed. BUT, there's no bookmark_draggable or bookmark_draggable_target directives here (!)

    <ng-container *ngFor="let session_window_name of session_keys;">

                    label
                    clear
                    {{bookmark.url}}

    </ng-container>

The directives

import { Output, EventEmitter, Input, HostListener, Directive, HostBinding } from '@angular/core';

export interface DropTargetOptions {
    zone?: any;
    id?: any;
    event_type?:any;
}

@Directive({
    selector: '[bookmark_draggable_target]'
})

export class DropTargetDirective {
    private options: DropTargetOptions = {};

    @Input() set bookmark_draggable_target(options: DropTargetOptions) {
        if (options)
            this.options = options;
    }

    @Output('drop_here') drop = new EventEmitter();

    @HostListener('dragover', ['$event']) onDragOver(ev:any) {
        const {zone={},id={},event_type='default_event'} = this.options;
        if (ev.dataTransfer.types.indexOf('application/x-$'+event_type) >= 0)
            ev.preventDefault();
        else
            console.log(ev.dataTransfer.types)
    }

    @HostListener('drop', ['$event']) onDrop(ev:any) {
console.log('what')
        const {zone={},event_type='default_event'} = this.options;
        const info = JSON.parse(ev.dataTransfer.getData('application/x-$'+event_type));
        this.drop.next({info,zone});
    }
}

and

import { Input, HostListener, Directive, HostBinding } from '@angular/core';

export interface DraggableOptions {
    id?: any; // ? is for optional
    event_type?:any;
}

@Directive({
    selector: '[bookmark_draggable]'
})

export class DraggableDirective {
    private options: DraggableOptions = {};

    @HostBinding('draggable') get draggable() {
        return true;
    }

    @Input() set bookmark_draggable(options: DraggableOptions) {
        if (options)
            this.options = options;
    }

    @HostListener('dragstart', ['$event']) onDragStart(event:any) {
        const {id={}, event_type='default_event'} = this.options;
//      event.dataTransfer.setDragImage(document.getElementById(id),0,0);
        event.dataTransfer.setData('application/x-$'+event_type, JSON.stringify(this.options));
    }

}

EDIT: tab.config.js

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
//      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
//      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
//      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
//      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
//      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
//      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
//      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
//      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
//      'rxjs':                      'npm:rxjs',
//      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'

      // chrome extension changes
      '@angular/core': 'lib/core.umd.js',
      '@angular/common': 'lib/common.umd.js',
      '@angular/compiler': 'lib/compiler.umd.js',
      '@angular/platform-browser': 'lib/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'lib/platform-browser-dynamic.umd.js',
      '@angular/http': 'lib/http.umd.js',
      '@angular/router': 'lib/router.umd.js',
      '@angular/forms': 'lib/forms.umd.js',

      'rxjs': 'lib/rxjs',
      'angular-in-memory-web-api': 'lib/in-memory-web-api.umd.js',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './tabs.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

System.import('app').catch(function(err){ console.error(err); });

EDIT: package.json dependencies

  "dependencies": {
    "@angular/common": "^4.0.1",
    "@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",
    "angular-in-memory-web-api": "^0.3.1",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "^5.0.1",
    "systemjs": "^0.20.11",
    "zone.js": "^0.8.5"
  },
  "devDependencies": {
    "@types/jasmine": "^2.5.36",
    "@types/node": "^7.0.12",
    "canonical-path": "0.0.2",
    "concurrently": "^3.1.0",
    "http-server": "^0.9.0",
    "jasmine-core": "^2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "lite-server": "^2.2.2",
    "lodash": "^4.16.4",
    "protractor": "^5.1.1",
    "rimraf": "^2.5.4",
    "tslint": "^5.0.0",
    "typescript": "^2.0.10"
  },

Body:
1) Instead of using sanitize function i would use custom pure pipe.

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url) {
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }
}

Angular executes a pure pipe only when it detects a pure change to the input value while your sanitize function is executed during each change detection cycle.

[href]="bookmark.url | safe">
<img class="bookmark_favicon" [src]="('chrome://favicon/'+bookmark.url) | safe"

https://plnkr.co/edit/7Qnxsh2a4OIODgQX13u0?p=preview

2) When you deal with sorting and moving items i would also use trackBy within ngFor

3) Another improvement is subscribing to dragover event outside angular zone:

drop-target.directive.ts

listener: Function;

constructor(private elRef: ElementRef, private zone: NgZone, private renderer: Renderer2) {
  zone.runOutsideAngular(() => {
    this.listener = this.renderer.listen(this.elRef.nativeElement, 'dragover', (ev) => {
        const { zone = {}, id = {}, event_type = 'default_event' } = this.options; // the one defined in "bookmark_draggable_target"
        if (ev.dataTransfer.types.indexOf('application/x-$' + event_type) >= 0) // the one sent in the event
            ev.preventDefault();
        else
            console.log(ev.dataTransfer.types)
    });
  })
}

ngOnDestroy() {
    this.listener();
}

https://plnkr.co/edit/NXOZUk8L5bM2k6ceQUpx?p=preview

or

import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/fromEvent';
...
zone.runOutsideAngular(() => {
  this.subscription = Observable.fromEvent(this.elRef.nativeElement, 'dragover').subscribe((ev: any) => {
    const { zone = {}, id = {}, event_type = 'default_event' } = this.options; // the one defined in "bookmark_draggable_target"
    if (ev.dataTransfer.types.indexOf('application/x-$' + event_type) >= 0) // the one sent in the event
      ev.preventDefault();
    else
      console.log(ev.dataTransfer.types)
  });
})

ngOnDestroy() {
    this.subscription.unsubscribe();
}

https://plnkr.co/edit/HrmPPHJ63WjYC1SHNUQp?p=preview

4) Next step is having component that will render bookmarks and have OnPush change detection strategy


来源: stackexchange

问:
install glib-2.52 on centos 6 from source
i want instal glib.2.52.0 on centos 6 64
in ./configure no error
enter image description here
 in make step has error :

```<code>        CC       libglib_2_0_la-gqueue.lo
    CC       libglib_2_0_la-grand.lo
    CC       libglib_2_0_la-gregex.lo
    gregex.c: In function ‘g_regex_get_max_lookbehind’:
    gregex.c:1573:18: error: ‘PCRE_INFO_MAXLOOKBEHIND’ undeclared (first use in this function)
                  PCRE_INFO_MAXLOOKBEHIND, &max_lookbehind);
                  ^
    gregex.c:1573:18: note: each undeclared identifier is reported only once for each function it appears in
    make[4]: *** [libglib_2_0_la-gr[enter image description here][2]egex.lo] Error 1
</code>```

i have
gcc (GCC) 4.9.2 20150212 (Red Hat 4.9.2-6)
g++ (GCC) 4.9.2 20150212 (Red Hat 4.9.2-6)

please help me

答:
The warning comes from PCRE; it seems you have an older version of PCRE installed; sadly, PCRE tends to change its API without notice.

You can build GLib with an internal copy of PCRE to avoid this issue, by passing the --with-pcre=internal argument to the configure script.

ContentLicense: CC BY-SA 3.0

Body:
i want instal glib.2.52.0 on centos 6 64
in ./configure no error
enter image description here
 in make step has error :

        CC       libglib_2_0_la-gqueue.lo
    CC       libglib_2_0_la-grand.lo
    CC       libglib_2_0_la-gregex.lo
    gregex.c: In function ‘g_regex_get_max_lookbehind’:
    gregex.c:1573:18: error: ‘PCRE_INFO_MAXLOOKBEHIND’ undeclared (first use in this function)
                  PCRE_INFO_MAXLOOKBEHIND, &max_lookbehind);
                  ^
    gregex.c:1573:18: note: each undeclared identifier is reported only once for each function it appears in
    make[4]: *** [libglib_2_0_la-gr[enter image description here][2]egex.lo] Error 1

i have
gcc (GCC) 4.9.2 20150212 (Red Hat 4.9.2-6)
g++ (GCC) 4.9.2 20150212 (Red Hat 4.9.2-6)

please help me


问:
Use of foreignKey between app models in Django 1.10
I have a website built in Django 1.10. The site has 3 different apps: teams, members and news.

The first app, called teams has one model called Team.

This is the Team/models.py:

```<code>from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify

class Team(models.Model):
        name = models.CharField(max_length=255)
        description = models.TextField()
        slug = models.CharField(max_length=255, default='team', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

The second app, called members has one model called Member.

This is the Member/models.py:

```<code>from django.db import models

class Piloto(models.Model):
        name = models.CharField(max_length=255)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

What I want is include the name of the team inside the member profile, so I know it should be something like:

```<code>team_of_member = models.ForeignKey();
</code>```

But I don't know what to put in the parenthesis or how to import the model of the team to the model of the member. I was following the documentation of Django 1.10 but it wasn't working, also I've tried this link but it doesn't work. Could you give a hand?  Thanks

Edit:
I tried to do as @Bulva was suggesting, so my code is now like this:

```<code>from django.db import models
from equipos.models import Team

class Member(models.Model):
        name = models.CharField(max_length=255)
        team = models.ForeignKey('teams.Team', null=True)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

答:
What you want is to provide the teams the member is a member of.  It all depends on your business logic.  A team has many members by definition, but can a member be a part of many teams?  If yes, you have a many-to-many relationship.  If no, you have a one-to-many relationship.

Under one-to-many assumption, the foreignkey information has to be put in the referenced model.  Then:

```<code>from django.db import models
from team.models import Team  # Generally, apps are in all lower-case (assuming your app is called team)

class Member(models.Model):
    name = models.CharField(max_length=255)
    team = models.ForeignKey('team.Team', related_name = 'members', null=True)  # Do not forget to put team.Team inside a pair of single-quotes.
    biography = models.TextField()
    slug = models.CharField(max_length=255, default='piloto', editable=True)

    class Meta:
            ordering = ('name',)

    def __unicode__(self):  # use def __str__(self): in Python 3+
            return self.name
</code>```

In your view, you can then say this:

```<code>albert_team = albert.team
albert_teammates = albert_team.members
</code>```

Under Many-to-Many assumption, it is more natural to capture the relationship in the team model:

```<code>from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify

class Team(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    slug = models.CharField(max_length=255, default='team', editable=True)
    members = models.ManyToManyField('team.Member', related_name = 'teams')

    class Meta:
            ordering = ('name',)

    def __unicode__(self):
            return self.name
</code>```

In views.py:

```<code>albert_teams = albert.teams

all_albert_teammates = []
for team in albert_teams:
    all_albert_teammates.append(team.members)
</code>```

Body:
I have a website built in Django 1.10. The site has 3 different apps: teams, members and news.

The first app, called teams has one model called Team.

This is the Team/models.py:

from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify

class Team(models.Model):
        name = models.CharField(max_length=255)
        description = models.TextField()
        slug = models.CharField(max_length=255, default='team', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

The second app, called members has one model called Member.

This is the Member/models.py:

from django.db import models

class Piloto(models.Model):
        name = models.CharField(max_length=255)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

What I want is include the name of the team inside the member profile, so I know it should be something like:

team_of_member = models.ForeignKey();

But I don't know what to put in the parenthesis or how to import the model of the team to the model of the member. I was following the documentation of Django 1.10 but it wasn't working, also I've tried this link but it doesn't work. Could you give a hand?  Thanks

Edit:
I tried to do as @Bulva was suggesting, so my code is now like this:

from django.db import models
from equipos.models import Team

class Member(models.Model):
        name = models.CharField(max_length=255)
        team = models.ForeignKey('teams.Team', null=True)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

Body:
What you want is to provide the teams the member is a member of.  It all depends on your business logic.  A team has many members by definition, but can a member be a part of many teams?  If yes, you have a many-to-many relationship.  If no, you have a one-to-many relationship.

Under one-to-many assumption, the foreignkey information has to be put in the referenced model.  Then:

from django.db import models
from team.models import Team  # Generally, apps are in all lower-case (assuming your app is called team)

class Member(models.Model):
    name = models.CharField(max_length=255)
    team = models.ForeignKey('team.Team', related_name = 'members', null=True)  # Do not forget to put team.Team inside a pair of single-quotes.
    biography = models.TextField()
    slug = models.CharField(max_length=255, default='piloto', editable=True)

    class Meta:
            ordering = ('name',)

    def __unicode__(self):  # use def __str__(self): in Python 3+
            return self.name

In your view, you can then say this:

albert_team = albert.team
albert_teammates = albert_team.members

Under Many-to-Many assumption, it is more natural to capture the relationship in the team model:

from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify

class Team(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    slug = models.CharField(max_length=255, default='team', editable=True)
    members = models.ManyToManyField('team.Member', related_name = 'teams')

    class Meta:
            ordering = ('name',)

    def __unicode__(self):
            return self.name

In views.py:

albert_teams = albert.teams

all_albert_teammates = []
for team in albert_teams:
    all_albert_teammates.append(team.members)


问:
emplace_back calls move constructor, and destructor
I try to emplace two instance of the class cBar to a vector with emplace_back function.

According to the reference calling an emplace_back only reserve the place in the vector, then create the new instance "in place".

Now, I tried to experiment with it:

```<code>#include <vector>
#include <iostream>
#include <memory>
#include <string>

class cBar
{
public:

    cBar(const int index);
    cBar(cBar&& other); //needed for emplace_back?
    ~cBar();

private:
    cBar(const cBar& other) = delete;
    cBar& operator=(const cBar& other) = delete;

public:
    int                         mIndex;

};

cBar::cBar(const int index) : mIndex(index)
{
    std::cout << "cBar being created ..." << std::endl;
}
cBar::cBar(cBar&& other) : mIndex(other.mIndex)
{
    std::cout << "cBar being moved ..." << std::endl;
}
cBar::~cBar()
{
    std::cout << "cBar being destroyed ..." << std::endl;
}

int main()
{
    std::vector<cBar> mBars;

    std::cout << "Begin to create 2 cBar instance, I am expecting 2 \"cBar being created ...\" messages here" << std::endl;
    mBars.emplace_back(0);//this supposed to call only cBar(const int index) constructor, and nothing more
    mBars.emplace_back(1);//this works as expected, only one constructor call

    //destroy all
    std::cout << "Destroy the 2 isntances (this works, I see the two expected \"cBar being destroyed ...\" messages here" << std::endl;
    mBars.clear();

    std::cin.get();
    return 0;
}
</code>```

Output:

```<code>Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here
cBar being created ...
cBar being moved ...
cBar being destroyed ...
cBar being created ...
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here
cBar being destroyed ...
cBar being destroyed ...
</code>```

If you run the one above, you will see that the first emplace_back creates the instance "in place", but then immediately call the move constructor, and then destructor is called.

What is more strange, that in case of the second emplace, I see the expected behavior: Only one constructor call.

I have two questions:

Why do I need to define a move constructor in my class if I just want to emplace_back items, and never use push_back.

In case of the first instance creation, why the move constructor, then the destructor is called? If I access the data of the first instance all seems to correct, so I have no idea why the move constructor, and destructor is called.

I use Visual Studio 2015.

Output with vector sizes in each step:

```<code>Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here
Vector size:0
cBar being created ...
Vector size:1
cBar being moved ...
cBar being destroyed ...
cBar being created ...
Vector size:2
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here
cBar being destroyed ...
cBar being destroyed ...
</code>```

答:
2.In case of the first instance creation, why the move constructor, then the destructor is called?

Because the insertion of the 2nd element by emplace_back causes the reallocation; the inner storage of the vector needs to be extended, the elements in the old storage have to be copied/moved to the new storage, then destroyed.

You can use reserve in advance to avoid reallocation.

1.Why do I need to define a move constructor in my class if I just want to emplace_back items, and never use push_back.

As the above explanation said, vector needs to move elements by copy/move operation. So you have to define the copy or move constructor for the class. This is true for both emplace_back and push_back, because they both add elements to vector and might cause reallocation.

Body:
I try to emplace two instance of the class cBar to a vector with emplace_back function.

According to the reference calling an emplace_back only reserve the place in the vector, then create the new instance "in place".

Now, I tried to experiment with it:

#include <vector>
#include <iostream>
#include <memory>
#include <string>

class cBar
{
public:

    cBar(const int index);
    cBar(cBar&& other); //needed for emplace_back?
    ~cBar();

private:
    cBar(const cBar& other) = delete;
    cBar& operator=(const cBar& other) = delete;

public:
    int                         mIndex;

};

cBar::cBar(const int index) : mIndex(index)
{
    std::cout << "cBar being created ..." << std::endl;
}
cBar::cBar(cBar&& other) : mIndex(other.mIndex)
{
    std::cout << "cBar being moved ..." << std::endl;
}
cBar::~cBar()
{
    std::cout << "cBar being destroyed ..." << std::endl;
}

int main()
{
    std::vector<cBar> mBars;

    std::cout << "Begin to create 2 cBar instance, I am expecting 2 \"cBar being created ...\" messages here" << std::endl;
    mBars.emplace_back(0);//this supposed to call only cBar(const int index) constructor, and nothing more
    mBars.emplace_back(1);//this works as expected, only one constructor call

    //destroy all
    std::cout << "Destroy the 2 isntances (this works, I see the two expected \"cBar being destroyed ...\" messages here" << std::endl;
    mBars.clear();

    std::cin.get();
    return 0;
}

Output:

Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here
cBar being created ...
cBar being moved ...
cBar being destroyed ...
cBar being created ...
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here
cBar being destroyed ...
cBar being destroyed ...

If you run the one above, you will see that the first emplace_back creates the instance "in place", but then immediately call the move constructor, and then destructor is called.

What is more strange, that in case of the second emplace, I see the expected behavior: Only one constructor call.

I have two questions:

Why do I need to define a move constructor in my class if I just want to emplace_back items, and never use push_back.

In case of the first instance creation, why the move constructor, then the destructor is called? If I access the data of the first instance all seems to correct, so I have no idea why the move constructor, and destructor is called.

I use Visual Studio 2015.

Output with vector sizes in each step:

Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here
Vector size:0
cBar being created ...
Vector size:1
cBar being moved ...
cBar being destroyed ...
cBar being created ...
Vector size:2
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here
cBar being destroyed ...
cBar being destroyed ...

ContentLicense: CC BY-SA 4.0


问:
Uploaded Image doesn't get stored in the 'uploads' folder using php code
I used the code from w3schools http://www.w3schools.com/php/php_file_upload.asp

However, when I click Upload my whole form gets submitted to the database, but the image doesn't get stored in the folder in my localhost.

php.ini file

```<code> <? php
     phpinfo();
     file_uploads = on;
 ?>
</code>```

upload.php file

```<code>  <?php
      $target_dir = "content/uploads/images";
      $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
      $uploadOk = 1;
      $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
   // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
      $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
     } else {
    echo "File is not an image.";
    $uploadOk = 0;
     }
  }
   // Check if file already exists
     if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
   }
  // Check file size
     if ($_FILES["fileToUpload"]["size"] > 500000) {
         echo "Sorry, your file is too large.";
         $uploadOk = 0;
   }
  // Allow certain file formats
     if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
     && $imageFileType != "gif" ) {
      echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
      $uploadOk = 0;
    }
  // Check if $uploadOk is set to 0 by an error
      if ($uploadOk == 0) {
      echo "Sorry, your file was not uploaded.";
  // if everything is ok, try to upload file
      } else {
     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
       echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
       echo "Sorry, there was an error uploading your file.";
    }
  }
?>
</code>```

Am I referring incorrectly to the destination folder or is there an error in the code?

答:
I had a problem with uploading files into the /uploads/requiredfolder.
Instead it was uploading files to /uploads and changing file names to requiredfolder & files names.

What I did was:

```<code>$slash="/";
$target_file1 = $target_dir .$slash . basename($_FILES["fileToUpload1"]["name"]);
</code>```

Hope it helps somebody

Body:
I used the code from w3schools http://www.w3schools.com/php/php_file_upload.asp

However, when I click Upload my whole form gets submitted to the database, but the image doesn't get stored in the folder in my localhost.

php.ini file

 <? php
     phpinfo();
     file_uploads = on;
 ?>

upload.php file

  <?php
      $target_dir = "content/uploads/images";
      $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
      $uploadOk = 1;
      $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
   // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
      $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
     } else {
    echo "File is not an image.";
    $uploadOk = 0;
     }
  }
   // Check if file already exists
     if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
   }
  // Check file size
     if ($_FILES["fileToUpload"]["size"] > 500000) {
         echo "Sorry, your file is too large.";
         $uploadOk = 0;
   }
  // Allow certain file formats
     if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
     && $imageFileType != "gif" ) {
      echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
      $uploadOk = 0;
    }
  // Check if $uploadOk is set to 0 by an error
      if ($uploadOk == 0) {
      echo "Sorry, your file was not uploaded.";
  // if everything is ok, try to upload file
      } else {
     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
       echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
       echo "Sorry, there was an error uploading your file.";
    }
  }
?>

Am I referring incorrectly to the destination folder or is there an error in the code?

Body:
I had a problem with uploading files into the /uploads/requiredfolder.
Instead it was uploading files to /uploads and changing file names to requiredfolder & files names.

What I did was:

$slash="/";
$target_file1 = $target_dir .$slash . basename($_FILES["fileToUpload1"]["name"]);

Hope it helps somebody


问:
Make a single property optional in TypeScript
In TypeScript, 2.2...

Let's say I have a Person type:

```<code>interface Person {
  name: string;
  hometown: string;
  nickname: string;
}
</code>```

And I'd like to create a function that returns a Person, but doesn't require a nickname:

```<code>function makePerson(input: ???): Person {
  return {...input, nickname: input.nickname || input.name};
}
</code>```

What should be the type of input? I'm looking for a dynamic way to specify a type that is identical to Person except that nickname is optional (nickname?: string | undefined). The closest thing I've figured out so far is this:

```<code>type MakePersonInput = Partial<Person> & {
  name: string;
  hometown: string;
}
</code>```

but that's not quite what I'm looking for, since I have to specify all the types that are required instead of the ones that are optional.

答:
After a lot of digging, I think what I'm trying to do just isn't possible in TypeScript... yet. When spread/rest types land, I think it will be, though, with syntax something along the lines of { ...Person, nickname?: string }.

For now, I've gone with a more verbose approach, declaring the properties that are required:

```<code>type MakePersonInput = Partial<Person> & {
  name: string;
  hometown: string;
};
function makePerson(input: MakePersonInput): Person {
  return {...input, nickname: input.nickname || input.name};
}
</code>```

This unfortunately requires me to update MakePersonInput whenever I add more required properties to Person, but it's impossible to forget to do this, because it will cause a type error in makePerson.

Body:
In TypeScript, 2.2...

Let's say I have a Person type:

interface Person {
  name: string;
  hometown: string;
  nickname: string;
}

And I'd like to create a function that returns a Person, but doesn't require a nickname:

function makePerson(input: ???): Person {
  return {...input, nickname: input.nickname || input.name};
}

What should be the type of input? I'm looking for a dynamic way to specify a type that is identical to Person except that nickname is optional (nickname?: string | undefined). The closest thing I've figured out so far is this:

type MakePersonInput = Partial<Person> & {
  name: string;
  hometown: string;
}

but that's not quite what I'm looking for, since I have to specify all the types that are required instead of the ones that are optional.

Body:
After a lot of digging, I think what I'm trying to do just isn't possible in TypeScript... yet. When spread/rest types land, I think it will be, though, with syntax something along the lines of { ...Person, nickname?: string }.

For now, I've gone with a more verbose approach, declaring the properties that are required:

type MakePersonInput = Partial<Person> & {
  name: string;
  hometown: string;
};
function makePerson(input: MakePersonInput): Person {
  return {...input, nickname: input.nickname || input.name};
}

This unfortunately requires me to update MakePersonInput whenever I add more required properties to Person, but it's impossible to forget to do this, because it will cause a type error in makePerson.


问:
Azure published app does not look like debugging app
I am trying to do a basic 'cloud project' -> 'Asp.Net Web Application' in VS2017

When I debug the application I get what I expect the 'MVC landing page'.

Then when I publish i get an Azure landing page, but I was expecting to see my 'MVC landing page'

It appears to deploy correctly, so I must be doing missing something obvious.

When I publish project from VS2017 I get this:

1>------ Build started: Project: zerocloud, Configuration: Release Any CPU ------
1>  zerocloud -> C:\Users\patrick\Documents\Visual Studio 2017\Projects\zerocloud\zerocloud\bin\zerocloud.dll
2>------ Publish started: Project: zerocloud, Configuration: Release Any CPU ------
2>Transformed Web.config using C:\Users\patrick\Documents\Visual Studio 2017\Projects\zerocloud\zerocloud\Web.Release.config into obj\Release\TransformWebConfig\transformed\Web.config.
2>Auto ConnectionString Transformed Views\Web.config into obj\Release\CSAutoParameterize\transformed\Views\Web.config.
2>Auto ConnectionString Transformed obj\Release\TransformWebConfig\transformed\Web.config into obj\Release\CSAutoParameterize\transformed\Web.config.
2>Copying all files to temporary location below for package/publish:
2>obj\Release\Package\PackageTmp.
2>Start Web Deploy Publish the Application/package to https://zerocloud20170318070155.scm.azurewebsites.net/msdeploy.axd?site=zerocloud20170318070155 ...
2>Adding ACL's for path (zerocloud20170318070155)
2>Adding ACL's for path (zerocloud20170318070155)
2>Updating file (zerocloud20170318070155\bin\zerocloud.dll).
2>Adding ACL's for path (zerocloud20170318070155)
2>Adding ACL's for path (zerocloud20170318070155)
2>Publish Succeeded.
2>Web App was published successfully http://zerocloud20170318070155.azurewebsites.net/
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========

答:
The website (http://zerocloud20170318070155.azurewebsites.net/) does load correct. Any chance you could be seeing a cached version?

This is what I see:


问:
combining a names array with the values array in object es6
I'm using the influxdata API and that data comes back in this format:

```<code>{
  "columns": [
    "time",
    "commit_time",
    "expiration_time",
    "kafka_consumer_group",
    "kafka_offset_group",
    "kafka_topic",
    "kafka_topic_parition",
    "message_metadata"
  ],
  "name": "offsets",
  "values": [
    [
      "2017-04-01T22:51:50.301Z",
      "1491087110301",
      "1491173510301",
      "group-general-service-master",
      0,
      "replica-conversion-dev",
      "6",
      "NO_METADATA"
    ],
    [
      "2017-04-01T22:51:50.301Z",
      "1491087110301",
      "1491173510301",
      "group-message-service-master",
      2,
      "service-dev",
      "4",
      "NO_METADATA"
    ],
    [
      "2017-04-01T22:51:50.303Z",
      "1491087110303",
      "1491173510303",
      "group-general-service-mk-threadc",
      7073,
      "posted-dev",
      "1",
      "NO_METADATA"
    ]
  ]
}
</code>```

The columns and values are separate but how can I combine the columns and values arrays together so that the values have the names with them:

```<code>{
    [
     {
      "time": "2017-04-01T22:51:50.301Z",
      "commit_time": "1491087110301",
      "expiration_time": "1491173510301",
      "kafka_consumer_group": "group-general-service-master",
      "kafka_offset_group": 0,
      "kafka_topic": "replica-conversion-dev",
      "kafka_topic_partition": "6",
      "message_metadata": "NO_METADATA"
     }
    ]...
}
</code>```

答:
Your desired result is not a valid object/array notation.

Assuming you would like to get an array of object, you can try the following:

```<code>res.values.map(arr => ({
    time: arr[0],
    commit_time: arr[1],
    expiration: arr[2],
    // you get the idea...
}));
</code>```

Or using array destructuring:

```<code>res.values.map(arr => {
    var obj = {};
    [
        obj.time,
        obj.commit_time,
        obj.expiration,
        // you get the idea...
    ] = arr;
    return obj;
});
</code>```

Body:
I'm using the influxdata API and that data comes back in this format:

{
  "columns": [
    "time",
    "commit_time",
    "expiration_time",
    "kafka_consumer_group",
    "kafka_offset_group",
    "kafka_topic",
    "kafka_topic_parition",
    "message_metadata"
  ],
  "name": "offsets",
  "values": [
    [
      "2017-04-01T22:51:50.301Z",
      "1491087110301",
      "1491173510301",
      "group-general-service-master",
      0,
      "replica-conversion-dev",
      "6",
      "NO_METADATA"
    ],
    [
      "2017-04-01T22:51:50.301Z",
      "1491087110301",
      "1491173510301",
      "group-message-service-master",
      2,
      "service-dev",
      "4",
      "NO_METADATA"
    ],
    [
      "2017-04-01T22:51:50.303Z",
      "1491087110303",
      "1491173510303",
      "group-general-service-mk-threadc",
      7073,
      "posted-dev",
      "1",
      "NO_METADATA"
    ]
  ]
}

The columns and values are separate but how can I combine the columns and values arrays together so that the values have the names with them:

{
    [
     {
      "time": "2017-04-01T22:51:50.301Z",
      "commit_time": "1491087110301",
      "expiration_time": "1491173510301",
      "kafka_consumer_group": "group-general-service-master",
      "kafka_offset_group": 0,
      "kafka_topic": "replica-conversion-dev",
      "kafka_topic_partition": "6",
      "message_metadata": "NO_METADATA"
     }
    ]...
}

Body:
Your desired result is not a valid object/array notation.

Assuming you would like to get an array of object, you can try the following:

res.values.map(arr => ({
    time: arr[0],
    commit_time: arr[1],
    expiration: arr[2],
    // you get the idea...
}));

Or using array destructuring:

res.values.map(arr => {
    var obj = {};
    [
        obj.time,
        obj.commit_time,
        obj.expiration,
        // you get the idea...
    ] = arr;
    return obj;
});


答:
Assuming you need an array of objects, you could iterate the values array and for the keys the columns array and assign the objects to the collecting object. Then return a new array with the objects.

var data = { columns: ["time", "commit_time", "expiration_time", "kafka_consumer_group", "kafka_offset_group", "kafka_topic", "kafka_topic_parition", "message_metadata"], name: "offsets", values: [["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-general-service-master", 0, "replica-conversion-dev", "6", "NO_METADATA"], ["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-message-service-master", 2, "service-dev", "4", "NO_METADATA"], ["2017-04-01T22:51:50.303Z", "1491087110303", "1491173510303", "group-general-service-mk-threadc", 7073, "posted-dev", "1", "NO_METADATA"]] },
    result = data.values.map(a => Object.assign({}, ...data.columns.map((k, i) => ({ [k]: a[i] }))));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: combining a names array with the values array in object es6

Body:
Assuming you need an array of objects, you could iterate the values array and for the keys the columns array and assign the objects to the collecting object. Then return a new array with the objects.

var data = { columns: ["time", "commit_time", "expiration_time", "kafka_consumer_group", "kafka_offset_group", "kafka_topic", "kafka_topic_parition", "message_metadata"], name: "offsets", values: [["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-general-service-master", 0, "replica-conversion-dev", "6", "NO_METADATA"], ["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-message-service-master", 2, "service-dev", "4", "NO_METADATA"], ["2017-04-01T22:51:50.303Z", "1491087110303", "1491173510303", "group-general-service-mk-threadc", 7073, "posted-dev", "1", "NO_METADATA"]] },
    result = data.values.map(a => Object.assign({}, ...data.columns.map((k, i) => ({ [k]: a[i] }))));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Nav bar background not displaying correctly and menu not drop down on click
I am trying to make my navbar background appear white on all screens. What could be prohibiting this from happening?I change the css to !important on default and it displays correctly only on wide. I have tried adding a media query at the small and medium screen size and no luck. Also, my menu is dropping down.

.navbar-default {
    background-color:white  !important;
    border-color: white  !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
       <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false"  aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
       </button>
      <img src=".png" alt=""/> <span class="ms-rteThemeForeColor-1-0 ms-rteFontSize-4 ms-rteFontFace-5"></span>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active">Home<span class="sr-only">(current)</span></li>
        <li>site1</li>
        <li>site2</li>
             <li>Site 3</li>
                  <li>Site 4</li></ul>
                </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav></code>```

答:
Do the following--

add

Use data-target="#bs-example-navbar-collapse-1".

Don't use !important rather use a id and style it.

Add custom css after bootstrap css.

Working snippet

#mynav {
    background-color:white;
    border-color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav id="mynav" class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
       <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"  aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
       </button>
      <img src=".png" alt=""/> <span class="ms-rteThemeForeColor-1-0 ms-rteFontSize-4 ms-rteFontFace-5"></span>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active">Home<span class="sr-only">(current)</span></li>
        <li>site1</li>
        <li>site2</li>
             <li>Site 3</li>
                  <li>Site 4</li></ul>
                </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav></code>```

Hope this helps!

Body:
I am trying to make my navbar background appear white on all screens. What could be prohibiting this from happening?I change the css to !important on default and it displays correctly only on wide. I have tried adding a media query at the small and medium screen size and no luck. Also, my menu is dropping down.

.navbar-default {
    background-color:white  !important;
    border-color: white  !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

       <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false"  aria-controls="navbar">
        Toggle navigation

       </button>

Home(current)

site1

site2

Site 3

Site 4

Body:
Do the following--

add <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Use data-target="#bs-example-navbar-collapse-1".

Don't use !important rather use a id and style it.

Add custom css after bootstrap css.

Working snippet

#mynav {
    background-color:white;
    border-color: white;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav id="mynav" class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
       <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"  aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
       </button>
      <a class="navbar-brand" href="#"><img src=".png" alt=""/>&#160;<span class="ms-rteThemeForeColor-1-0 ms-rteFontSize-4 ms-rteFontFace-5"></span></a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home<span class="sr-only">(current)</span></a></li>
        <li><a href="#">site1</a></li>
        <li><a href="#">site2</a></li>
             <li><a href="#">Site 3</a></li>
                  <li><a href="#">Site 4</a></li></ul>
                </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

Hope this helps!


问:
Constraints not working properly when iPhone language is Arabic for iOS version 9.0 and 9.1
When iPhone language is English all the constraints are working fine and properly for every iOS version but when I change the iPhone language to Arabic, views either disappears or goes to negative x coordinates (checked this by view hierarchy debugger) it shows the view's x coordinates is in -values.
and this happens only for iOS Version 9.0 and 9.1 with device language as Arabic.

I have changed the constraints from centre x to leading but it only shows view like this.

答: Check your constraints for the correct usage of "left / right" vs. "leading / trailing". "Left" means "left" and "right" means "right", always. "Leading" is on the left side for left-to-right text like English, but on the right side for right-to-left text like Arabic. If you mix them up, all kinds of things can go horribly wrong. </p>


问:
default error pages with angular2
I'd like to have a default error page my application. to achieve that, I implemented an error handler:

```<code>import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  router: Router;

  constructor(private injector: Injector) {
    this.router = this.injector.get(Router);
  }

  handleError(error) {
    this.router.navigate(['error']);
    throw error;
  }
}
</code>```

and create error-page component and route as well:

```<code>export const routes: Routes = [
  { path: '', component: RecipeListComponent },
  ...
  { path: 'error', component: ErrorPageComponent }
];
</code>```

but this line, at error hadler does not work... someone have some idea about why?

```<code>this.router.navigate(['error']);
</code>```

I mean, I'm receiving the error but I'm not able to route to my error page!

答:
Routes with an empty path '' and without child routes need pathMatch: 'full'

```<code>{ path: '', component: RecipeListComponent, pathMatch: 'full' },
</code>```

Also a leading / ensures the navigation works in all cases

```<code>this.router.navigate(['/error']);
</code>```

Title: default error pages with angular2

Body:
I'd like to have a default error page my application. to achieve that, I implemented an error handler:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  router: Router;

  constructor(private injector: Injector) {
    this.router = this.injector.get(Router);
  }

  handleError(error) {
    this.router.navigate(['error']);
    throw error;
  }
}

and create error-page component and route as well:

export const routes: Routes = [
  { path: '', component: RecipeListComponent },
  ...
  { path: 'error', component: ErrorPageComponent }
];

but this line, at error hadler does not work... someone have some idea about why?

this.router.navigate(['error']);

I mean, I'm receiving the error but I'm not able to route to my error page!

Body:
Routes with an empty path '' and without child routes need pathMatch: 'full'

{ path: '', component: RecipeListComponent, pathMatch: 'full' },

Also a leading / ensures the navigation works in all cases

this.router.navigate(['/error']);


问:
Strange issue with Laravel 5.4 app.js -> register and login content not displayed on live server version
I just rolled out a fresh laravel 5.4 installation with basic authentication. Nothing more. In local development everything works as expected. In the production version I'm not able to see the content of the pages login, register and password reset.

If I disable JavaScript everything is displayed. Also by renaming the first

 to
 it's getting displayed.

Here's the link to the live version:

glembo.de/login

I don't know what is wrong with the application. Here are all the steps I've done until deployment:

laravel new app

php artisan make:auth

uploaded the project to live server

edited .env file with environment specific data

php artisan migrate

Edit: All the code is out of the box from the laravel installer.

Here is the resources/assets/js/app.js

```<code>/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app'
});
</code>```

Here is the resources/assets/js/bootstrap.js

```<code>window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

window.$ = window.jQuery = require('jquery');

require('bootstrap-sass');

/**
 * Vue is a modern JavaScript library for building interactive web interfaces
 * using reactive data binding and reusable components. Vue's API is clean
 * and simple, leaving you to focus on building your next great project.
 */

window.Vue = require('vue');

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
};

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo'

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: 'your-pusher-key'
// });
</code>```

答:
I found the reason for this "error". It was caused by my own directive in the apache header settings. I placed a CSP directive:

```<code>Header set Content-Security-Policy "default-src * 'unsafe-inline'"
</code>```

wich caused the problem. Now everything works. Thanks to @MayankPandeyz for the detected error message with firefox. Unfortunately chrome and safari didn't throw an error into the console.

Body:
I just rolled out a fresh laravel 5.4 installation with basic authentication. Nothing more. In local development everything works as expected. In the production version I'm not able to see the content of the pages login, register and password reset.

If I disable JavaScript everything is displayed. Also by renaming the first

 to
 it's getting displayed.

Here's the link to the live version:

glembo.de/login

I don't know what is wrong with the application. Here are all the steps I've done until deployment:

laravel new app

php artisan make:auth

uploaded the project to live server

edited .env file with environment specific data

php artisan migrate

Edit: All the code is out of the box from the laravel installer.

Here is the resources/assets/js/app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app'
});

Here is the resources/assets/js/bootstrap.js

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

window.$ = window.jQuery = require('jquery');

require('bootstrap-sass');

/**
 * Vue is a modern JavaScript library for building interactive web interfaces
 * using reactive data binding and reusable components. Vue's API is clean
 * and simple, leaving you to focus on building your next great project.
 */

window.Vue = require('vue');

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
};

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo'

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: 'your-pusher-key'
// });

Body:
I found the reason for this "error". It was caused by my own directive in the apache header settings. I placed a CSP directive:

Header set Content-Security-Policy "default-src * 'unsafe-inline'"

wich caused the problem. Now everything works. Thanks to @MayankPandeyz for the detected error message with firefox. Unfortunately chrome and safari didn't throw an error into the console.


问:
Algorithm to find a graph with given number of nodes and edges
I have a number of nodes and each node has a number of edges.
e.g. node A has 3 edges, B has 2, C has 2, D has 1. I'm looking for an algorithm, to find possible undirected graphs without multiple edges between two nodes.
A possible solution for this simple example would be:

```<code>   A
  /|\
 / | \
B--C  D
</code>```

So A is connected with 3 other nodes because it has 3 connections, B is connected to A and C, D is connected with A.
All edges of all nodes must be satisfied.
Another example:

A(3), B(3), C(2), D(1), E(1)

solution:

```<code>     A-----D       OR:       A-----E
    / \                     / \
   /   \                   /   \
  C-----B-----E           C-----B-----D
</code>```

So, sometimes there are multiple solutions. But it is also possible, than there is no solution, e.g.
A(2), B(2), C(1)

There is no way to make a graph with these 3 nodes and their given number of edges.

Now, I am looking for an algorithm to find possible solutions for this problem. Is there maybe already a known problem like this?
I'd be glad for any kind of help or hints.

答:
This is known as the Graph Realization Problem.

The Erdős–Gallai theorem gives an easily-coded criterion for deciding when it is solvable and the Havel–Hakimi algorithm gives a recursive way of constructing such a graph. One of my favorite books in graph theory, "Pearls in Graph Theory" by Harsfield and Ringel has a nice discussion of the Havel–Hakimi algorithm.

Body:
I have a number of nodes and each node has a number of edges.
e.g. node A has 3 edges, B has 2, C has 2, D has 1. I'm looking for an algorithm, to find possible undirected graphs without multiple edges between two nodes.
A possible solution for this simple example would be:

   A
  /|\
 / | \
B--C  D

So A is connected with 3 other nodes because it has 3 connections, B is connected to A and C, D is connected with A.
All edges of all nodes must be satisfied.
Another example:

A(3), B(3), C(2), D(1), E(1)

solution:

     A-----D       OR:       A-----E
    / \                     / \
   /   \                   /   \
  C-----B-----E           C-----B-----D

So, sometimes there are multiple solutions. But it is also possible, than there is no solution, e.g.
A(2), B(2), C(1)

There is no way to make a graph with these 3 nodes and their given number of edges.

Now, I am looking for an algorithm to find possible solutions for this problem. Is there maybe already a known problem like this?
I'd be glad for any kind of help or hints.


问:
How do you change the style of a bootstrap checkbox
ive been looking on how to change the style of a bootstrap checkbox, and HAVE CHECKED THE OTHER ATTEMPTS! Made on here however every single attempt has not been successful, so is there a way to successfully change the style of a bootstrap check box or a normal checkbox.

```<code><label>text</label>
<input type="checkbox"/>
</code>```

http://jsfiddle.net/s12jx7su/

UPDATED

http://jsfiddle.net/s12jx7su/1/

答:
Maybe this is not exactly about the checkbox style, but you may consider using icons for each of checkbox state. For example http://fontawesome.io/icon/square-o/ for not checked state and http://fontawesome.io/icon/check-square-o/ for checked state.
For AngularJs it might be something like this:</p>

```<code><div ng-show="checked"><i class="fa fa-check-square-o" aria-hidden="true"></i></div>

<div ng-show="not-checked"><i class="fa fa-square-o" aria-hidden="true"></i></div>
</code>```

Body:
ive been looking on how to change the style of a bootstrap checkbox, and HAVE CHECKED THE OTHER ATTEMPTS! Made on here however every single attempt has not been successful, so is there a way to successfully change the style of a bootstrap check box or a normal checkbox.

text
<input type="checkbox"/>

http://jsfiddle.net/s12jx7su/

UPDATED

http://jsfiddle.net/s12jx7su/1/

Body:
Maybe this is not exactly about the checkbox style, but you may consider using icons for each of checkbox state. For example http://fontawesome.io/icon/square-o/ for not checked state and http://fontawesome.io/icon/check-square-o/ for checked state.
For AngularJs it might be something like this:

<div ng-show="checked"><i class="fa fa-check-square-o" aria-hidden="true"></i></div>

<div ng-show="not-checked"><i class="fa fa-square-o" aria-hidden="true"></i></div>


问:
C fscanf reading data from file error
I am new in C and I am trying to write a program that will read data from a file and store them in an array (so I can later work with them).

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

int day[3], month[3], year[3], hour[3], minute[3], second[3];
float value[3];

int main()
{
    // Open the file for read
    FILE* file1 = fopen("test.txt", "r");

    // Safety check
    if (file1 == NULL)
    {
        printf("Error: file1 == NULL\n");
        getchar();
        return 0;
    }

    // Open the new file for write
    FILE* file2 = fopen("new.txt", "w");

    // Safety check
    if (file2 == NULL)
    {
        printf("Error: file2 == NULL\n");
        getchar();
        return 0;
    }

    int j = 0;

        for (j = 0; j < 4; j++)
        {
            int count = fscanf(file1, "%d-%d-%d %d:%d:%d %f", &day[j], &month[j], &year[j], &hour[j], &minute[j], &second[j], &value[j]);
            printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
            // Check for finising early
            if (count == EOF)
            {
                printf("EOF");
            }
        }

    // Close the original file
    fclose(file1);
    // Close the target file
    fclose(file2);

    getchar();
}
</code>```

The file contains the data in this format:

```<code>20-03-17 08:49:01 28,515
20-03-17 08:49:31 29,1837
20-03-17 08:50:01 27,845
</code>```

EDIT AFTER COMMENTS:

The code now does not crash any more and it works almost perfectly!

This is what comes out:

```<code>20-3-17 8:49:1 28.514999
20-3-17 8:49:31 29.183701
20-3-17 8:50:1 27.844999
1105469112-1-20 17:8:49 0.000000
</code>```

is there a way to fix the decimal problem?
and any idea what is that last line?

Thank you for your time!

答:
In here:

```<code>for (j = 0; j < 3; j++)
{
    int count = fscanf(file1, "%i-%i-%i %i:%i:%i %f ", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
    printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
    // Check for finising early
    if (count == EOF)
    {
        printf("EOF");
    }
}
</code>```

Put & before every variables you wish to read.

Like:

```<code>for (j = 0; j < 3; j++)
{
    int count = fscanf(file1, "%i-%i-%i %i:%i:%i %f ", &day[j], &month[j], &year[j], &hour[j], &minute[j], &second[j], &value[j]);
    printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
    // Check for finising early
    if (count == EOF)
    {
        printf("EOF");
    }
}
</code>```

After question edited:

Ok, the problem is your data file(test.txt) is formated like

```<code>20-03-17 08:49:01 28,515
</code>```

, Not

```<code>20-03-17 08:49:01 28.515
</code>```

So %f will read only 28, not 28.515(since , is not used for floating point numbers). You have two choices: (1) Change 28,515 to 28.515 in your data file (2) Read 28 and 515 seperately. I think the first choice would be good.

Title: C fscanf reading data from file error

Body:
I am new in C and I am trying to write a program that will read data from a file and store them in an array (so I can later work with them).

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

int day[3], month[3], year[3], hour[3], minute[3], second[3];
float value[3];

int main()
{
    // Open the file for read
    FILE* file1 = fopen("test.txt", "r");

    // Safety check
    if (file1 == NULL)
    {
        printf("Error: file1 == NULL\n");
        getchar();
        return 0;
    }

    // Open the new file for write
    FILE* file2 = fopen("new.txt", "w");

    // Safety check
    if (file2 == NULL)
    {
        printf("Error: file2 == NULL\n");
        getchar();
        return 0;
    }

    int j = 0;

        for (j = 0; j < 4; j++)
        {
            int count = fscanf(file1, "%d-%d-%d %d:%d:%d %f", &day[j], &month[j], &year[j], &hour[j], &minute[j], &second[j], &value[j]);
            printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
            // Check for finising early
            if (count == EOF)
            {
                printf("EOF");
            }
        }

    // Close the original file
    fclose(file1);
    // Close the target file
    fclose(file2);

    getchar();
}

The file contains the data in this format:

20-03-17 08:49:01 28,515
20-03-17 08:49:31 29,1837
20-03-17 08:50:01 27,845

EDIT AFTER COMMENTS:

The code now does not crash any more and it works almost perfectly!

This is what comes out:

20-3-17 8:49:1 28.514999
20-3-17 8:49:31 29.183701
20-3-17 8:50:1 27.844999
1105469112-1-20 17:8:49 0.000000

is there a way to fix the decimal problem?
and any idea what is that last line?

Thank you for your time!

Body:
In here:

for (j = 0; j < 3; j++)
{
    int count = fscanf(file1, "%i-%i-%i %i:%i:%i %f ", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
    printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
    // Check for finising early
    if (count == EOF)
    {
        printf("EOF");
    }
}

Put & before every variables you wish to read.

Like:

for (j = 0; j < 3; j++)
{
    int count = fscanf(file1, "%i-%i-%i %i:%i:%i %f ", &day[j], &month[j], &year[j], &hour[j], &minute[j], &second[j], &value[j]);
    printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
    // Check for finising early
    if (count == EOF)
    {
        printf("EOF");
    }
}

After question edited:

Ok, the problem is your data file(test.txt) is formated like

20-03-17 08:49:01 28,515

, Not

20-03-17 08:49:01 28.515

So %f will read only 28, not 28.515(since , is not used for floating point numbers). You have two choices: (1) Change 28,515 to 28.515 in your data file (2) Read 28 and 515 seperately. I think the first choice would be good.


问:
Reading multiple value types from input to produce a linked list in c
I need to create a linked list based on info put in by the user. The user will put all info in at once and will contain a command and potentially be followed by a string to be loaded to the list or an int value (to reference nodes). ie input: ins monkey  OR prv 1 8  (In these cases the first 3 characters are the command 1st requires an insert of 'monkey' the 2nd would require the printing of nodes with a value between 1 and 8)

I have been working on this for weeks and cannot figure out how to have my program process the second part of the input. I store all the input into an array and then parse it into various arrays depending on the string values but I can't even figure out how to set the struct value for the string to the string that was put in after the command.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//self referring struct (keystone to LL)
struct Node
{
    char symbol [11];// each Node contains a array 'symbol'
    int count; // each Node contains a symbol counter
    struct Node *next; // points to the next node (this is the self referential aspect)
    };// end struct

int main()
{
    //function prototypes to be used by main
    void insert(struct Node**, struct Node **,char y[]);
    //char delSym(NodePtr *xPtr, char y[]);
    //char forceDel(NodePtr *xPtr, int z);
    void printList(struct Node*);

    struct Node *head, *tail;
     head = tail= NULL;

    //Declare variables needed for input and output
    char input[15];
    char cmd [4];
    char info [11];
    char str [11];
    char *x= info;
    int val=0;

    //possible command strings
    char ins[4]={'i','n','s'};
    char del[4]={'d','e','l'};
    char fde[4]={'f','d','e'};
    char pst[4]={'p','s','t'};
    char prl[4]={'p','r','l'};
    char pcr[4]={'p','c','r'};
    char ppr[4]={'p','p','r'};
    char psu[4]={'p','s','u'};
    char end[4]={'e','n','d'};

    // Prompt user for command and corresponding input
    puts("Please enter a command with corresponding value(s) where necessary");
    fgets(input,15, stdin);

    //Read the command
    memcpy(cmd, &input[0], 4 );// I am getting the command twice followed by the info????
    memcpy(info, &input[4], 11 );

    printf("%s\n", cmd);// put in to check memcpy
    printf("%s\n", info);

//While command is not 'end':
    while (memcmp(end,cmd,3) != 0)
    {
         // Read value(s) for the command, in necessary
         if (memcmp(ins,cmd, 3)==0)
         {
             insert(&head, &tail, info);
         }

.....

    void insert(struct Node **h, struct Node **t, char y[])
{
   struct Node *temp; // New node
   struct Node *previous; // Previous node
   struct Node *nodePtr; // To walk the LL

    //Allocates a new node and store the appropriate data
    if((temp =(struct Node *)maaloc(sizeof(struct Node)))==NULL)
        {
            printf("Node allocation failed.\n");
            exit(1);
        }
    temp->symbol = y;
    temp->count = count++;

    if(!*h)// If the list is empty make newNode the first node
    {
        *h = temp;
        temp->next = NULL;
    }
    else// Insert node if list is not empty
    {
        nodePtr = *h;

        previousNode = NULL;

        while(nodePtr !=NULL)
            {

            if(memcmp(nodePtr->symbol, temp->y, 11)!=0)
            {

                while(nodePtr != NULL && nodePtr->count < temp->count)
                    {
                        previousNode = nodePtr;
                        nodePtr = nodePtr ->next;
                    }
                if (previousNode == NULL)
                {
                    *h = temp;
                    temp->next = nodePtr;

                }
                else
                {
                    previousNode->next  = temp;
                    temp->next = nodePtr;
                }
            }
            else
            {
                nodePtr->count=count++;
            }
            nodePtr= nodePtr->next;
            }
    }
</code>```

答:
The particular problem that you describe can be traced to this line:

```<code>memcpy(cmd, &input[0], 4 );
</code>```

This code copies the first 4 characters of input into cmd[]. Presumably the fourth character is a space, so cmd is not a string, i.e., cmd is not a null-terminated character array. Thus, printf("%s\n", cmd) is undefined behavior, likely printing characters until a 0 is encountered somewhere past the end of cmd.

You could change the offending line so that it only copies three characters from input:

```<code>memcpy(cmd, &input[0], 3);
</code>```

Note that cmd is still not a string, as the final element has not been initialized to \0 yet. You could now do cmd[3] = '\0'. It may be better to initialize cmd at the point of declaration:

```<code>char cmd[4] = {0};
</code>```

Note also that fgets() keeps the newline (so long as the input buffer is large enough), so info will likely contain a \n before the \0 that you may wish to remove.

None of the "possible command strings" are actually strings, they are character arrays, and only the first three bytes have been initialized in each of them.

One fix would be to add null terminators:

```<code>char ins[4]={'i', 'n', 's', '\0'};
</code>```

It would be better to initialize from a string literal, and let the compiler determine the sizes of the arrays:

```<code>char ins[] = "ins";
</code>```

Body:
I need to create a linked list based on info put in by the user. The user will put all info in at once and will contain a command and potentially be followed by a string to be loaded to the list or an int value (to reference nodes). ie input: ins monkey  OR prv 1 8  (In these cases the first 3 characters are the command 1st requires an insert of 'monkey' the 2nd would require the printing of nodes with a value between 1 and 8)

I have been working on this for weeks and cannot figure out how to have my program process the second part of the input. I store all the input into an array and then parse it into various arrays depending on the string values but I can't even figure out how to set the struct value for the string to the string that was put in after the command.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//self referring struct (keystone to LL)
struct Node
{
    char symbol [11];// each Node contains a array 'symbol'
    int count; // each Node contains a symbol counter
    struct Node *next; // points to the next node (this is the self referential aspect)
    };// end struct

int main()
{
    //function prototypes to be used by main
    void insert(struct Node**, struct Node **,char y[]);
    //char delSym(NodePtr *xPtr, char y[]);
    //char forceDel(NodePtr *xPtr, int z);
    void printList(struct Node*);

    struct Node *head, *tail;
     head = tail= NULL;

    //Declare variables needed for input and output
    char input[15];
    char cmd [4];
    char info [11];
    char str [11];
    char *x= info;
    int val=0;

    //possible command strings
    char ins[4]={'i','n','s'};
    char del[4]={'d','e','l'};
    char fde[4]={'f','d','e'};
    char pst[4]={'p','s','t'};
    char prl[4]={'p','r','l'};
    char pcr[4]={'p','c','r'};
    char ppr[4]={'p','p','r'};
    char psu[4]={'p','s','u'};
    char end[4]={'e','n','d'};

    // Prompt user for command and corresponding input
    puts("Please enter a command with corresponding value(s) where necessary");
    fgets(input,15, stdin);

    //Read the command
    memcpy(cmd, &input[0], 4 );// I am getting the command twice followed by the info????
    memcpy(info, &input[4], 11 );

    printf("%s\n", cmd);// put in to check memcpy
    printf("%s\n", info);

//While command is not 'end':
    while (memcmp(end,cmd,3) != 0)
    {
         // Read value(s) for the command, in necessary
         if (memcmp(ins,cmd, 3)==0)
         {
             insert(&head, &tail, info);
         }

.....

    void insert(struct Node **h, struct Node **t, char y[])
{
   struct Node *temp; // New node
   struct Node *previous; // Previous node
   struct Node *nodePtr; // To walk the LL

    //Allocates a new node and store the appropriate data
    if((temp =(struct Node *)maaloc(sizeof(struct Node)))==NULL)
        {
            printf("Node allocation failed.\n");
            exit(1);
        }
    temp->symbol = y;
    temp->count = count++;

    if(!*h)// If the list is empty make newNode the first node
    {
        *h = temp;
        temp->next = NULL;
    }
    else// Insert node if list is not empty
    {
        nodePtr = *h;

        previousNode = NULL;

        while(nodePtr !=NULL)
            {

            if(memcmp(nodePtr->symbol, temp->y, 11)!=0)
            {

                while(nodePtr != NULL && nodePtr->count < temp->count)
                    {
                        previousNode = nodePtr;
                        nodePtr = nodePtr ->next;
                    }
                if (previousNode == NULL)
                {
                    *h = temp;
                    temp->next = nodePtr;

                }
                else
                {
                    previousNode->next  = temp;
                    temp->next = nodePtr;
                }
            }
            else
            {
                nodePtr->count=count++;
            }
            nodePtr= nodePtr->next;
            }
    }

Body:
The particular problem that you describe can be traced to this line:

memcpy(cmd, &input[0], 4 );

This code copies the first 4 characters of input into cmd[]. Presumably the fourth character is a space, so cmd is not a string, i.e., cmd is not a null-terminated character array. Thus, printf("%s\n", cmd) is undefined behavior, likely printing characters until a 0 is encountered somewhere past the end of cmd.

You could change the offending line so that it only copies three characters from input:

memcpy(cmd, &input[0], 3);

Note that cmd is still not a string, as the final element has not been initialized to \0 yet. You could now do cmd[3] = '\0'. It may be better to initialize cmd at the point of declaration:

char cmd[4] = {0};

Note also that fgets() keeps the newline (so long as the input buffer is large enough), so info will likely contain a \n before the \0 that you may wish to remove.

None of the "possible command strings" are actually strings, they are character arrays, and only the first three bytes have been initialized in each of them.

One fix would be to add null terminators:

char ins[4]={'i', 'n', 's', '\0'};

It would be better to initialize from a string literal, and let the compiler determine the sizes of the arrays:

char ins[] = "ins";


问:
Multiset<String> is shown empty on Android
On my Android app I'm using Multiset:

```<code>Multiset<String> multiset = HashMultiset.create();
</code>```

I want to convert it to a String using toString() method. The problem is that when it's a single item from every String then it looks OK, but when there are multiple strings with the same text, it is shown as [] instead of [A x 2, B, C x 3] for example.

How can I fix this so it will be shown as above instead of []?

答:
The easiest way is to convert Multiset to Set by calling Multiset#elementSet method:

```<code>Set<String> set = multiset.elementSet();
</code>```

Then just call toString on this method to get the desired result.

Body:
On my Android app I'm using Multiset:

Multiset<String> multiset = HashMultiset.create();

I want to convert it to a String using toString() method. The problem is that when it's a single item from every String then it looks OK, but when there are multiple strings with the same text, it is shown as [] instead of [A x 2, B, C x 3] for example.

How can I fix this so it will be shown as above instead of []?

Body:
The easiest way is to convert Multiset to Set by calling Multiset#elementSet method:

Set<String> set = multiset.elementSet();

Then just call toString on this method to get the desired result.


问:
How to pass an argument to 'isa' function in matlab
I want to check a variable is existing in Matlab workspace, then check its class.
All thing was done by commands in m file.
In the case, the name of the variable is a symbolic or character, how I can use isa function.

```<code>a='x';
isa(a,'timeseries')
</code>```

the above code is not worked, but if I change to

```<code>isa(x,'timeseries')
</code>```

it is ok, so how I can check the class of an object by not directly pass its name?
Thank you!

答:
You cannot use isa like that because when you pass a string as the first argument to isa, the class of that string is a char

```<code>isa('x', 'double')
%   0

isa('x', 'char')
%   1
</code>```

You could use eval to pass the value of x to isa

```<code>isa(eval('x'), 'double')
</code>```

However the better approach is to explicitly get the class of the variable using whos

```<code>S = whos('x');
strcmp(S.class, 'double')
%   1
</code>```

Body:
I want to check a variable is existing in Matlab workspace, then check its class.
All thing was done by commands in m file.
In the case, the name of the variable is a symbolic or character, how I can use isa function.

a='x';
isa(a,'timeseries')

the above code is not worked, but if I change to

isa(x,'timeseries')

it is ok, so how I can check the class of an object by not directly pass its name?
Thank you!

Body:
You cannot use isa like that because when you pass a string as the first argument to isa, the class of that string is a char

isa('x', 'double')
%   0

isa('x', 'char')
%   1

You could use eval to pass the value of x to isa

isa(eval('x'), 'double')

However the better approach is to explicitly get the class of the variable using whos

S = whos('x');
strcmp(S.class, 'double')
%   1


问:
Table Names in formula
In the Name Manager, I have a few Table Names defined: A, B, C and D.
Now, I want to check which formulas in the current workbook that contain one particular table name, say C. How I can check it apart from opening all formulas via the shortcut Control + ~ (or Ctrl + `)?

Or can I create such a formula via VBA?

答:
Please see images below. I am unable to comment on Ron Rosenfeld's comment due to lack of reputation points. But since that solution is incomplete, I am providing complete solution below.

See sample data taken by me -

Go to Home > Editing > Find & Select > Formulas

It will select formulas. Now go to Home > Styles > Conditional Formatting > EQUAL TO  and give the exact data you want to see

Hope it helps.

Title: Table Names in formula


问:
Windows equivalent to pause() syscall?
I would like to create a minimal Windows executable that does nothing - and is minimal in size.

All I care about is keeping a process entry in the task manager.

On Linux, this is very easy (it only takes 2 assembly instructions to use the pause
 syscall). How can I achieve similar results on Windows?

I'm trying to keep the executable size to a minimum, I don't want to have 10kB executable that literally does nothing.

Is there a way to achieve this in assembly? As I mentioned, I'd rather not include huge libraries just to make the process "hang".

答:
As Hans suggests in the comments, Sleep(INFINITE) is probably the simplest non-busy wait. It does however mean you have to kill the process with Task Manager to stop it.

Calling MessageBox followed by ExitProcess is probably less annoying if you need to start/stop this process multiple times.

You can probably get it down to 1 KiB with Visual C++ if you don't use the CRT (WinMainCRTStartup and compile with /Zl and smaller alignment)

You can get it slightly smaller with assembly but it is probably not worth it.

Title: Windows equivalent to pause() syscall?


问:
how i can count the element who have the class "goo"
i want to check how much element have class "goo".

are i can check for specific element or all using jQuery. show me how i can do this task in jQuery

答:
There a .length property to see how many elements a jQuery object references, so just combine that with a .class selector, like this:

```<code>var count = $(".goo").length;
</code>```

OwnerDisplayName: Steven Spielberg

ContentLicense: CC BY-SA 2.5

Body:
There a .length property to see how many elements a jQuery object references, so just combine that with a .class selector, like this:

var count = $(".goo").length;


问:
AttributeError: '_NamespacePath' object has no attribute 'sort'
I downloaded anaconda and when try to launch jupyter notebook using cmd, the error appear as AttributeError: '_NamespacePath' object has no attribute 'sort'. I am launching jypyter by typing jupyter notebook in cmd in windows os. Thanks for solving my error</p>

答:
I recommend you try this:

```<code>pip install --upgrade pip setuptools
</code>```

Based on https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2990.

Body:
I recommend you try this:

pip install --upgrade pip setuptools

Based on https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2990.


问:
Data Warehouse schema design - how to improve schema model
I have to create Data Warehouse for travel agency. I'm doing it for the first time. I've learned all the basics about star, snowflake and constellation schema and about creating data warhouses. I would like to ask what could be changed for better and if this design is good overall.

Here are my dimensions hierarchy:

Here is what I've achived for now (creating schema in MySQL Workbench):

答:
To take DimClient as an example. You have a nice surrogate key in there. Next you need to fill in all the things about a client (including the clientID) and then also include district, city, region and country. When you have all that in there, that dimension is complete.

You link to it in your Fact table by the ClientKey, so you need to put that Key in the Fact table as a foreign key.

Go through a similar process with your other dimensions, filling out both the dimensions and facts, and you'll be in a good shape. You don't need subdimensions to reflect your hiearchies: dimensions are denormalised.

Edit: The question was originally quite different, hence the answer above which was relevant to its original form.


问:
Counting zeroes in binary representation of decimal number
Here is my code: *edited

```<code>private static long zeros(long y){
    int count= 0;

    for(long i= y; i<=0; i/=2){
        if((i%2)==0) {
        count+=1;
   }
    return count;
  }
</code>```

It has to count all the zeros that given decimal number (long y) when method is called contains in binary form by using just one for loop, but I can't figure out why this won't work

答:
Your loop

```<code>for(long i= y; i>=y; i/=2)
</code>```

will finish after the first iteration for positive ys, except when y is zero, in which case the loop is infinite.

You should make several modifications to your program:

Make sure y is not negative before entering the loop

Add a special case producing the count of 1 when y is zero

Make your loop stop when i reaches zero.

Body:
Here is my code: *edited

private static long zeros(long y){
    int count= 0;

    for(long i= y; i<=0; i/=2){
        if((i%2)==0) {
        count+=1;
   }
    return count;
  }

It has to count all the zeros that given decimal number (long y) when method is called contains in binary form by using just one for loop, but I can't figure out why this won't work

Body:
Your loop

for(long i= y; i>=y; i/=2)

will finish after the first iteration for positive ys, except when y is zero, in which case the loop is infinite.

You should make several modifications to your program:

Make sure y is not negative before entering the loop

Add a special case producing the count of 1 when y is zero

Make your loop stop when i reaches zero.