问:
How to bind class to more than two options in Vue.js?
I have the following Vue.js bound HTML:

```<code><span :class="[obj.status === 'Online' ? 'badge-success' : 'badge-danger', 'badge badge-pill']">{{obj.status}}</span>
</code>```

I want to add another variant:

if obj.status === 'Updating' then the class should be badge-warning.

What is the best way to achieve this efficiently? I think I can add another ternary in the existing one but it will look messy.

答:
```<code><span v-if="obj.status === 'Online'" class="badge-success">
   {{obj.status}}
</span>

<span v-if="obj.status === 'Updating'" class="badge-warning">
   {{obj.status}}
</span>

<span v-if="obj.status !== 'Updating' && obj.status !== 'Online'" class="badge-default">
    {{obj.status}}
</span>
</code>```

You can conditionally render based on the status property.

The other way is to switch-case your class:

```<code>new Vue({
  el: "#app",
  data: {
    obj: {
       status: 'Online'
    }
  },
  methods: {
  getBadgeClass(status) {
      switch(status) {
          case 'Online':
               return 'badge-success';
          case 'Updating':
               return 'badge-warning';
          default:
               return 'badge-default'
      }
    }
  }
})
</code>```

and then in your template you can do this:

```<code><span :class="getBadgeClass(obj.status)">{{obj.status}}</span>
</code>```

Body:
I have the following Vue.js bound HTML:

{{obj.status}}

I want to add another variant:

if obj.status === 'Updating' then the class should be badge-warning.

What is the best way to achieve this efficiently? I think I can add another ternary in the existing one but it will look messy.

Body:
<span v-if="obj.status === 'Online'" class="badge-success">
   {{obj.status}}
</span>

<span v-if="obj.status === 'Updating'" class="badge-warning">
   {{obj.status}}
</span>

<span v-if="obj.status !== 'Updating' && obj.status !== 'Online'" class="badge-default">
    {{obj.status}}
</span>

You can conditionally render based on the status property.

The other way is to switch-case your class:

new Vue({
  el: "#app",
  data: {
    obj: {
       status: 'Online'
    }
  },
  methods: {
  getBadgeClass(status) {
      switch(status) {
          case 'Online':
               return 'badge-success';
          case 'Updating':
               return 'badge-warning';
          default:
               return 'badge-default'
      }
    }
  }
})

and then in your template you can do this:

<span :class="getBadgeClass(obj.status)">{{obj.status}}</span>


来源: stackexchange

问:
Cause line to wrap to new line after 100 characters
Is there a way in CSS that I can cause the 3rd element in this list, which is longer than the rest, to wrap to a new line if it extends over 100 characters? so that the rest of the text is on the next line?

I tried giving that
 a less width, but the content overflows.

I also tried overflow:hidden; and that cuts it off, but the rest is hidden and not on a new line.

How can I do this?

Here is a JS Fiddle where I am trying to do this: http://jsfiddle.net/ZC3zK/

答:
That worked pretty well for me :

Using a  tag where you want the line to wrap, and then prevent white spaces from wrapping.

.h2_wrap
{
   white-space: nowrap;
  font-size: 18px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 class="h2_wrap">Pretty long sentence that looks<wbr> better when cut at one specific spot</h2></code>```

ContentLicense: CC BY-SA 3.0

Body:
That worked pretty well for me :

Using a  tag where you want the line to wrap, and then prevent white spaces from wrapping.

.h2_wrap
{
   white-space: nowrap;
  font-size: 18px;
}

<h2 class="h2_wrap">Pretty long sentence that looks<wbr> better when cut at one specific spot</h2>

ContentLicense: CC BY-SA 4.0


问:
Facebook share text
I have these links on my site

```<code><a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/4')" target="_blank" style="text-decoration:none;"></a>
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/5')" target="_blank" style="text-decoration:none;"></a>
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/8')" target="_blank" style="text-decoration:none;"></a>
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/9')" target="_blank" style="text-decoration:none;"></a>
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/10')" target="_blank" style="text-decoration:none;"></a>
</code>```

with this javascript

```<code><script>
function fbs_click(location_place) {
        u=location_place;
        t=document.title;
        window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
        return false;
    }
</script>
</code>```

and i want to know if there is a way to add text or some sort to each one uniquely so that each link as a different body ..here is my code working but where and how do i add a description of some sort

答:
Edit: Read the OP wrong...
As far as I know/have found, you can't adjust the body text of what gets displayed in the share dialog using facebook.com/sharer.php. You may have to look into the other methods of social interaction with facebook api.</p>

Title: Facebook share text

Body:
I have these links on my site

<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/4')" target="_blank" style="text-decoration:none;">
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/5')" target="_blank" style="text-decoration:none;">
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/8')" target="_blank" style="text-decoration:none;">
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/9')" target="_blank" style="text-decoration:none;">
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" class="fb_share_button" onclick="return fbs_click('http://site.com/profile/10')" target="_blank" style="text-decoration:none;">

with this javascript

and i want to know if there is a way to add text or some sort to each one uniquely so that each link as a different body ..here is my code working but where and how do i add a description of some sort


问:
Search by belongs_to custom foreign_key
I try to search for a match via the 2 teams, I tried several syntax, but nothing helps ...

Model Match:

```<code>class Match < ApplicationRecord
  belongs_to :home, class_name: 'Team', foreign_key: :home_id
  belongs_to :away, class_name: 'Team', foreign_key: :away_id
end
</code>```

Model Team:

```<code>class Team < ApplicationRecord
  has_many :home_matches, class_name: 'Match', foreign_key: :home_id
  has_many :away_matches, class_name: 'Match', foreign_key: :away_id

  # Fields: name
end
</code>```

I tried something like this:

```<code> Match.includes(:home, :away).where(homes: { name: 'Germany' }, aways: {name: 'China'})
</code>```

Error:

ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  missing
  FROM-clause entry for table "homes")

答:
Option 1.

Inspect in Rails Console query puts Match.joins(:home, :away).to_sql.
You could get result like:

```<code>SELECT "matches".* FROM "matches" INNER JOIN "teams" ON "teams"."id" = "matches"."home_id" INNER JOIN "teams" "away_matches" ON "away_matches"."id" = "matches"."away_id"
</code>```

If so, use query like

```<code>Match.joins(:home, :away).where(teams: { name: 'Germany' }, away_matches: {name: 'China'})
</code>```

Option 2.

Try query like

```<code>Match.where(home: Team.where(name: 'Germany'), away: Team.where(name: 'China'))
</code>```

You can also pre-find ids of Teams:

```<code>home_id = Team.find_by(name: 'Germany').id
away_id = Team.find_by(name: 'China').id
Match.where(home_id: home_id, away_id: away_id)
</code>```

Title: Search by belongs_to custom foreign_key

Body:
I try to search for a match via the 2 teams, I tried several syntax, but nothing helps ...

Model Match:

class Match < ApplicationRecord
  belongs_to :home, class_name: 'Team', foreign_key: :home_id
  belongs_to :away, class_name: 'Team', foreign_key: :away_id
end

Model Team:

class Team < ApplicationRecord
  has_many :home_matches, class_name: 'Match', foreign_key: :home_id
  has_many :away_matches, class_name: 'Match', foreign_key: :away_id

  # Fields: name
end

I tried something like this:

 Match.includes(:home, :away).where(homes: { name: 'Germany' }, aways: {name: 'China'})

Error:

ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  missing
  FROM-clause entry for table "homes")

Body:
Option 1.

Inspect in Rails Console query puts Match.joins(:home, :away).to_sql.
You could get result like:

SELECT "matches".* FROM "matches" INNER JOIN "teams" ON "teams"."id" = "matches"."home_id" INNER JOIN "teams" "away_matches" ON "away_matches"."id" = "matches"."away_id"

If so, use query like

Match.joins(:home, :away).where(teams: { name: 'Germany' }, away_matches: {name: 'China'})

Option 2.

Try query like

Match.where(home: Team.where(name: 'Germany'), away: Team.where(name: 'China'))

You can also pre-find ids of Teams:

home_id = Team.find_by(name: 'Germany').id
away_id = Team.find_by(name: 'China').id
Match.where(home_id: home_id, away_id: away_id)


答:
You could parse it using JsonPath :</p>

```<code>static String json = "...";
public static void main(String[] args) {
    String pageName = JsonPath.read(json, "$.pageInfo.pageName");
    System.out.println(pageName);

    Integer posts = JsonPath.read(json, "$.posts.length()");

    for(int i=0; i < posts; i++) {
        String post_id = JsonPath.read(json, "$.posts[" + i + "].post_id");
        System.out.println(post_id);
    }
}
</code>```

Title: How to get each value from JSON string

Body:
I have this JSON String and I need to get each docmanId and each dz so,I could loop through them and work with them.

I have tried using gson library to do that,but I dont seem to figure it out.

JSON Array :

[{"docmanId":1,"dz":"CR"},
{"docmanId":1,"dz":"EU"},
{"docmanId":1,"dz":"JD"},
{"docmanId":1,"dz":"LT"},
{"docmanId":10,"dz":"CR"},
{"docmanId":10,"dz":"EU"},
{"docmanId":10,"dz":"LT"},
{"docmanId":100,"dz":"CR"},
{"docmanId":100,"dz":"EU"},
{"docmanId":100,"dz":"JD"},
{"docmanId":100,"dz":"LT"},
{"docmanId":1000,"dz":"CR"},
{"docmanId":1000,"dz":"EU"},
{"docmanId":1000,"dz":"JD"},
{"docmanId":1000,"dz":"LT"},
{"docmanId":10000,"dz":"ES"},
{"docmanId":10000,"dz":"EU"},
{"docmanId":10000,"dz":"JD"},
{"docmanId":100000,"dz":"CR"},
{"docmanId":100000,"dz":"EU"},
{"docmanId":100000,"dz":"JD"},
{"docmanId":100000,"dz":"LT"},
{"docmanId":100001,"dz":"CR"},
{"docmanId":100001,"dz":"EU"},
{"docmanId":100001,"dz":"LT"},
{"docmanId":100002,"dz":"CR"},
{"docmanId":100002,"dz":"EU"},
{"docmanId":100002,"dz":"JD"},
{"docmanId":100003,"dz":"CR"},
{"docmanId":100003,"dz":"EU"},
{"docmanId":100003,"dz":"JD"},
{"docmanId":100003,"dz":"LT"},
{"docmanId":100004,"dz":"CR"},
{"docmanId":100004,"dz":"EU"},
{"docmanId":100004,"dz":"JD"},
{"docmanId":100005,"dz":"CR"},
{"docmanId":100005,"dz":"EU"},
{"docmanId":100005,"dz":"JD"},
{"docmanId":100005,"dz":"LT"},
{"docmanId":100006,"dz":"CR"},
{"docmanId":100006,"dz":"EU"},
{"docmanId":100006,"dz":"JD"},
{"docmanId":100006,"dz":"LT"},
{"docmanId":100007,"dz":"CR"},
{"docmanId":100007,"dz":"EU"},
{"docmanId":100007,"dz":"JD"}]

Body:
You could parse it using JsonPath :

static String json = "...";
public static void main(String[] args) {
    String pageName = JsonPath.read(json, "$.pageInfo.pageName");
    System.out.println(pageName);

    Integer posts = JsonPath.read(json, "$.posts.length()");

    for(int i=0; i < posts; i++) {
        String post_id = JsonPath.read(json, "$.posts[" + i + "].post_id");
        System.out.println(post_id);
    }
}


问:
Using item-text as a function to customize Vietify v-combobox items
I'd like to customize my combobox items, to as using item-text prop as described here:
https://vuetifyjs.com/en/components/combobox

Here is a fork of a vuetify example where I define a function whick always returns 'test':

```<code>:item-text="() => 'test'"
</code>```

Codepen : https://codepen.io/anon/pen/yWxQdN?editors=1010

Is there a reason why my function is not called?

答:
For your Codepen example, instead of the item-text property, use the selection scoped slot.

```<code><v-combobox :items="items">
    <template slot="selection" slot-scope="{item, index}">
        {{ yourFunc() }}
    </template>
</v-combobox>
</code>```

Body:
I'd like to customize my combobox items, to as using item-text prop as described here:
https://vuetifyjs.com/en/components/combobox

Here is a fork of a vuetify example where I define a function whick always returns 'test':

:item-text="() => 'test'"

Codepen : https://codepen.io/anon/pen/yWxQdN?editors=1010

Is there a reason why my function is not called?

Body:
For your Codepen example, instead of the item-text property, use the selection scoped slot.

<v-combobox :items="items">
    <template slot="selection" slot-scope="{item, index}">
        {{ yourFunc() }}
    </template>
</v-combobox>


问:
`Can't bind to 'eventList' since it isn't a known property of 'header-nav'.`
I am getting above error on async value added with my template. how to fix this for pass out my testing?

here is the template:

```<code><header-nav
    [eventList]="eventList$ | async"
    [eventListSize]="(eventList$ | async).length"
    (selectedEvent)="eventSelected($event)"
    (setLang)="langChanged($event)"
    [currentLang]="currentLang$ | async"
    [langList] = "langList$ | async"
    (leftNavi) = "leftNaviHandler($event)"
    >
</header-nav>
</code>```

Here is my component file:

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Store, select } from "@ngrx/store";
import { Observable } from "rxjs";
import { ModelEvent, EventState } from "./../../../calendar/models/model.event";
import { ModelLang, ModelLonguage } from "./../../../shared-components/models/models";
import { CalendarActions, Load, EventSelected } from "./../../../calendar/state/calendar.actions";
import * as fromRoot from  "./../../../calendar/state";
import * as fromObservables from  "./../../state";
import { Lang, LoadLang } from "./../../state/actions/shared.actions";
import { ShowNavi } from "./../../../shared-components/state/actions/shared.actions";

@Component({
    selector: 'header-nav-shell',
    templateUrl: './header-nav-shell.component.html',
    styleUrls: ['./header-nav-shell.component.scss']
})
export class HeaderNavShellComponent implements OnInit {
    /**
    * declartion of observable events
    */
    eventList$:Observable<ModelEvent[]>;
    eventListSize$:number;
    currentLang$:Observable<string>;
    langList$:Observable<ModelLonguage[]>;

    constructor(private store:Store<fromRoot.NewState>, private router:Router) { }

    ngOnInit() {
        this.store.dispatch(new Load());
        this.store.dispatch( new LoadLang());
        this.eventList$ = this.store.pipe(select(fromRoot.getEvents));
        this.currentLang$ = this.store.pipe(select(fromObservables.getCurrentLang));
        this.langList$ = this.store.pipe(select(fromObservables.getLangList));
    }

    eventSelected(event) {
        this.store.dispatch(new EventSelected(event));
        this.router.navigateByUrl("iboCalendar");
    }

    langChanged(event) {
        this.store.dispatch( new Lang(event.Name));
    }

    leftNaviHandler(event):void {
        this.store.dispatch(new ShowNavi(event));
    }

}
</code>```

as well here is my test spec file:

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

import { HeaderNavShellComponent } from './header-nav-shell.component';
import { HeaderComponent } from './../../header/header.component';
import { Store, select } from "@ngrx/store";
import { StoreModule } from '@ngrx/store';
import { reducerShared } from "./../../state/reducers/shared.reducer";

describe('HeaderNavShellComponent', () => {

    let component: HeaderNavShellComponent;
    let fixture: ComponentFixture<HeaderNavShellComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ HeaderNavShellComponent, HeaderComponent ],
            imports:[StoreModule.forFeature("shared", reducerShared )]
        })
        .compileComponents();
    }));

     beforeEach(fakeAsync(() => {
        fixture = TestBed.createComponent(HeaderNavShellComponent);
        component = fixture.componentInstance;
        tick(1000);
        fixture.detectChanges();
    }));

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

});
</code>```

I am getting the following error:

```<code>Failed: Template parse errors:
Can't bind to 'eventList' since it isn't a known property of 'header-nav'.
1. If 'header-nav' is an Angular component and it has 'eventList' input, then verify that it is part of this module.
2. If 'header-nav' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("<app-header></app-header>
<header-nav
    [ERROR ->][eventList]="eventList$ | async"
    [eventListSize]="(eventList$ | async).length"
    (selectedEvent)="eve"): ng:///DynamicTestModule/HeaderNavShellComponent.html@2:1
