问:
angular http get using c#.Net
I am new to Angular 2.4 and using Visual Studio 2017. I have created a project using .NET Core 1.1. I am trying to use some of the code from the Angular Tour of Heroes tutorial. I have created a controller in Visual Studio .Net using the Web API and it is successfully returning a JSON file of customer data.

Similar to the tutorial, I am creating a customer.service.ts and customers.component.ts.

I am getting a 404 File Not Found error on the calls to getCustomers(). I am having trouble figuring out why it isn't working. Any help would be greatly appreciated.

Here is the code snippet for the customer.service.ts:

```<code>import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Customer } from './customer';

@Injectable()
export class CustomerService {
    private customerUrl = 'api/customer';  // URL to web api
    private headers = new Headers({ 'Content-Type': 'application/json' });
    private customers: Customer[];

    constructor(private http: Http) { }

    getCustomers(): Promise<Customer[]> {
        return this.http.get('api/customer')
            .toPromise()
            .then(response => response.json() as Customer[])
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}
</code>```

Here is the code snippet for customers.component.ts:

```<code>import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Customer } from './customer';
import { CustomerService } from './customer.service';

@Component({
    selector: 'customers',
    templateUrl: './customers.component.html',

    // an array of style file names (with paths).
    styleUrls: ['./customers.component.css'],
})

export class CustomersComponent implements OnInit {
    title = 'Northwind Customers';
    public customers: Customer[];
    selectedCustomer: Customer;
    http: Http;

    constructor(private router: Router, private customerService: CustomerService) { }

    onSelect(customer: Customer): void {
        this.selectedCustomer = customer;
    }

    getCustomers(): void {
        //this.customers = this.customerService.getCustomers();
        this.customerService.getCustomers().then(customers => this.customers = customers);
    }

    ngOnInit(): void {
        this.getCustomers();
    }
}
</code>```

Here is the customers.component.html:

```<code><h1>{{title}}</h1>

<h2>Customers</h2>

<div>
    <label>Company name:</label> <input #companyName />
    <button (click)="add(companyName.value); companyName.value=''">Add</button>
</div>

<ul>
    <li *ngFor="let customer of customers"
        [class.selected]="customer === selectedCustomer">
        <span class="badge">{{customer.customerID}}</span>
        <span>{{customer.companyName}}</span>

    </li>
</ul>
</code>```

Here is the customer.ts:

```<code>export class Customer {
    customerID: string;
    companyName: string;
    contactName: string;
    contactTitle: string;
    address: string;
    city: string;
    region: string;
    postalCode: string;
    country: string;
    phone: string;
    fax: string;
}
</code>```

