问:
Sticky navbar is not working at bottom?
I tried to bring the sticky navbar at bottom similarly top but its not working.
For instance: whenever I scroll until navbar it should not be visible, if i reached navbar location, always navbar should be open. Please suggest why its not working.

I want to done by pure CSS not bootstrap.

Test page: https://codepen.io/burner/pen/qVVomv

var navbar = document.getElementById("navbar");
var sticky = $(navbar).height() - top - link.height();

function myFunction() {
  if (window.pageYOffset < sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  margin: 0;
  font-size: 28px;
}

.header {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

#navbar {
 overflow: hidden;
 background-color: #333;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background-color: #4CAF50;
  color: white;
}

.content {
  padding: 16px;
}

.sticky {
  position: fixed;
  bottom: 0;
  width: 100%
}

.sticky + .content {
  padding-top: 60px;
}</code>```

Sticky Navigation Example

The navbar will stick to the top when you reach its scroll position.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

  Home
  News
  Contact

Scroll UP

Scroll up to see the sticky effect.

```

答:
As i said in the comment to your question, your js/jq code is missing some values for different variables you used.

Anyway, i made a jQuery code that achieves what you want. See below or here > jsFiddle

The code is pretty straight forward. You compare the position of the navbar to the scroll distance. Keeping in mind the height of the nav and also of the window

var navbar = $("#navbar"),
  nTop = navbar.offset().top,
  nBottom = nTop + navbar.outerHeight()
$(window).on("scroll", function() {
  var wScroll = $(this).scrollTop(),
    stickyHere = wScroll + $(this).height()

  if ((nBottom < stickyHere) && (nTop > wScroll)) {
    navbar.addClass("sticky")
  } else {
    navbar.removeClass("sticky")
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin:0;
}
div {
  margin: 0;
  font-size: 28px;
}

.header {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

#navbar {
  overflow: hidden;
  background-color: #333;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background-color: #4CAF50;
  color: white;
}

.content {
  padding: 16px;
}

.sticky {
  position: fixed;
  bottom: 0;
  width: 100%
}

.sticky + .content {
  padding-top: 60px;
}</code>```

Sticky Navigation Example

The navbar will stick to the top when you reach its scroll position.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.

  Home
  News
  Contact

Scroll UP

Scroll up to see the sticky effect.

```

Title: Sticky navbar is not working at bottom?

Body:
I tried to bring the sticky navbar at bottom similarly top but its not working.
For instance: whenever I scroll until navbar it should not be visible, if i reached navbar location, always navbar should be open. Please suggest why its not working.

I want to done by pure CSS not bootstrap.

Test page: https://codepen.io/burner/pen/qVVomv

var navbar = document.getElementById("navbar");
var sticky = $(navbar).height() - top - link.height();

function myFunction() {
  if (window.pageYOffset < sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}

div {
  margin: 0;
  font-size: 28px;
}

.header {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

#navbar {
 overflow: hidden;
 background-color: #333;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background-color: #4CAF50;
  color: white;
}

.content {
  padding: 16px;
}

.sticky {
  position: fixed;
  bottom: 0;
  width: 100%
}

.sticky + .content {
  padding-top: 60px;
}

Sticky Navigation Example

The navbar will stick to the top when you reach its scroll position.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

  Home
  News
  Contact

Scroll UP

Scroll up to see the sticky effect.

Body:
As i said in the comment to your question, your js/jq code is missing some values for different variables you used.

Anyway, i made a jQuery code that achieves what you want. See below or here > jsFiddle

The code is pretty straight forward. You compare the position of the navbar to the scroll distance. Keeping in mind the height of the nav and also of the window

var navbar = $("#navbar"),
  nTop = navbar.offset().top,
  nBottom = nTop + navbar.outerHeight()
$(window).on("scroll", function() {
  var wScroll = $(this).scrollTop(),
    stickyHere = wScroll + $(this).height()

  if ((nBottom < stickyHere) && (nTop > wScroll)) {
    navbar.addClass("sticky")
  } else {
    navbar.removeClass("sticky")
  }
})

body {
margin:0;
}
div {
  margin: 0;
  font-size: 28px;
}

.header {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

#navbar {
  overflow: hidden;
  background-color: #333;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background-color: #4CAF50;
  color: white;
}

.content {
  padding: 16px;
}

.sticky {
  position: fixed;
  bottom: 0;
  width: 100%
}

.sticky + .content {
  padding-top: 60px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <h3>Sticky Navigation Example</h3>
  <p>The navbar will stick to the top when you reach its scroll position.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint
    efficiantur his ad. Eum no molestiae voluptatibus.</p>
</div>

<div id="navbar">
  <a class="active" href="javascript:void(0)">Home</a>
  <a href="javascript:void(0)">News</a>
  <a href="javascript:void(0)">Contact</a>
</div>
<div class="header">
  <h2>Scroll UP</h2>
  <p>Scroll up to see the sticky effect.</p>
</div>


来源: stackexchange

问:
TSQL Email Validation (without regex)
Ok, there are a million regexes out there for validating an email address, but how about some basic email validation that can be integrated into a TSQL query for Sql Server 2005?

I don't want to use a CLR procedure or function.  Just straight TSQL.

Has anybody tackled this already?

答:
On SQL 2016 or +</p>

```<code>CREATE FUNCTION [DBO].[F_IsEmail] (
 @EmailAddr varchar(360) -- Email address to check
)   RETURNS BIT -- 1 if @EmailAddr is a valid email address

AS BEGIN
DECLARE @AlphabetPlus VARCHAR(255)
      , @Max INT -- Length of the address
      , @Pos INT -- Position in @EmailAddr
      , @OK BIT  -- Is @EmailAddr OK
-- Check basic conditions
IF @EmailAddr IS NULL
   OR @EmailAddr NOT LIKE '[0-9a-zA-Z]%@__%.__%'
   OR @EmailAddr LIKE '%@%@%'
   OR @EmailAddr LIKE '%..%'
   OR @EmailAddr LIKE '%.@'
   OR @EmailAddr LIKE '%@.'
   OR @EmailAddr LIKE '%@%.-%'
   OR @EmailAddr LIKE '%@%-.%'
   OR @EmailAddr LIKE '%@-%'
   OR CHARINDEX(' ',LTRIM(RTRIM(@EmailAddr))) > 0
       RETURN(0)

declare @AfterLastDot varchar(360);
declare @AfterArobase varchar(360);
declare @BeforeArobase varchar(360);
declare @HasDomainTooLong bit=0;

--Control des longueurs et autres incoherence
set @AfterLastDot=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('.',REVERSE(@EmailAddr))));
if  len(@AfterLastDot) not between 2 and 17
RETURN(0);

set @AfterArobase=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('@',REVERSE(@EmailAddr))));
if len(@AfterArobase) not between 2 and 255
RETURN(0);

select top 1 @BeforeArobase=value from  string_split(@EmailAddr, '@');
if len(@AfterArobase) not between 2 and 255
RETURN(0);

--Controle sous-domain pas plus grand que 63
select top 1 @HasDomainTooLong=1 from string_split(@AfterArobase, '.') where LEN(value)>63
if @HasDomainTooLong=1
return(0);

--Control de la partie locale en detail
SELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890!#$%&‘*+-/=?^_`.{|}~'
     , @Max = LEN(@BeforeArobase)
     , @Pos = 0
     , @OK = 1

WHILE @Pos < @Max AND @OK = 1 BEGIN
    SET @Pos = @Pos + 1
    IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@BeforeArobase, @Pos, 1) + '%'
        SET @OK = 0
END

if @OK=0
RETURN(0);

--Control de la partie domaine en detail
SELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890-.'
     , @Max = LEN(@AfterArobase)
     , @Pos = 0
     , @OK = 1

WHILE @Pos < @Max AND @OK = 1 BEGIN
    SET @Pos = @Pos + 1
    IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@AfterArobase, @Pos, 1) + '%'
        SET @OK = 0
END

if @OK=0
RETURN(0);

return(1);

END
</code>```

OwnerDisplayName: Eric Z Beard

ContentLicense: CC BY-SA 2.5

Title: TSQL Email Validation (without regex)

Body:
On SQL 2016 or +

CREATE FUNCTION [DBO].[F_IsEmail] (
 @EmailAddr varchar(360) -- Email address to check
)   RETURNS BIT -- 1 if @EmailAddr is a valid email address

AS BEGIN
DECLARE @AlphabetPlus VARCHAR(255)
      , @Max INT -- Length of the address
      , @Pos INT -- Position in @EmailAddr
      , @OK BIT  -- Is @EmailAddr OK
-- Check basic conditions
IF @EmailAddr IS NULL
   OR @EmailAddr NOT LIKE '[0-9a-zA-Z]%@__%.__%'
   OR @EmailAddr LIKE '%@%@%'
   OR @EmailAddr LIKE '%..%'
   OR @EmailAddr LIKE '%.@'
   OR @EmailAddr LIKE '%@.'
   OR @EmailAddr LIKE '%@%.-%'
   OR @EmailAddr LIKE '%@%-.%'
   OR @EmailAddr LIKE '%@-%'
   OR CHARINDEX(' ',LTRIM(RTRIM(@EmailAddr))) > 0
       RETURN(0)

declare @AfterLastDot varchar(360);
declare @AfterArobase varchar(360);
declare @BeforeArobase varchar(360);
declare @HasDomainTooLong bit=0;

--Control des longueurs et autres incoherence
set @AfterLastDot=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('.',REVERSE(@EmailAddr))));
if  len(@AfterLastDot) not between 2 and 17
RETURN(0);

set @AfterArobase=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('@',REVERSE(@EmailAddr))));
if len(@AfterArobase) not between 2 and 255
RETURN(0);

select top 1 @BeforeArobase=value from  string_split(@EmailAddr, '@');
if len(@AfterArobase) not between 2 and 255
RETURN(0);

--Controle sous-domain pas plus grand que 63
select top 1 @HasDomainTooLong=1 from string_split(@AfterArobase, '.') where LEN(value)>63
if @HasDomainTooLong=1
return(0);

--Control de la partie locale en detail
SELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890!#$%&‘*+-/=?^_`.{|}~'
     , @Max = LEN(@BeforeArobase)
     , @Pos = 0
     , @OK = 1

WHILE @Pos < @Max AND @OK = 1 BEGIN
    SET @Pos = @Pos + 1
    IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@BeforeArobase, @Pos, 1) + '%'
        SET @OK = 0
END

if @OK=0
RETURN(0);

--Control de la partie domaine en detail
SELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890-.'
     , @Max = LEN(@AfterArobase)
     , @Pos = 0
     , @OK = 1

WHILE @Pos < @Max AND @OK = 1 BEGIN
    SET @Pos = @Pos + 1
    IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@AfterArobase, @Pos, 1) + '%'
        SET @OK = 0
END

if @OK=0
RETURN(0);

return(1);

END

ContentLicense: CC BY-SA 3.0


问:
rails Gem's the Access the GMAIL, Y! Contact Lists via an API
Anyone know of any solid GEMs that integrate with the GMAIl and Y! Mail APIs to download a user's contacts (emails)?

thanks

答:
You login to gmail using AuthSub mechanism. https://github.com/stuart/google-authsub

Try google contacts using some method as :
http://blog.adsdevshop.com/2008/04/18/import-gmail-contacts-using-ruby-on-rails/


问:
*ngIf="authService.loggedIn()" not showing links
View

```<code>    <nav class="navbar navbar-inverse">
      <div class="container">
       <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-    toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">MEAN Auth App</a>
     </div>
     <div id="navbar" class="collapse navbar-collapse">
      <ul class="nav navbar-nav navbar-left">
        <li [routerLinkActive]="['active']" [routerLinkActiveOptions] =  "{exact:true}"><a [routerLink]="['/']">Home</a></li>
      </ul>

       <ul class="nav navbar-nav navbar-right">
        <li *ngIf="authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions] = "{exact:true}"><a [routerLink]="['/dashboard']">Dashboard</a></li>
        <li *ngIf="authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions] = "{exact:true}"><a [routerLink]="['/profile']">Profile</a></li>

        <li *ngIf="!authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions] = "{exact:true}"><a [routerLink]="['/login']">Login</a></li>
        <li *ngIf="!authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions] = "{exact:true}"><a [routerLink]="['/register']">Register</a></li>
        <li *ngIf="authService.loggedIn()"><a (click)="onLogoutClick()" href="#">Logout</a></li>
      </ul>
    </div><!--/.nav-collapse -->
  </div>
</nav>
</code>```

Component

```<code>import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
import {Router} from '@angular/router';
import {FlashMessagesService} from 'angular2-flash-messages';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  constructor(
    private authService:AuthService,
    private router:Router,
    private flashMessage:FlashMessagesService) { }

  ngOnInit() {
  }

  onLogoutClick(){
    this.authService.logout();
    this.flashMessage.show('You are logged out', {
      cssClass:'alert-success',
      timeout: 3000
    });
    this.router.navigate(['/login']);
    return false;
  }

}
</code>```

I'm new to the mean stack, and I'm having a problem with angular *ngIf, it removes the link from the navbar but doesn't put it back, it does not toggle when you log in or out. However, the ! does remove them, but permanently.
Any help is greatly appreciated.

EDIT
forgot to add this

auth.service

```<code>import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired } from 'angular2-jwt';

@Injectable()
export class AuthService {
  authToken: any;
  user: any;

  constructor(private http:Http) { }

  registerUser(user){
    let headers = new Headers();
    headers.append('Content-Type','application/json');
    return this.http.post('http://localhost:3000/users/register', user,{headers: headers})
      .map(res => res.json());
  }

  authenticateUser(user){
    let headers = new Headers();
    headers.append('Content-Type','application/json');
    return this.http.post('http://localhost:3000/users/authenticate', user,{headers: headers})
      .map(res => res.json());
  }

  getProfile () {
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type','application/json');
    return this.http.get('http://localhost:3000/users/profile',{headers: headers})
      .map(res => res.json());
  }

  storeUserData(token, user){
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  loadToken () {
    const token = localStorage.getItem('id_token');
    this.authToken = token;
  }

  loggedIn () {
    return tokenNotExpired();
  }

  logout(){
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }
}
</code>```

答:
You need to pass the id_token from your local storage to tokenNotExpired() for it to actually check what token is not expired.

so your loggedIn() function should read likes this:

```<code>  loggedIn () {
    return tokenNotExpired('id_token');
  }
</code>```

Body:
View

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

      </button>
      MEAN Auth App

Home

Dashboard

Profile

Login

Register

Logout

Component

import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
import {Router} from '@angular/router';
import {FlashMessagesService} from 'angular2-flash-messages';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  constructor(
    private authService:AuthService,
    private router:Router,
    private flashMessage:FlashMessagesService) { }

  ngOnInit() {
  }

  onLogoutClick(){
    this.authService.logout();
    this.flashMessage.show('You are logged out', {
      cssClass:'alert-success',
      timeout: 3000
    });
    this.router.navigate(['/login']);
    return false;
  }

}