</code>```

Any one help me to understand, what is the dependency i am missing here or how to initiate the test in case when you async pipes?

Thanks in advance.

答:
All the other components that are used by that component should be declared in TestBed configuration, so HeaderNavComponent should be added to the declarations of the TestBed.

Or you can just use CUSTOM_ELEMENTS_SCHEMA in TestBed configuration instead of declaring those components.

```<code>beforeEach(async(() => {
  TestBed.configureTestingModule({
      declarations: [ HeaderNavShellComponent, HeaderComponent ],
      imports:[StoreModule.forFeature("shared", reducerShared )],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
  })
  .compileComponents();
}));
</code>```

Body:
I am getting above error on async value added with my template. how to fix this for pass out my testing?

here is the template:

Here is my component file:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Store, select } from "@ngrx/store";
import { Observable } from "rxjs";
import { ModelEvent, EventState } from "./../../../calendar/models/model.event";
import { ModelLang, ModelLonguage } from "./../../../shared-components/models/models";
import { CalendarActions, Load, EventSelected } from "./../../../calendar/state/calendar.actions";
import * as fromRoot from  "./../../../calendar/state";
import * as fromObservables from  "./../../state";
import { Lang, LoadLang } from "./../../state/actions/shared.actions";
import { ShowNavi } from "./../../../shared-components/state/actions/shared.actions";

@Component({
    selector: 'header-nav-shell',
    templateUrl: './header-nav-shell.component.html',
    styleUrls: ['./header-nav-shell.component.scss']
})
export class HeaderNavShellComponent implements OnInit {
    /**
    * declartion of observable events
    */
    eventList$:Observable<ModelEvent[]>;
    eventListSize$:number;
    currentLang$:Observable<string>;
    langList$:Observable<ModelLonguage[]>;

    constructor(private store:Store<fromRoot.NewState>, private router:Router) { }

    ngOnInit() {
        this.store.dispatch(new Load());
        this.store.dispatch( new LoadLang());
        this.eventList$ = this.store.pipe(select(fromRoot.getEvents));
        this.currentLang$ = this.store.pipe(select(fromObservables.getCurrentLang));
        this.langList$ = this.store.pipe(select(fromObservables.getLangList));
    }

    eventSelected(event) {
        this.store.dispatch(new EventSelected(event));
        this.router.navigateByUrl("iboCalendar");
    }

    langChanged(event) {
        this.store.dispatch( new Lang(event.Name));
    }

    leftNaviHandler(event):void {
        this.store.dispatch(new ShowNavi(event));
    }

}

as well here is my test spec file:

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

import { HeaderNavShellComponent } from './header-nav-shell.component';
import { HeaderComponent } from './../../header/header.component';
import { Store, select } from "@ngrx/store";
import { StoreModule } from '@ngrx/store';
import { reducerShared } from "./../../state/reducers/shared.reducer";

describe('HeaderNavShellComponent', () => {

    let component: HeaderNavShellComponent;
    let fixture: ComponentFixture<HeaderNavShellComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ HeaderNavShellComponent, HeaderComponent ],
            imports:[StoreModule.forFeature("shared", reducerShared )]
        })
        .compileComponents();
    }));

     beforeEach(fakeAsync(() => {
        fixture = TestBed.createComponent(HeaderNavShellComponent);
        component = fixture.componentInstance;
        tick(1000);
        fixture.detectChanges();
    }));

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

});

I am getting the following error:

Failed: Template parse errors:
Can't bind to 'eventList' since it isn't a known property of 'header-nav'.
1. If 'header-nav' is an Angular component and it has 'eventList' input, then verify that it is part of this module.
2. If 'header-nav' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("<app-header></app-header>
][eventList]="eventList$ | async"
    [eventListSize]="(eventList$ | async).length"
    (selectedEvent)="eve"): ng:///DynamicTestModule/HeaderNavShellComponent.html@2:1

Any one help me to understand, what is the dependency i am missing here or how to initiate the test in case when you async pipes?

Thanks in advance.

Body:
All the other components that are used by that component should be declared in TestBed configuration, so HeaderNavComponent should be added to the declarations of the TestBed.

Or you can just use CUSTOM_ELEMENTS_SCHEMA in TestBed configuration instead of declaring those components.

beforeEach(async(() => {
  TestBed.configureTestingModule({
      declarations: [ HeaderNavShellComponent, HeaderComponent ],
      imports:[StoreModule.forFeature("shared", reducerShared )],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
  })
  .compileComponents();
}));


问:
Convert time (HH:MM:SS) to minutes in python
How to convert HH:MM:SS to Minutes?

I tried below works fine:

```<code>  import datetime as DT
  t1 = DT.datetime.strptime('0:10:00', '%H:%M:%S')
</code>```

I tried another example and getting error:

```<code>  import datetime as DT
  t1 = DT.datetime.strptime('9715:56:46', '%H:%M:%S')