My ASP.NET controller seems to be working. It returns a JSON file with the data when I navigate to api/customer in the browser. Here is the code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NorthwindAngular.DAL;
using NorthwindAngular.Models;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace NorthwindAngular.Controllers
{
    [Route("api/[controller]")]
    public class CustomerController : Controller
    {
        private readonly NorthwindContext _context;

        public CustomerController(NorthwindContext context)
        {
            _context = context;
        }

        // GET: api/values
        //[HttpGet("[action]")]
        [HttpGet]
        public IEnumerable<Customer> Get()
        {
            return _context.Customers.ToList();
        }

        // GET: api/values
        [HttpGet("{id}")]
        public Customer Get(string id)
        {
            if (String.IsNullOrEmpty(id))
                return null;
            else
                return _context.Customers.Find(id);
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
</code>```

答:
I guess you are not giving the full url of the web api, append the url  with the localhost address like </p>

```<code> http.get('http://localhost:[port number where your api is running]/api/customer')
</code>```

Title: angular http get using c#.Net

Body:
I am new to Angular 2.4 and using Visual Studio 2017. I have created a project using .NET Core 1.1. I am trying to use some of the code from the Angular Tour of Heroes tutorial. I have created a controller in Visual Studio .Net using the Web API and it is successfully returning a JSON file of customer data.

Similar to the tutorial, I am creating a customer.service.ts and customers.component.ts.

I am getting a 404 File Not Found error on the calls to getCustomers(). I am having trouble figuring out why it isn't working. Any help would be greatly appreciated.

Here is the code snippet for the customer.service.ts:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Customer } from './customer';

@Injectable()
export class CustomerService {
    private customerUrl = 'api/customer';  // URL to web api
    private headers = new Headers({ 'Content-Type': 'application/json' });
    private customers: Customer[];

    constructor(private http: Http) { }

    getCustomers(): Promise<Customer[]> {
        return this.http.get('api/customer')
            .toPromise()
            .then(response => response.json() as Customer[])
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

Here is the code snippet for customers.component.ts:

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Customer } from './customer';
import { CustomerService } from './customer.service';

@Component({
    selector: 'customers',
    templateUrl: './customers.component.html',

    // an array of style file names (with paths).
    styleUrls: ['./customers.component.css'],
})

export class CustomersComponent implements OnInit {
    title = 'Northwind Customers';
    public customers: Customer[];
    selectedCustomer: Customer;
    http: Http;

    constructor(private router: Router, private customerService: CustomerService) { }

    onSelect(customer: Customer): void {
        this.selectedCustomer = customer;
    }

    getCustomers(): void {
        //this.customers = this.customerService.getCustomers();
        this.customerService.getCustomers().then(customers => this.customers = customers);
    }

    ngOnInit(): void {
        this.getCustomers();
    }
}

Here is the customers.component.html:

{{title}}

Customers

    Company name: <input #companyName />
    <button (click)="add(companyName.value); companyName.value=''">Add</button>

        {{customer.customerID}}
        {{customer.companyName}}

Here is the customer.ts:

export class Customer {
    customerID: string;
    companyName: string;
    contactName: string;
    contactTitle: string;
    address: string;
    city: string;
    region: string;
    postalCode: string;
    country: string;
    phone: string;
    fax: string;
}

My ASP.NET controller seems to be working. It returns a JSON file with the data when I navigate to api/customer in the browser. Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NorthwindAngular.DAL;
using NorthwindAngular.Models;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace NorthwindAngular.Controllers
{
    [Route("api/[controller]")]
    public class CustomerController : Controller
    {
        private readonly NorthwindContext _context;

        public CustomerController(NorthwindContext context)
        {
            _context = context;
        }

        // GET: api/values
        //[HttpGet("[action]")]
        [HttpGet]
        public IEnumerable<Customer> Get()
        {
            return _context.Customers.ToList();
        }

        // GET: api/values
        [HttpGet("{id}")]
        public Customer Get(string id)
        {
            if (String.IsNullOrEmpty(id))
                return null;
            else
                return _context.Customers.Find(id);
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

Body:
I guess you are not giving the full url of the web api, append the url  with the localhost address like

 http.get('http://localhost:[port number where your api is running]/api/customer')


来源: stackexchange

问:
Load new a new component onKeyPress - reactjs
I'm trying to load a new component i have made when i press the button 'Enter'. I have implemented the onKeyPress function successfully as follows.

```<code>    class SearchBar extends Component {

        constructor(props) {

            super(props);

            this.handleKeyPress = this.handleKeyPress.bind(this);

        }

        handleKeyPress(e) {

            if (e.key === 'Enter') {

                console.log("load new page");

            }
        }

        render() {

            return (

                <div className="search_bar_div">

                    <div className="search_bar_internal_div">

                        {/* Search bar for desktop and tablets */}
                        <span className="Rev_logo">Revegator</span>

                        <input type="search" placeholder="Search here" className="search_bar"
                               onKeyPress={this.handleKeyPress}/>

                    </div>

                 </div>
}
</code>```

I get the console log correctly but the problem i have is how to load the component when i press Enter.

答:
What you can do is to establish Routes for you component and then dynamically change the route with this.context.router like

```<code>class SearchBar extends Component {

        constructor(props) {

            super(props);

            this.handleKeyPress = this.handleKeyPress.bind(this);

        }

        handleKeyPress(e) {

            if (e.key === 'Enter') {

                console.log("load new page");
                this.context.router.push('/home');
            }
        }

        render() {

            return (

                <div className="search_bar_div">

                    <div className="search_bar_internal_div">

                        {/* Search bar for desktop and tablets */}
                        <span className="Rev_logo">Revegator</span>

                        <input type="search" placeholder="Search here" className="search_bar"
                               onKeyPress={this.handleKeyPress}/>

                    </div>

                 </div>
              )
       }
}

SearchBar.contextTypes = {
  router: React.PropTypes.func.isRequired
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to load a new component i have made when i press the button 'Enter'. I have implemented the onKeyPress function successfully as follows.

    class SearchBar extends Component {

        constructor(props) {

            super(props);

            this.handleKeyPress = this.handleKeyPress.bind(this);

        }

        handleKeyPress(e) {

            if (e.key === 'Enter') {

                console.log("load new page");

            }
        }

        render() {

            return (

                        {/* Search bar for desktop and tablets */}
                        Revegator

                        <input type="search" placeholder="Search here" className="search_bar"
                               onKeyPress={this.handleKeyPress}/>

}

I get the console log correctly but the problem i have is how to load the component when i press Enter.

Body:
What you can do is to establish Routes for you component and then dynamically change the route with this.context.router like

class SearchBar extends Component {

        constructor(props) {

            super(props);

            this.handleKeyPress = this.handleKeyPress.bind(this);

        }

        handleKeyPress(e) {

            if (e.key === 'Enter') {

                console.log("load new page");
                this.context.router.push('/home');
            }
        }

        render() {

            return (

                <div className="search_bar_div">

                    <div className="search_bar_internal_div">

                        {/* Search bar for desktop and tablets */}
                        <span className="Rev_logo">Revegator</span>

                        <input type="search" placeholder="Search here" className="search_bar"
                               onKeyPress={this.handleKeyPress}/>

                    </div>

                 </div>
              )
       }
}

SearchBar.contextTypes = {
  router: React.PropTypes.func.isRequired
};


问:
android data binding <include> layout OnClick listener doesn't work
I have a data binding layout that contains a frame layout with <include> of other layout inside:

```<code><FrameLayout
    android:id="@+id/global_actions_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.075"
    android:background="@color/colorToolBar">
    <include
        android:id="@+id/included"
        layout="@layout/global_actions">
    </include>
</FrameLayout>
</code>```

the layout has image buttons inside in this format:

```<code><ImageButton
    android:id="@+id/settingsButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_settings_black_36dp"
    android:layout_gravity="end"
    android:background="@color/colorToolBar"
    android:layout_margin="4dp"
    android:layout_marginLeft="20dp"
    android:onClick="@{listener::onClickState}"
android:alpha="0.4"/>
</code>```

and I added the  tag around them and I added data with  name of activity

```<code> <data>
    <import type="android.view.View"/>
    <variable name="listener" type="MyActivity"/>
</data>
</code>```

and in MyActivity I called a function to listen to On click from the image buttons:

```<code>public void onClickState(View view){
int id = view.getId();
}
</code>```

but from some reason I don't get to this function when I click
 I tried also

```<code> android:onClick="@{listener.onClickState}"
</code>```

but nothing helped.

答:
If you want to use DataBinding variables in an included layout, you need to pass them to the included layout, and also make your parent view use DataBinding:

```<code><layout>
    <data>
        <variable type="your.packages.here.MainActivity" name="listener"/>
    </data>

    <FrameLayout>
        <include
            android:id="@+id/included"
            layout="@layout/global_actions"
            app:listener="@{listener}"/>
        </include>
    </FrameLayout>
</layout>
</code>```

You need to set your listener in your MainActivity.class to the corresponding binding class:

```<code>activityMainBinding.setListener(this);
</code>```

and in your included layout, you need to use the same name that you used in your parent layout (app:listener):

```<code><layout>
    <data>
        <variable type="your.packages.here.MainActivity" name="listener"/>
    </data>

    <ImageButton
     android:onClick="@{listener::onClickState}"/>
</layout>
</code>```

Please take a look at George Mounts answer to a similiar question.

ContentLicense: CC BY-SA 4.0

Body:
I have a data binding layout that contains a frame layout with <include> of other layout inside:

<FrameLayout
    android:id="@+id/global_actions_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.075"
    android:background="@color/colorToolBar">
    <include
        android:id="@+id/included"
        layout="@layout/global_actions">
    </include>
</FrameLayout>

the layout has image buttons inside in this format:

<ImageButton
    android:id="@+id/settingsButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_settings_black_36dp"
    android:layout_gravity="end"
    android:background="@color/colorToolBar"
    android:layout_margin="4dp"
    android:layout_marginLeft="20dp"
    android:onClick="@{listener::onClickState}"
android:alpha="0.4"/>

and I added the  tag around them and I added data with  name of activity

 <data>
    <import type="android.view.View"/>
    <variable name="listener" type="MyActivity"/>
</data>

and in MyActivity I called a function to listen to On click from the image buttons:

public void onClickState(View view){
int id = view.getId();
}

but from some reason I don't get to this function when I click
 I tried also

 android:onClick="@{listener.onClickState}"

but nothing helped.

Body:
If you want to use DataBinding variables in an included layout, you need to pass them to the included layout, and also make your parent view use DataBinding:

<layout>
    <data>
        <variable type="your.packages.here.MainActivity" name="listener"/>
    </data>

    <FrameLayout>
        <include
            android:id="@+id/included"
            layout="@layout/global_actions"
            app:listener="@{listener}"/>
        </include>
    </FrameLayout>
</layout>

You need to set your listener in your MainActivity.class to the corresponding binding class:

activityMainBinding.setListener(this);

and in your included layout, you need to use the same name that you used in your parent layout (app:listener):

<layout>
    <data>
        <variable type="your.packages.here.MainActivity" name="listener"/>
    </data>

    <ImageButton
     android:onClick="@{listener::onClickState}"/>
</layout>

Please take a look at George Mounts answer to a similiar question.


问:
ReferenceError on all google Sheet build in functions
I am getting started with Google App Scripts and have written a little something.
The problem I am having is the following: ReferenceError: "COUNT" is not defined

I am getting this too when I try to use COUNTA or any other build in function of the Google App Script.

I am uncertain weather or not my script will work but testing it would be much easier if I was able to execute it.

For reference I have the script in question here:

```<code>function fillMonthFromChildSheet()
{
  var sheet = SpreadsheetApp.getActiveSheet();
  var dates = [];
  var dateCell;
  var totalExpense = 0;
  var rangeB = "B:B";

  for (var i = 0; i < COUNT(rangeB) - COUNTBLANK(rangeB); ++i)
  {
    dateCell = "B" + i;
    dates.push(DATE(dateCell));
  }

  for (var i = 0; i < dates.length(); ++i)
  {
    if (MONTH(dates[i]) == MONTH(TODAY()))
    {
      var range = "A" + i;
      totalExpense += sheet.getRange(range).getValue();
    }
  }
  return totalExpense;
}
</code>```

Help is much appreciated! Thank you in advance

答:
Your problems are COUNT(rangeB) COUNTBLANK(rangeB) DATE(dateCell) MONTH(dates[i]) MONTH(TODAY()) as you have not defined these anywhere. By the looks of things you are trying to write a Google Apps script and use a spreadsheet function, like =COUNT(A1:A2). These functions do not work in Google Apps script

In general it's just JavaScript with the addition of these classes and methods that you can find here.

Body:
I am getting started with Google App Scripts and have written a little something.
The problem I am having is the following: ReferenceError: "COUNT" is not defined

I am getting this too when I try to use COUNTA or any other build in function of the Google App Script.

I am uncertain weather or not my script will work but testing it would be much easier if I was able to execute it.

For reference I have the script in question here:

function fillMonthFromChildSheet()
{
  var sheet = SpreadsheetApp.getActiveSheet();
  var dates = [];
  var dateCell;
  var totalExpense = 0;
  var rangeB = "B:B";

  for (var i = 0; i < COUNT(rangeB) - COUNTBLANK(rangeB); ++i)
  {
    dateCell = "B" + i;
    dates.push(DATE(dateCell));
  }

  for (var i = 0; i < dates.length(); ++i)
  {
    if (MONTH(dates[i]) == MONTH(TODAY()))
    {
      var range = "A" + i;
      totalExpense += sheet.getRange(range).getValue();
    }
  }
  return totalExpense;
}

Help is much appreciated! Thank you in advance


问:
Local Notification is not displayed in iOS 10
i have tried this Code in Appdelegates.

```<code>@import UserNotifications;

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
        completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
            NSLog(@"request authorization succeeded!");

                center.delegate = self;
            }
    }];
</code>```

And the local notification is fired by this code

```<code>-(void)localNotification{

NSLog(@"local notification fired");

UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];

objNotificationContent.title = @"local notificatin";

objNotificationContent.body = @"message";

objNotificationContent.sound = [UNNotificationSound defaultSound];

/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);

// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                              triggerWithTimeInterval:0.3 repeats:NO];

    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"three"
                                                                      content:objNotificationContent trigger:trigger];

/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (!error) {
        NSLog(@"Local Notification succeeded");
    }
    else {
        NSLog(@"Local Notification failed");
    }
}];
</code>```

}

But Local notification is not displayed. As  i have used two Delegates method one is for present notification in foreground and one method that Must be called when local notification received.

that Delegates methods does not called at any Scenario.

please find Silly Mistake where i m wrong

答:
If you're in foreground, your delegate method will be called but no visual notification will be displayed. If you really want to show a notification in foreground you can use something like:

https://github.com/pikacode/EBForeNotification

Body:
i have tried this Code in Appdelegates.

@import UserNotifications;

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
        completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
            NSLog(@"request authorization succeeded!");

                center.delegate = self;
            }
    }];

And the local notification is fired by this code

-(void)localNotification{

NSLog(@"local notification fired");

UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];

objNotificationContent.title = @"local notificatin";

objNotificationContent.body = @"message";

objNotificationContent.sound = [UNNotificationSound defaultSound];

/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);

// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                              triggerWithTimeInterval:0.3 repeats:NO];

    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"three"
                                                                      content:objNotificationContent trigger:trigger];

/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (!error) {
        NSLog(@"Local Notification succeeded");
    }
    else {
        NSLog(@"Local Notification failed");
    }
}];

}

But Local notification is not displayed. As  i have used two Delegates method one is for present notification in foreground and one method that Must be called when local notification received.

that Delegates methods does not called at any Scenario.

please find Silly Mistake where i m wrong


问:
Align checkBoxGroupInput vertically and horizontally
In a similar post (How to align a group of checkboxGroupInput in R Shiny) checkboxes are aligned only vertically (as in my example) or only horizontally (R Shiny display checkboxGroupInput horizontally ). I wonder if there is a way to accomplish this in both senses (when in columns).