I'm new to the mean stack, and I'm having a problem with angular *ngIf, it removes the link from the navbar but doesn't put it back, it does not toggle when you log in or out. However, the ! does remove them, but permanently.
Any help is greatly appreciated.

EDIT
forgot to add this

auth.service

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired } from 'angular2-jwt';

@Injectable()
export class AuthService {
  authToken: any;
  user: any;

  constructor(private http:Http) { }

  registerUser(user){
    let headers = new Headers();
    headers.append('Content-Type','application/json');
    return this.http.post('http://localhost:3000/users/register', user,{headers: headers})
      .map(res => res.json());
  }

  authenticateUser(user){
    let headers = new Headers();
    headers.append('Content-Type','application/json');
    return this.http.post('http://localhost:3000/users/authenticate', user,{headers: headers})
      .map(res => res.json());
  }

  getProfile () {
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type','application/json');
    return this.http.get('http://localhost:3000/users/profile',{headers: headers})
      .map(res => res.json());
  }

  storeUserData(token, user){
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  loadToken () {
    const token = localStorage.getItem('id_token');
    this.authToken = token;
  }

  loggedIn () {
    return tokenNotExpired();
  }

  logout(){
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }
}

Body:
You need to pass the id_token from your local storage to tokenNotExpired() for it to actually check what token is not expired.

so your loggedIn() function should read likes this:

  loggedIn () {
    return tokenNotExpired('id_token');
  }


问:
Get CSS path from Dom element
I got this function to get a cssPath :

```<code>var cssPath = function (el) {
  var path = [];

  while (
    (el.nodeName.toLowerCase() != 'html') &&
    (el = el.parentNode) &&
    path.unshift(el.nodeName.toLowerCase() +
      (el.id ? '#' + el.id : '') +
      (el.className ? '.' + el.className.replace(/\s+/g, ".") : ''))
  );
  return path.join(" > ");
}
console.log(cssPath(document.getElementsByTagName('a')[123]));
</code>```

But i got something like this :

```html > body > div#div-id > div.site > div.clearfix > ul.choices > li```

But to be totally right, it should look like this :```html > body > div#div-id > div.site:nth-child(1) > div.clearfix > ul.choices > li:nth-child(5)```

Did someone have any idea to implement it simply in javascript ?

答:
I somehow find all the implementations unreadable due to unnecessary mutation. Here I provide mine in ClojureScript and JS:

```<code>(defn element? [x]
  (and (not (nil? x))
      (identical? (.-nodeType x) js/Node.ELEMENT_NODE)))

(defn nth-child [el]
  (loop [sib el nth 1]
    (if sib
      (recur (.-previousSibling sib) (inc nth))
      (dec nth))))

(defn element-path
  ([el] (element-path el []))
  ([el path]
  (if (element? el)
    (let [tag (.. el -nodeName (toLowerCase))
          id (and (not (string/blank? (.-id el))) (.-id el))]
      (if id
        (element-path nil (conj path (str "#" id)))
        (element-path
          (.-parentNode el)
          (conj path (str tag ":nth-child(" (nth-child el) ")")))))
    (string/join " > " (reverse path)))))
</code>```

Javascript:

```<code>const isElement = (x) => x && x.nodeType === Node.ELEMENT_NODE;

const nthChild = (el, nth = 1) => {
  if (el) {
    return nthChild(el.previousSibling, nth + 1);
  } else {
    return nth - 1;
  }
};

const elementPath = (el, path = []) => {
  if (isElement(el)) {
    const tag = el.nodeName.toLowerCase(),
          id = (el.id.length != 0 && el.id);
    if (id) {
      return elementPath(
        null, path.concat([`#${id}`]));
    } else {
      return elementPath(
        el.parentNode,
        path.concat([`${tag}:nth-child(${nthChild(el)})`]));
    }
  } else {
    return path.reverse().join(" > ");
  }
};
</code>```

Title: Get CSS path from Dom element

Body:
I got this function to get a cssPath :

var cssPath = function (el) {
  var path = [];

  while (
    (el.nodeName.toLowerCase() != 'html') &&
    (el = el.parentNode) &&
    path.unshift(el.nodeName.toLowerCase() +
      (el.id ? '#' + el.id : '') +
      (el.className ? '.' + el.className.replace(/\s+/g, ".") : ''))
  );
  return path.join(" > ");
}
console.log(cssPath(document.getElementsByTagName('a')[123]));

But i got something like this :

html > body > div#div-id > div.site > div.clearfix > ul.choices > li

But to be totally right, it should look like this :
html > body > div#div-id > div.site:nth-child(1) > div.clearfix > ul.choices > li:nth-child(5)

Did someone have any idea to implement it simply in javascript ?

Body:
I somehow find all the implementations unreadable due to unnecessary mutation. Here I provide mine in ClojureScript and JS:

(defn element? [x]
  (and (not (nil? x))
      (identical? (.-nodeType x) js/Node.ELEMENT_NODE)))

(defn nth-child [el]
  (loop [sib el nth 1]
    (if sib
      (recur (.-previousSibling sib) (inc nth))
      (dec nth))))

(defn element-path
  ([el] (element-path el []))
  ([el path]
  (if (element? el)
    (let [tag (.. el -nodeName (toLowerCase))
          id (and (not (string/blank? (.-id el))) (.-id el))]
      (if id
        (element-path nil (conj path (str "#" id)))
        (element-path
          (.-parentNode el)
          (conj path (str tag ":nth-child(" (nth-child el) ")")))))
    (string/join " > " (reverse path)))))

Javascript:

const isElement = (x) => x && x.nodeType === Node.ELEMENT_NODE;

const nthChild = (el, nth = 1) => {
  if (el) {
    return nthChild(el.previousSibling, nth + 1);
  } else {
    return nth - 1;
  }
};

const elementPath = (el, path = []) => {
  if (isElement(el)) {
    const tag = el.nodeName.toLowerCase(),
          id = (el.id.length != 0 && el.id);
    if (id) {
      return elementPath(
        null, path.concat([`#${id}`]));
    } else {
      return elementPath(
        el.parentNode,
        path.concat([`${tag}:nth-child(${nthChild(el)})`]));
    }
  } else {
    return path.reverse().join(" > ");
  }
};