</code>```

Error:

```<code>  ValueError: time data '9715:56:46' does not match format '%H:%M:%S'
</code>```

In this example it support Max 23 for %H, If my hours has more than 23(in this case i have 9715 hours) how to get it?

答:
simple one that supports d:h:m:s / h:m:s / m:s / s !

```<code>def dhms_to_sec(dhms_str):
    '''supports also format of d:h:m:s, h:m:s, m:s and s'''
    _,d,h,m,s = (':0'*10+dhms_str).rsplit(':',4)
    return int(d)*24*60*60+int(h)*60*60+int(m)*60+int(s)

# examples:
print(dhms_to_sec('04'))  # will print 4
print(dhms_to_sec('1:04'))  # will print 64
print(dhms_to_sec('1:01:04'))  # will print 3664
print(dhms_to_sec('1:1:4'))  # will print 3664
</code>```

you can convert it to minutes by /60 ...
it will accept also weird cases like 1:56:0

Body:
How to convert HH:MM:SS to Minutes?

I tried below works fine:

  import datetime as DT
  t1 = DT.datetime.strptime('0:10:00', '%H:%M:%S')

I tried another example and getting error:

  import datetime as DT
  t1 = DT.datetime.strptime('9715:56:46', '%H:%M:%S')

Error:

  ValueError: time data '9715:56:46' does not match format '%H:%M:%S'

In this example it support Max 23 for %H, If my hours has more than 23(in this case i have 9715 hours) how to get it?

Body:
simple one that supports d:h:m:s / h:m:s / m:s / s !

def dhms_to_sec(dhms_str):
    '''supports also format of d:h:m:s, h:m:s, m:s and s'''
    _,d,h,m,s = (':0'*10+dhms_str).rsplit(':',4)
    return int(d)*24*60*60+int(h)*60*60+int(m)*60+int(s)

# examples:
print(dhms_to_sec('04'))  # will print 4
print(dhms_to_sec('1:04'))  # will print 64
print(dhms_to_sec('1:01:04'))  # will print 3664
print(dhms_to_sec('1:1:4'))  # will print 3664

you can convert it to minutes by /60 ...
it will accept also weird cases like 1:56:0


答:
One way to add multiple conditions can be like this </p>

```<code><span
:class="[{'badge-success':obj.status === 'Online', 'badge-warning':obj.status === 'Updating', 'badge-danger':obj.status === 'Failed'},'badge badge-pill']"
>
{{obj.status}}
</span>
</code>```

Title: How to bind class to more than two options in Vue.js?

Body:
One way to add multiple conditions can be like this

<span
:class="[{'badge-success':obj.status === 'Online', 'badge-warning':obj.status === 'Updating', 'badge-danger':obj.status === 'Failed'},'badge badge-pill']"
>
{{obj.status}}
</span>


问:
Cannot read property 'DocumentDir' of undefined React-Native Firebase React-native-fetch-blob
I have exhausted all threads on the internet and can't find a solution.
I'm trying to photo upload to firebase from my react-native app using react-native-fetch-blob.
RN ios simulator running iphone 6.
Not using Expo
I have NOT tried running on android emulator yet, due to android env setup on different computer.

This line causes the error.

```<code>import RNFetchBlob from 'react-native-fetch-blob'
</code>```

I have read many of the tutorials about using react-native-fetch-blob.

I can't seem to link it correctly, or please tell me what my issue is.

```<code>"react": "16.0.0-beta.5",
"react-native": "0.49.3",
"react-native-fetch-blob": "^0.10.8",
</code>```

What I've tried already...

```<code>npm install --save react-native-fetch-blob
react-native link
</code>```

...

```<code>npm install --save react-native-fetch-blob
react-native link react-native-fetch-blob
</code>```

...

```<code>rm -rf node_modules, then reinstall, then clean and build
</code>```

...
I've followed the WIKI to manually link packages. Verified packages are linked via SS's
...

Clean and build after all of these scenario's.

I won't list EVERYTHING I've done because I've literally tried everything on stack and RNFB Issues/github.

Here are some screenshots from Xcode, RNFB is getting linked correctly, or at least I think.

I have found this https://github.com/benjreinhart/react-native-aws3

And will attempt a workout through AWS until someone can help with the linking of fetch blob. Ill update after I have time to work.

答:
Just kill all node process and start npm server and run application:

Step1: run command killall -9 node
    For windows users, run taskkill /im node.exe
    Run taskkill /f /im node.exe if the process still persists.

Step2: run command npm start

Step3: run command react-native run-ios OR react-native run-android

Body:
I have exhausted all threads on the internet and can't find a solution.
I'm trying to photo upload to firebase from my react-native app using react-native-fetch-blob.
RN ios simulator running iphone 6.
Not using Expo
I have NOT tried running on android emulator yet, due to android env setup on different computer.

This line causes the error.

import RNFetchBlob from 'react-native-fetch-blob'

I have read many of the tutorials about using react-native-fetch-blob.

I can't seem to link it correctly, or please tell me what my issue is.

"react": "16.0.0-beta.5",
"react-native": "0.49.3",
"react-native-fetch-blob": "^0.10.8",

What I've tried already...

npm install --save react-native-fetch-blob
react-native link

...

npm install --save react-native-fetch-blob
react-native link react-native-fetch-blob

...

rm -rf node_modules, then reinstall, then clean and build

...
I've followed the WIKI to manually link packages. Verified packages are linked via SS's
...

Clean and build after all of these scenario's.

I won't list EVERYTHING I've done because I've literally tried everything on stack and RNFB Issues/github.

Here are some screenshots from Xcode, RNFB is getting linked correctly, or at least I think.

I have found this https://github.com/benjreinhart/react-native-aws3

And will attempt a workout through AWS until someone can help with the linking of fetch blob. Ill update after I have time to work.


问:
How to pass custom yaml file to helm without mentioning its name
I am new to helm chart. As part of the requirement I named my values.yaml to customize.yaml

To tell helm engine that I am using custom yaml file, I used the below command.

 helm install mychart -f customize.yaml

but now the question is how should I not pass the name of the yaml (customize.yaml) file as part of the command, so the command should be like this

 helm install mychart

and helm should know that it will get the values from customize.yaml
without explicitly mentioning it in the command. Is there a way to do this?

I tried to include it in  _helpers.tpl but it didn't work

答:
```<code>// ValuesfileName is the default values file name.
ValuesfileName = "values.yaml"
</code>```

<p>values.yaml have been defined as the default file in helm's source code. So, in your case, you may have to build helm from source with your changes. </p>

Body:
// ValuesfileName is the default values file name.
ValuesfileName = "values.yaml"

values.yaml have been defined as the default file in helm's source code. So, in your case, you may have to build helm from source with your changes.


问:
Image concatenation script
everyone. I'm trying to write a script that would render images from file inputs on a canvas in a row.

First I cycle through images to calculate the canvas width (because the canvas is wiped on resizing). Then cycle again to render the images.

```<code>canvas.width = 0;
let x = 0,
    y = 0,
    totalWidth = 0;
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
  let input = document.querySelectorAll(".has-file")[i];
  let image = input.files[0];
  let img = new Image();
  console.log(img);
  img.src = window.URL.createObjectURL(image);
  img.addEventListener('load', () => {
    console.log(img);
    let newWidth = img.width * canvas.height / img.height;
    totalWidth += newWidth;
    canvas.width = totalWidth;
  }, false);
};
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
  let input = document.querySelectorAll(".has-file")[i];
  let image = input.files[0];
  let img = new Image();
  img.src = window.URL.createObjectURL(image);
  img.addEventListener('load', () => {
    let newWidth = img.width * canvas.height / img.height;
    ctx.drawImage(img, x, y, newWidth, canvas.height);
    x += newWidth;
  }, false);
};
</code>```

}

The app behaves weird, the images are not always rendered, and when they do, not always where they supposed to be.

答:
First problem with the code is that you're loading images twice, and the randomness is due to the fact that image loading can be ambiguous. Check out this jsfiddle. I have used text input instead of files, drawing takes place when it is the last image otherwise resizing the canvas can cause canvas to reset, losing the previous draw.

var canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d', {
  antialias: false,
  depth: false
 });
canvas.width = 0;
let x = 0,
    y = 0,
    totalWidth = 0;
    let obj = [];
    let k = 0;
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
  let input = document.querySelectorAll(".has-file")[i];
  let image = input.value;
  let img = new Image();
  img.src = image;//window.URL.createObjectURL(image);
  img.addEventListener('load', () => {
    console.log(img);
    let newWidth = img.width * canvas.height / img.height;
    totalWidth += newWidth;
    canvas.width = totalWidth;
    obj.push({img: img, x: x, y: y, newWidth: newWidth, height: canvas.height});
    k++;
    x += newWidth;
    if (k == document.querySelectorAll(".has-file").length )
     draw();
  }, false);
};

function draw() {
  for (var i = 0; i < obj.length; i++) {
      ctx.drawImage(obj[i].img, obj[i].x, obj[i].y, obj[i].newWidth, obj[i].height);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input style="display: none;" class="has-file" value="https://i.imgur.com/I86rTVl.jpg" />
<input style="display: none;" class="has-file" value="https://images.unsplash.com/photo-1446292267125-fecb4ecbf1a5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" />

<canvas id="canvas"></canvas></code>```

Title: Image concatenation script

Body:
everyone. I'm trying to write a script that would render images from file inputs on a canvas in a row.

First I cycle through images to calculate the canvas width (because the canvas is wiped on resizing). Then cycle again to render the images.

canvas.width = 0;
let x = 0,
    y = 0,
    totalWidth = 0;
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
  let input = document.querySelectorAll(".has-file")[i];
  let image = input.files[0];
  let img = new Image();
  console.log(img);
  img.src = window.URL.createObjectURL(image);
  img.addEventListener('load', () => {
    console.log(img);
    let newWidth = img.width * canvas.height / img.height;
    totalWidth += newWidth;
    canvas.width = totalWidth;
  }, false);
};
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
  let input = document.querySelectorAll(".has-file")[i];
  let image = input.files[0];
  let img = new Image();
  img.src = window.URL.createObjectURL(image);
  img.addEventListener('load', () => {
    let newWidth = img.width * canvas.height / img.height;
    ctx.drawImage(img, x, y, newWidth, canvas.height);
    x += newWidth;
  }, false);
};

}

The app behaves weird, the images are not always rendered, and when they do, not always where they supposed to be.

Body:
First problem with the code is that you're loading images twice, and the randomness is due to the fact that image loading can be ambiguous. Check out this jsfiddle. I have used text input instead of files, drawing takes place when it is the last image otherwise resizing the canvas can cause canvas to reset, losing the previous draw.

var canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d', {
  antialias: false,
  depth: false
 });