```<code>library(shiny)
examplesubset<-read.table(text="
                          elements locations
                          element_One A,M,P,R
                          element_Two A,B,C,M,P,E,I
                          element_Three G,M,T,F,O,H,A,B,C,D" ,  header=TRUE, stringsAsFactors=FALSE)
examplesubset$elements<-as.factor(examplesubset$elements)

ui<-fluidPage(
  tags$head(tags$style(HTML("
                            .multicol {
                            -webkit-column-count: 3; /* Chrome, Safari, Opera */
                            -moz-column-count: 3;    /* Firefox */
                            column-count: 3;
                            -moz-column-fill: auto;
                            -column-fill: auto;
                            }
                            "))),
  titlePanel("Panel"),
  sidebarLayout(
    sidebarPanel(
      selectInput("elements", "Select elements:",
                  choices=examplesubset$elements)
    ) ,
    mainPanel(
      fluidRow(
        column(3,
               uiOutput("checkboxesui")
        ))))
  )

server<-function(input, output,session) {
  elementsselected<-reactive({
    sp<-examplesubset[examplesubset$elements==input$elements,]
    sp<-droplevels(sp)
  })
  locationsreactive<- reactive({
    j<-as.factor(unique(unlist(strsplit(elementsselected()$locations, ",", fixed = TRUE) ) ) )
    j<-droplevels(j)
  })
  output$checkboxesui<-renderUI({
    tags$div(align = 'left',
             class = 'multicol',
             checkboxGroupInput("locationscheckboxes", "locations",
                                choices=levels(locationsreactive())
                                , selected=c() )
             )
  })
}
shinyApp(ui = ui, server = server)
</code>```

答:
The following code should do the trick.  You needed to apply the CSS columns a div below where you had them and then remove padding from above and below the check boxes, I also changed the column fill to balanced:

```<code>library(shiny)
examplesubset<-read.table(text="
                          elements locations
                          element_One A,M,P,A,R,T
                          element_Two A,B,C,M,P,E,I,N,S
                          element_Three G,M,T,F,S,V,P" ,  header=TRUE, stringsAsFactors=FALSE)
examplesubset$elements<-as.factor(examplesubset$elements)

ui<-fluidPage(
  tags$head(tags$style(HTML("
                            .multicol .shiny-options-group{
                            -webkit-column-count: 3; /* Chrome, Safari, Opera */
                            -moz-column-count: 3;    /* Firefox */
                            column-count: 3;
                            -moz-column-fill: balanced;
                            -column-fill: balanced;
                            }
                            .checkbox{
                            margin-top: 0px !important;
                            -webkit-margin-after: 0px !important;
                            }
                            "))),
  titlePanel("Panel"),
  sidebarLayout(
    sidebarPanel(
      selectInput("elements", "Select elements:",
                  choices=examplesubset$elements)
    ) ,
    mainPanel(
      fluidRow(
        column(3,
               uiOutput("checkboxesui")
        ))))
  )

server<-function(input, output,session) {
  elementsselected<-reactive({
    sp<-examplesubset[examplesubset$elements==input$elements,]
    sp<-droplevels(sp)
  })
  locationsreactive<- reactive({
    j<-as.factor(unique(unlist(strsplit(elementsselected()$locations, ",", fixed = TRUE) ) ) )
    j<-droplevels(j)
  })
  output$checkboxesui<-renderUI({
    tags$div(align = 'left',
             class = 'multicol',
             checkboxGroupInput("locationscheckboxes", "locations",
                                choices=levels(locationsreactive())
                                , selected=c() )
    )
  })
}
shinyApp(ui = ui, server = server)
</code>```

The other option is to use CSS flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

This would solve the ordering issues you described, but you would need to dink with the sizes of the shiny-options-group div to get everything to fit the way you want, depending on your content.  It is probably easier to just reorder your checkbox options so they display the way you want.

Body:
In a similar post (How to align a group of checkboxGroupInput in R Shiny) checkboxes are aligned only vertically (as in my example) or only horizontally (R Shiny display checkboxGroupInput horizontally ). I wonder if there is a way to accomplish this in both senses (when in columns).