问:
How to get full value of number input in Firefox with zeros
Firefox shows just 1 when I type 1,00 in the input. All other browsers I tested are showing 1,00. How can I read the full value of the input in Firefox with the zeros after the comma? The type of the input has to be number and can't be text.

$("#input").keyup(function() {
  $("#output").text($("#input").val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" min="0.00" step="0.01" max="999.99">
<p id="output"></p></code>```

Edit: For me it doesn't matter if decimal mark is a comma or a period.
See the Screenshot of the difference between Chrome and Firefox.

答:
You can parse the value to a float and use the toFixed function to always print the number with two decimals.

$("#input").keyup(function() {
  $("#output").text(
    parseFloat($("#input").val()).toFixed(2)
  );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" min="0.00" step="0.01" max="999.99">
<p id="output"></p></code>```

Body:
Firefox shows just 1 when I type 1,00 in the input. All other browsers I tested are showing 1,00. How can I read the full value of the input in Firefox with the zeros after the comma? The type of the input has to be number and can't be text.

$("#input").keyup(function() {
  $("#output").text($("#input").val());
});

<input type="number" id="input" min="0.00" step="0.01" max="999.99">

Edit: For me it doesn't matter if decimal mark is a comma or a period.
See the Screenshot of the difference between Chrome and Firefox.

Body:
You can parse the value to a float and use the toFixed function to always print the number with two decimals.

$("#input").keyup(function() {
  $("#output").text(
    parseFloat($("#input").val()).toFixed(2)
  );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" min="0.00" step="0.01" max="999.99">
<p id="output"></p>


问:
PrimeNg dropdown in editable datatable not holding the selected value
Below is the code for the column in the datatable

                                                                               <ng-template let-col let-csp="rowData" pTemplate="editor">
 *

 Partner is required
  </ng-template>
```
</div>
</div>
</p>

<p>ts code to populate the droupdown </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> getPartners() {
    this.partners.push({ label: 'Please Select', value: '' });
    this.parameterService.getPartners().subscribe((data) => {
      for (let record of data) {
        this.partners.push({ label: record.description, value: record.organizationId });
      }
    });
  }</code>```

Whenever i edit the grid the dropdown shows the "Please select" instead of showing the selected Organization name.
When i print the "csp.organization.organizationId" it is giving the selected organizationId but [(ngModel)] doesn't seem to set the selected value.

where am i going wrong?

答:
Had the same issue, I found that, in my case, the app was trying to search the value set in ngModel when the dropdown was still empty.

The solution was to add a *ngIf to be sure that the list wasn't null, in your case it'll be smthng like this :

```<code><p-dropdown *ngIf="partners != null && partners.lenght > 0"
name="organization" [(ngModel)]="csp.organization.organizationId"...
</code>```

Hope this will help :)

Body:
Below is the code for the column in the datatable

                                                                               <ng-template let-col let-csp="rowData" pTemplate="editor">
 *

 Partner is required
  </ng-template>

ts code to populate the droupdown

 getPartners() {
    this.partners.push({ label: 'Please Select', value: '' });
    this.parameterService.getPartners().subscribe((data) => {
      for (let record of data) {
        this.partners.push({ label: record.description, value: record.organizationId });
      }
    });
  }

Whenever i edit the grid the dropdown shows the "Please select" instead of showing the selected Organization name.
When i print the "csp.organization.organizationId" it is giving the selected organizationId but [(ngModel)] doesn't seem to set the selected value.

where am i going wrong?

Body:
Had the same issue, I found that, in my case, the app was trying to search the value set in ngModel when the dropdown was still empty.

The solution was to add a *ngIf to be sure that the list wasn't null, in your case it'll be smthng like this :

<p-dropdown *ngIf="partners != null && partners.lenght > 0"
name="organization" [(ngModel)]="csp.organization.organizationId"...

Hope this will help :)


问:
Failed to resolve: android.arch.persistence.room:runtime: 1.0.0-alpha1
I am unable to compile the following gradle :-

```<code>compile 'android.arch.persistence.room:runtime: 1.0.0-alpha1'
</code>```

Error Message :-

```<code>Error:(26, 13) Failed to resolve: android.arch.persistence.room:runtime: 1.0.0-alpha1
</code>```

Show in File Show in Project Structure dialog

It would be of help if somebody could loop in and help me here!!

答:
Library has a release version, update your gradle:

```<code>implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
</code>```

More: https://developer.android.com/topic/libraries/architecture/adding-components.html

Body:
I am unable to compile the following gradle :-

compile 'android.arch.persistence.room:runtime: 1.0.0-alpha1'

Error Message :-

Error:(26, 13) Failed to resolve: android.arch.persistence.room:runtime: 1.0.0-alpha1

Show in File Show in Project Structure dialog

It would be of help if somebody could loop in and help me here!!

Body:
Library has a release version, update your gradle:

implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"

More: https://developer.android.com/topic/libraries/architecture/adding-components.html


问:
push_back operation in c# containers
I need container like c++ vector. Often it is adviced to use List, but it dosen't support push_back operation. I know this is rather simple implementing an extension method for List container. But. Would Stack be a good alternative?

Thanks!

答: It does support List<T>.Add.  Isn't that what you are looking for?

Title: push_back operation in c# containers


问:
Excel - Way to check if number is within range in a single step?
In Excel, I am trying to check if a certain number is within a certain range without typing the number twice. Why? Because the number I am checking is part of a very large formula and I'm trying to avoid typing it twice. Helper cell could be used but I am trying to avoid, if possible.

Is there a way to effectively accomplish the formula shown below, except that without typing the {very long expression} twice?

```<code>= AND({very long expression}<{upper bound},{very long expression}>{lower bound})
</code>```

NOTE

I am answering my own question here but I am wondering if anyone else has a better solution, or if there's just a built-in Excel function that already does this.

答:
You can use a single condition to check if the absolute value of the very long expression offset by the average value of the upper and lower bounds is less than the upper bound offset by the average value of the upper and lower bounds.

Simple example below:

```<code>0 < x < 6

(average of 0 and 6 is 3, so subtract 3 from all expressions below)

-3 < x-3 < 3

abs(x-3) < 3
</code>```

To incorporate this into an Excel formula, you can do this:

```<code>= ABS({long expression}-AVERAGE({upper},{lower}))<({upper}-AVERAGE({upper},{lower}))
</code>```

The only repetition that occurs in this formula above is AVERAGE({upper},{lower}), but assuming the upper and lower bounds are either hardcoded or are single cell references, this formula will be shorter (and more efficient) than typing out the {very long expression} twice. And actually, if the upper and lower bounds are hardcoded, you could also just hardcode the average of them to make the formula even shorter.

Body:
In Excel, I am trying to check if a certain number is within a certain range without typing the number twice. Why? Because the number I am checking is part of a very large formula and I'm trying to avoid typing it twice. Helper cell could be used but I am trying to avoid, if possible.

Is there a way to effectively accomplish the formula shown below, except that without typing the {very long expression} twice?

= AND({very long expression}<{upper bound},{very long expression}>{lower bound})

NOTE

I am answering my own question here but I am wondering if anyone else has a better solution, or if there's just a built-in Excel function that already does this.

Body:
You can use a single condition to check if the absolute value of the very long expression offset by the average value of the upper and lower bounds is less than the upper bound offset by the average value of the upper and lower bounds.

Simple example below:

0 < x < 6

(average of 0 and 6 is 3, so subtract 3 from all expressions below)

-3 < x-3 < 3

abs(x-3) < 3

To incorporate this into an Excel formula, you can do this:

= ABS({long expression}-AVERAGE({upper},{lower}))<({upper}-AVERAGE({upper},{lower}))

The only repetition that occurs in this formula above is AVERAGE({upper},{lower}), but assuming the upper and lower bounds are either hardcoded or are single cell references, this formula will be shorter (and more efficient) than typing out the {very long expression} twice. And actually, if the upper and lower bounds are hardcoded, you could also just hardcode the average of them to make the formula even shorter.


问:
Java jsoup html parsing robot index / bot detection, noindex
Firstly, this is not a duplicated question, because I have already checked almost all 503 / robot index problems. None of them solved my problem. I am trying to get giveaway list from indiegala.com but this site has some kind of protection to prevent bots and robots. My purpose is not illegal, I just want to get giveaway list then check games whether they have steam trade cards or not. But right know, indiegala gives me a robot index. Currently I am using that code;

```<code>       String url = "https://www.indiegala.com/giveaways";
    try {
        String content = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36").ignoreHttpErrors(true).followRedirects(true).get().html();
        System.out.println(content);
    } catch (IOException ex) {
        System.out.println(ex.toString());
    }
</code>```

To see the output(source of the site, in my code, variable "content"), you can run the code that I gave, I cannot add output here because it is a little bit long. But it looks like that;

```<code><head>
 <meta name="ROBOTS" content="NOINDEX, NOFOLLOW" />
</head>
</code>```

So how can I pass this protection ? Can my program pretend like a human to pass this protection ?

答:
That is my Case. That might help. The robot detector detected my browser agent and showed the well-known captcha "Please Show I am not Robot". First, by using the chrome plugin located in this address The Header passed to the website was shown and the cookies and userAgent were known. I just Copied the cookie and userAgent shown there in my code and each time the robot is detected I manually bypass the captcha with my resident browser.</p>

```<code>Doc = Jsoup.connect(URL_String)
  .userAgent("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36")
  .header("cookie","AWSALB=7ygHW4oBnXOkLMVFehmoTM8F1lLfDiTJVVeP5DTIw4dpGgQ4o2F5mYYm4bvCkJul1nkWqAjq9s0pKojKFqdP7wRm/NX/Ye2ntYKwtlOhVvA4dwSM8QTn1uwi4jgI; Expires=Fri, 24 Nov 2017 11:37:10 GMT; Path=/")
  .timeout(0)
  .get();
</code>```

Body:
Firstly, this is not a duplicated question, because I have already checked almost all 503 / robot index problems. None of them solved my problem. I am trying to get giveaway list from indiegala.com but this site has some kind of protection to prevent bots and robots. My purpose is not illegal, I just want to get giveaway list then check games whether they have steam trade cards or not. But right know, indiegala gives me a robot index. Currently I am using that code;

       String url = "https://www.indiegala.com/giveaways";
    try {
        String content = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36").ignoreHttpErrors(true).followRedirects(true).get().html();
        System.out.println(content);
    } catch (IOException ex) {
        System.out.println(ex.toString());
    }

To see the output(source of the site, in my code, variable "content"), you can run the code that I gave, I cannot add output here because it is a little bit long. But it looks like that;

 <meta name="ROBOTS" content="NOINDEX, NOFOLLOW" />

So how can I pass this protection ? Can my program pretend like a human to pass this protection ?

Body:
That is my Case. That might help. The robot detector detected my browser agent and showed the well-known captcha "Please Show I am not Robot". First, by using the chrome plugin located in this address The Header passed to the website was shown and the cookies and userAgent were known. I just Copied the cookie and userAgent shown there in my code and each time the robot is detected I manually bypass the captcha with my resident browser.

Doc = Jsoup.connect(URL_String)
  .userAgent("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36")
  .header("cookie","AWSALB=7ygHW4oBnXOkLMVFehmoTM8F1lLfDiTJVVeP5DTIw4dpGgQ4o2F5mYYm4bvCkJul1nkWqAjq9s0pKojKFqdP7wRm/NX/Ye2ntYKwtlOhVvA4dwSM8QTn1uwi4jgI; Expires=Fri, 24 Nov 2017 11:37:10 GMT; Path=/")
  .timeout(0)
  .get();


问:
How to get video duration, dimension and size in PHP?
I want to know how to get the  duration, dimension and size of uploaded video file in PHP. The file can be in any video format.</p>

答:
https://github.com/JamesHeinrich/getID3
download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...</p>

```<code><?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '```';print_r($fileinfo);echo '```';
?>
</code>```

Body:
https://github.com/JamesHeinrich/getID3
download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

<?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';
?>


问:
Alexa configuration deployment (staging and product) practice
Hello I am new to Alexa Skill Kit deployment using ask-cli. I just want to know if there are any deployment practices in place where we have different configurations i.e skills.json and .ask/config

For example, I have a repository some-alexa-skill with 2 branches: staging and production.

staging has this configuration for the skills.json

```<code>{
  "skillManifest": {
    "publishingInformation": {
      "locales": {
        "en-US": {
          "name": "staging"
        }
      },
      "isAvailableWorldwide": true,
      "distributionCountries": []
    },
    "apis": {
      "custom": {
        "endpoint": {
          "uri": "staging",
          "sourceDir": "lambda/custom"
        }
      }
    },
    "manifestVersion": "1.0"
  }
}
</code>```

while production has this:

```<code>{
  "skillManifest": {
    "publishingInformation": {
      "locales": {
        "en-US": {
          "name": "production"
        }
      },
      "isAvailableWorldwide": true,
      "distributionCountries": []
    },
    "apis": {
      "custom": {
        "endpoint": {
          "uri": "production",
          "sourceDir": "lambda/custom"
        }
      }
    },
    "manifestVersion": "1.0"
  }
}
</code>```

As I can observe skill.json should  be "ignored" in the git respository since it will be replaced whenever merges occur during "release to production". I'm thinking of just ignoring skills.json and just change it when I want to deploy. But I am also considering the ability to allow others to deploy it in their own machines.

Any suggestions on how should I approach this using ask-cli?

答:
Using the API should allow you to control your source and target destinations however you like. Using "profiles" will allow you to keep separate sets of credentials also.

There are 2 different levels of control when using the ask-cli. One is high level, and simplifies creating, cloning, and updating skills. These use the format:

"ask new ..." or "ask clone" to create or copy an existing skill

"ask deploy ..." to update parts or all of the skill.

A lower level API is available that allows more specific control. These use the format "ask api ..." and allow you to specify for example the specific file to upload/download to/from. I've found these better for projects with staging, develop, testing branches, etc.

In all of the ask commands, you can provide a profile that specifies the credentials for the Alexa developer account and the AWS account for the Lambda. Use the "ask init" to set these up. I keep separate profiles for:

my home/hobby projects using my personal accounts

my work related development/debugging

my work client projects accessible by our testers and clients.

The Amazon doc is pretty well written, and explains how to use the ask-cli. It just doesn't go into why you would use multiple profiles, etc.

I hope this helps. Start with the Amazon ask-cli quick start then follow the links to the reference documentation.

One thing to be careful about is to make sure that you are using the latest ask-cli download. As of today it is 1.0.0-beta.4. You can use the "ask -v" command to display your installed version. There were problems with the deploy command in the earlier 1.0.0-beta.1 version.

Body:
Hello I am new to Alexa Skill Kit deployment using ask-cli. I just want to know if there are any deployment practices in place where we have different configurations i.e skills.json and .ask/config

For example, I have a repository some-alexa-skill with 2 branches: staging and production.

staging has this configuration for the skills.json

{
  "skillManifest": {
    "publishingInformation": {
      "locales": {
        "en-US": {
          "name": "staging"
        }
      },
      "isAvailableWorldwide": true,
      "distributionCountries": []
    },
    "apis": {
      "custom": {
        "endpoint": {
          "uri": "staging",
          "sourceDir": "lambda/custom"
        }
      }
    },
    "manifestVersion": "1.0"
  }
}

while production has this:

{
  "skillManifest": {
    "publishingInformation": {
      "locales": {
        "en-US": {
          "name": "production"
        }
      },
      "isAvailableWorldwide": true,
      "distributionCountries": []
    },
    "apis": {
      "custom": {
        "endpoint": {
          "uri": "production",
          "sourceDir": "lambda/custom"
        }
      }
    },
    "manifestVersion": "1.0"
  }
}

As I can observe skill.json should  be "ignored" in the git respository since it will be replaced whenever merges occur during "release to production". I'm thinking of just ignoring skills.json and just change it when I want to deploy. But I am also considering the ability to allow others to deploy it in their own machines.

Any suggestions on how should I approach this using ask-cli?


问:
d3 on click on circle pause and resume transition of marker along line
I would like help to correct my code to click the marker circle element to pause or resume transition of this element along the line. My code moves marker along a line and I can pause and resume this transition using on click on button element but I would like to be able to click on the marker circle itself, not the button. I have used various references including :
    http://www.nytimes.com/interactive/2013/09/25/sports/americas-cup-course.html
    http://jsfiddle.net/meetamit/UJuWX/3/
    http://jsfiddle.net/Y62Hq/2/
    D3 tween - pause and resume controls

I would ultimately like to be able animate a marker along a geo path, pause and resume this at points along the path and click through on these points.

this is my code so far:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
<meta charset="utf-8">
<title>Need help</title>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-geo.v1.min.js"></script>
<script src="https://d3js.org/d3-queue.v3.min.js"></script>

<style type="text/css">

body{
    font-family:"Helvetica Neue", Helvetica, sans-serif;
    color: red;
}
button {
  position: absolute;
  top: 15px;
  left: 10px;
  background: #004276;
  padding-right: 26px;
  border-radius: 2px;
  cursor: pointer;
}
circle {
  fill: steelblue;
  stroke: pink;
  stroke-width: 3px;
}
.point{
    fill:green;

}
.line{
  fill: none;
  stroke: red;
  stroke-width: 4;
  stroke-dasharray: 4px,8px;
}
</style>
</head>
<body>

<button>Start</button>

<script>

    var w = 960,
        h = 500;

    var duration = 10000;

    var svg = d3.select("body").append("svg")
        .attr("width", w)
        .attr("height", h);

    var line = d3.line()
    .x(function(d){return (d)[0];})
    .y(function(d){return (d)[1];});

var data =
 [
  [480, 200],
  [580, 400],
  [680, 100],
  [780, 300],
  [180, 300],
  [280, 100],
  [380, 400]
];

//path to animate
var linepath = svg.append("path")
  .data([data])
  .attr("d", line)
    .attr('class', 'line')
    .attr("d", function(d){
        console.log(this);
        return line(d)
    });

var points = svg.selectAll("circle")
      .data(data)
        .enter()
        .append("circle")
      .attr("r", 7)
        .attr("transform", function(d) { return "translate(" + (d) + ")"; })
        .attr("class", "point");

var pauseValues = {
        lastTime: 0,
        currentTime: 0
        };
        var marker = svg.append("circle")
          .attr("r", 19)
          .attr("transform", "translate(" + (data[0]) + ")")
            .on('click', function(d,i){
                d3.select(this)
                .style("fill", "orange")
                .transition()
            });

function transition() {
  marker.transition()
        .duration(duration - (duration * pauseValues.lastTime))
        .attrTween("transform", translateAlong(linepath.node()))
        .on("end", function(){
        pauseValues = {
          lastT: 0,
          currentT: 0
        };
        transition()
      });
}

function translateAlong(path) {
  var l = path.getTotalLength();
  return function(d, i, a) {
    return function(t) {
      t += pauseValues.lastTime;
      var p = path.getPointAtLength(t * l);
      pauseValues.currentTime = t;
      return "translate(" + p.x + "," + p.y + ")";
    };
  };
}

d3.select('button').on('click',function(d,i){
  var self = d3.select(this);
  if (self.text() == "Pause"){
        self.text('Start');
        marker.transition()
      .duration(0);
        setTimeout(function(){
            pauseValues.lastTime = pauseValues.currentTime;
        }, 100);
  }else{
    self.text('Pause');
    transition();
  }
});

</script>
</body>
</html>
</code>```

答:
To check if the circle is moving in the click function use d3.active(), which...

... returns null if there is no such active transition on the specified node.

Like this:

```<code>.on('click', function(d, i) {
    if (d3.active(this)) {
        marker.transition();
        setTimeout(function() {
            pauseValues.lastTime = pauseValues.currentTime;
        }, 100);
    } else {
        transition();
    }
});
</code>```

Here is your code with that change:

  <button>Start</button>

```

Body:
I would like help to correct my code to click the marker circle element to pause or resume transition of this element along the line. My code moves marker along a line and I can pause and resume this transition using on click on button element but I would like to be able to click on the marker circle itself, not the button. I have used various references including :
    http://www.nytimes.com/interactive/2013/09/25/sports/americas-cup-course.html
    http://jsfiddle.net/meetamit/UJuWX/3/
    http://jsfiddle.net/Y62Hq/2/
    D3 tween - pause and resume controls

I would ultimately like to be able animate a marker along a geo path, pause and resume this at points along the path and click through on these points.

this is my code so far:

<!DOCTYPE html>

<meta charset="utf-8">
<title>Need help</title>

<button>Start</button>

Body:
To check if the circle is moving in the click function use d3.active(), which...

... returns null if there is no such active transition on the specified node.

Like this:

.on('click', function(d, i) {
    if (d3.active(this)) {
        marker.transition();
        setTimeout(function() {
            pauseValues.lastTime = pauseValues.currentTime;
        }, 100);
    } else {
        transition();
    }
});

Here is your code with that change:

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-geo.v1.min.js"></script>
<script src="https://d3js.org/d3-queue.v3.min.js"></script>

<style type="text/css">
  body {
    font-family: "Helvetica Neue", Helvetica, sans-serif;
    color: red;
  }

  button {
    position: absolute;
    top: 15px;
    left: 10px;
    background: #004276;
    padding-right: 26px;
    border-radius: 2px;
    cursor: pointer;
  }

  circle {
    fill: steelblue;
    stroke: pink;
    stroke-width: 3px;
  }

  .point {
    fill: green;
  }

  .line {
    fill: none;
    stroke: red;
    stroke-width: 4;
    stroke-dasharray: 4px, 8px;
  }

</style>

<body>

  <button>Start</button>

  <script>
    var w = 960,
      h = 500;

    var duration = 10000;

    var svg = d3.select("body").append("svg")
      .attr("width", w)
      .attr("height", h);

    var line = d3.line()
      .x(function(d) {
        return (d)[0];
      })
      .y(function(d) {
        return (d)[1];
      });

    var data = [
      [480, 200],
      [580, 400],
      [680, 100],
      [780, 300],
      [180, 300],
      [280, 100],
      [380, 400]
    ];

    //path to animate
    var linepath = svg.append("path")
      .data([data])
      .attr("d", line)
      .attr('class', 'line')
      .attr("d", function(d) {
        return line(d)
      });

    var points = svg.selectAll("circle")
      .data(data)
      .enter()
      .append("circle")
      .attr("r", 7)
      .attr("transform", function(d) {
        return "translate(" + (d) + ")";
      })
      .attr("class", "point");

    var pauseValues = {
      lastTime: 0,
      currentTime: 0
    };
    var marker = svg.append("circle")
      .attr("r", 19)
      .attr("transform", "translate(" + (data[0]) + ")")
      .on('click', function(d, i) {
        if (d3.active(this)) {
          marker.transition();
          setTimeout(function() {
            pauseValues.lastTime = pauseValues.currentTime;
          }, 100);
        } else {
          transition();
        }
      });

    function transition() {
      marker.transition()
        .duration(duration - (duration * pauseValues.lastTime))
        .attrTween("transform", translateAlong(linepath.node()))
        .on("end", function() {
          pauseValues = {
            lastT: 0,
            currentT: 0
          };
          transition()
        });
    }

    function translateAlong(path) {
      var l = path.getTotalLength();
      return function(d, i, a) {
        return function(t) {
          t += pauseValues.lastTime;
          var p = path.getPointAtLength(t * l);
          pauseValues.currentTime = t;
          return "translate(" + p.x + "," + p.y + ")";
        };
      };
    }

    d3.select('button').on('click', function(d, i) {
      var self = d3.select(this);
      if (self.text() == "Pause") {
        self.text('Start');
        marker.transition()
          .duration(0);
        setTimeout(function() {
          pauseValues.lastTime = pauseValues.currentTime;
        }, 100);
      } else {
        self.text('Pause');
        transition();
      }
    });

  </script>
</body>


问:
What's the best way to determine at runtime if a browser is too slow to gracefully handle complex JavaScript/CSS?
I'm toying with the idea of progressively enabling/disabling JavaScript (and CSS) effects on a page - depending on how fast/slow the browser seems to be.

I'm specifically thinking about low-powered mobile devices and old desktop computers -- not just IE6 :-)

Are there any examples of this sort of thing being done?

What would be the best ways to measure this - accounting for things, like temporary slowdowns on busy CPUs?

Notes:

I'm not interested in browser/OS detection.

At the moment, I'm not interested in bandwidth measurements - only browser/cpu performance.

Things that might be interesting to measure:

Base JavaScript

DOM manipulation

DOM/CSS rendering

I'd like to do this in a way that affects the page's render-speed as little as possible.

BTW: In order to not confuse/irritate users with inconsistent behavior - this would, of course, require on-screen notifications to allow users to opt in/out of this whole performance-tuning process.

[Update: there's a related question that I missed: Disable JavaScript function based on user's computer's performance. Thanks Andrioid!]

答:
Take a look at some of Google's (copyrighted!) benchmarks for V8:

http://v8.googlecode.com/svn/data/benchmarks/v4/regexp.js

http://v8.googlecode.com/svn/data/benchmarks/v4/splay.js

I chose a couple of the simpler ones to give an idea of similar benchmarks you could create yourself to test feature sets.  As long as you keep the run-time of your tests between time logged at start to time logged at completion to less than 100 ms on the slowest systems (which these Google tests are vastly greater than) you should get the information you need without being detrimental to user experience.  While the Google benchmarks care at a granularity between the faster systems, you don't.  All that you need to know is which systems take longer than XX ms to complete.

Things you could test are regular expression operations (similar to the above), string concatenation, page scrolling, anything that causes a browser repaint or reflow, etc.


答:
You can cross join all distinct types to all distinct dates (a cartesian product)

```<code>MariaDB [sandbox]> select distinct type,t1.dt from t
    -> cross join (select distinct dt from t) t1;
+------+------------+
| type | dt         |
+------+------------+
| a    | 2017-11-01 |
| b    | 2017-11-01 |
| c    | 2017-11-01 |
| a    | 2017-11-02 |
| b    | 2017-11-02 |
| c    | 2017-11-02 |
| a    | 2017-11-03 |
| b    | 2017-11-03 |
| c    | 2017-11-03 |
+------+------------+
9 rows in set (0.00 sec)
</code>```

And then left join

```<code>MariaDB [sandbox]> select s.type,s.dt,ifnull(u.obs,0) obs
    -> from
    -> (
    -> select distinct type,t1.dt from t
    -> cross join (select distinct dt from t) t1
    -> ) s
    -> left join
    -> (select type,dt, count(*) obs from t group by type,dt) u on u.type = s.type and u.dt = s.dt ;
+------+------------+-----+
| type | dt         | obs |
+------+------------+-----+
| a    | 2017-11-01 |   3 |
| b    | 2017-11-01 |   1 |
| c    | 2017-11-01 |   0 |
| a    | 2017-11-02 |   1 |
| b    | 2017-11-02 |   3 |
| c    | 2017-11-02 |   1 |
| a    | 2017-11-03 |   2 |
| b    | 2017-11-03 |   0 |
| c    | 2017-11-03 |   0 |
+------+------------+-----+
9 rows in set (0.00 sec)
</code>```

note this only works if you are only interested in dates where there is some activity - if not think about building a calander table and use that in the sub query

Title: mysql:how to get 0 when using group by and result doesn't exist

Body:
this is table test's data:

time       | type
2017-11-01 | a
2017-11-01 | a
2017-11-01 | a
2017-11-01 | b
2017-11-02 | a
2017-11-02 | b
2017-11-02 | b
2017-11-02 | b
2017-11-02 | c
2017-11-03 | a
2017-11-03 | a

how to get the result:

time       | type | count(*)
2017-11-01 | a    | 3
2017-11-01 | b    | 1
2017-11-01 | c    | 0
2017-11-02 | a    | 1
2017-11-02 | b    | 3
2017-11-02 | c    | 1
2017-11-03 | a    | 2
2017-11-03 | b    | 0
2017-11-03 | c    | 0

I tried to use group by and ifnull, but it is not working. I can't get 0 from the data. Maybe 'join' can work, but how to edit the sql?

Body:
You can cross join all distinct types to all distinct dates (a cartesian product)

MariaDB [sandbox]> select distinct type,t1.dt from t
    -> cross join (select distinct dt from t) t1;
+------+------------+
| type | dt         |
+------+------------+
| a    | 2017-11-01 |
| b    | 2017-11-01 |
| c    | 2017-11-01 |
| a    | 2017-11-02 |
| b    | 2017-11-02 |
| c    | 2017-11-02 |
| a    | 2017-11-03 |
| b    | 2017-11-03 |
| c    | 2017-11-03 |
+------+------------+
9 rows in set (0.00 sec)

And then left join

MariaDB [sandbox]> select s.type,s.dt,ifnull(u.obs,0) obs
    -> from
    -> (
    -> select distinct type,t1.dt from t
    -> cross join (select distinct dt from t) t1
    -> ) s
    -> left join
    -> (select type,dt, count(*) obs from t group by type,dt) u on u.type = s.type and u.dt = s.dt ;
+------+------------+-----+
| type | dt         | obs |
+------+------------+-----+
| a    | 2017-11-01 |   3 |
| b    | 2017-11-01 |   1 |
| c    | 2017-11-01 |   0 |
| a    | 2017-11-02 |   1 |
| b    | 2017-11-02 |   3 |
| c    | 2017-11-02 |   1 |
| a    | 2017-11-03 |   2 |
| b    | 2017-11-03 |   0 |
| c    | 2017-11-03 |   0 |
+------+------------+-----+
9 rows in set (0.00 sec)

note this only works if you are only interested in dates where there is some activity - if not think about building a calander table and use that in the sub query


问:
How to return values in a query only if the subtraction of two queries are greater than 0 in MySQL
I know, is duplicated, but I do not know how to do it without a single query. Here is my problem:

Description of the model:
The "t_factura_detalle" stores the details of an invoce.
The posible products for the invoce details are stored in "t_licencia".
The table "t_asignacion" stores the product of a invoice (for the moment, is not important to save the invoice id from which each product is assigned) than has be assigned to a pc "id_pc" (only one license for record in the table assign).

Process in which I need help:
When i do the assignation process, i need return a list in which i return "t_licencia.id_licencia" and "t_licencia.licencia_name", but i need to sustract all the licenses already asigned stored in the "t_asignation" table. An example:

"t_licencia":

```<code>+-------------+--------------------------+
| id_licencia | licencia_name            |
+-------------+--------------------------+
|           6 | Adobe Photoshop CS6 Pro  |
|           4 | Microsoft Office 2013 SP |
+-------------+--------------------------+
</code>```

"t_factura_detalle":

```<code>+------------+---------------------+-------------+----------+
| id_factura | id_factura_licencia | id_licencia | cantidad |
+------------+---------------------+-------------+----------+
|          6 |                   1 |           6 |       30 |
|          6 |                   3 |           4 |       40 |
|          7 |                   4 |           4 |       40 |
|          6 |                   6 |           6 |       40 |
|          6 |                   8 |           6 |       40 |
+------------+---------------------+-------------+----------+
</code>```

So, the quantity of products (licenses) are:

```<code>+--------------------------+---------------+
| licencia_name            | sum(cantidad) |
+--------------------------+---------------+
| Adobe Photoshop CS6 Pro  |           110 |
| Microsoft Office 2013 SP |            80 |
+--------------------------+---------------+

# At the moment I do not care what invoice is associated,
# I just want to know the amount
select t_licencia.licencia_name, sum(cantidad)
from t_licencia, t_factura_detalle
where t_licencia.id_licencia = t_factura_detalle.id_licencia
group by licencia_name;
</code>```

And a example of the "t_asignation":

```<code>+---------------+---------------------+-------+------------------+
| id_asignacion | id_factura_licencia | id_pc | fecha_asignacion |
+---------------+---------------------+-------+------------------+
|             2 |                   3 |     1 | 2017-00-00       |
+---------------+---------------------+-------+------------------+
</code>```

So, the "t_asignacion" points to an "t_facture_detalle" record, where are a product.

How can i return values only if the the {substraction of the [sum of the available licenses] and the [sum of assigned licenses]} is greater than 0 in a stored procedure or a simply query (preferably)?

I do not know if I explain well.
Thank so much!

答:
Finally i managed to do it in a query. It's not so pretty, but it works... I put it here in case can help to others with similar problems.
Thanks a lot to Raymond and Jean.</p>

```<code>select totales_factura_detalle.id_factura_licencia, tl2.licencia_name
from (
    select ta.id_factura_licencia,
        count(tl.licencia_name) as usadas,
        (select tfd2.cantidad
    from t_factura_detalle tfd2
    where tfd2.id_factura_licencia = ta.id_factura_licencia
        ) as disponibles
    from t_asignacion ta, t_factura_detalle tfd, t_licencia tl
    where ta.id_factura_licencia = tfd.id_factura_licencia
        and tl.id_licencia = tfd.id_licencia
    group by id_factura_licencia
) totales_factura_detalle, t_factura_detalle tfd3, t_licencia tl2
where disponibles > usadas
    and tfd3.id_factura_licencia = totales_factura_detalle.id_factura_licencia
    and tl2.id_licencia = tfd3.id_licencia;
</code>```

Body:
I know, is duplicated, but I do not know how to do it without a single query. Here is my problem:

Description of the model:
The "t_factura_detalle" stores the details of an invoce.
The posible products for the invoce details are stored in "t_licencia".
The table "t_asignacion" stores the product of a invoice (for the moment, is not important to save the invoice id from which each product is assigned) than has be assigned to a pc "id_pc" (only one license for record in the table assign).

Process in which I need help:
When i do the assignation process, i need return a list in which i return "t_licencia.id_licencia" and "t_licencia.licencia_name", but i need to sustract all the licenses already asigned stored in the "t_asignation" table. An example:

"t_licencia":

+-------------+--------------------------+
| id_licencia | licencia_name            |
+-------------+--------------------------+
|           6 | Adobe Photoshop CS6 Pro  |
|           4 | Microsoft Office 2013 SP |
+-------------+--------------------------+

"t_factura_detalle":

+------------+---------------------+-------------+----------+
| id_factura | id_factura_licencia | id_licencia | cantidad |
+------------+---------------------+-------------+----------+
|          6 |                   1 |           6 |       30 |
|          6 |                   3 |           4 |       40 |
|          7 |                   4 |           4 |       40 |
|          6 |                   6 |           6 |       40 |
|          6 |                   8 |           6 |       40 |
+------------+---------------------+-------------+----------+

So, the quantity of products (licenses) are:

+--------------------------+---------------+
| licencia_name            | sum(cantidad) |
+--------------------------+---------------+
| Adobe Photoshop CS6 Pro  |           110 |
| Microsoft Office 2013 SP |            80 |
+--------------------------+---------------+

# At the moment I do not care what invoice is associated,
# I just want to know the amount
select t_licencia.licencia_name, sum(cantidad)
from t_licencia, t_factura_detalle
where t_licencia.id_licencia = t_factura_detalle.id_licencia
group by licencia_name;

And a example of the "t_asignation":

+---------------+---------------------+-------+------------------+
| id_asignacion | id_factura_licencia | id_pc | fecha_asignacion |
+---------------+---------------------+-------+------------------+
|             2 |                   3 |     1 | 2017-00-00       |
+---------------+---------------------+-------+------------------+

So, the "t_asignacion" points to an "t_facture_detalle" record, where are a product.

How can i return values only if the the {substraction of the [sum of the available licenses] and the [sum of assigned licenses]} is greater than 0 in a stored procedure or a simply query (preferably)?

I do not know if I explain well.
Thank so much!

Body:
Finally i managed to do it in a query. It's not so pretty, but it works... I put it here in case can help to others with similar problems.
Thanks a lot to Raymond and Jean.

select totales_factura_detalle.id_factura_licencia, tl2.licencia_name
from (
    select ta.id_factura_licencia,
        count(tl.licencia_name) as usadas,
        (select tfd2.cantidad
    from t_factura_detalle tfd2
    where tfd2.id_factura_licencia = ta.id_factura_licencia
        ) as disponibles
    from t_asignacion ta, t_factura_detalle tfd, t_licencia tl
    where ta.id_factura_licencia = tfd.id_factura_licencia
        and tl.id_licencia = tfd.id_licencia
    group by id_factura_licencia
) totales_factura_detalle, t_factura_detalle tfd3, t_licencia tl2
where disponibles > usadas
    and tfd3.id_factura_licencia = totales_factura_detalle.id_factura_licencia
    and tl2.id_licencia = tfd3.id_licencia;


问:
bootstrap active class background color
I have this HTML for navbar and I need to change the background color for the .active class.

```<code><nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" id="white" href="#">TableMailerMM</a>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
      <!--<ul class="nav navbar-nav navbar-right">
        <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
      </ul>-->
    </div>
  </div>
</nav>
</code>```

What I have tried is,

```<code>.nav.navbar-nav li:active{
   background-color: #ff812c;
}
</code>```

but it doesn't work, any ideas?

答:
You're using :active pseudeselector  which doesn't apply here use .active class selector and select descendant anchor like :

```<code>ul.nav.navbar-nav li.active a {
    //styles
}
</code>```

Title: bootstrap active class background color

Body:
I have this HTML for navbar and I need to change the background color for the .active class.

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>
      TableMailerMM

Home

About

Projects

Contact

What I have tried is,

.nav.navbar-nav li:active{
   background-color: #ff812c;
}

but it doesn't work, any ideas?

Body:
You're using :active pseudeselector  which doesn't apply here use .active class selector and select descendant anchor like :

ul.nav.navbar-nav li.active a {
    //styles
}


问:
QTKit audio mute and Stream Buffering status message
I'm muting volume in QTkit like this:

```<code>if
            ([muteButton state] == NSOnState){

    [mMovieVolumeSlider setFloatValue:0.1];
    [testMovie setVolume:0.1];
</code>```

The problem is the volume attenuation is sudden and abrupt. How can I implement a fade effect to the volume attenuation?

Also - my app runs .pls audio stream files. I have the .pls files embedded in the bundle. When selecting a stream within the app, a short delay is common before the stream begins to play. I want to display some sort of status message ("Buffering" or Connecting") during this short delay prior to connecting. When the stream begins the status message would end. Any idea's on how to approach this?

thanks for the help.

-paul.

答:
I'll just outline my answers to your two questions as suggestions:

What you want to accomplish sounds much like a good fit for NSAnimation (either through subclassing or delegation — animation:valueForProgress: will probably be your friend here).

Open the QTMovie asynchronously and listen for the QTMovieLoadStateDidChangeNotification.

HTH

Daniel

Body:
I'm muting volume in QTkit like this:

if
            ([muteButton state] == NSOnState){

    [mMovieVolumeSlider setFloatValue:0.1];
    [testMovie setVolume:0.1];

The problem is the volume attenuation is sudden and abrupt. How can I implement a fade effect to the volume attenuation?

Also - my app runs .pls audio stream files. I have the .pls files embedded in the bundle. When selecting a stream within the app, a short delay is common before the stream begins to play. I want to display some sort of status message ("Buffering" or Connecting") during this short delay prior to connecting. When the stream begins the status message would end. Any idea's on how to approach this?

thanks for the help.

-paul.


问:
this.setState not working when a parent's state has to be updated by a child
So I have a parent and a child component in my app. I want to update the state of the parent component by the child component but it doesn't seem to work. I have been working on Reactjs for a long time now and this is quite strange to me. Here is my code for the parent component:

```<code>import React from 'react';
import { Stage } from 'react-konva';
import CircleComponent from './CircleComponent';
import LineComponent from './LineComponent';
import { getUserPlan } from '../../assets/UserPlan';
import { addColorClasses } from '../../helpers/utils';

class PortfolioMix extends React.Component {
  constructor(props) {
    super(props);

    const data = addColorClasses(getUserPlan().plans[0]);

    this.state = {
      data: data,
      circlePoints: []
    };

    this.getCirclePoints = this.getCirclePoints.bind(this);
  }

  getCirclePoints(points) {
    this.setState({
      circlePoints: points,
      word: 'hello'
    }, () => { console.log(this.state); });
  }

  processData() {
    let data = this.state.data;

    if(data[0].weight > 0.25 || (data[0].weight+data[1].weight) > 0.67) {
      for(let i = 0; i < data.length; i++) {
        data[i].weight /= 3;
      }
    }

    return data;
  }

  render() {
    const processedData = this.processData();
    const firstCircle = processedData.splice(0,1);
    const pmData = processedData.splice(0,this.state.data.length);

    return(
      <div>
        <Stage
          height={800}
          width={1200}
          style={{ backgroundColor: '#fff'}}>
          <CircleComponent
            x={1200/2}
            y={800/2}
            outerRadius={firstCircle[0].weight*1200}
            outerColor={firstCircle[0].outerColor}
            innerRadius={firstCircle[0].weight*1200*0.3}
            innerColor={firstCircle[0].innerColor}
            shadowColor={firstCircle[0].innerColor}
            getCirclePoints={this.getCirclePoints}
          />
        </Stage>
      </div>
    );
  }
}

export default PortfolioMix;
</code>```

And here is the child component's code:

```<code>class CircleComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      points: this.getPoints(),
    };
  }

  componentDidMount() {
    this.props.getCirclePoints(this.state.points);
  }

  getPoints() {
    const radius = this.props.outerRadius;
    const x = this.props.x;
    const y = this.props.y;

    const points = [];
    let angle = 0;

    for(let i = 0; i < 8; i++) {
      points.push({
        pointX: x + radius * Math.cos(-angle * Math.PI / 180),
        pointY: y + radius * Math.sin(-angle * Math.PI / 180)
      });
      angle += 42.5;
    }

    return points;
  }

  render() {
    const {
      x,
      y,
      outerRadius,
      outerColor,
      shadowColor,
      innerRadius,
      innerColor
    } = this.props;

    return (
      <Layer>
        <Group>
          <Circle
            x={x}
            y={y}
            radius={outerRadius}
            fill={outerColor}
            shadowBlur={5}
            shadowColor={shadowColor}
          />
          <Circle
            x={x}
            y={y}
            radius={innerRadius}
            fill={innerColor}
          />
        </Group>
      </Layer>
    );
  }
}

CircleComponent.propTypes = {
  x: propTypes.number.isRequired,
  y: propTypes.number.isRequired,
  outerRadius: propTypes.number.isRequired,
  outerColor: propTypes.string.isRequired,
  shadowColor: propTypes.string,
  innerRadius: propTypes.number.isRequired,
  innerColor: propTypes.string.isRequired,
  getCirclePoints: propTypes.func
};

export default CircleComponent;
</code>```

Now, in parent component's getCirclePoints method, I am getting the points from the child but this.setState is not working. As you can see I have also passed a function to this.setState callback, it isn't getting called and also setting data state to an empty array. I have been banging my head on this for last 4 hours. Any kind of help is appreciated. I hope there's not some stupid mistake on my side.

答:
You need to .bind(this) at method processData() too, because React only automatically bind(this) to render method, constructor and component lifecycles methods.

```<code>class PortfolioMix extends React.Component {
  constructor(props) {
    super(props);

    const data = addColorClasses(getUserPlan().plans[0]);

    this.state = {
      data: data,
      circlePoints: []
    };

    this.getCirclePoints = this.getCirclePoints.bind(this);
    this.processData = this.processData.bind(this);
  }
// ...
</code>```

Body:
So I have a parent and a child component in my app. I want to update the state of the parent component by the child component but it doesn't seem to work. I have been working on Reactjs for a long time now and this is quite strange to me. Here is my code for the parent component:

import React from 'react';
import { Stage } from 'react-konva';
import CircleComponent from './CircleComponent';
import LineComponent from './LineComponent';
import { getUserPlan } from '../../assets/UserPlan';
import { addColorClasses } from '../../helpers/utils';

class PortfolioMix extends React.Component {
  constructor(props) {
    super(props);

    const data = addColorClasses(getUserPlan().plans[0]);

    this.state = {
      data: data,
      circlePoints: []
    };

    this.getCirclePoints = this.getCirclePoints.bind(this);
  }

  getCirclePoints(points) {
    this.setState({
      circlePoints: points,
      word: 'hello'
    }, () => { console.log(this.state); });
  }

  processData() {
    let data = this.state.data;

    if(data[0].weight > 0.25 || (data[0].weight+data[1].weight) > 0.67) {
      for(let i = 0; i < data.length; i++) {
        data[i].weight /= 3;
      }
    }

    return data;
  }

  render() {
    const processedData = this.processData();
    const firstCircle = processedData.splice(0,1);
    const pmData = processedData.splice(0,this.state.data.length);

    return(

        <Stage
          height={800}
          width={1200}
          style={{ backgroundColor: '#fff'}}>
          <CircleComponent
            x={1200/2}
            y={800/2}
            outerRadius={firstCircle[0].weight*1200}
            outerColor={firstCircle[0].outerColor}
            innerRadius={firstCircle[0].weight*1200*0.3}
            innerColor={firstCircle[0].innerColor}
            shadowColor={firstCircle[0].innerColor}
            getCirclePoints={this.getCirclePoints}
          />
        </Stage>

    );
  }
}

export default PortfolioMix;

And here is the child component's code:

class CircleComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      points: this.getPoints(),
    };
  }

  componentDidMount() {
    this.props.getCirclePoints(this.state.points);
  }

  getPoints() {
    const radius = this.props.outerRadius;
    const x = this.props.x;
    const y = this.props.y;

    const points = [];
    let angle = 0;

    for(let i = 0; i < 8; i++) {
      points.push({
        pointX: x + radius * Math.cos(-angle * Math.PI / 180),
        pointY: y + radius * Math.sin(-angle * Math.PI / 180)
      });
      angle += 42.5;
    }

    return points;
  }

  render() {
    const {
      x,
      y,
      outerRadius,
      outerColor,
      shadowColor,
      innerRadius,
      innerColor
    } = this.props;

    return (
      <Layer>
        <Group>
          <Circle
            x={x}
            y={y}
            radius={outerRadius}
            fill={outerColor}
            shadowBlur={5}
            shadowColor={shadowColor}
          />
          <Circle
            x={x}
            y={y}
            radius={innerRadius}
            fill={innerColor}
          />
        </Group>
      </Layer>
    );
  }
}

CircleComponent.propTypes = {
  x: propTypes.number.isRequired,
  y: propTypes.number.isRequired,
  outerRadius: propTypes.number.isRequired,
  outerColor: propTypes.string.isRequired,
  shadowColor: propTypes.string,
  innerRadius: propTypes.number.isRequired,
  innerColor: propTypes.string.isRequired,
  getCirclePoints: propTypes.func
};

export default CircleComponent;

Now, in parent component's getCirclePoints method, I am getting the points from the child but this.setState is not working. As you can see I have also passed a function to this.setState callback, it isn't getting called and also setting data state to an empty array. I have been banging my head on this for last 4 hours. Any kind of help is appreciated. I hope there's not some stupid mistake on my side.

Body:
You need to .bind(this) at method processData() too, because React only automatically bind(this) to render method, constructor and component lifecycles methods.

class PortfolioMix extends React.Component {
  constructor(props) {
    super(props);

    const data = addColorClasses(getUserPlan().plans[0]);

    this.state = {
      data: data,
      circlePoints: []
    };

    this.getCirclePoints = this.getCirclePoints.bind(this);
    this.processData = this.processData.bind(this);
  }
// ...


问:
Sql script to find invalid email addresses
A data import was done from an access database and there was no validation on the email address field.  Does anyone have an sql script that can return a list of invalid email addresses (missing @, etc).</p>

答:
On sql server 2016 and up</p>

```<code>CREATE FUNCTION [DBO].[F_IsEmail] (
 @EmailAddr varchar(360) -- Email address to check
)   RETURNS BIT -- 1 if @EmailAddr is a valid email address

AS BEGIN
DECLARE @AlphabetPlus VARCHAR(255)
      , @Max INT -- Length of the address
      , @Pos INT -- Position in @EmailAddr
      , @OK BIT  -- Is @EmailAddr OK
-- Check basic conditions
IF @EmailAddr IS NULL
   OR @EmailAddr NOT LIKE '[0-9a-zA-Z]%@__%.__%'
   OR @EmailAddr LIKE '%@%@%'
   OR @EmailAddr LIKE '%..%'
   OR @EmailAddr LIKE '%.@'
   OR @EmailAddr LIKE '%@.'
   OR @EmailAddr LIKE '%@%.-%'
   OR @EmailAddr LIKE '%@%-.%'
   OR @EmailAddr LIKE '%@-%'
   OR CHARINDEX(' ',LTRIM(RTRIM(@EmailAddr))) > 0
       RETURN(0)

declare @AfterLastDot varchar(360);
declare @AfterArobase varchar(360);
declare @BeforeArobase varchar(360);
declare @HasDomainTooLong bit=0;

--Control des longueurs et autres incoherence
set @AfterLastDot=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('.',REVERSE(@EmailAddr))));
if  len(@AfterLastDot) not between 2 and 17
RETURN(0);

set @AfterArobase=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('@',REVERSE(@EmailAddr))));
if len(@AfterArobase) not between 2 and 255
RETURN(0);

select top 1 @BeforeArobase=value from  string_split(@EmailAddr, '@');
if len(@AfterArobase) not between 2 and 255
RETURN(0);

--Controle sous-domain pas plus grand que 63
select top 1 @HasDomainTooLong=1 from string_split(@AfterArobase, '.') where LEN(value)>63
if @HasDomainTooLong=1
return(0);

--Control de la partie locale en detail
SELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890!#$%&‘*+-/=?^_`.{|}~'
     , @Max = LEN(@BeforeArobase)
     , @Pos = 0
     , @OK = 1

WHILE @Pos < @Max AND @OK = 1 BEGIN
    SET @Pos = @Pos + 1
    IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@BeforeArobase, @Pos, 1) + '%'
        SET @OK = 0
END

if @OK=0
RETURN(0);

--Control de la partie domaine en detail
SELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890-.'
     , @Max = LEN(@AfterArobase)
     , @Pos = 0
     , @OK = 1

WHILE @Pos < @Max AND @OK = 1 BEGIN
    SET @Pos = @Pos + 1
    IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@AfterArobase, @Pos, 1) + '%'
        SET @OK = 0
END

if @OK=0
RETURN(0);

return(1);

END
</code>```

ContentLicense: CC BY-SA 4.0

Body:
On sql server 2016 and up

CREATE FUNCTION [DBO].[F_IsEmail] (
 @EmailAddr varchar(360) -- Email address to check
)   RETURNS BIT -- 1 if @EmailAddr is a valid email address

AS BEGIN
DECLARE @AlphabetPlus VARCHAR(255)
      , @Max INT -- Length of the address
      , @Pos INT -- Position in @EmailAddr
      , @OK BIT  -- Is @EmailAddr OK
-- Check basic conditions
IF @EmailAddr IS NULL
   OR @EmailAddr NOT LIKE '[0-9a-zA-Z]%@__%.__%'
   OR @EmailAddr LIKE '%@%@%'
   OR @EmailAddr LIKE '%..%'
   OR @EmailAddr LIKE '%.@'
   OR @EmailAddr LIKE '%@.'
   OR @EmailAddr LIKE '%@%.-%'
   OR @EmailAddr LIKE '%@%-.%'
   OR @EmailAddr LIKE '%@-%'
   OR CHARINDEX(' ',LTRIM(RTRIM(@EmailAddr))) > 0
       RETURN(0)

declare @AfterLastDot varchar(360);
declare @AfterArobase varchar(360);
declare @BeforeArobase varchar(360);
declare @HasDomainTooLong bit=0;

--Control des longueurs et autres incoherence
set @AfterLastDot=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('.',REVERSE(@EmailAddr))));
if  len(@AfterLastDot) not between 2 and 17
RETURN(0);

set @AfterArobase=REVERSE(SUBSTRING(REVERSE(@EmailAddr),0,CHARINDEX('@',REVERSE(@EmailAddr))));
if len(@AfterArobase) not between 2 and 255
RETURN(0);

select top 1 @BeforeArobase=value from  string_split(@EmailAddr, '@');
if len(@AfterArobase) not between 2 and 255
RETURN(0);

--Controle sous-domain pas plus grand que 63
select top 1 @HasDomainTooLong=1 from string_split(@AfterArobase, '.') where LEN(value)>63
if @HasDomainTooLong=1
return(0);

--Control de la partie locale en detail
SELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890!#$%&‘*+-/=?^_`.{|}~'
     , @Max = LEN(@BeforeArobase)
     , @Pos = 0
     , @OK = 1

WHILE @Pos < @Max AND @OK = 1 BEGIN
    SET @Pos = @Pos + 1
    IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@BeforeArobase, @Pos, 1) + '%'
        SET @OK = 0
END

if @OK=0
RETURN(0);

--Control de la partie domaine en detail
SELECT @AlphabetPlus = 'abcdefghijklmnopqrstuvwxyz01234567890-.'
     , @Max = LEN(@AfterArobase)
     , @Pos = 0
     , @OK = 1

WHILE @Pos < @Max AND @OK = 1 BEGIN
    SET @Pos = @Pos + 1
    IF @AlphabetPlus NOT LIKE '%' + SUBSTRING(@AfterArobase, @Pos, 1) + '%'
        SET @OK = 0
END

if @OK=0
RETURN(0);

return(1);

END


问:
Adding precommit hooks with Husky without pushing addition to git
Hey i want to add a script to my package.json but don't want to check in this addition to our git because it affects the behaviour of the project for my colleagues.

The script i want to add is a precommit-Hook which is handled by husky. Is there a possibility to have something like a package.override.json where i define the script and ignore the file in .gitignore or are there different approaches?

答:
I can think of two solutions without using husky:

You can set up your own git hooks directly in the .git/hooks folder of your local repository. See https://git-scm.com/book/gr/v2/Customizing-Git-Git-Hooks for information on how to do that.

If that doesn't work out you and you're running a *nix OS, can always write your own commit alias using bash. Add something like

```<code>alias commit="npm run test && git commit"
</code>```

to your ~/.bashrc file.

(Of course, the ideal is to convince your colleagues of the value husky provides.)

Body:
I can think of two solutions without using husky:

You can set up your own git hooks directly in the .git/hooks folder of your local repository. See https://git-scm.com/book/gr/v2/Customizing-Git-Git-Hooks for information on how to do that.

If that doesn't work out you and you're running a *nix OS, can always write your own commit alias using bash. Add something like

alias commit="npm run test && git commit"

to your ~/.bashrc file.

(Of course, the ideal is to convince your colleagues of the value husky provides.)


问:
Doubt on immediate attribute for command button
HI,

I have a doubt on setting the immediate attribute for the command button. I would like to know what will be the changes in the life cycle?

I have read that setting immediate attribute will call the action listener or action methods in the apply request values phase. My doubts is it only the difference of preponding the phase. Also it will execute the all the business logic in the action methods regardless of setting the immediate attribute.

Please clarify my doubts.

答:
If immediate="true" is set in an UICommand component, then the apply request values phase until with update model values phases will be skipped for any of the UIInput component(s) in the same UIForm. Use this to skip the entire processing of the form. E.g. "Cancel" or "Back" button.

If immediate="true" is set in both UIInput and UICommand components in the same UIForm, then the apply request values phase until with update model values phases will be skipped for any of the UIInput component(s) in the same form which does not have this attribute set. Use this to skip the processing of the entire form expect for certain fields (with immediate). E.g. "Password forgotten" button in a login form with a required but non-immediate password field.

See also

Debug JSF lifecycle