canvas.width = 0;
let x = 0,
    y = 0,
    totalWidth = 0;
    let obj = [];
    let k = 0;
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
  let input = document.querySelectorAll(".has-file")[i];
  let image = input.value;
  let img = new Image();
  img.src = image;//window.URL.createObjectURL(image);
  img.addEventListener('load', () => {
    console.log(img);
    let newWidth = img.width * canvas.height / img.height;
    totalWidth += newWidth;
    canvas.width = totalWidth;
    obj.push({img: img, x: x, y: y, newWidth: newWidth, height: canvas.height});
    k++;
    x += newWidth;
    if (k == document.querySelectorAll(".has-file").length )
     draw();
  }, false);
};

function draw() {
  for (var i = 0; i < obj.length; i++) {
      ctx.drawImage(obj[i].img, obj[i].x, obj[i].y, obj[i].newWidth, obj[i].height);
  }
}

<input style="display: none;" class="has-file" value="https://i.imgur.com/I86rTVl.jpg" />
<input style="display: none;" class="has-file" value="https://images.unsplash.com/photo-1446292267125-fecb4ecbf1a5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" />

<canvas id="canvas"></canvas>


问:
Upload file (> 4MB) to OneDrive using Graph API
I am trying to upload files to OneDrive using Graph API. The below code works fine when I upload files with size lesser than 4MB but it shows an error when I try to upload files more than 4 MB. I went through this documentation but still, I am not sure how can I get this work.

Below is my working code for files less than 4MB.

```<code>using (var client = new HttpClient())
{
    var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content";
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());

    byte[] sContents = System.IO.File.ReadAllBytes(filePath);
    var content = new ByteArrayContent(sContents);

    var response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}
</code>```

Please help

答:
We need to split the byte array by length (i.e. 4MB) and pass them to the OneDrive API. The working version is below:

```<code>using (var client = new HttpClient())
{
    var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/createUploadSession";
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());

    var sessionResponse = client.PostAsync(apiUrl, null).Result.Content.ReadAsStringAsync().Result;

    byte[] sContents = System.IO.File.ReadAllBytes(filePath);
    var uploadSession = JsonConvert.DeserializeObject<UploadSessionResponse>(sessionResponse);
    string response = UploadFileBySession(uploadSession.uploadUrl, sContents);
}
</code>```

UploadFileBySession is as follows:

```<code>private string UploadFileBySession(string url, byte[] file)
{
    int fragSize = 1024 * 1024 * 4;
    var arrayBatches = ByteArrayIntoBatches(file, fragSize);
    int start = 0;
    string response = "";

    foreach (var byteArray in arrayBatches)
    {
        int byteArrayLength = byteArray.Length;
        var contentRange = " bytes " + start + "-" + (start + (byteArrayLength - 1)) + "/" + file.Length;

        using (var client = new HttpClient())
        {
            var content = new ByteArrayContent(byteArray);
            content.Headers.Add("Content-Length", byteArrayLength.ToProperString());
            content.Headers.Add("Content-Range", contentRange);

            response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
        }

        start = start + byteArrayLength;
    }
    return response;
}

internal IEnumerable<byte[]> ByteArrayIntoBatches(byte[] bArray, int intBufforLengt)
{
    int bArrayLenght = bArray.Length;
    byte[] bReturn = null;

    int i = 0;
    for (; bArrayLenght > (i + 1) * intBufforLengt; i++)
    {
        bReturn = new byte[intBufforLengt];
        Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLengt);
        yield return bReturn;
    }

    int intBufforLeft = bArrayLenght - i * intBufforLengt;
    if (intBufforLeft > 0)
    {
        bReturn = new byte[intBufforLeft];
        Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLeft);
        yield return bReturn;
    }
}
</code>```

UploadSessionResponse class file to deserialize JSON response when you create upload session

```<code>public class UploadSessionResponse
{
    public string odatacontext { get; set; }
    public DateTime expirationDateTime { get; set; }
    public string[] nextExpectedRanges { get; set; }
    public string uploadUrl { get; set; }
}
</code>```

Body:
I am trying to upload files to OneDrive using Graph API. The below code works fine when I upload files with size lesser than 4MB but it shows an error when I try to upload files more than 4 MB. I went through this documentation but still, I am not sure how can I get this work.

Below is my working code for files less than 4MB.

using (var client = new HttpClient())
{
    var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content";
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());

    byte[] sContents = System.IO.File.ReadAllBytes(filePath);
    var content = new ByteArrayContent(sContents);

    var response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}

Please help

Body:
We need to split the byte array by length (i.e. 4MB) and pass them to the OneDrive API. The working version is below:

using (var client = new HttpClient())
{
    var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/createUploadSession";
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());

    var sessionResponse = client.PostAsync(apiUrl, null).Result.Content.ReadAsStringAsync().Result;

    byte[] sContents = System.IO.File.ReadAllBytes(filePath);
    var uploadSession = JsonConvert.DeserializeObject<UploadSessionResponse>(sessionResponse);
    string response = UploadFileBySession(uploadSession.uploadUrl, sContents);
}

UploadFileBySession is as follows:

private string UploadFileBySession(string url, byte[] file)
{
    int fragSize = 1024 * 1024 * 4;
    var arrayBatches = ByteArrayIntoBatches(file, fragSize);
    int start = 0;
    string response = "";

    foreach (var byteArray in arrayBatches)
    {
        int byteArrayLength = byteArray.Length;
        var contentRange = " bytes " + start + "-" + (start + (byteArrayLength - 1)) + "/" + file.Length;

        using (var client = new HttpClient())
        {
            var content = new ByteArrayContent(byteArray);
            content.Headers.Add("Content-Length", byteArrayLength.ToProperString());
            content.Headers.Add("Content-Range", contentRange);

            response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
        }

        start = start + byteArrayLength;
    }
    return response;
}

internal IEnumerable<byte[]> ByteArrayIntoBatches(byte[] bArray, int intBufforLengt)
{
    int bArrayLenght = bArray.Length;
    byte[] bReturn = null;

    int i = 0;
    for (; bArrayLenght > (i + 1) * intBufforLengt; i++)
    {
        bReturn = new byte[intBufforLengt];
        Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLengt);
        yield return bReturn;
    }

    int intBufforLeft = bArrayLenght - i * intBufforLengt;
    if (intBufforLeft > 0)
    {
        bReturn = new byte[intBufforLeft];
        Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLeft);
        yield return bReturn;
    }
}

UploadSessionResponse class file to deserialize JSON response when you create upload session

public class UploadSessionResponse
{
    public string odatacontext { get; set; }
    public DateTime expirationDateTime { get; set; }
    public string[] nextExpectedRanges { get; set; }
    public string uploadUrl { get; set; }
}


问:
Select top * from 2 table orderb by some field
I have 2 table like this

[Info]

[Score]

I want to select top3 * orderby score in May DESC
the result should be look like this.

答:
Try a JOIN on both tables in a derived table with a SUM on Score and order on that</p>

```<code>SELECT TOP 3 *
FROM(
SELECT
    I.User_Id, I.[Name], I.Age, Score = SUM(S.Score)
FROM
    Info I
INNER JOIN
    Score S On S.User_Id = I.User_Id
WHERE MONTH(S.[DATE]) = 5 --May (however I suspect this might not be a DATE object)
GROUP BY
    I.User_Id, I.[Name], I.Age
) X
ORDER BY X.Score DESC
</code>```

Body:
Try a JOIN on both tables in a derived table with a SUM on Score and order on that

SELECT TOP 3 *
FROM(
SELECT
    I.User_Id, I.[Name], I.Age, Score = SUM(S.Score)
FROM
    Info I
INNER JOIN
    Score S On S.User_Id = I.User_Id
WHERE MONTH(S.[DATE]) = 5 --May (however I suspect this might not be a DATE object)
GROUP BY
    I.User_Id, I.[Name], I.Age
) X
ORDER BY X.Score DESC


问:
How to count no of rows in Google Spreadsheet and check if it contains a emailId value in the required column
Cant work out how to count the number of rows that have an email address in them, to populate the number of rows to process. I have a spreadsheet with a list of emails, the number of emailable rows changes regularly, so I'd like to count emailable rows, and instead of manually typing "28" or whatever, I'd like it to automatically find that number :) </p>

```<code>function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 28;  // Number of rows to process
  // Fetch the range of cells
  var dataRange = sheet.getRange(startRow, 1, numRows, 4)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var subject = "membership number"
    MailApp.sendEmail(emailAddress, subject, message);
  }
}
</code>```

答:
Returns the current number of rows in the sheet, regardless of content.

```<code>var emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

var noOfRows = sheet.getMaxRows();
var dataRange = sheet.getRange(startRow, 1, noOfRows , 4)
var data = dataRange.getValues();
data.foreach((row)=>{
  if(emailRegex.test(row[0])){
    var emailAddress = row[0];
    var message = row[1];
    var subject = "membership number"
    MailApp.sendEmail(emailAddress, subject, message);
  }
});
</code>```

https://developers.google.com/apps-script/reference/spreadsheet/sheet#getLastRow%28%29

Body:
Cant work out how to count the number of rows that have an email address in them, to populate the number of rows to process. I have a spreadsheet with a list of emails, the number of emailable rows changes regularly, so I'd like to count emailable rows, and instead of manually typing "28" or whatever, I'd like it to automatically find that number :)

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 28;  // Number of rows to process
  // Fetch the range of cells
  var dataRange = sheet.getRange(startRow, 1, numRows, 4)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var subject = "membership number"
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

Body:
Returns the current number of rows in the sheet, regardless of content.

var emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

var noOfRows = sheet.getMaxRows();
var dataRange = sheet.getRange(startRow, 1, noOfRows , 4)
var data = dataRange.getValues();
data.foreach((row)=>{
  if(emailRegex.test(row[0])){
    var emailAddress = row[0];
    var message = row[1];
    var subject = "membership number"
    MailApp.sendEmail(emailAddress, subject, message);
  }
});

https://developers.google.com/apps-script/reference/spreadsheet/sheet#getLastRow%28%29


问:
C# SQL Server 2008 DATETIME2 Column
How can I work in C# with a DATETIME2 column through LINQ and get microsecond resolution? Right now, even with the server datatype set to DATETIME2, my LINQ object has a DateTime field, which doesn't seem to deal with microseconds.</p>

答:
Even though DATETIME2 handles microseconds, .NET 4 does not. If you need microseconds handled specifically, you can use procedures in SQL Server without reading values through your application.

The .NET reference says:

The fractional part of value is the
  fractional part of a millisecond. For
  example, 4.5 is equivalent to 4
  milliseconds and 5000 ticks, where one
  millisecond = 10000 ticks.