library(shiny)
examplesubset<-read.table(text="
                          elements locations
                          element_One A,M,P,R
                          element_Two A,B,C,M,P,E,I
                          element_Three G,M,T,F,O,H,A,B,C,D" ,  header=TRUE, stringsAsFactors=FALSE)
examplesubset$elements<-as.factor(examplesubset$elements)

ui<-fluidPage(
  tags$head(tags$style(HTML("
                            .multicol {
                            -webkit-column-count: 3; /* Chrome, Safari, Opera */
                            -moz-column-count: 3;    /* Firefox */
                            column-count: 3;
                            -moz-column-fill: auto;
                            -column-fill: auto;
                            }
                            "))),
  titlePanel("Panel"),
  sidebarLayout(
    sidebarPanel(
      selectInput("elements", "Select elements:",
                  choices=examplesubset$elements)
    ) ,
    mainPanel(
      fluidRow(
        column(3,
               uiOutput("checkboxesui")
        ))))
  )

server<-function(input, output,session) {
  elementsselected<-reactive({
    sp<-examplesubset[examplesubset$elements==input$elements,]
    sp<-droplevels(sp)
  })
  locationsreactive<- reactive({
    j<-as.factor(unique(unlist(strsplit(elementsselected()$locations, ",", fixed = TRUE) ) ) )
    j<-droplevels(j)
  })
  output$checkboxesui<-renderUI({
    tags$div(align = 'left',
             class = 'multicol',
             checkboxGroupInput("locationscheckboxes", "locations",
                                choices=levels(locationsreactive())
                                , selected=c() )
             )
  })
}
shinyApp(ui = ui, server = server)

Body:
The following code should do the trick.  You needed to apply the CSS columns a div below where you had them and then remove padding from above and below the check boxes, I also changed the column fill to balanced:

library(shiny)
examplesubset<-read.table(text="
                          elements locations
                          element_One A,M,P,A,R,T
                          element_Two A,B,C,M,P,E,I,N,S
                          element_Three G,M,T,F,S,V,P" ,  header=TRUE, stringsAsFactors=FALSE)
examplesubset$elements<-as.factor(examplesubset$elements)

ui<-fluidPage(
  tags$head(tags$style(HTML("
                            .multicol .shiny-options-group{
                            -webkit-column-count: 3; /* Chrome, Safari, Opera */
                            -moz-column-count: 3;    /* Firefox */
                            column-count: 3;
                            -moz-column-fill: balanced;
                            -column-fill: balanced;
                            }
                            .checkbox{
                            margin-top: 0px !important;
                            -webkit-margin-after: 0px !important;
                            }
                            "))),
  titlePanel("Panel"),
  sidebarLayout(
    sidebarPanel(
      selectInput("elements", "Select elements:",
                  choices=examplesubset$elements)
    ) ,
    mainPanel(
      fluidRow(
        column(3,
               uiOutput("checkboxesui")
        ))))
  )

server<-function(input, output,session) {
  elementsselected<-reactive({
    sp<-examplesubset[examplesubset$elements==input$elements,]
    sp<-droplevels(sp)
  })
  locationsreactive<- reactive({
    j<-as.factor(unique(unlist(strsplit(elementsselected()$locations, ",", fixed = TRUE) ) ) )
    j<-droplevels(j)
  })
  output$checkboxesui<-renderUI({
    tags$div(align = 'left',
             class = 'multicol',
             checkboxGroupInput("locationscheckboxes", "locations",
                                choices=levels(locationsreactive())
                                , selected=c() )
    )
  })
}
shinyApp(ui = ui, server = server)

The other option is to use CSS flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

This would solve the ordering issues you described, but you would need to dink with the sizes of the shiny-options-group div to get everything to fit the way you want, depending on your content.  It is probably easier to just reorder your checkbox options so they display the way you want.


问:
Speed of different data structures in Python
I have a piece of code I need to run, however, it is taking so long. I estimate it will take a minimum of 2 hours to run and at most 100 hours. As you can see, I would like to speed this up.

My code is as follows:

```<code>#B1
file = open("/home/1015097/Downloads/B1/tour5.txt", "r").readlines()
# This is a very large file. You can find it on http://codemasters.eng.unimelb.edu.au/bit_problems/B1.zip
# It is named tour5.txt, you can also find the question I am trying to solve there.
racers = [int(file[0].split()[0]) / float(x) for x in file[0].split()[1::]]
print("hi")
def av(race):
    race = race.split()
    j = 0
    while j != len([float(race[0]) / float(x) for x in race[1::]]):
        racers[j] = [float(race[0]) / float(x) for x in race[1::]][j] + racers[j]
        j += 1
        print(j)
    print("yay...")
for i in range(1, len(file)):
    print("yay")
    av(file[i])
print("yaaay")
a = min(racers)
del(racers[racers.index(min(racers))])
b = min(racers)
c = b-a
h = int(c)
c-=h

m = int(c * 60)
c-=m/60
s = round(c * 60 * 60)
print(str(h) + "h" + str(m) + "m" + str(s) + "s")
</code>```

We are currently coming first in Australia for the Code Bits contest and would not like to drop our perfect score. The random print statements were so that we could tell if the code was actually running, they are essentially checkpoints. the number that is printed out is the racer number, there are at least 3000 racers, we do not know exactly.

答:
I would start with changing:

```<code>while j != len([float(race[0]) / float(x) for x in race[1::]]):
    racers[j] = [float(race[0]) / float(x) for x in race[1::]][j] + racers[j]
</code>```

into

```<code>while j != len(race) - 1:
    racers[j] += float(race[0]) / float(race[j])
</code>```

Body:
I have a piece of code I need to run, however, it is taking so long. I estimate it will take a minimum of 2 hours to run and at most 100 hours. As you can see, I would like to speed this up.

My code is as follows:

#B1
file = open("/home/1015097/Downloads/B1/tour5.txt", "r").readlines()
# This is a very large file. You can find it on http://codemasters.eng.unimelb.edu.au/bit_problems/B1.zip
# It is named tour5.txt, you can also find the question I am trying to solve there.
racers = [int(file[0].split()[0]) / float(x) for x in file[0].split()[1::]]
print("hi")
def av(race):
    race = race.split()
    j = 0
    while j != len([float(race[0]) / float(x) for x in race[1::]]):
        racers[j] = [float(race[0]) / float(x) for x in race[1::]][j] + racers[j]
        j += 1
        print(j)
    print("yay...")
for i in range(1, len(file)):
    print("yay")
    av(file[i])
print("yaaay")
a = min(racers)
del(racers[racers.index(min(racers))])
b = min(racers)
c = b-a
h = int(c)
c-=h

m = int(c * 60)
c-=m/60
s = round(c * 60 * 60)
print(str(h) + "h" + str(m) + "m" + str(s) + "s")

We are currently coming first in Australia for the Code Bits contest and would not like to drop our perfect score. The random print statements were so that we could tell if the code was actually running, they are essentially checkpoints. the number that is printed out is the racer number, there are at least 3000 racers, we do not know exactly.

Body:
I would start with changing:

while j != len([float(race[0]) / float(x) for x in race[1::]]):
    racers[j] = [float(race[0]) / float(x) for x in race[1::]][j] + racers[j]

into

while j != len(race) - 1:
    racers[j] += float(race[0]) / float(race[j])


问:
How to set Navigation Drawer to be opened from right to left
First of all I know this question appeared here before but after trying a lot I still didn't succeed.
I working on the example from
Android Developers site.

I'm trying to set the menu to be opened from right to left instead of how its implementing in the example (from left to right). In addition I want to move the open menu button to the right side of the action bar. I also red some answers here, for example in this answer.

I try to change the gravity of the views and the layouts but I get the error:

no drawer view found with absolute gravity LEFT

Can you please help me to figure out what is the problem in my code and what should I change in order to set the menu to be opened from the right, and to move the action bar button to the right side?

the xml code is here:

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_gravity="right"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/content_frame"
        android:layoutDirection="rtl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    <ListView android:id="@+id/left_drawer"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="10dp"
        android:background="#111"/>

</android.support.v4.widget.DrawerLayout>
</code>```

答:
I did following modification to the Navigation Drawer Activity example in Android Studio. With support libraries 25.3.1.

MainActivity.java:

```<code>private DrawerLayout mDrawerLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
        mDrawerLayout.closeDrawer(GravityCompat.END);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    switch (itemId) {
        case android.R.id.home:
            finish();
            return true;

        case R.id.action_right_drawer:
            if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
                mDrawerLayout.closeDrawer(GravityCompat.END);
            } else {
                mDrawerLayout.openDrawer(GravityCompat.END);
            }
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.

    mDrawerLayout.closeDrawer(GravityCompat.END);
    return true;
}
</code>```

main.xml (download ic_menu_white_24px from https://material.io/icons/):

```<code><?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_right_drawer"
        android:title="Drawer menu"
        android:icon="@drawable/ic_menu_white_24px"
        android:orderInCategory="100"
        app:showAsAction="always" />
</menu>
</code>```

In activity_main.xml change

```<code>android:layout_gravity="start"
</code>```

to

```<code>android:layout_gravity="end"
</code>```

Body:
First of all I know this question appeared here before but after trying a lot I still didn't succeed.
I working on the example from
Android Developers site.

I'm trying to set the menu to be opened from right to left instead of how its implementing in the example (from left to right). In addition I want to move the open menu button to the right side of the action bar. I also red some answers here, for example in this answer.

I try to change the gravity of the views and the layouts but I get the error:

no drawer view found with absolute gravity LEFT

Can you please help me to figure out what is the problem in my code and what should I change in order to set the menu to be opened from the right, and to move the action bar button to the right side?

the xml code is here:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_gravity="right"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/content_frame"
        android:layoutDirection="rtl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    <ListView android:id="@+id/left_drawer"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="10dp"
        android:background="#111"/>

</android.support.v4.widget.DrawerLayout>

Body:
I did following modification to the Navigation Drawer Activity example in Android Studio. With support libraries 25.3.1.

MainActivity.java:

private DrawerLayout mDrawerLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
        mDrawerLayout.closeDrawer(GravityCompat.END);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    switch (itemId) {
        case android.R.id.home:
            finish();
            return true;

        case R.id.action_right_drawer:
            if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
                mDrawerLayout.closeDrawer(GravityCompat.END);
            } else {
                mDrawerLayout.openDrawer(GravityCompat.END);
            }
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.

    mDrawerLayout.closeDrawer(GravityCompat.END);
    return true;
}

main.xml (download ic_menu_white_24px from https://material.io/icons/):

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_right_drawer"
        android:title="Drawer menu"
        android:icon="@drawable/ic_menu_white_24px"
        android:orderInCategory="100"
        app:showAsAction="always" />
</menu>

In activity_main.xml change

android:layout_gravity="start"

to

android:layout_gravity="end"


问:
Akka don't elect existing worker node as seed node, once the seed node is killed
I am a newbie with akka.
Having a very simple configuration of one seed node and one non-seed node.

Please find below, sequence of operation :-

Seed node started :-

```<code>val pConfig = ConfigFactory.load("application.conf").getConfig("PrimaryNode")

val demoSystem = ActorSystem("DemoSystem", pConfig)
</code>```

```<code>[INFO] [04/01/2017 23:42:48.438] [run-main-0] [akka.remote.Remoting] Starting remoting
[INFO] [04/01/2017 23:42:48.673] [run-main-0] [akka.remote.Remoting] Remoting started; listening on addresses :[akka.tcp://DemoSystem@127.0.0.1:2551]
[INFO] [04/01/2017 23:42:48.688] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Starting up...
[INFO] [04/01/2017 23:42:48.759] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Registered cluster JMX MBean [akka:type=Cluster]
[INFO] [04/01/2017 23:42:48.759] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Started up successfully
[INFO] [04/01/2017 23:42:48.776] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Metrics will be retreived from MBeans, and may be incorrect on som
e platforms. To increase metric accuracy add the 'sigar.jar' to the classpath and the appropriate platform-specific native libary to 'java.library.path'. Reason: java.lang.ClassNotFoundException: org.hyperic.sigar.Sigar
[INFO] [04/01/2017 23:42:48.779] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Metrics collection has started successfully
p: akka.actor.ActorSystem = akka://DemoSystem

[INFO] [04/01/2017 23:42:48.795] [DemoSystem-akka.actor.default-dispatcher-2] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Node [akka.tcp://DemoSystem@127.0.0.1:2551] is JOINING, rol
es []
[INFO] [04/01/2017 23:42:48.805] [DemoSystem-akka.actor.default-dispatcher-2] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Leader is moving node [akka.tcp://DemoSystem@127.0.0.1:2551] to [U
p]
</code>```

Non-seed node started :-

```<code>val sConfig = ConfigFactory.load("application.conf").getConfig("SecondaryNode")
val secSystem = ActorSystem("DemoSystem", sConfig)
</code>```

```<code>[INFO] [04/01/2017 23:44:15.530] [run-main-0] [akka.remote.Remoting] Starting remoting
[INFO] [04/01/2017 23:44:15.845] [run-main-0] [akka.remote.Remoting] Remoting started; listening on addresses :[akka.tcp://DemoSystem@127.0.0.1:49169]
[INFO] [04/01/2017 23:44:15.847] [run-main-0] [akka.remote.Remoting] Remoting now listens on addresses: [akka.tcp://DemoSystem@127.0.0.1:49169]
[INFO] [04/01/2017 23:44:15.854] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Starting up...
[INFO] [04/01/2017 23:44:15.929] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Registered cluster JMX MBean [akka:type=Cluster]
[INFO] [04/01/2017 23:44:15.929] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Started up successfully
[INFO] [04/01/2017 23:44:15.945] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Metrics will be retreived from MBeans, and may be incorrect on some platforms. To increase metric accuracy add the 'sigar.jar' to the classpath and the appropriate platform-specific native libary to 'java.library.path'. Reason: java.lang.ClassNotFoundException: org.hyperic.sigar.Sigar
[INFO] [04/01/2017 23:44:15.951] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Metrics collection has started successfully
s: akka.actor.ActorSystem = akka://DemoSystem

[INFO] [04/01/2017 23:44:16.265] [DemoSystem-akka.actor.default-dispatcher-14] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Welcome from [akka.tcp://DemoSystem@127.0.0.1:2551]
</code>```

And seed node moves non-seed node to up (seed node logs after starting
  non-seed node) :-

```<code>[INFO] [04/01/2017 23:44:16.190] [DemoSystem-akka.actor.default-dispatcher-14] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Node [akka.tcp://DemoSystem@127.0.0.1:49169] is JOINING, roles []

[INFO] [04/01/2017 23:44:16.782] [DemoSystem-akka.actor.default-dispatcher-25] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Leader is moving node [akka.tcp://DemoSystem@127.0.0.1:49169] to [Up]
</code>```

Now seed node is killed (logs on non seed node says, that seed node is quaretined) :-

```<code>............
............

[WARN] [04/01/2017 23:46:14.301] [DemoSystem-akka.remote.default-remote-dispatcher-6] [akka.tcp://DemoSystem@127.0.0.1:49169/system/endpointManager/reliableEndpointWriter-akka.tcp%3A%2F%2FDemoSystem%40127.0.0.1%3A2551-2] Association with remote system [akka.tcp://DemoSystem@127.0.0.1:2551] has failed, address is now gated for [5000] ms. Reason: [Association failed with [akka.tcp://DemoSystem@127.0.0.1:2551]] Caused by: [Connection refused: no further information: /127.0.0.1:2551]
[INFO] [04/01/2017 23:46:14.959] [DemoSystem-akka.actor.default-dispatcher-21] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Leader is auto-downing unreachable node [akka.tcp://DemoSystem@127.0.0.1:2551]
[INFO] [04/01/2017 23:46:14.960] [DemoSystem-akka.actor.default-dispatcher-20] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Marking unreachable node [akka.tcp://DemoSystem@127.0.0.1:2551] as [Down]
[INFO] [04/01/2017 23:46:15.953] [DemoSystem-akka.actor.default-dispatcher-21] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Leader is removing unreachable node [akka.tcp://DemoSystem@127.0.0.1:2551]
[WARN] [04/01/2017 23:46:15.953] [DemoSystem-akka.remote.default-remote-dispatcher-5] [akka.remote.Remoting] Association to [akka.tcp://DemoSystem@127.0.0.1:2551] having UID [-273153546] is irrecoverably failed. UID is now quarantined and all messages to this UID will be delivered to dead letters. Remote actorsystem must be restarted to recover from this situation.
</code>```

Now when i check the following things on non-seed node console :-

which node is the leader

Leader ship is successfully transferred to the non seed node

```<code>scala> val cluster = Cluster(secSystem)

scala> cluster.state
res1: akka.cluster.ClusterEvent.CurrentClusterState = CurrentClusterState(TreeSet(Member(address = akka.tcp://DemoSystem@127.0.0.1:49169, status = Up)),Set(),Set(akka.tcp://DemoSystem@127.0.0.1:49169),Some(akka.tcp://DemoSystem@127.0.0.1:49169),Map())

scala> cluster.state.leader
res2: Option[akka.actor.Address] = Some(akka.tcp://DemoSystem@127.0.0.1:49169)
</code>```

which node is the seed node :-

Seed node still points to the dead node

```<code>scala> cluster.settings.SeedNodes
res0: scala.collection.immutable.IndexedSeq[akka.actor.Address] = Vector(akka.tcp://DemoSystem@127.0.0.1:2551)
</code>```

I was thinking, that the non-seed node will be elected as a new seed node, but that was not the case.

Also, please find below configuration of two nodes :-

```<code>PrimaryNode {
  akka {
    actor {
      provider = "akka.cluster.ClusterActorRefProvider"
    }
    remote {
      log-remote-lifecycle-events = off
      enabled-transports = ["akka.remote.netty.tcp"]
      netty.tcp {
        hostname = "127.0.0.1"
        port = 2551
      }
    }
    cluster {
      seed-nodes = ["akka.tcp://DemoSystem@127.0.0.1:2551"]
      auto-down-unreachable-after = 10s
    }
  }
}

SecondaryNode {
  akka {
    actor {
      provider = "akka.cluster.ClusterActorRefProvider"
    }
    remote {
      enabled-transports = ["akka.remote.netty.tcp"]
      netty.tcp {
        hostname = "127.0.0.1"
        port = 49169
      }
    }
    cluster {
        seed-nodes = ["akka.tcp://DemoSystem@127.0.0.1:2551"]
        auto-down-unreachable-after = 10s
    }
  }
}
</code>```

Please enlighten me. Why the non seed node was not elected as new seed node once the previous seed node was killed.

答:
Sorry that I have very little time now, I'll try my best in a few words.

There's no such thing as seed node election.

Once an akka cluster has booted, every cluster member can act as a seed node for a joining node i.e., be used as initial contact point by any joining node. And this happens without configuration as all cluster nodes listen for incoming connections.

Before a cluster has booted though, the (first) seed node is very important as it is required to be part of the initial nodes available when starting up the cluster. Without that node, the cluster won't be able to boot. But once booted (as said above), that seed node can disappear and everything will be still fine.

This is most likely why the value of cluster.settings.SeedNodes doesn't change or is not updated. It has no impact after initial cluster setup.

references:

http://doc.akka.io/docs/akka/2.4.17/common/cluster.html#Seed_Nodes

http://doc.akka.io/docs/akka/2.4.17/scala/cluster-usage.html#Joining_to_Seed_Nodes

Body:
I am a newbie with akka.
Having a very simple configuration of one seed node and one non-seed node.

Please find below, sequence of operation :-

Seed node started :-

val pConfig = ConfigFactory.load("application.conf").getConfig("PrimaryNode")

val demoSystem = ActorSystem("DemoSystem", pConfig)

[INFO] [04/01/2017 23:42:48.438] [run-main-0] [akka.remote.Remoting] Starting remoting
[INFO] [04/01/2017 23:42:48.673] [run-main-0] [akka.remote.Remoting] Remoting started; listening on addresses :[akka.tcp://DemoSystem@127.0.0.1:2551]
[INFO] [04/01/2017 23:42:48.688] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Starting up...
[INFO] [04/01/2017 23:42:48.759] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Registered cluster JMX MBean [akka:type=Cluster]
[INFO] [04/01/2017 23:42:48.759] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Started up successfully
[INFO] [04/01/2017 23:42:48.776] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Metrics will be retreived from MBeans, and may be incorrect on som
e platforms. To increase metric accuracy add the 'sigar.jar' to the classpath and the appropriate platform-specific native libary to 'java.library.path'. Reason: java.lang.ClassNotFoundException: org.hyperic.sigar.Sigar
[INFO] [04/01/2017 23:42:48.779] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Metrics collection has started successfully
p: akka.actor.ActorSystem = akka://DemoSystem

[INFO] [04/01/2017 23:42:48.795] [DemoSystem-akka.actor.default-dispatcher-2] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Node [akka.tcp://DemoSystem@127.0.0.1:2551] is JOINING, rol
es []
[INFO] [04/01/2017 23:42:48.805] [DemoSystem-akka.actor.default-dispatcher-2] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Leader is moving node [akka.tcp://DemoSystem@127.0.0.1:2551] to [U
p]

Non-seed node started :-

val sConfig = ConfigFactory.load("application.conf").getConfig("SecondaryNode")
val secSystem = ActorSystem("DemoSystem", sConfig)

[INFO] [04/01/2017 23:44:15.530] [run-main-0] [akka.remote.Remoting] Starting remoting
[INFO] [04/01/2017 23:44:15.845] [run-main-0] [akka.remote.Remoting] Remoting started; listening on addresses :[akka.tcp://DemoSystem@127.0.0.1:49169]
[INFO] [04/01/2017 23:44:15.847] [run-main-0] [akka.remote.Remoting] Remoting now listens on addresses: [akka.tcp://DemoSystem@127.0.0.1:49169]
[INFO] [04/01/2017 23:44:15.854] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Starting up...
[INFO] [04/01/2017 23:44:15.929] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Registered cluster JMX MBean [akka:type=Cluster]
[INFO] [04/01/2017 23:44:15.929] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Started up successfully
[INFO] [04/01/2017 23:44:15.945] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Metrics will be retreived from MBeans, and may be incorrect on some platforms. To increase metric accuracy add the 'sigar.jar' to the classpath and the appropriate platform-specific native libary to 'java.library.path'. Reason: java.lang.ClassNotFoundException: org.hyperic.sigar.Sigar
[INFO] [04/01/2017 23:44:15.951] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Metrics collection has started successfully
s: akka.actor.ActorSystem = akka://DemoSystem

[INFO] [04/01/2017 23:44:16.265] [DemoSystem-akka.actor.default-dispatcher-14] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Welcome from [akka.tcp://DemoSystem@127.0.0.1:2551]

And seed node moves non-seed node to up (seed node logs after starting
  non-seed node) :-

[INFO] [04/01/2017 23:44:16.190] [DemoSystem-akka.actor.default-dispatcher-14] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Node [akka.tcp://DemoSystem@127.0.0.1:49169] is JOINING, roles []

[INFO] [04/01/2017 23:44:16.782] [DemoSystem-akka.actor.default-dispatcher-25] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Leader is moving node [akka.tcp://DemoSystem@127.0.0.1:49169] to [Up]

Now seed node is killed (logs on non seed node says, that seed node is quaretined) :-

............
............

[WARN] [04/01/2017 23:46:14.301] [DemoSystem-akka.remote.default-remote-dispatcher-6] [akka.tcp://DemoSystem@127.0.0.1:49169/system/endpointManager/reliableEndpointWriter-akka.tcp%3A%2F%2FDemoSystem%40127.0.0.1%3A2551-2] Association with remote system [akka.tcp://DemoSystem@127.0.0.1:2551] has failed, address is now gated for [5000] ms. Reason: [Association failed with [akka.tcp://DemoSystem@127.0.0.1:2551]] Caused by: [Connection refused: no further information: /127.0.0.1:2551]
[INFO] [04/01/2017 23:46:14.959] [DemoSystem-akka.actor.default-dispatcher-21] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Leader is auto-downing unreachable node [akka.tcp://DemoSystem@127.0.0.1:2551]
[INFO] [04/01/2017 23:46:14.960] [DemoSystem-akka.actor.default-dispatcher-20] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Marking unreachable node [akka.tcp://DemoSystem@127.0.0.1:2551] as [Down]
[INFO] [04/01/2017 23:46:15.953] [DemoSystem-akka.actor.default-dispatcher-21] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Leader is removing unreachable node [akka.tcp://DemoSystem@127.0.0.1:2551]
[WARN] [04/01/2017 23:46:15.953] [DemoSystem-akka.remote.default-remote-dispatcher-5] [akka.remote.Remoting] Association to [akka.tcp://DemoSystem@127.0.0.1:2551] having UID [-273153546] is irrecoverably failed. UID is now quarantined and all messages to this UID will be delivered to dead letters. Remote actorsystem must be restarted to recover from this situation.

Now when i check the following things on non-seed node console :-

which node is the leader

Leader ship is successfully transferred to the non seed node

scala> val cluster = Cluster(secSystem)

scala> cluster.state
res1: akka.cluster.ClusterEvent.CurrentClusterState = CurrentClusterState(TreeSet(Member(address = akka.tcp://DemoSystem@127.0.0.1:49169, status = Up)),Set(),Set(akka.tcp://DemoSystem@127.0.0.1:49169),Some(akka.tcp://DemoSystem@127.0.0.1:49169),Map())

scala> cluster.state.leader
res2: Option[akka.actor.Address] = Some(akka.tcp://DemoSystem@127.0.0.1:49169)

which node is the seed node :-

Seed node still points to the dead node

scala> cluster.settings.SeedNodes
res0: scala.collection.immutable.IndexedSeq[akka.actor.Address] = Vector(akka.tcp://DemoSystem@127.0.0.1:2551)

I was thinking, that the non-seed node will be elected as a new seed node, but that was not the case.

Also, please find below configuration of two nodes :-

PrimaryNode {
  akka {
    actor {
      provider = "akka.cluster.ClusterActorRefProvider"
    }
    remote {
      log-remote-lifecycle-events = off
      enabled-transports = ["akka.remote.netty.tcp"]
      netty.tcp {
        hostname = "127.0.0.1"
        port = 2551
      }
    }
    cluster {
      seed-nodes = ["akka.tcp://DemoSystem@127.0.0.1:2551"]
      auto-down-unreachable-after = 10s
    }
  }
}

SecondaryNode {
  akka {
    actor {
      provider = "akka.cluster.ClusterActorRefProvider"
    }
    remote {
      enabled-transports = ["akka.remote.netty.tcp"]
      netty.tcp {
        hostname = "127.0.0.1"
        port = 49169
      }
    }
    cluster {
        seed-nodes = ["akka.tcp://DemoSystem@127.0.0.1:2551"]
        auto-down-unreachable-after = 10s
    }
  }
}

Please enlighten me. Why the non seed node was not elected as new seed node once the previous seed node was killed.


问:
Waiting for Target Device to Come Online
I recently updated to Android Studio 2.3, and now when I try to run the application, the emulator does not come online. It times out after 300 seconds.

Additionally, The app has been experiencing a FATAL EXCEPTION ERROR (OOM), and I am not sure how to fix that either, or if that is part of the emulator problem.

Any help is much appreciated. Again, my knowledge in the program is very limited so if your answer can be kept simple, that would be great.

答:
Question is too old but may be helpful to someone in future.
After search many things, most of them is not worked for me. SO, as per my try This solution is worked for me. In short uninstall and install "Android SDK Tools" in Android SDK.

Few steps for that are below:-

go to "SDK Manager" in Android Studio

go to "SDK Tools" tab

Uninstall "Android SDK Tools" (means remove check(uncheck) ahead of "Android SDK Tools" and Apply then OK)

Close and Restart Android Studio

Install "Android SDK Tools" (means check ahead of "Android SDK Tools" and Apply then OK)

Image of Uninstall and Install Android SDK Tools again


问:
How to configure build step for maven goal in teamcity to run unit test
I use junit in my java project (developed using intellij idea) for unit test, and I want to configure build step in team city to run my unit tests only. I also use maven to build my project. It works when I set goals for maven to "clean compile" but I dont know how to configure build step to run unit tests. </p>

<p>Also in command line. when i run "maven test" it runs unit tests correctly and shows the failures. </p>

答:
I can't comment on TeamCity, but I'll try to help anyway out of my maven knowledge.

So first of all mvn clean compile will never run your unit tests, because maven has a concept of lifecycle and testing phase is coming after compile phase.

When you run mvn test it will run all the face up to (including) the test phase so the unit tests will run as a part of maven default lifecycle.

Now you're asking about a "build step for running unit tests" from which I conclude that you need a separate step. In maven phase is nothing more than running a series of plugins. In maven plugin has goals, so you can run a plugin responsible for running unit tests directly.

In maven this plugin is called "surefire" and a goal is called "test", so you can run:

```<code>mvn surefire:test
</code>```

Given the classes (production code and tests) are compiled, you will see that this only runs your unit tests. So this probably has to be configured in Team City.

Body:
I use junit in my java project (developed using intellij idea) for unit test, and I want to configure build step in team city to run my unit tests only. I also use maven to build my project. It works when I set goals for maven to "clean compile" but I dont know how to configure build step to run unit tests.

Also in command line. when i run "maven test" it runs unit tests correctly and shows the failures.

Body:
I can't comment on TeamCity, but I'll try to help anyway out of my maven knowledge.

So first of all mvn clean compile will never run your unit tests, because maven has a concept of lifecycle and testing phase is coming after compile phase.

When you run mvn test it will run all the face up to (including) the test phase so the unit tests will run as a part of maven default lifecycle.

Now you're asking about a "build step for running unit tests" from which I conclude that you need a separate step. In maven phase is nothing more than running a series of plugins. In maven plugin has goals, so you can run a plugin responsible for running unit tests directly.

In maven this plugin is called "surefire" and a goal is called "test", so you can run:

mvn surefire:test

Given the classes (production code and tests) are compiled, you will see that this only runs your unit tests. So this probably has to be configured in Team City.


问:
OneHotEncoding mapping issue between training data and test data
I've transformed training and test data set by sklearn OneHotEncoding method. However, trnsformed results have different type shape. So It is impossible to apply to other algorithms like logistic regression.

How do I reshape the test data in accordance with the training data set's shape?

Best Regardings, Chris

```<code>import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder, LabelEncoder

def data_transformation(data, dummy):
    le = LabelEncoder()

    # Encoding the columns with multiple categorical levels
    for col1 in dummy:
        le.fit(data[col1])
        data[col1] = le.transform(data[col1])

    dummy_data = np.array(data[dummy])
    enc = OneHotEncoder()
    enc.fit(dummy_data)

    dummy_data = enc.transform(dummy_data).toarray()

if __name__ == '__main__':
    data = pd.read_csv('train.data', delimiter=',')
    data_test = pd.read_csv('test.data', delimiter=',')

    dummy_columns = ['Column1', 'Column2']
    data = data_transformation(data, dummy_columns)
    data_test = data_transformation(data_test, dummy_columns)

# result
# data shape : (200000, 71 )
# data_test shape : ( 15000, 32)
</code>```

答:
Thank you so much, Vivek! I've solved this issue due to your help.  </p>

```<code>def data_transformation2(data, data_test, dummy):
    le = LabelEncoder()

    # Encoding the columns with multiple categorical levels
    for col in dummy:
        le.fit(data[col])
        data[col] = le.transform(data[col])

    for col in dummy:
        le.fit(data_test[col])
        data_test[col] = le.transform(data_test[col])

    enc = OneHotEncoder()
    dummy_data = np.array(data[dummy])
    dummy_data_test = np.array(data_test[dummy])

    enc.fit(dummy_data)

    dummy_data = enc.transform(dummy_data).toarray()
    dummy_data_test = enc.transform(dummy_data_test).toarray()

    print(dummy_data.shape)
    print(dummy_data_test.shape)
</code>```

Body:
I've transformed training and test data set by sklearn OneHotEncoding method. However, trnsformed results have different type shape. So It is impossible to apply to other algorithms like logistic regression.

How do I reshape the test data in accordance with the training data set's shape?

Best Regardings, Chris

import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder, LabelEncoder

def data_transformation(data, dummy):
    le = LabelEncoder()

    # Encoding the columns with multiple categorical levels
    for col1 in dummy:
        le.fit(data[col1])
        data[col1] = le.transform(data[col1])

    dummy_data = np.array(data[dummy])
    enc = OneHotEncoder()
    enc.fit(dummy_data)

    dummy_data = enc.transform(dummy_data).toarray()

if __name__ == '__main__':
    data = pd.read_csv('train.data', delimiter=',')
    data_test = pd.read_csv('test.data', delimiter=',')

    dummy_columns = ['Column1', 'Column2']
    data = data_transformation(data, dummy_columns)
    data_test = data_transformation(data_test, dummy_columns)

# result
# data shape : (200000, 71 )
# data_test shape : ( 15000, 32)

Body:
Thank you so much, Vivek! I've solved this issue due to your help.

def data_transformation2(data, data_test, dummy):
    le = LabelEncoder()

    # Encoding the columns with multiple categorical levels
    for col in dummy:
        le.fit(data[col])
        data[col] = le.transform(data[col])

    for col in dummy:
        le.fit(data_test[col])
        data_test[col] = le.transform(data_test[col])

    enc = OneHotEncoder()
    dummy_data = np.array(data[dummy])
    dummy_data_test = np.array(data_test[dummy])

    enc.fit(dummy_data)

    dummy_data = enc.transform(dummy_data).toarray()
    dummy_data_test = enc.transform(dummy_data_test).toarray()

    print(dummy_data.shape)
    print(dummy_data_test.shape)


问:
Twitter Bootstrap 3: How to center a block
It seems to me that the class center-block is missing from the bootstrap 3 style sheets.  Am I missing something?

Its usage is described here, http://getbootstrap.com/css/#helper-classes-center

答:
A few answers here seem incomplete. Here are several variations:

```<code><style>
.box {
    height: 200px;
    width: 200px;
    border: 4px solid gray;
}
</style>

<!-- This works: .container>.row>.center-block.box -->
<div class="container">
        <div class="row">
            <div class="center-block bg-primary box">This div is centered with .center-block</div>
        </div>
    </div>

<!-- This does not work -->
<div class="container">
        <div class="row">
            <div class="center-block bg-primary box col-xs-4">This div is centered with .center-block</div>
        </div>
    </div>

<!-- This is the hybrid solution from other answers:
     .container>.row>.col-xs-6>.center-block.box
 -->
<div class="container">
        <div class="row">
            <div class="col-xs-6 bg-info">
                <div class="center-block bg-primary box">This div is centered with .center-block</div>
            </div>
        </div>
    </div>
</code>```

To make it work with col-* classes, you need to wrap the .center-block inside a .col-* class, but remember to either add another class that sets the width (.box in this case), or to alter the .center-block itself by giving it a width.

Check it out on bootply.

Body:
A few answers here seem incomplete. Here are several variations:

<style>
.box {
    height: 200px;
    width: 200px;
    border: 4px solid gray;
}
</style>

<!-- This works: .container>.row>.center-block.box -->
<div class="container">
        <div class="row">
            <div class="center-block bg-primary box">This div is centered with .center-block</div>
        </div>
    </div>

<!-- This does not work -->
<div class="container">
        <div class="row">
            <div class="center-block bg-primary box col-xs-4">This div is centered with .center-block</div>
        </div>
    </div>

<!-- This is the hybrid solution from other answers:
     .container>.row>.col-xs-6>.center-block.box
 -->
<div class="container">
        <div class="row">
            <div class="col-xs-6 bg-info">
                <div class="center-block bg-primary box">This div is centered with .center-block</div>
            </div>
        </div>
    </div>

To make it work with col-* classes, you need to wrap the .center-block inside a .col-* class, but remember to either add another class that sets the width (.box in this case), or to alter the .center-block itself by giving it a width.

Check it out on bootply.


问:
API for chemical information?
I'm trying to write a python script that retrieves boiling points, melting points, molecular weight, chemical structure, and density for chemical compounds I input.

I was looking through databases and found chemspipy and PubChemPy, but neither have the ability to retrieve all of the properties I need.

I have part of a script that uses chemspipy written, that works fine:

```<code>from chemspipy import ChemSpider
import urllib

cs = ChemSpider('my_token')

def getImage(compound):
    c = cs.search(compound)[0]
    imgUrl = c.image_url
    urllib.request.urlretrieve(imgUrl, c.common_name + '.png')

def getWeight(compound):
    c = cs.search(compound)[0]
    return(c.molecular_weight)
</code>```

But I still need to find a way to retrieve boiling / melting points.

(This is my first question on here, so apologies if it's in the wrong place!)

答:
I don't know anything at all about chemistry, but a quick google search got me this:

https://materialsproject.org/docs/api

This is not really a python question though, you might want to edit your tags.

//edit
In general, googling "chemistry information API" got me lots of results, I'm sure there's one in there that fits your needs.

Title: API for chemical information?

Body:
I'm trying to write a python script that retrieves boiling points, melting points, molecular weight, chemical structure, and density for chemical compounds I input.

I was looking through databases and found chemspipy and PubChemPy, but neither have the ability to retrieve all of the properties I need.

I have part of a script that uses chemspipy written, that works fine:

from chemspipy import ChemSpider
import urllib

cs = ChemSpider('my_token')

def getImage(compound):
    c = cs.search(compound)[0]
    imgUrl = c.image_url
    urllib.request.urlretrieve(imgUrl, c.common_name + '.png')

def getWeight(compound):
    c = cs.search(compound)[0]
    return(c.molecular_weight)

But I still need to find a way to retrieve boiling / melting points.

(This is my first question on here, so apologies if it's in the wrong place!)


问:
Error: not conform to protocol 'Equatable'
I'm new to swift and following a tutorial to learn more.

In The following code, I have defined custom operators (< and ==) and however  the code works fine but Xcode shows these errors in the 1st line of code.

```<code>Type 'SuitedCard' does not conform to protocol 'Equatable'
Type 'SuitedCard' does not conform to protocol 'Comparable'
</code>```

here is the code:

```<code>struct SuitedCard: Equatable, Comparable {

    // a card can be ♥, ♣, ♦, ♠
    enum Suit {
        case hearts
        case spades
        case diamonds
        case clubs
    }

    // the possible values of a card
    enum Value: Int {
        case two = 2
        case three = 3
        case four = 4
        case five = 5
        case six = 6
        case seven = 7
        case eight = 8
        case nine = 9
        case ten = 10
        case jack = 11
        case queen = 12
        case king = 13
        case ace = 14
    }

    // properties
    let suit: Suit
    let value: Value
    var isFaceDown: Bool
}

var valueArray: [SuitedCard.Value] = [.ten, .jack, .queen, .king]

func ==(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    for cardValue in valueArray {
        if lhs.value == cardValue {
            for cardValue2 in valueArray {
                if rhs.value == cardValue2 {
                    return true
                }
            }
        }
    }
    if lhs.value == rhs.value {
        return true
    }
    return false
}

func <(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    var lhsRawValue: Int
    var rhsRawValue: Int
    if lhs.value == .jack || lhs.value == .queen || lhs.value == .king {
        lhsRawValue = 10
    } else {
        lhsRawValue = lhs.value.rawValue
    }
    if rhs.value == .jack || rhs.value == .queen || rhs.value == .king {
        rhsRawValue = 10
    } else {
        rhsRawValue = rhs.value.rawValue
    }
    return lhsRawValue < rhsRawValue
}

let smaller = SuitedCard(suit: .hearts, value: .five, isFaceDown: true)

let bigger = SuitedCard(suit: .diamonds, value: .six, isFaceDown: false)

smaller >= smaller

smaller < bigger
</code>```

What's wrong?

答:
The answer by OOPer solves the problem but in Swift 3, operator methods can be defined outside of the class/struct body too. So in this case, just moving the valueArray declaration into the body of == method solves the problem. Here is the corrected code:

```<code>struct SuitedCard: Equatable, Comparable {

    // a card can be ♥, ♣, ♦, ♠
    enum Suit {
        case hearts
        case spades
        case diamonds
        case clubs
    }

    // the possible values of a card
    enum Value: Int {
        case two = 2
        case three = 3
        case four = 4
        case five = 5
        case six = 6
        case seven = 7
        case eight = 8
        case nine = 9
        case ten = 10
        case jack = 11
        case queen = 12
        case king = 13
        case ace = 14
    }

    // properties
    let suit: Suit
    let value: Value
    var isFaceDown: Bool
}

func ==(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
</code>```

//declaration of valueArray moved here:

```<code>    let valueArray: [SuitedCard.Value] = [.ten, .jack, .queen, .king]
    for cardValue in valueArray {
        if lhs.value == cardValue {
            for cardValue2 in valueArray {
                if rhs.value == cardValue2 {
                    return true
                }
            }
        }
    }
    if lhs.value == rhs.value {
        return true
    }
    return false
}

func <(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    var lhsRawValue: Int
    var rhsRawValue: Int
    if lhs.value == .jack || lhs.value == .queen || lhs.value == .king {
        lhsRawValue = 10
    } else {
        lhsRawValue = lhs.value.rawValue
    }
    if rhs.value == .jack || rhs.value == .queen || rhs.value == .king {
        rhsRawValue = 10
    } else {
        rhsRawValue = rhs.value.rawValue
    }
    return lhsRawValue < rhsRawValue
}

let smaller = SuitedCard(suit: .hearts, value: .five, isFaceDown: true)

let bigger = SuitedCard(suit: .diamonds, value: .six, isFaceDown: false)

smaller >= smaller

smaller < bigger
</code>```

Body:
I'm new to swift and following a tutorial to learn more.

In The following code, I have defined custom operators (< and ==) and however  the code works fine but Xcode shows these errors in the 1st line of code.

Type 'SuitedCard' does not conform to protocol 'Equatable'
Type 'SuitedCard' does not conform to protocol 'Comparable'

here is the code:

struct SuitedCard: Equatable, Comparable {

    // a card can be ♥, ♣, ♦, ♠
    enum Suit {
        case hearts
        case spades
        case diamonds
        case clubs
    }

    // the possible values of a card
    enum Value: Int {
        case two = 2
        case three = 3
        case four = 4
        case five = 5
        case six = 6
        case seven = 7
        case eight = 8
        case nine = 9
        case ten = 10
        case jack = 11
        case queen = 12
        case king = 13
        case ace = 14
    }

    // properties
    let suit: Suit
    let value: Value
    var isFaceDown: Bool
}

var valueArray: [SuitedCard.Value] = [.ten, .jack, .queen, .king]

func ==(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    for cardValue in valueArray {
        if lhs.value == cardValue {
            for cardValue2 in valueArray {
                if rhs.value == cardValue2 {
                    return true
                }
            }
        }
    }
    if lhs.value == rhs.value {
        return true
    }
    return false
}

func <(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    var lhsRawValue: Int
    var rhsRawValue: Int
    if lhs.value == .jack || lhs.value == .queen || lhs.value == .king {
        lhsRawValue = 10
    } else {
        lhsRawValue = lhs.value.rawValue
    }
    if rhs.value == .jack || rhs.value == .queen || rhs.value == .king {
        rhsRawValue = 10
    } else {
        rhsRawValue = rhs.value.rawValue
    }
    return lhsRawValue < rhsRawValue
}

let smaller = SuitedCard(suit: .hearts, value: .five, isFaceDown: true)

let bigger = SuitedCard(suit: .diamonds, value: .six, isFaceDown: false)

smaller >= smaller

smaller < bigger

What's wrong?

Body:
The answer by OOPer solves the problem but in Swift 3, operator methods can be defined outside of the class/struct body too. So in this case, just moving the valueArray declaration into the body of == method solves the problem. Here is the corrected code:

struct SuitedCard: Equatable, Comparable {

    // a card can be ♥, ♣, ♦, ♠
    enum Suit {
        case hearts
        case spades
        case diamonds
        case clubs
    }

    // the possible values of a card
    enum Value: Int {
        case two = 2
        case three = 3
        case four = 4
        case five = 5
        case six = 6
        case seven = 7
        case eight = 8
        case nine = 9
        case ten = 10
        case jack = 11
        case queen = 12
        case king = 13
        case ace = 14
    }

    // properties
    let suit: Suit
    let value: Value
    var isFaceDown: Bool
}

func ==(lhs: SuitedCard, rhs: SuitedCard) -> Bool {

//declaration of valueArray moved here:

    let valueArray: [SuitedCard.Value] = [.ten, .jack, .queen, .king]
    for cardValue in valueArray {
        if lhs.value == cardValue {
            for cardValue2 in valueArray {
                if rhs.value == cardValue2 {
                    return true
                }
            }
        }
    }
    if lhs.value == rhs.value {
        return true
    }
    return false
}

func <(lhs: SuitedCard, rhs: SuitedCard) -> Bool {
    var lhsRawValue: Int
    var rhsRawValue: Int
    if lhs.value == .jack || lhs.value == .queen || lhs.value == .king {
        lhsRawValue = 10
    } else {
        lhsRawValue = lhs.value.rawValue
    }
    if rhs.value == .jack || rhs.value == .queen || rhs.value == .king {
        rhsRawValue = 10
    } else {
        rhsRawValue = rhs.value.rawValue
    }
    return lhsRawValue < rhsRawValue
}

let smaller = SuitedCard(suit: .hearts, value: .five, isFaceDown: true)

let bigger = SuitedCard(suit: .diamonds, value: .six, isFaceDown: false)

smaller >= smaller

smaller < bigger


问:
Alamofire 4 + Model return an empty value
I'm still beginner in iOS development. I'm using Alamofire 4 and SwiftyJSON in order to fetch the data. When I debug, I noticed that its execute return country_list first, and then only go to Alamofire body. I have do some search but still not found the answer.

Model

```<code>import UIKit
import SwiftyJSON
import Alamofire

class CountryList {

    var ReturnOK: String?
    var Countryid: String?
    var Countryname: String?

    init(ReturnOK: String, Countryid: String, Countryname: String) {
        self.ReturnOK = ReturnOK
        self.Countryid = Countryid
        self.Countryname = Countryname
    }

    /*
     *  Fetch the country list
     */
    class func fetchCountryList() -> [CountryList] {

        var country_list = [CountryList]()

        // Add parameters
        let param: [String: String] = [
            Constants.LIST_COUNTRY.strAppID: Constants.OTHERS.temp_strAppID
        ]

            Alamofire.request(Constants.LIST_COUNTRY.URL, parameters:param, encoding: URLEncoding.default).responseJSON { (response) in
                switch response.result {

                case .success(let value):
                    let json = JSON(value)

                    for (_, subJson):(String, JSON) in json {

                        let item = CountryList(
                            ReturnOK: subJson["ReturnOK"].stringValue,
                            Countryid: subJson["Countryid"].stringValue,
                            Countryname: subJson["Countryname"].stringValue)

                        country_list.append(item)
                    }

                case .failure(let error):
                    print(error)
                }

            }

        return country_list
    }

}
</code>```

ViewController

```<code>class CreateAccountViewController: UIViewController, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var tf_country: UITextField!

    @IBOutlet weak var picker_country: UIPickerView!

    var countryL: [CountryList]?

    override func viewDidLoad() {
        super.viewDidLoad()
        //  Get the country list
        countryL = CountryList.fetchCountryList()
        print(countryL)
    }

func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            textView.text = "Address"
            textView.textColor = UIColor.lightGray
        }
    }

    //  Sets number of columns in picker view
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    //  Sets the number of rows in the picker view
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if let countryL = countryL {
            return countryL.count
        } else {
            return 0
        }
    }

    //  This function sets the text of the picker view to the content of the "salutations" array
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        let titleRow = (countryL?[row] as? String)!
        return titleRow
    }

    // When user selects an option, this function will set the text of the text field to reflect
    // the selected option.
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if (countryL?.count)! > 0 && (countryL?.count)! >= 0 {
            self.tf_country.text = self.countryL?[row] as! String
            self.picker_country.isHidden = true
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        //  When select th texfield, begin editing
        if (textField == self.tf_country) {
            self.picker_country.isHidden = false
            self.view.endEditing(true)
        }
    }
}
</code>```

On Model I can see data is append. But when I print, it was nil.

Any help is really appreciated.

答:
you should create a function with Completion Handler

idea here is that your Alamofire function is asynchronous, which means that, when you call return country_list, Alamofire request is not yet finished.

you should create a function with handler like

```<code>class func fetchCountries(handler: @escaping ([CountryList]) -> Void)) {
    //alamofire request here
    ...
    case .success(let value):
        let json = JSON(value)

        for (_, subJson):(String, JSON) in json {

            let item = CountryList(
                ReturnOK: subJson["ReturnOK"].stringValue,
                Countryid: subJson["Countryid"].stringValue,
                Countryname: subJson["Countryname"].stringValue)

             country_list.append(item)
         }
         handler(countryList) //this return countryList from this functions
}
</code>```

and inside your UIViewController it will look like

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    //  Get the country list
    CountryList.fetchCountryList { [weak self] countryList in
        guard let `self` = self else { //this here to avoid reference cycle
          return
        }
        self.countryL = countryList
        //update your UI here
        print(countryL)
    }
}
</code>```

Body:
I'm still beginner in iOS development. I'm using Alamofire 4 and SwiftyJSON in order to fetch the data. When I debug, I noticed that its execute return country_list first, and then only go to Alamofire body. I have do some search but still not found the answer.

Model

import UIKit
import SwiftyJSON
import Alamofire

class CountryList {

    var ReturnOK: String?
    var Countryid: String?
    var Countryname: String?

    init(ReturnOK: String, Countryid: String, Countryname: String) {
        self.ReturnOK = ReturnOK
        self.Countryid = Countryid
        self.Countryname = Countryname
    }

    /*
     *  Fetch the country list
     */
    class func fetchCountryList() -> [CountryList] {

        var country_list = [CountryList]()

        // Add parameters
        let param: [String: String] = [
            Constants.LIST_COUNTRY.strAppID: Constants.OTHERS.temp_strAppID
        ]

            Alamofire.request(Constants.LIST_COUNTRY.URL, parameters:param, encoding: URLEncoding.default).responseJSON { (response) in
                switch response.result {

                case .success(let value):
                    let json = JSON(value)

                    for (_, subJson):(String, JSON) in json {

                        let item = CountryList(
                            ReturnOK: subJson["ReturnOK"].stringValue,
                            Countryid: subJson["Countryid"].stringValue,
                            Countryname: subJson["Countryname"].stringValue)

                        country_list.append(item)
                    }

                case .failure(let error):
                    print(error)
                }

            }

        return country_list
    }

}

ViewController

class CreateAccountViewController: UIViewController, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var tf_country: UITextField!

    @IBOutlet weak var picker_country: UIPickerView!

    var countryL: [CountryList]?

    override func viewDidLoad() {
        super.viewDidLoad()
        //  Get the country list
        countryL = CountryList.fetchCountryList()
        print(countryL)
    }

func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            textView.text = "Address"
            textView.textColor = UIColor.lightGray
        }
    }

    //  Sets number of columns in picker view
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    //  Sets the number of rows in the picker view
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if let countryL = countryL {
            return countryL.count
        } else {
            return 0
        }
    }

    //  This function sets the text of the picker view to the content of the "salutations" array
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        let titleRow = (countryL?[row] as? String)!
        return titleRow
    }

    // When user selects an option, this function will set the text of the text field to reflect
    // the selected option.
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if (countryL?.count)! > 0 && (countryL?.count)! >= 0 {
            self.tf_country.text = self.countryL?[row] as! String
            self.picker_country.isHidden = true
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        //  When select th texfield, begin editing
        if (textField == self.tf_country) {
            self.picker_country.isHidden = false
            self.view.endEditing(true)
        }
    }
}

On Model I can see data is append. But when I print, it was nil.

Any help is really appreciated.

Body:
you should create a function with Completion Handler

idea here is that your Alamofire function is asynchronous, which means that, when you call return country_list, Alamofire request is not yet finished.

you should create a function with handler like

class func fetchCountries(handler: @escaping ([CountryList]) -> Void)) {
    //alamofire request here
    ...
    case .success(let value):
        let json = JSON(value)

        for (_, subJson):(String, JSON) in json {

            let item = CountryList(
                ReturnOK: subJson["ReturnOK"].stringValue,
                Countryid: subJson["Countryid"].stringValue,
                Countryname: subJson["Countryname"].stringValue)

             country_list.append(item)
         }
         handler(countryList) //this return countryList from this functions
}

and inside your UIViewController it will look like

override func viewDidLoad() {
    super.viewDidLoad()
    //  Get the country list
    CountryList.fetchCountryList { [weak self] countryList in
        guard let `self` = self else { //this here to avoid reference cycle
          return
        }
        self.countryL = countryList
        //update your UI here
        print(countryL)
    }
}


问:
Polymer 2.0 async and getComputedStyle
In our polymer1.0 component, we had this:

```<code>attached: function ()
{
    var something=this.getComputedStyleValue("--flxs-" + prop)
    this.async(function()
    {
        // do some work here.
    });
}
</code>```

In 2.0, both this.getComputedStyleValue  this.async is not defined.

Any idea what is the alternative?

答:
Polymer.Async seems like the alternate to this.async.

For getComputedStyleValue you can try StyleGather, but i doubt it'll work.

Otherwise, LegacyMixin contains all the old methods.

Title: Polymer 2.0 async and getComputedStyle

Body:
In our polymer1.0 component, we had this:

attached: function ()
{
    var something=this.getComputedStyleValue("--flxs-" + prop)
    this.async(function()
    {
        // do some work here.
    });
}

In 2.0, both this.getComputedStyleValue  this.async is not defined.

Any idea what is the alternative?