```<code>string dateFormat = "MM/dd/yyyy hh:mm:ss.fffffff";
DateTime date1 = new DateTime(2010, 9, 8, 16, 0, 0);
Console.WriteLine("Original date: {0} ({1:N0} ticks)\n",
                  date1.ToString(dateFormat), date1.Ticks);

DateTime date2 = date1.AddMilliseconds(1);
Console.WriteLine("Second date:   {0} ({1:N0} ticks)",
                  date2.ToString(dateFormat), date2.Ticks);
Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)\n",
                  date2 - date1, date2.Ticks - date1.Ticks);

DateTime date3 = date1.AddMilliseconds(1.5);
Console.WriteLine("Third date:    {0} ({1:N0} ticks)",
                  date3.ToString(dateFormat), date3.Ticks);
Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)",
                  date3 - date1, date3.Ticks - date1.Ticks);
// The example displays the following output:
//    Original date: 09/08/2010 04:00:00.0000000 (634,195,584,000,000,000 ticks)
//
//    Second date:   09/08/2010 04:00:00.0010000 (634,195,584,000,010,000 ticks)
//    Difference between dates: 00:00:00.0010000 (10,000 ticks)
//
//    Third date:    09/08/2010 04:00:00.0020000 (634,195,584,000,020,000 ticks)
//    Difference between dates: 00:00:00.0020000 (20,000 ticks)
</code>```

Ref: DateTime.AddMilliseconds Method

Title: C# SQL Server 2008 DATETIME2 Column

Body:
Even though DATETIME2 handles microseconds, .NET 4 does not. If you need microseconds handled specifically, you can use procedures in SQL Server without reading values through your application.

The .NET reference says:

The fractional part of value is the
  fractional part of a millisecond. For
  example, 4.5 is equivalent to 4
  milliseconds and 5000 ticks, where one
  millisecond = 10000 ticks.

string dateFormat = "MM/dd/yyyy hh:mm:ss.fffffff";
DateTime date1 = new DateTime(2010, 9, 8, 16, 0, 0);
Console.WriteLine("Original date: {0} ({1:N0} ticks)\n",
                  date1.ToString(dateFormat), date1.Ticks);

DateTime date2 = date1.AddMilliseconds(1);
Console.WriteLine("Second date:   {0} ({1:N0} ticks)",
                  date2.ToString(dateFormat), date2.Ticks);
Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)\n",
                  date2 - date1, date2.Ticks - date1.Ticks);

DateTime date3 = date1.AddMilliseconds(1.5);
Console.WriteLine("Third date:    {0} ({1:N0} ticks)",
                  date3.ToString(dateFormat), date3.Ticks);
Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)",
                  date3 - date1, date3.Ticks - date1.Ticks);
// The example displays the following output:
//    Original date: 09/08/2010 04:00:00.0000000 (634,195,584,000,000,000 ticks)
//
//    Second date:   09/08/2010 04:00:00.0010000 (634,195,584,000,010,000 ticks)
//    Difference between dates: 00:00:00.0010000 (10,000 ticks)
//
//    Third date:    09/08/2010 04:00:00.0020000 (634,195,584,000,020,000 ticks)
//    Difference between dates: 00:00:00.0020000 (20,000 ticks)

Ref: DateTime.AddMilliseconds Method


问:
Adaptive Cards rendering multiple times on react
I am binding json with Adaptive cards dyncamically, tried static also, still whenever we call setState method or reinitialize the component,
Multiple instances of adaptive cards bound with the UI.

<AdaptiveCard payload={this.state.adapJson} />

```<code>class Home extends PureComponent {

    constructor() {
        super();
        this.state = {
            name: '',
            response: {},
            adaJson: {},
            renderFlag : false,
            weather: {},
            tempt: '',
            tempDesc: ''
        };
    }
    getTime() {
        var myDate = new Date(); var greet = "";
        var hrs = myDate.getHours();
        if (hrs < 12)
            greet = "Good Morning";
        else if (hrs >= 12 && hrs <= 17)
            greet = "Good Afternoon";
        else if (hrs >= 17 && hrs <= 24)
            greet = "Good Evening";
        return greet;
    }
    componentDidMount() {
        this.showPosition();

        // if (navigator.geolocation) {
        //   navigator.geolocation.getCurrentPosition(this.showPosition, this.err);

        //   }
    }

 showPosition() {
    //some code
    }
    render() {
        var d = new Date()

        this.state.adaJson = {
            "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
            "type": "AdaptiveCard",
            "version": "1.0",
            "body": [
                {
                    ..data..
                }
            ]
        };

        return (<div className="App">
                        <html...>
                    {this.state.tempt ? <AdaptiveCard payload={this.state.adaJson} /> : ""}

        )

    }
}
</code>```

This occurs when I click on home button again and again(same page routing)
How to fix it ?

答:
This occurs it's because you render your script when THE componentDidMount(). SO, when you go back, etc. The render is the same.

You can remove the render with componentWillUnmount().

Bye bye ^^

Body:
I am binding json with Adaptive cards dyncamically, tried static also, still whenever we call setState method or reinitialize the component,
Multiple instances of adaptive cards bound with the UI.

<AdaptiveCard payload={this.state.adapJson} />

class Home extends PureComponent {

    constructor() {
        super();
        this.state = {
            name: '',
            response: {},
            adaJson: {},
            renderFlag : false,
            weather: {},
            tempt: '',
            tempDesc: ''
        };
    }
    getTime() {
        var myDate = new Date(); var greet = "";
        var hrs = myDate.getHours();
        if (hrs < 12)
            greet = "Good Morning";
        else if (hrs >= 12 && hrs <= 17)
            greet = "Good Afternoon";
        else if (hrs >= 17 && hrs <= 24)
            greet = "Good Evening";
        return greet;
    }
    componentDidMount() {
        this.showPosition();

        // if (navigator.geolocation) {
        //   navigator.geolocation.getCurrentPosition(this.showPosition, this.err);

        //   }
    }

 showPosition() {
    //some code
    }
    render() {
        var d = new Date()

        this.state.adaJson = {
            "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
            "type": "AdaptiveCard",
            "version": "1.0",
            "body": [
                {
                    ..data..
                }
            ]
        };

        return (

                    {this.state.tempt ? <AdaptiveCard payload={this.state.adaJson} /> : ""}

        )

    }
}

This occurs when I click on home button again and again(same page routing)
How to fix it ?


问:
Open "Opt" folder with Terminal on Mac
So here is a simple question whose answer has proved elusive. I recently installed a folder that I need to add some files to. The folder is stored in the "opt" folder I thought it would be as simple as:

myusername ~/opt/foldername

But I can't seem to find "opt". I can view the files in Finder, but I need to create some files and I'd rather do that on the command line. Can anyone give me some tips for accessing it?

答:
The opt folder in OSX is hidden by default

To make it visible in Finder, you would need to run this command

```<code>    defaults write com.apple.finder AppleShowAllFiles YES;
</code>```

and

```<code>    killall Finder /System/Library/CoreServices/Finder.app;
</code>```

Next, goto Finder and there you would be able to see the opt folder when you click on Macintosh HD.

opt is accessible in the Terminal anyways.

The command you are using is wrong I suppose

```<code>    myusername ~/opt/foldername
</code>```

~ represents the Home directory of the current logged in user. So you need to change it as:

```<code>    myusername$ cd /opt/
</code>```

Note:
To undo your changes, run these commands

```<code>    defaults write com.apple.finder AppleShowAllFiles NO;
</code>```

and

```<code>    killall Finder /System/Library/CoreServices/Finder.app;
</code>```

Title: Open "Opt" folder with Terminal on Mac

Body:
The opt folder in OSX is hidden by default

To make it visible in Finder, you would need to run this command

    defaults write com.apple.finder AppleShowAllFiles YES;

and

    killall Finder /System/Library/CoreServices/Finder.app;

Next, goto Finder and there you would be able to see the opt folder when you click on Macintosh HD.

opt is accessible in the Terminal anyways.

The command you are using is wrong I suppose

    myusername ~/opt/foldername

~ represents the Home directory of the current logged in user. So you need to change it as:

    myusername$ cd /opt/

Note:
To undo your changes, run these commands

    defaults write com.apple.finder AppleShowAllFiles NO;

and

    killall Finder /System/Library/CoreServices/Finder.app;


问:
Update in nested array based on Date queries may not work properly (or maybe I am doing sth wrong.. )
Create collection "test", and insert one document into it:

```<code>   {
    "_id" : NumberLong(1),
    "pointsBalances" : [
        {
            "period" : "2020",
            "startDate" : ISODate("2020-01-01T00:00:00.000Z"),
            "endDate" : ISODate("2020-12-31T23:59:59.999Z"),
            "value" : 0
        },
        {
            "period" : "2019",
            "startDate" : ISODate("2019-01-01T00:00:00.000Z"),
            "endDate" : ISODate("2019-12-31T23:59:59.999Z"),
            "value" : 0
        }
    ]
}
</code>```

Then please perform update - it should work properly:

```<code>db.getCollection('test').update(
  {$and: [ {'_id': 1}, {"pointsBalances.period": '2019'}]},
  {$set: { "pointsBalances.$.value": 100 } }
)
</code>```

Now lets try to update based on dates:

```<code>   db.getCollection('test').update(
{ $and: [
    {'_id': 1},
    {"pointsBalances.startDate": {$lte: ISODate("2019-05-01T00:00:00.000Z")}},
    {"pointsBalances.endDate": {$gte: ISODate("2019-05-01T00:00:00.000Z")}}
  ]},
{$set: { "pointsBalances.$.value": 200 } })
</code>```

It seems that wrong element is is updated

答:
MongoDB updates the first matching document to the condition, try elemMatch</p>

```<code> db.michel.update(
{ $and: [
    {'_id': 1},
    {"pointsBalances" : {
        "$elemMatch" : { $and: [

                    {"startDate": {$lte: ISODate("2019-05-01T00:00:00.000Z")}},
                    {"endDate": {$gte: ISODate("2019-05-01T00:00:00.000Z")}}

                            ]}}}]},
{$set: { "pointsBalances.$.value": 200 } });
</code>```

Body:
Create collection "test", and insert one document into it:

   {
    "_id" : NumberLong(1),
    "pointsBalances" : [
        {
            "period" : "2020",
            "startDate" : ISODate("2020-01-01T00:00:00.000Z"),
            "endDate" : ISODate("2020-12-31T23:59:59.999Z"),
            "value" : 0
        },
        {
            "period" : "2019",
            "startDate" : ISODate("2019-01-01T00:00:00.000Z"),
            "endDate" : ISODate("2019-12-31T23:59:59.999Z"),
            "value" : 0
        }
    ]
}

Then please perform update - it should work properly:

db.getCollection('test').update(
  {$and: [ {'_id': 1}, {"pointsBalances.period": '2019'}]},
  {$set: { "pointsBalances.$.value": 100 } }
)

Now lets try to update based on dates:

   db.getCollection('test').update(
{ $and: [
    {'_id': 1},
    {"pointsBalances.startDate": {$lte: ISODate("2019-05-01T00:00:00.000Z")}},
    {"pointsBalances.endDate": {$gte: ISODate("2019-05-01T00:00:00.000Z")}}
  ]},
{$set: { "pointsBalances.$.value": 200 } })

It seems that wrong element is is updated

Body:
MongoDB updates the first matching document to the condition, try elemMatch

 db.michel.update(
{ $and: [
    {'_id': 1},
    {"pointsBalances" : {
        "$elemMatch" : { $and: [

                    {"startDate": {$lte: ISODate("2019-05-01T00:00:00.000Z")}},
                    {"endDate": {$gte: ISODate("2019-05-01T00:00:00.000Z")}}

                            ]}}}]},
{$set: { "pointsBalances.$.value": 200 } });


问:
How to listen for 'props' changes
In the VueJs 2.0 docs I can't find any hooks that would listen on props changes.

Does VueJs have such hooks like onPropsUpdated() or similar?

Update

As @wostex suggested, I tried to watch my property but nothing changed. Then I realized that I've got a special case:

```<code><template>
    <child :my-prop="myProp"></child>
</template>

<script>
   export default {
      props: ['myProp']
   }
</script>
</code>```

I am passing myProp that the parent component receives to the child component. Then the watch: {myProp: ...} is not working.

答:
You can use the watch mode to detect changes:

Do everything at atomic level. So first check if watch method itself is getting called or not by consoling something inside. Once it has been established that watch is getting called, smash it out with your business logic.

```<code>watch: {
  myProp: function() {
   console.log('Prop changed')
  }
}
</code>```

Title: How to listen for 'props' changes

Body:
In the VueJs 2.0 docs I can't find any hooks that would listen on props changes.

Does VueJs have such hooks like onPropsUpdated() or similar?

Update

As @wostex suggested, I tried to watch my property but nothing changed. Then I realized that I've got a special case:

<template>
    <child :my-prop="myProp"></child>
</template>

I am passing myProp that the parent component receives to the child component. Then the watch: {myProp: ...} is not working.

Body:
You can use the watch mode to detect changes:

Do everything at atomic level. So first check if watch method itself is getting called or not by consoling something inside. Once it has been established that watch is getting called, smash it out with your business logic.

watch: {
  myProp: function() {
   console.log('Prop changed')
  }
}


问:
JSON serialization if there is blank or null from API
Hi I am using an API to call from a server a list of requirements called availability requirements before an app goes online. However, when there availability requirements has a null, it crashes the app.

I have attempted to to write the code down below with my fix. . There may be other ways to write this but I was hoping to use just JSON serialization. I have checked the forums and most have older code.

```<code>    let rquirements = company.availabilityRequirements
    if rquirements != nil {
        let data = rquirements?.data(using: .utf8)!
        do {
            if let jsonArray = try JSONSerialization.jsonObject(with: data!, options : .allowFragments) as? [Dictionary<String,Any>]
            {
                print(jsonArray) //using the json here
                for requirements in jsonArray {
                    let hist = AvailabilityRequirements(data: requirements)
                    availabitlityReqirements.append(hist)
                }
            } else { //where our error happens if nil
                print("Bad JSON Cannot Convert Value")
                return
            }
        } catch let error as NSError {
            print(error)
            return
        }

        for requirement in availabitlityReqirements {
            if requirement.required == 1{
                requirementItems.append(requirement.displayName)

            }
        }
</code>```

I am trying to fix the swift error, if the there is a blank or missing data from availability requirements. I was hoping if anything I did solved the problem, otherwise I was wondering if someone can help me not crash my app if I get null. Thanks

答:
You should use try? to avoid error. Whole code can be:

```<code>if let rquirements = company.availabilityRequirements,
    let data = rquirements.data(using: .utf8) {

    do {
        if let jsonArray = try? JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String: Any] {
            print(jsonArray)

            for requirements in jsonArray {
                let hist = AvailabilityRequirements(data: requirements)
                availabitlityReqirements.append(hist)
            }
        }

    } catch let error as Error {
        print(error)
        return
    }

    for requirement in availabitlityReqirements {
        if requirement.required == 1 {
            requirementItems.append(requirement.displayName)
        }
    }

}
</code>```

Body:
Hi I am using an API to call from a server a list of requirements called availability requirements before an app goes online. However, when there availability requirements has a null, it crashes the app.

I have attempted to to write the code down below with my fix. . There may be other ways to write this but I was hoping to use just JSON serialization. I have checked the forums and most have older code.

    let rquirements = company.availabilityRequirements
    if rquirements != nil {
        let data = rquirements?.data(using: .utf8)!
        do {
            if let jsonArray = try JSONSerialization.jsonObject(with: data!, options : .allowFragments) as? [Dictionary<String,Any>]
            {
                print(jsonArray) //using the json here
                for requirements in jsonArray {
                    let hist = AvailabilityRequirements(data: requirements)
                    availabitlityReqirements.append(hist)
                }
            } else { //where our error happens if nil
                print("Bad JSON Cannot Convert Value")
                return
            }
        } catch let error as NSError {
            print(error)
            return
        }

        for requirement in availabitlityReqirements {
            if requirement.required == 1{
                requirementItems.append(requirement.displayName)

            }
        }

I am trying to fix the swift error, if the there is a blank or missing data from availability requirements. I was hoping if anything I did solved the problem, otherwise I was wondering if someone can help me not crash my app if I get null. Thanks

Body:
You should use try? to avoid error. Whole code can be:

if let rquirements = company.availabilityRequirements,
    let data = rquirements.data(using: .utf8) {

    do {
        if let jsonArray = try? JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String: Any] {
            print(jsonArray)

            for requirements in jsonArray {
                let hist = AvailabilityRequirements(data: requirements)
                availabitlityReqirements.append(hist)
            }
        }

    } catch let error as Error {
        print(error)
        return
    }

    for requirement in availabitlityReqirements {
        if requirement.required == 1 {
            requirementItems.append(requirement.displayName)
        }
    }

}


问:
Keras layer asks for different shape than in the summary
I'm writing a U-net CNN in keras, and trying to use fit_generator for training. In order for this to work, I used a generator script, that could feed the images and labels for my network (simple fit function is working but I want to train a big dataset which cannot fit into the memory).

My problem is that in the model summary, it says correctly that, the output layer has a shape: (None, 288, 512, 4)
https://i.imgur.com/69xG8pO.jpg

but when I try actual training I get this error:
https://i.imgur.com/j7H6sHX.jpg

I don't get why keras wants (288, 512, 1) when in the summary it expects (288, 512, 4)

I tried it with my own unet code, and copied a working code from github also, but both of them has the exact same problem which leads me to believe that my generator script is the weak link. Below is the code I used (the image and label array functions used here were already working when I used them with "fit" in a previous CNN):

def generator(img_path, label_path, batch_size, height, width, num_classes):

    input_pairs = get_pairs(img_path, label_path) # rewrite if param name changes
    random.shuffle(input_pairs)

    iterate_pairs = itertools.cycle(input_pairs)

    while True:
        X = []
        Y = []
        for _ in range(batch_size):
            im, lab = next(iterate_pairs)

            appended_im = next(iter(im))
            appended_lab = next(iter(lab))

            X.append(input_image_array(appended_im, width, height))
            Y.append(input_label_array(appended_lab, width, height, num_classes, palette))

        yield (np.array(X), np.array(Y))
```

<p>I tried the generator out and the provided batches has the shapes of (for batch size of 15):
(15, 288, 512, 3)
(15, 288, 512, 4)
So I really do not know what could be the problem here.</p>

<p>EDIT: Here is the model code I used:</p>

<pre class="lang-py prettyprint-override"><code>def conv_block(input_tensor, n_filter, kernel=(3, 3), padding='same', initializer="he_normal"):
    x = Conv2D(n_filter, kernel, padding=padding, kernel_initializer=initializer)(input_tensor)
    x = BatchNormalization()(x)
    x = Activation("relu")(x)
    x = Conv2D(n_filter, kernel, padding=padding, kernel_initializer=initializer)(x)
    x = BatchNormalization()(x)
    x = Activation("relu")(x)
    return x

def deconv_block(input_tensor, residual, n_filter, kernel=(3, 3), strides=(2, 2), padding='same'):
    y = Conv2DTranspose(n_filter, kernel, strides, padding)(input_tensor)
    y = concatenate([y, residual], axis=3)
    y = conv_block(y, n_filter)
    return y

# NETWORK - n_classes is the desired number of classes, filters are fixed
def Unet(input_height, input_width, n_classes=4, filters=64):

    # Downsampling
    input_layer = Input(shape=(input_height, input_width, 3), name='input')

    conv_1 = conv_block(input_layer, filters)
    conv_1_out = MaxPooling2D(pool_size=(2, 2))(conv_1)

    conv_2 = conv_block(conv_1_out, filters*2)
    conv_2_out = MaxPooling2D(pool_size=(2, 2))(conv_2)

    conv_3 = conv_block(conv_2_out, filters*4)
    conv_3_out = MaxPooling2D(pool_size=(2, 2))(conv_3)

    conv_4 = conv_block(conv_3_out, filters*8)
    conv_4_out = MaxPooling2D(pool_size=(2, 2))(conv_4)
    conv_4_drop = Dropout(0.5)(conv_4_out)

    conv_5 = conv_block(conv_4_drop, filters*16)
    conv_5_drop = Dropout(0.5)(conv_5)

    # Upsampling
    deconv_1 = deconv_block(conv_5_drop, conv_4, filters*8)
    deconv_1_drop = Dropout(0.5)(deconv_1)

    deconv_2 = deconv_block(deconv_1_drop, conv_3, filters*4)
    deconv_2_drop = Dropout(0.5)(deconv_2)

    deconv_3 = deconv_block(deconv_2_drop, conv_2, filters*2)
    deconv_3 = deconv_block(deconv_3, conv_1, filters)

    # Output - mapping each 64-component feature vector to number of classes
    output = Conv2D(n_classes, (1, 1))(deconv_3)
    output = BatchNormalization()(output)
    output = Activation("softmax")(output)

    # embed into functional API
    model = Model(inputs=input_layer, outputs=output, name="Unet")
    return model
</code>```

答:
Change your loss to categorical_crossentropy.

When using the sparse_categorical_crossentropy loss, your targets
  should be integer targets.

Body:
I'm writing a U-net CNN in keras, and trying to use fit_generator for training. In order for this to work, I used a generator script, that could feed the images and labels for my network (simple fit function is working but I want to train a big dataset which cannot fit into the memory).

My problem is that in the model summary, it says correctly that, the output layer has a shape: (None, 288, 512, 4)
https://i.imgur.com/69xG8pO.jpg

but when I try actual training I get this error:
https://i.imgur.com/j7H6sHX.jpg

I don't get why keras wants (288, 512, 1) when in the summary it expects (288, 512, 4)

I tried it with my own unet code, and copied a working code from github also, but both of them has the exact same problem which leads me to believe that my generator script is the weak link. Below is the code I used (the image and label array functions used here were already working when I used them with "fit" in a previous CNN):

def generator(img_path, label_path, batch_size, height, width, num_classes):

    input_pairs = get_pairs(img_path, label_path) # rewrite if param name changes
    random.shuffle(input_pairs)

    iterate_pairs = itertools.cycle(input_pairs)

    while True:
        X = []
        Y = []
        for _ in range(batch_size):
            im, lab = next(iterate_pairs)

            appended_im = next(iter(im))
            appended_lab = next(iter(lab))

            X.append(input_image_array(appended_im, width, height))
            Y.append(input_label_array(appended_lab, width, height, num_classes, palette))

        yield (np.array(X), np.array(Y))

I tried the generator out and the provided batches has the shapes of (for batch size of 15):
(15, 288, 512, 3)
(15, 288, 512, 4)
So I really do not know what could be the problem here.

EDIT: Here is the model code I used:

def conv_block(input_tensor, n_filter, kernel=(3, 3), padding='same', initializer="he_normal"):
    x = Conv2D(n_filter, kernel, padding=padding, kernel_initializer=initializer)(input_tensor)
    x = BatchNormalization()(x)
    x = Activation("relu")(x)
    x = Conv2D(n_filter, kernel, padding=padding, kernel_initializer=initializer)(x)
    x = BatchNormalization()(x)
    x = Activation("relu")(x)
    return x

def deconv_block(input_tensor, residual, n_filter, kernel=(3, 3), strides=(2, 2), padding='same'):
    y = Conv2DTranspose(n_filter, kernel, strides, padding)(input_tensor)
    y = concatenate([y, residual], axis=3)
    y = conv_block(y, n_filter)
    return y

# NETWORK - n_classes is the desired number of classes, filters are fixed
def Unet(input_height, input_width, n_classes=4, filters=64):

    # Downsampling
    input_layer = Input(shape=(input_height, input_width, 3), name='input')

    conv_1 = conv_block(input_layer, filters)
    conv_1_out = MaxPooling2D(pool_size=(2, 2))(conv_1)

    conv_2 = conv_block(conv_1_out, filters*2)
    conv_2_out = MaxPooling2D(pool_size=(2, 2))(conv_2)

    conv_3 = conv_block(conv_2_out, filters*4)
    conv_3_out = MaxPooling2D(pool_size=(2, 2))(conv_3)

    conv_4 = conv_block(conv_3_out, filters*8)
    conv_4_out = MaxPooling2D(pool_size=(2, 2))(conv_4)
    conv_4_drop = Dropout(0.5)(conv_4_out)

    conv_5 = conv_block(conv_4_drop, filters*16)
    conv_5_drop = Dropout(0.5)(conv_5)

    # Upsampling
    deconv_1 = deconv_block(conv_5_drop, conv_4, filters*8)
    deconv_1_drop = Dropout(0.5)(deconv_1)

    deconv_2 = deconv_block(deconv_1_drop, conv_3, filters*4)
    deconv_2_drop = Dropout(0.5)(deconv_2)

    deconv_3 = deconv_block(deconv_2_drop, conv_2, filters*2)
    deconv_3 = deconv_block(deconv_3, conv_1, filters)

    # Output - mapping each 64-component feature vector to number of classes
    output = Conv2D(n_classes, (1, 1))(deconv_3)
    output = BatchNormalization()(output)
    output = Activation("softmax")(output)

    # embed into functional API
    model = Model(inputs=input_layer, outputs=output, name="Unet")
    return model


问:
Class is giving output even when a variable is not defined globally
Define a class which will have getstring() to input a string and printstring() convert it in uppercase and another function to use __init__

```<code>class a:
    def __init__(self,b,c):
        self.b=b
        self.c=c
    def getstring(self):
        print "Please enter input"
        self.x=raw_input()
        return x
    def printstring(self):
        y=self.x.upper()
        return y
    def sum(self):
        c=self.c+self.b
        return c
d=a(23,53)
d.getstring()
d.printstring()
</code>```

The result is that the input string should be converted to uppercase. This code is working but it shouldn't as x doesn't have global scope.

Another weird thing is that if in the above code, the 'sum' function is called then the input string is not converted to upper case. It will just print the string as given in input and will give the sum.

答:
To get uppercased result change your getstring function like this:

def getstring(self):
    print "Please enter input"
    self.x=raw_input().upper()
    return x
```

You need to assign the str.upper() result in the variable, upper() method doesn't work inplace

Body:
Define a class which will have getstring() to input a string and printstring() convert it in uppercase and another function to use __init__

class a:
    def __init__(self,b,c):
        self.b=b
        self.c=c
    def getstring(self):
        print "Please enter input"
        self.x=raw_input()
        return x
    def printstring(self):
        y=self.x.upper()
        return y
    def sum(self):
        c=self.c+self.b
        return c
d=a(23,53)
d.getstring()
d.printstring()

The result is that the input string should be converted to uppercase. This code is working but it shouldn't as x doesn't have global scope.

Another weird thing is that if in the above code, the 'sum' function is called then the input string is not converted to upper case. It will just print the string as given in input and will give the sum.

Body:
To get uppercased result change your getstring function like this:

def getstring(self):
    print "Please enter input"
    self.x=raw_input().upper()
    return x

You need to assign the str.upper() result in the variable, upper() method doesn't work inplace


问:
Selecting a record with several values in two tables
In two tables there are records (colors) with different values. I want the result to show only the color that has all the same values in both tables. If any of the values are missing, it should be completely rejected.

Another example:

Bellow code should return only BLUE

```<code>WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),

t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)

SELECT *
FROM t1
FULL OUTER JOIN t2 ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR
</code>```

答:
```<code>SELECT t1.COLOR, t1.VALUE
FROM TABLE1 t1
INNER JOIN TABLE2 t2 ON (t1.COLOR = t2.COLOR) AND (t1.VALUE = t2.VALUE);
</code>```

Body:
In two tables there are records (colors) with different values. I want the result to show only the color that has all the same values in both tables. If any of the values are missing, it should be completely rejected.

Another example:

Bellow code should return only BLUE

WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),

t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)

SELECT *
FROM t1
FULL OUTER JOIN t2 ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR


答:
Here you go, You can use join statement.</p>

```<code>SELECT TOP(3) a.user_id, a.Name, a.Age, b.Score FROM Users a JOIN Score b On a.user_id=b.user_id Order By b.Score desc
</code>```

Title: Select top * from 2 table orderb by some field

Body:
I have 2 table like this

[Info]

[Score]

I want to select top3 * orderby score in May DESC
the result should be look like this.

Body:
Here you go, You can use join statement.

SELECT TOP(3) a.user_id, a.Name, a.Age, b.Score FROM Users a JOIN Score b On a.user_id=b.user_id Order By b.Score desc


问:
Help displaying png files which require scrolling/zooming and sufficient image quality
We are attempting to port a very simple application from android/iphone to blackberry.  The application is simply a tool which allows the user to navigate and view png files which are pages in a reference manual.  On iphone/android, we used the webviewer to view the images.  The images range in size from 500x900 to 900x1500.  It all works great on android/iphone. We tried the same thing on the blackberry (curve, storm, torch: 5.0, 6.0) but the Blackberry BrowserField does not appear to scroll horizontally when the image is zoomed.  We also tried using ZoomScreen, but the image quality is so poor that the manual pages are unreadable.

Does anyone have a suggestion for how we can implement a functional viewer of these images which allows zooming/scrolling and which provides good readable image quality?

答:
I received this answer on the Blackberry forum which appears to work:

You seem to use MainScreen which by default scrolls vertically but not horizontally. To remedy that, create it like this:

MainScreen myScreen = new MainScreen(VERTICAL_SCROLL | HORIZONTAL_SCROLL);

or, if you extend it, put something like this as the first line of your custom screen constructor:

super(VERTICAL_SCROLL | HORIZONTAL_SCROLL);


问:
Conversion of number not match with length of datatype in SQL Server
I refer the following number with datatype bigInt.

```<code>DECLARE @Number Bigint = '269687584'
</code>```

When I convert the datatype to Varbinary(4), it returns 0x10131B20.

But when I calculate the length of the Varbinary data, it returns only 3.
I didn't know exact what wrong.

In SQL Server database, I want to write an query to convert Bigint to
Varbinary(4), but is converted as only as Varbinary(3).

Here is what I have tried:

```<code>DECLARE @Number BIGINT = '269687584'

SELECT
    @Number,
    CONVERT(VARBINARY(4), @Number),
    LEN(CONVERT(VARBINARY(4), @Number))
</code>```

答:
There is nothing wrong. You should check lenght using datalength:</p>

```<code>DECLARE @Number Bigint ='269687584'
SELECT @Number, CAST(@Number AS Varbinary(4)), DATALENGTH(CAST(@Number AS Varbinary(4)))
</code>```

Body:
I refer the following number with datatype bigInt.

DECLARE @Number Bigint = '269687584'

When I convert the datatype to Varbinary(4), it returns 0x10131B20.

But when I calculate the length of the Varbinary data, it returns only 3.
I didn't know exact what wrong.

In SQL Server database, I want to write an query to convert Bigint to
Varbinary(4), but is converted as only as Varbinary(3).

Here is what I have tried:

DECLARE @Number BIGINT = '269687584'

SELECT
    @Number,
    CONVERT(VARBINARY(4), @Number),
    LEN(CONVERT(VARBINARY(4), @Number))

Body:
There is nothing wrong. You should check lenght using datalength:

DECLARE @Number Bigint ='269687584'
SELECT @Number, CAST(@Number AS Varbinary(4)), DATALENGTH(CAST(@Number AS Varbinary(4)))


问:
How to implement/show following pop-over above textField?
I m trying to implement following functionality in my iOS project.
Here is the screen,

If user do not enter anything or entered wrong data in email and mobile textFields, I want to show like this.

Case 1: If user didn't entered the email or entered incorrect email then it will show an message/view with "Enter valid Email Address"

Case 2: If user didn't entered the mobile number or entered incorrect mobile number then it will show an message/view with "Enter valid Mobile Number"

How to achieve this using swift?

答:
You can use a popoverPresentationController to get a popover on any of your textFields.

1. Create a UIViewController with a UILabel inside it.

```<code>class PopoverVC: UIViewController {
    @IBOutlet weak var textLabel: UILabel!

    var text: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textLabel.text = self.text
    }
}
</code>```

2. In you ViewController create an instance of PopoverVC whenever you want to present the message. Present it as popoverPresentationController and pass the instance of textField over which you want to present the message, i.e.

```<code>class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
    @IBOutlet weak var textField: UITextField!

    @IBAction func onTapButton(_ sender: UIButton) {
        let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PopoverVC") as! PopoverVC
        controller.text = "Enter valid Mobile Number"
        controller.modalPresentationStyle = .popover
        controller.preferredContentSize = CGSize(width: 300 , height: 70)

        let popover = controller.popoverPresentationController
        popover?.delegate = self
        popover?.permittedArrowDirections = .down
        popover?.sourceView = self.textField
        popover?.sourceRect = self.textField.bounds
        self.present(controller, animated: true, completion: nil)
    }

    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
}
</code>```

Output:

Body:
You can use a popoverPresentationController to get a popover on any of your textFields.

1. Create a UIViewController with a UILabel inside it.

class PopoverVC: UIViewController {
    @IBOutlet weak var textLabel: UILabel!

    var text: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textLabel.text = self.text
    }
}

2. In you ViewController create an instance of PopoverVC whenever you want to present the message. Present it as popoverPresentationController and pass the instance of textField over which you want to present the message, i.e.

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
    @IBOutlet weak var textField: UITextField!

    @IBAction func onTapButton(_ sender: UIButton) {
        let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PopoverVC") as! PopoverVC
        controller.text = "Enter valid Mobile Number"
        controller.modalPresentationStyle = .popover
        controller.preferredContentSize = CGSize(width: 300 , height: 70)

        let popover = controller.popoverPresentationController
        popover?.delegate = self
        popover?.permittedArrowDirections = .down
        popover?.sourceView = self.textField
        popover?.sourceRect = self.textField.bounds
        self.present(controller, animated: true, completion: nil)
    }

    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
}

Output:


问:
Extracting Data from Ajax Request in Python
I am unsure how to extract data from an Ajax request from my Javascript code in a python application in Flask. My Ajax request does not use jQuery.

I have tried using request.form.get() and request.get_json() in my Python code but both produce a None value.

```<code>@app.route("/", methods=["GET", "POST"])
def index():
    if not request.get_json() == None:
        print(request.get_json())
        name = request.get_json()
        session["name"] = name.user
    return render_template("index.html", channels=channels)
</code>```

In my Javascript code I perform a simple Ajax request:

```<code>    if(localStorage.getItem("user")) {
        document.querySelector("#logout").addEventListener("click", () => {
            localStorage.removeItem("user");
        })

        const request = new XMLHttpRequest();
        request.open("POST", "/")
        user = JSON.stringify(localStorage.getItem("user"))
        request.send(user)
    }
</code>```

答:
The data should be coming in request.get_data() not in request.get_json()

refer request.get_json &
request.get_data for more info

Body:
I am unsure how to extract data from an Ajax request from my Javascript code in a python application in Flask. My Ajax request does not use jQuery.

I have tried using request.form.get() and request.get_json() in my Python code but both produce a None value.

@app.route("/", methods=["GET", "POST"])
def index():
    if not request.get_json() == None:
        print(request.get_json())
        name = request.get_json()
        session["name"] = name.user
    return render_template("index.html", channels=channels)

In my Javascript code I perform a simple Ajax request:

    if(localStorage.getItem("user")) {
        document.querySelector("#logout").addEventListener("click", () => {
            localStorage.removeItem("user");
        })

        const request = new XMLHttpRequest();
        request.open("POST", "/")
        user = JSON.stringify(localStorage.getItem("user"))
        request.send(user)
    }


问:
PHP MySQL Insert not working without error
i used this code and i didnt get any errors but when i check the phpadmin and my database its all empty no data added to the table what should i do ?
where is the problem?

i checked also my database and table values and my html names

```<code><?php
    if(isset( $_POST['submit'] ) )
    {
        $name = $_POST['p_name'];
        $price = $_POST['p_price'];
        $type = $_POST['p_type'];
        $des = $_POST['p_desc'];
        $img = 'images/is7.jpeg';
        //***********************
        require_once 'setting.php';
        $dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
        mysqli_set_charset($dbc, 'utf8');
        $query = "INSERT INTO products(name, price, type, des, img)
                        VALUES('$name', '$price', '$type', $des, '$img')";
        mysqli_query($dbc, $query);
        mysqli_close($dbc);
        header('Location: success.php');
        exit;
    }
?>
</code>```

答:
Replare this formate

```<code><?php
$query = "INSERT INTO products(name, price, type, des, img)VALUES('$name', '$price', '$type', $des, '$img')";
?>
</code>```

TO

```<code><?php
$query = "INSERT INTO products(name, price, type, des, img)VALUES('".$name."', '".$price."', '".$type."', '".$des."', '".$img."')";
?>
</code>```

In feature apply mySQL error check up to get mySQL error.

Body:
i used this code and i didnt get any errors but when i check the phpadmin and my database its all empty no data added to the table what should i do ?
where is the problem?

i checked also my database and table values and my html names

<?php
    if(isset( $_POST['submit'] ) )
    {
        $name = $_POST['p_name'];
        $price = $_POST['p_price'];
        $type = $_POST['p_type'];
        $des = $_POST['p_desc'];
        $img = 'images/is7.jpeg';
        //***********************
        require_once 'setting.php';
        $dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
        mysqli_set_charset($dbc, 'utf8');
        $query = "INSERT INTO products(name, price, type, des, img)
                        VALUES('$name', '$price', '$type', $des, '$img')";
        mysqli_query($dbc, $query);
        mysqli_close($dbc);
        header('Location: success.php');
        exit;
    }
?>

Body:
Replare this formate

<?php
$query = "INSERT INTO products(name, price, type, des, img)VALUES('$name', '$price', '$type', $des, '$img')";
?>

TO

<?php
$query = "INSERT INTO products(name, price, type, des, img)VALUES('".$name."', '".$price."', '".$type."', '".$des."', '".$img."')";
?>

In feature apply mySQL error check up to get mySQL error.


问:
Accessing children in auxiliary routing : Angular
I have root routing defined as

const routes: Routes = [{
    path: '',
    component: HomeComponent
  },
  {
    path: 'module1',
    loadChildren: './module1/module1.module#Module1Module'
  },
  {
    path: '**',
    redirectTo: ''
  }
];```
</div>
</div>
</p>

<p>the <code>module1.routing.ts</code> has:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const routes: Routes = [{
  path: '',
  component: SubModule1Component,
  children: [{
      path: 'mod1child1',
      component: SubMod1Child1Component
    },
    {
      path: 'mod1child2',
      component: SubMod1Child2Component,
      children: [{
          path: '',
          component: Outlet1Component,
          outlet: 'outlet1'
        },
        {
          path: 'newout1',
          component: Outlet1NewComponent,
          outlet: 'outlet1'
        },
        {
          path: '',
          component: Outlet2Component,
          outlet: 'outlet2',
          children: [{
            path: 'childoutlet2',
            component: ChildOutlet2Component,
            outlet: 'outlet2'
          }],
        },
      ],
    },
  ],
  canActivate: [AuthGuardService],
}, ];</code>```

This code works when I navigate to /module1/mod1child2 as below:

My HTML page for above image is:

Child 2

<button [routerLink]="[{outlets: {'outlet1': ['newout1']}}]">Change Outlet 1</button>
<button [routerLink]="[{outlets: {'outlet2': ['childoutlet2']}}]">Change Outlet 2</button>

    <router-outlet name="outlet1"></router-outlet>

    <router-outlet name="outlet2"></router-outlet>

```
</div>
</div>
</p>

<p><strong>I am unable to load</strong></p>

<p><code>{ path: 'childoutlet2', component: ChildOutlet2Component , outlet: 'outlet2'}</code></p>

<p>by clicking on :</p>

<p><code><button [routerLink]="[{outlets: {'outlet2': ['childoutlet2']}}]">Change Outlet 2</button></code></p>

<p>What am I doing wrong. I tried </p>

```<button [routerLink]="['/module1/mod1child2',{outlets: {'outlet2': ['childoutlet2']}}]">
   Change Outlet 2
 </button>`
```

but this doesn't seem to work as well

答:
I've encountered that bug 2 years ago.

There's a pull request that you should definitely 1) check out, 2) upvote with a thumbsup so it eventually gets merged https://github.com/angular/angular/pull/25483

I was so tired of that and didn't want to rename all the empty routes within my app in order to have that working so I ending up patching that fix from a postinstall hook after the npm modules have been fetched...

Far from ideal but it just works and hopefully it might be merged at some point!

Shady, but if you want to go this way too, check my comment on the PR
https://github.com/angular/angular/pull/25483#issuecomment-495249672

Body:
I have root routing defined as

const routes: Routes = [{
    path: '',
    component: HomeComponent
  },
  {
    path: 'module1',
    loadChildren: './module1/module1.module#Module1Module'
  },
  {
    path: '**',
    redirectTo: ''
  }
];

the module1.routing.ts has:

const routes: Routes = [{
  path: '',
  component: SubModule1Component,
  children: [{
      path: 'mod1child1',
      component: SubMod1Child1Component
    },
    {
      path: 'mod1child2',
      component: SubMod1Child2Component,
      children: [{
          path: '',
          component: Outlet1Component,
          outlet: 'outlet1'
        },
        {
          path: 'newout1',
          component: Outlet1NewComponent,
          outlet: 'outlet1'
        },
        {
          path: '',
          component: Outlet2Component,
          outlet: 'outlet2',
          children: [{
            path: 'childoutlet2',
            component: ChildOutlet2Component,
            outlet: 'outlet2'
          }],
        },
      ],
    },
  ],
  canActivate: [AuthGuardService],
}, ];

This code works when I navigate to /module1/mod1child2 as below:

My HTML page for above image is:

Child 2

<button [routerLink]="[{outlets: {'outlet1': ['newout1']}}]">Change Outlet 1</button>
<button [routerLink]="[{outlets: {'outlet2': ['childoutlet2']}}]">Change Outlet 2</button>

    <router-outlet name="outlet1"></router-outlet>

    <router-outlet name="outlet2"></router-outlet>

I am unable to load

{ path: 'childoutlet2', component: ChildOutlet2Component , outlet: 'outlet2'}

by clicking on :

<button [routerLink]="[{outlets: {'outlet2': ['childoutlet2']}}]">Change Outlet 2</button>

What am I doing wrong. I tried

<button [routerLink]="['/module1/mod1child2',{outlets: {'outlet2': ['childoutlet2']}}]">
   Change Outlet 2
 </button>`

but this doesn't seem to work as well