问:
No Provider for Array?
When I compile using ng server, the code compiles but returns this error in the Chrome console:

this is my app.component.ts . This is where I instantiate for the first time the MySideMenu Service

```<code> import {SubMenu, MenuItem,  MySideMenu} from './Modules/Layout/side-menu/side-menu.component';
import { ToastrService } from 'ngx-toastr';
import { Component, Renderer2, ElementRef, OnInit, ViewEncapsulation, HostBinding, ViewChild } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
  providers: [MySideMenu, MenuItem, SubMenu]
})
export class AppComponent implements OnInit {
   private toolBarState= false;

   ngOnInit() {
  }

  constructor(private renderer: Renderer2, public menuItems: MySideMenu) {
    const item1 = new MenuItem('TCPO', 'fa fa-android', [
      new SubMenu('Insumos', 'fa fa-book'),
      new SubMenu('CUB', 'fa fa-book'),
      new SubMenu('Budget', 'fa fa-book')
    ] );
    const item2 = new MenuItem('Market', 'fa fa-money', [
      new SubMenu('Sell', 'fa fa-bomb'),
      new SubMenu('Sign', 'fa fa-book'),
    ] );

    menuItems._items.push(item1);
    menuItems._items.push(item2);

  }

  onToolBarClick() {
    this.toolBarState = !this.toolBarState;
  }

}
</code>```

The menuitems variable are passed into the component using this code:

```<code> <appSideMenu [menuItems]='menuItems'></appSideMenu>
</code>```

Now, the SideMenuModule, declares the SideMenuComponent which has the Services from where I think the error comes from:

```<code>import { Component, OnInit, ViewEncapsulation, ViewChild, ElementRef,
  Input, Injectable } from '@angular/core';
import { state, trigger, style, transition, animate } from '@angular/animations';

@Injectable()
export class MySideMenu {
  public _items: MenuItem[] = [];
  constructor (items: MenuItem[]) {
    this._items = items;
  }
}

@Injectable()
export class MenuItem {
  public _title: string;
  public _icon: string;
  public _subMenu: SubMenu[] = [];
  constructor(title: string, icon: string, subMenu: SubMenu[]) {
    this._title = title;
    this._icon = icon;
    this._subMenu = subMenu;
   }
}

@Injectable()
export class SubMenu {
  public _title: string;
  public _icon: string;
  constructor(title: string, icon: string) {
    this._title = title;
    this._icon = icon;
   }
}

@Component({
  selector: 'appSideMenu',
  templateUrl: './side-menu.component.html',
  styleUrls: ['./side-menu.component.css'],
  animations: [
    trigger('menuTrigger', [
      state('open', style({ width: '100px' })),
      state('close', style({ width: '50px' })),
      transition('open<=>close', animate('300ms ease-in'))
    ])]
})
export class SideMenuComponent implements OnInit {

  state = 'close';
  activeMenuItem: number;
  @Input() stateSubSideMenu = 'invisible';
  @Input() menuItems: MySideMenu;

  constructor() { }

  ngOnInit() { }

  SideMenuToggle(el: HTMLElement) {
    if (el.id === 'sidebar') {
      (this.state === 'open') ? this.state = 'close' : this.state = 'open';
      this.stateSubSideMenu = 'invisible';
    }else {
      (this.state === 'open') ? this.stateSubSideMenu = 'open' : this.stateSubSideMenu = 'close';
    }
  }

  onMenuItemClick(i: number) {
    this.activeMenuItem = i;
    (this.state === 'open') ? this.stateSubSideMenu = 'opened' : this.stateSubSideMenu = 'closed';
  }

  trackByFn(index, item) {
    return index;
  }

}
</code>```

答:
(Posted on behalf of the OP).

Here is how I solved it.

The problem was in the constructor. I was defining an empty array without initializing it with empty values. Now, MenuItem is initialized in the constructor with public _subMenu: SubMenu[]= [], and not only _subMenu: SubMenu[].

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class SubMenu {
  /*public _title: string;
  public _icon: string;*/
  constructor(public _title: string, public _icon: string) {
  }
}

@Injectable()
export class MenuItem {
  /*public _title: string;
  public _icon: string;
  public _subMenu: SubMenu[] = [];*/
  constructor(public _title: string, public _icon: string, public _subMenu: SubMenu[]= []){
  }
}

@Injectable()
export class MySideMenu {
  public _items: MenuItem[] = [];
}
</code>```

Now I can call my SideMenu in the constructor of my App.Component.ts

```<code> constructor(private renderer: Renderer2, public menuItems: MySideMenu) {
    const item1 = new MenuItem('TCPO', 'fa fa-android', [
      new SubMenu('Inputs', 'fa fa-book'),
      new SubMenu('CUB', 'fa fa-book'),
      new SubMenu('Budget', 'fa fa-book')
    ] );
    const item2 = new MenuItem('Market', 'fa fa-money', [
      new SubMenu('Sell', 'fa fa-bomb'),
      new SubMenu('Sign', 'fa fa-book'),
    ] );

    menuItems._items.push(item1);
    menuItems._items.push(item2);

  }
</code>```

And the MENU is automatically generated:

Title: No Provider for Array?

Body:
When I compile using ng server, the code compiles but returns this error in the Chrome console:

this is my app.component.ts . This is where I instantiate for the first time the MySideMenu Service

 import {SubMenu, MenuItem,  MySideMenu} from './Modules/Layout/side-menu/side-menu.component';
import { ToastrService } from 'ngx-toastr';
import { Component, Renderer2, ElementRef, OnInit, ViewEncapsulation, HostBinding, ViewChild } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
  providers: [MySideMenu, MenuItem, SubMenu]
})
export class AppComponent implements OnInit {
   private toolBarState= false;

   ngOnInit() {
  }

  constructor(private renderer: Renderer2, public menuItems: MySideMenu) {
    const item1 = new MenuItem('TCPO', 'fa fa-android', [
      new SubMenu('Insumos', 'fa fa-book'),
      new SubMenu('CUB', 'fa fa-book'),
      new SubMenu('Budget', 'fa fa-book')
    ] );
    const item2 = new MenuItem('Market', 'fa fa-money', [
      new SubMenu('Sell', 'fa fa-bomb'),
      new SubMenu('Sign', 'fa fa-book'),
    ] );

    menuItems._items.push(item1);
    menuItems._items.push(item2);

  }

  onToolBarClick() {
    this.toolBarState = !this.toolBarState;
  }

}

The menuitems variable are passed into the component using this code:

 <appSideMenu [menuItems]='menuItems'></appSideMenu>

Now, the SideMenuModule, declares the SideMenuComponent which has the Services from where I think the error comes from:

import { Component, OnInit, ViewEncapsulation, ViewChild, ElementRef,
  Input, Injectable } from '@angular/core';
import { state, trigger, style, transition, animate } from '@angular/animations';

@Injectable()
export class MySideMenu {
  public _items: MenuItem[] = [];
  constructor (items: MenuItem[]) {
    this._items = items;
  }
}

@Injectable()
export class MenuItem {
  public _title: string;
  public _icon: string;
  public _subMenu: SubMenu[] = [];
  constructor(title: string, icon: string, subMenu: SubMenu[]) {
    this._title = title;
    this._icon = icon;
    this._subMenu = subMenu;
   }
}

@Injectable()
export class SubMenu {
  public _title: string;
  public _icon: string;
  constructor(title: string, icon: string) {
    this._title = title;
    this._icon = icon;
   }
}

@Component({
  selector: 'appSideMenu',
  templateUrl: './side-menu.component.html',
  styleUrls: ['./side-menu.component.css'],
  animations: [
    trigger('menuTrigger', [
      state('open', style({ width: '100px' })),
      state('close', style({ width: '50px' })),
      transition('open<=>close', animate('300ms ease-in'))
    ])]
})
export class SideMenuComponent implements OnInit {

  state = 'close';
  activeMenuItem: number;
  @Input() stateSubSideMenu = 'invisible';
  @Input() menuItems: MySideMenu;

  constructor() { }

  ngOnInit() { }

  SideMenuToggle(el: HTMLElement) {
    if (el.id === 'sidebar') {
      (this.state === 'open') ? this.state = 'close' : this.state = 'open';
      this.stateSubSideMenu = 'invisible';
    }else {
      (this.state === 'open') ? this.stateSubSideMenu = 'open' : this.stateSubSideMenu = 'close';
    }
  }

  onMenuItemClick(i: number) {
    this.activeMenuItem = i;
    (this.state === 'open') ? this.stateSubSideMenu = 'opened' : this.stateSubSideMenu = 'closed';
  }

  trackByFn(index, item) {
    return index;
  }

}

Body:
(Posted on behalf of the OP).

Here is how I solved it.

The problem was in the constructor. I was defining an empty array without initializing it with empty values. Now, MenuItem is initialized in the constructor with public _subMenu: SubMenu[]= [], and not only _subMenu: SubMenu[].

import { Injectable } from '@angular/core';

@Injectable()
export class SubMenu {
  /*public _title: string;
  public _icon: string;*/
  constructor(public _title: string, public _icon: string) {
  }
}

@Injectable()
export class MenuItem {
  /*public _title: string;
  public _icon: string;
  public _subMenu: SubMenu[] = [];*/
  constructor(public _title: string, public _icon: string, public _subMenu: SubMenu[]= []){
  }
}

@Injectable()
export class MySideMenu {
  public _items: MenuItem[] = [];
}

Now I can call my SideMenu in the constructor of my App.Component.ts

 constructor(private renderer: Renderer2, public menuItems: MySideMenu) {
    const item1 = new MenuItem('TCPO', 'fa fa-android', [
      new SubMenu('Inputs', 'fa fa-book'),
      new SubMenu('CUB', 'fa fa-book'),
      new SubMenu('Budget', 'fa fa-book')
    ] );
    const item2 = new MenuItem('Market', 'fa fa-money', [
      new SubMenu('Sell', 'fa fa-bomb'),
      new SubMenu('Sign', 'fa fa-book'),
    ] );

    menuItems._items.push(item1);
    menuItems._items.push(item2);

  }

And the MENU is automatically generated:


来源: stackexchange

问:
Array function with number at position returning zero
I am new to javascript and was trying this code below.

This code was working properly but seems now its only returning -1.

Array.prototype.nthIndexOf = function (element,location) {
    var index = -1;
    for(var i=0; i< this.length; i++) {
        if(element === this[i] && !--location) {
            index = i;
            break;
        }
    }
    return index;
}

var findNumber = prompt("Please enter number to be found");
var positionAt = prompt("Please enter position");

var position = [1, 2, 3, 3, 2, 89, 34, 12].nthIndexOf(findNumber, positionAt);
console.log(position); // position is -1 all the time```

答:
you need to use Number() to change values from prompt to numbers. prompt always returns string values.

Array.prototype.nthIndexOf = function (element,location) {
    var index = -1;
    for(var i=0; i< this.length; i++) {
        if(element === this[i] && !--location) {
            index = i;
            break;
        }
    }
    return index;
}

var findNumber = prompt("Please enter number to be found");
var positionAt = prompt("Please enter position");

var position = [1, 2, 3, 3, 2, 89, 34, 12].nthIndexOf(Number(findNumber), Number(positionAt));
console.log(position); // position is -1 all the time```

ContentLicense: CC BY-SA 3.0


问:
I have installed extension for sorting product by quantity, it show above mention error?
Fatal error: Uncaught Error: Call to a member function setStoreId() on boolean in /home/zohaibs4/public_html/includes/src/__default.php:7032 </p>

答:
Open includes folder in root and replace code : </p>

```<code>#define('COMPILER_INCLUDE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'src');
 With  define('COMPILER_INCLUDE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'src');
</code>```

Body:
Open includes folder in root and replace code :

#define('COMPILER_INCLUDE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'src');
 With  define('COMPILER_INCLUDE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'src');


问:
Joomla Extension AcySMS Need to modify source code

hello all i need to change the style of Joomla extension AcySMS but
  unable to find where i need to change

here is actual problem i need to change the style so that button must
  in front of text box and in country code selection i need to add
  county code with the flag of country Thanks :)

答:
I don't know this specific Joomla-extension, but you seem to need two changes:

change the markup of the button

place the button before the input

The first can be done by changing your own custom css-file. Use firebug or developer tools to find out which classes are used and override or extend them in your own css-file.

For the second one, you need to know whether you're using a plugin, a module or a component. The answer to this question leads you to the right Joomla-subfolder. There you will probably find a acysms-folder. Then you'll have to look (even in subfolders) for a file called default.php.

You should use template overrides to manipulate these files, otherwise your changes will be lost with the next regular update of this extension. You can search the Joomla website for help on template overrides. It's not very complicated. https://docs.joomla.org/How_to_override_the_output_from_the_Joomla!_core

If (for example) you want to make changes to the mod_login module then you would have to copy the file default.php from
PATH_TO_JOOMLA/modules/mod_login/tmpl/
to
PATH_TO_JOOMLA/TEMPLATE_NAME/html/mod_login/
and apply your changes there.

I hope this will get you started.


问:
RecyclerView with in recyclerView with start ActivityOnresult
I have a recycler view(A) containing another recyclerview(B). When I click on the plus icon in recyclerview(A) item, it opens up a new activity with a recyclerview(C). Long pressing and selecting few items and clicking on done. This needs to update a recyclerview(B) on recyclerview (A) item on which I clicked the plus icon.

But instead, all the items of recyclerview(A) which contains recyclerview(B)  is being updated.

```<code>private void displayUpcomingEvents(View view) {
    upcomingEventsArrayList = new ArrayList<>();
    upcomingEvents = new UpcomingEvents("Meet and greet", "Coffee Connect | ", "Phython", "21 - ", "Jun - ", "22", "Jun", "21 Jun 10 AM", "Washinton");
    upcomingEventsArrayList.add(upcomingEvents);
    upcomingEvents = new UpcomingEvents("Meet and greet", "Coffee Connect | ", "Phython", "21 - ", "Jun - ", "22", "Jun", "21 Jun 10 AM", "Washinton");
    upcomingEventsArrayList.add(upcomingEvents);
    upcomingEvents = new UpcomingEvents("Meet and greet", "Coffee Connect | ", "Phython", "21 - ", "Jun - ", "22", "Jun", "21 Jun 10 AM", "Washinton");
    upcomingEventsArrayList.add(upcomingEvents);
    upcomingEventsAdapter = new RecyclerAdapterUpcomingEvents(getContext(), upcomingEventsArrayList);

    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_upcoming_event);

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getAppContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(upcomingEventsAdapter);

}

class RecyclerAdapterUpcomingEvents extends RecyclerView.Adapter<RecyclerAdapterUpcomingEvents.MyViewHolder> {

    private List<UpcomingEvents> upcomingEventsList;
    private Context context;
    private LayoutInflater inflater;

    RecyclerAdapterUpcomingEvents(Context context, List<UpcomingEvents> upcomingEventsList) {
        this.context = context;
        this.upcomingEventsList = upcomingEventsList;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View rootView = inflater.inflate(R.layout.card_view_upcoming_event, parent, false);
        return new RecyclerAdapterUpcomingEvents.MyViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        UpcomingEvents upcomingEvents = upcomingEventsList.get(position);

        holder.eventUpcomingName.setText(upcomingEvents.getEventUpcomingName());
        holder.eventUpcomingType.setText(upcomingEvents.getEventUpcomingType());
        holder.eventUpcomingDate.setText(upcomingEvents.getEventUpcomingDateStart() + upcomingEvents.getEventUpcomingDateEnd());
        holder.eventUpcomingMonth.setText(upcomingEvents.getEventUpcomingMonthEnd() + upcomingEvents.getEventUpcomingMonthEnd());
        holder.eventUpcomingAlarmNotify.setText(upcomingEvents.getEventUpcomingAlarmNotify());
        holder.eventUpcomingPlace.setText(upcomingEvents.getEventUpcomingPlace());

        holder.eventUpcomingAddPeople.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Activity origin = (Activity) context;
                origin.startActivityForResult(new Intent(getAppContext(), ContactsActivity.class), CONTACT_CODE);
            }
        });

        holder.contactRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        contactAdapter = new ContactAdapter(getAppContext(), R.layout.card__contact_image, contactsList);`enter code here`
        holder.contactRecyclerView.setAdapter(contactAdapter);

    }

    @Override
    public int getItemCount() {
        return upcomingEventsList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView eventUpcomingName, eventUpcomingType, eventUpcomingDate, eventUpcomingMonth, eventUpcomingAlarmNotify, eventUpcomingPlace, eventUpcomingYes, eventUpcomingInterested, eventUpcomingNo;
        private ImageView eventUpcomingAddPeople, eventUpcomingmore;
        private RecyclerView contactRecyclerView;

        MyViewHolder(View itemView) {
            super(itemView);
            eventUpcomingName = (TextView) itemView.findViewById(R.id.event_name);
            eventUpcomingType = (TextView) itemView.findViewById(R.id.event_type);
            eventUpcomingDate = (TextView) itemView.findViewById(R.id.event_date);
            eventUpcomingMonth = (TextView) itemView.findViewById(R.id.event_month);

            eventUpcomingAlarmNotify = (TextView) itemView.findViewById(R.id.event_time_notify);
            eventUpcomingPlace = (TextView) itemView.findViewById(R.id.event_place);

            eventUpcomingYes = (TextView) itemView.findViewById(R.id.event_yes);
            eventUpcomingInterested = (TextView) itemView.findViewById(R.id.event_interested);
            eventUpcomingNo = (TextView) itemView.findViewById(R.id.event_no);

            eventUpcomingmore = (ImageView) itemView.findViewById(R.id.event_more);
            eventUpcomingAddPeople = (ImageView) itemView.findViewById(R.id.hex_one_event);

            contactRecyclerView = (RecyclerView) itemView.findViewById(R.id.upcome_events_recycler);

        }
    }
}

@Override
public void onReceived(int requestCode, int resultCode, Intent data) {

    if (requestCode == CONTACT_CODE && resultCode == RESULT_OK && data != null) {

        List<Contact> contactsLists = (ArrayList<Contact>) data.getSerializableExtra("contacts");
        contactsList.clear();
        contactsList.addAll(contactsLists);

        contactAdapter.setContactList(contactsLists);

        upcomingEventsAdapter = new RecyclerAdapterUpcomingEvents(getContext(), upcomingEventsArrayList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getAppContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(upcomingEventsAdapter);
    }
}
</code>```

CardView

```<code>        <android.support.v7.widget.RecyclerView
            android:id="@+id/upcome_events_recycler"
            android:layout_width="match_parent"
            android:layout_height="52dp"
            android:layout_below="@id/event_place"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="52dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp">

        </android.support.v7.widget.RecyclerView>

        <ImageView
            android:id="@+id/hex_one_event"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_alignParentEnd="true"
            android:layout_below="@id/event_place"
            android:layout_margin="8dp"
            android:src="@drawable/hex_src_plus" />
</code>```

答:
First change your code by this below :

```<code>   holder.eventUpcomingAddPeople.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Activity origin = (Activity) context;
            Intent i = new Intent(getAppContext(), ContactsActivity.class);
            i.putExtra("selectedPosition", position);
            origin.startActivityForResult(i, CONTACT_CODE);
        }
    });

@Override
public void onReceived(int requestCode, int resultCode, Intent data) {

if (requestCode == CONTACT_CODE && resultCode == RESULT_OK && data != null) {
    int result = data.getIntExtra("selectedPosition","put a default value in case of null");
    List<Contact> contactsLists = (ArrayList<Contact>) data.getSerializableExtra("contacts");
    contactsList.clear();
    contactsList.addAll(contactsLists);

    contactAdapter.setContactList(contactsLists);
     upcomingEventsAdapter.notifyItemChanged(result);
}
}
</code>```

on the second activity you should have something like that when you click on done :

```<code>int param = getIntent().getIntExtra("selectedPosition");
Intent resultIntent = new Intent();
resultIntent.putExtra("contacts", Your selected contacts);
resultIntent.putExtra("selectedPosition", param);

setResult(RESULT_OK, resultIntent);
finish();
</code>```

Hope it's clear and helpful :)

Body:
I have a recycler view(A) containing another recyclerview(B). When I click on the plus icon in recyclerview(A) item, it opens up a new activity with a recyclerview(C). Long pressing and selecting few items and clicking on done. This needs to update a recyclerview(B) on recyclerview (A) item on which I clicked the plus icon.

But instead, all the items of recyclerview(A) which contains recyclerview(B)  is being updated.

private void displayUpcomingEvents(View view) {
    upcomingEventsArrayList = new ArrayList<>();
    upcomingEvents = new UpcomingEvents("Meet and greet", "Coffee Connect | ", "Phython", "21 - ", "Jun - ", "22", "Jun", "21 Jun 10 AM", "Washinton");
    upcomingEventsArrayList.add(upcomingEvents);
    upcomingEvents = new UpcomingEvents("Meet and greet", "Coffee Connect | ", "Phython", "21 - ", "Jun - ", "22", "Jun", "21 Jun 10 AM", "Washinton");
    upcomingEventsArrayList.add(upcomingEvents);
    upcomingEvents = new UpcomingEvents("Meet and greet", "Coffee Connect | ", "Phython", "21 - ", "Jun - ", "22", "Jun", "21 Jun 10 AM", "Washinton");
    upcomingEventsArrayList.add(upcomingEvents);
    upcomingEventsAdapter = new RecyclerAdapterUpcomingEvents(getContext(), upcomingEventsArrayList);

    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_upcoming_event);

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getAppContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(upcomingEventsAdapter);

}

class RecyclerAdapterUpcomingEvents extends RecyclerView.Adapter<RecyclerAdapterUpcomingEvents.MyViewHolder> {

    private List<UpcomingEvents> upcomingEventsList;
    private Context context;
    private LayoutInflater inflater;

    RecyclerAdapterUpcomingEvents(Context context, List<UpcomingEvents> upcomingEventsList) {
        this.context = context;
        this.upcomingEventsList = upcomingEventsList;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View rootView = inflater.inflate(R.layout.card_view_upcoming_event, parent, false);
        return new RecyclerAdapterUpcomingEvents.MyViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        UpcomingEvents upcomingEvents = upcomingEventsList.get(position);

        holder.eventUpcomingName.setText(upcomingEvents.getEventUpcomingName());
        holder.eventUpcomingType.setText(upcomingEvents.getEventUpcomingType());
        holder.eventUpcomingDate.setText(upcomingEvents.getEventUpcomingDateStart() + upcomingEvents.getEventUpcomingDateEnd());
        holder.eventUpcomingMonth.setText(upcomingEvents.getEventUpcomingMonthEnd() + upcomingEvents.getEventUpcomingMonthEnd());
        holder.eventUpcomingAlarmNotify.setText(upcomingEvents.getEventUpcomingAlarmNotify());
        holder.eventUpcomingPlace.setText(upcomingEvents.getEventUpcomingPlace());

        holder.eventUpcomingAddPeople.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Activity origin = (Activity) context;
                origin.startActivityForResult(new Intent(getAppContext(), ContactsActivity.class), CONTACT_CODE);
            }
        });

        holder.contactRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        contactAdapter = new ContactAdapter(getAppContext(), R.layout.card__contact_image, contactsList);`enter code here`
        holder.contactRecyclerView.setAdapter(contactAdapter);

    }

    @Override
    public int getItemCount() {
        return upcomingEventsList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView eventUpcomingName, eventUpcomingType, eventUpcomingDate, eventUpcomingMonth, eventUpcomingAlarmNotify, eventUpcomingPlace, eventUpcomingYes, eventUpcomingInterested, eventUpcomingNo;
        private ImageView eventUpcomingAddPeople, eventUpcomingmore;
        private RecyclerView contactRecyclerView;

        MyViewHolder(View itemView) {
            super(itemView);
            eventUpcomingName = (TextView) itemView.findViewById(R.id.event_name);
            eventUpcomingType = (TextView) itemView.findViewById(R.id.event_type);
            eventUpcomingDate = (TextView) itemView.findViewById(R.id.event_date);
            eventUpcomingMonth = (TextView) itemView.findViewById(R.id.event_month);

            eventUpcomingAlarmNotify = (TextView) itemView.findViewById(R.id.event_time_notify);
            eventUpcomingPlace = (TextView) itemView.findViewById(R.id.event_place);

            eventUpcomingYes = (TextView) itemView.findViewById(R.id.event_yes);
            eventUpcomingInterested = (TextView) itemView.findViewById(R.id.event_interested);
            eventUpcomingNo = (TextView) itemView.findViewById(R.id.event_no);

            eventUpcomingmore = (ImageView) itemView.findViewById(R.id.event_more);
            eventUpcomingAddPeople = (ImageView) itemView.findViewById(R.id.hex_one_event);

            contactRecyclerView = (RecyclerView) itemView.findViewById(R.id.upcome_events_recycler);

        }
    }
}

@Override
public void onReceived(int requestCode, int resultCode, Intent data) {

    if (requestCode == CONTACT_CODE && resultCode == RESULT_OK && data != null) {

        List<Contact> contactsLists = (ArrayList<Contact>) data.getSerializableExtra("contacts");
        contactsList.clear();
        contactsList.addAll(contactsLists);

        contactAdapter.setContactList(contactsLists);

        upcomingEventsAdapter = new RecyclerAdapterUpcomingEvents(getContext(), upcomingEventsArrayList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getAppContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(upcomingEventsAdapter);
    }
}

CardView

        <android.support.v7.widget.RecyclerView
            android:id="@+id/upcome_events_recycler"
            android:layout_width="match_parent"
            android:layout_height="52dp"
            android:layout_below="@id/event_place"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="52dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp">

        </android.support.v7.widget.RecyclerView>

        <ImageView
            android:id="@+id/hex_one_event"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_alignParentEnd="true"
            android:layout_below="@id/event_place"
            android:layout_margin="8dp"
            android:src="@drawable/hex_src_plus" />

Body:
First change your code by this below :

   holder.eventUpcomingAddPeople.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Activity origin = (Activity) context;
            Intent i = new Intent(getAppContext(), ContactsActivity.class);
            i.putExtra("selectedPosition", position);
            origin.startActivityForResult(i, CONTACT_CODE);
        }
    });

@Override
public void onReceived(int requestCode, int resultCode, Intent data) {

if (requestCode == CONTACT_CODE && resultCode == RESULT_OK && data != null) {
    int result = data.getIntExtra("selectedPosition","put a default value in case of null");
    List<Contact> contactsLists = (ArrayList<Contact>) data.getSerializableExtra("contacts");
    contactsList.clear();
    contactsList.addAll(contactsLists);

    contactAdapter.setContactList(contactsLists);
     upcomingEventsAdapter.notifyItemChanged(result);
}
}

on the second activity you should have something like that when you click on done :

int param = getIntent().getIntExtra("selectedPosition");
Intent resultIntent = new Intent();
resultIntent.putExtra("contacts", Your selected contacts);
resultIntent.putExtra("selectedPosition", param);

setResult(RESULT_OK, resultIntent);
finish();

Hope it's clear and helpful :)


问:
Error installing Meteor on Ubuntu
I'm having trouble installing Meteor on Ubuntu 14.04. I searched through previous answers, but none had the same problem that I'm having.

When I run the command given on the Meteor website:

```<code>sudo curl https://install.meteor.com/ | sh
</code>```

I get the following message:

curl: (7) Failed to connect to meteorinstall-4168.kxcdn.com port 443: 拒绝连接

  Retrying download in 5 seconds...

Any idea what's going on here?

答:
Try this</p>

```<code>curl --insecure https://install.meteor.com/ | sh
</code>```

Title: Error installing Meteor on Ubuntu

Body:
I'm having trouble installing Meteor on Ubuntu 14.04. I searched through previous answers, but none had the same problem that I'm having.

When I run the command given on the Meteor website:

sudo curl https://install.meteor.com/ | sh

I get the following message:

curl: (7) Failed to connect to meteorinstall-4168.kxcdn.com port 443: 拒绝连接

  Retrying download in 5 seconds...

Any idea what's going on here?

Body:
Try this

curl --insecure https://install.meteor.com/ | sh


问:
Function returning "This" object in C++
So, following is a member function of Class Sales_data which is defined outside the class,

```<code>Sales_data& Sales_data::combine(const Sales_data &rhs) {
    units_sold += rhs.units_sold;
    revenue += rhs.revenue; //adding the members of rhs into the members of "this" object
    return *this;
} //units_sold and revenue are both data members of class
</code>```

When the function is called, it is called like

```<code>total.combine(trans); //total and trans are the objects of class
</code>```

What i am not understanding is the function returning *this,
i understand it returns an instance of the object but it is not returning that instance to anything as we can see during function call, also if i don't write the return statement, would it work any differently.

Someone please explain elaborately because i am just not getting it.

答:
I understand it returns an instance of the object but it is not returning that instance to anything as we can see during function call

Correct, in this case.

But you could use the return value if you wanted to. It's there just in case.

This is a common convention, allowing for function call chaining.

Also if i don't write the return statement, would it work any differently.

It would have undefined behaviour, because the function has a return type and therefore must return something. But you could make the return type void without altering the functionality of this particular program, sure.

Title: Function returning "This" object in C++

Body:
So, following is a member function of Class Sales_data which is defined outside the class,

Sales_data& Sales_data::combine(const Sales_data &rhs) {
    units_sold += rhs.units_sold;
    revenue += rhs.revenue; //adding the members of rhs into the members of "this" object
    return *this;
} //units_sold and revenue are both data members of class

When the function is called, it is called like

total.combine(trans); //total and trans are the objects of class

What i am not understanding is the function returning *this,
i understand it returns an instance of the object but it is not returning that instance to anything as we can see during function call, also if i don't write the return statement, would it work any differently.

Someone please explain elaborately because i am just not getting it.


问:
background color transition in few seconds w/o JQuery
https://codepen.io/codeispoetry/pen/dRKKEY

.back {
  margin: 20px;
  padding: 100px;
  background: yellow;
  font-size: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="back">

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

</div></code>```

I want that yellow background should change with time to yellow, but I want to do ith through CSS. there is enough solution available on StackOverflow that do it with Jquery, but can we achieve this through CSS so that it works on all the browser.

https://www.w3schools.com/css/css3_animations.asp i tried this, but it roll backs to the original color. How to make th after color permanent.

答:
```<code>.back {
  margin:20px;
  padding: 100px;
  font-size: 30px;
  animation-name: changeColor;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

@-webkit-keyframes changeColor {
  0% {
    background-color: yellow;
  }
  50% {
    background-color: white;
  }
  100%{
    background-color: yellow;
  }
}

@keyframes changeColor {
  0% {
    background-color: yellow;
  }
  50% {
    background-color: white;
  }
  100%{
    background-color: yellow;
  }
}
</code>```

It will change change color infinite amount of time from yellow to white back to yellow to make it look smooth.

Body:
https://codepen.io/codeispoetry/pen/dRKKEY

.back {
  margin: 20px;
  padding: 100px;
  background: yellow;
  font-size: 30px;
}

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

I want that yellow background should change with time to yellow, but I want to do ith through CSS. there is enough solution available on StackOverflow that do it with Jquery, but can we achieve this through CSS so that it works on all the browser.

https://www.w3schools.com/css/css3_animations.asp i tried this, but it roll backs to the original color. How to make th after color permanent.

Body:
.back {
  margin:20px;
  padding: 100px;
  font-size: 30px;
  animation-name: changeColor;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

@-webkit-keyframes changeColor {
  0% {
    background-color: yellow;
  }
  50% {
    background-color: white;
  }
  100%{
    background-color: yellow;
  }
}

@keyframes changeColor {
  0% {
    background-color: yellow;
  }
  50% {
    background-color: white;
  }
  100%{
    background-color: yellow;
  }
}

It will change change color infinite amount of time from yellow to white back to yellow to make it look smooth.


问:
Convert simple array into two-dimensional array (matrix)
Imagine I have an array:

```<code>A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
</code>```

And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:

```<code>A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));
</code>```

Note, that rows and columns of the matrix is changeable.

答:
Something like this?

```<code>function listToMatrix(list, elementsPerSubArray) {
    var matrix = [], i, k;

    for (i = 0, k = -1; i < list.length; i++) {
        if (i % elementsPerSubArray === 0) {
            k++;
            matrix[k] = [];
        }

        matrix[k].push(list[i]);
    }

    return matrix;
}
</code>```

Usage:

```<code>var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);
// result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Imagine I have an array:

A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);

And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:

A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));

Note, that rows and columns of the matrix is changeable.

Body:
Something like this?

function listToMatrix(list, elementsPerSubArray) {
    var matrix = [], i, k;

    for (i = 0, k = -1; i < list.length; i++) {
        if (i % elementsPerSubArray === 0) {
            k++;
            matrix[k] = [];
        }

        matrix[k].push(list[i]);
    }

    return matrix;
}

Usage:

var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);
// result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

ContentLicense: CC BY-SA 2.5


问:
Tinymce not working in angularjs mdDialog
I'm trying to use TinyMCE editor in angularjs mdDialog.

Worling Plukr: http://embed.plnkr.co/s3NsemdcDAtG7AoQRvLh/

Plunkr with issues: http://embed.plnkr.co/fL8kGLl3b4TNdxW1AtKG/

All features are working normally instead of drop down:
http://prntscr.com/fop9u0

 It works fine if I increase the top position of drop down around 100px. http://prntscr.com/fope8o

I noticed that this problem appearing due to page scroll..

Can someone help me out to get these drop downs in right position.

答:
There is a top position calculation issue, It can be fixed adding below code in app.js file in
`

```<code>$scope.addMoreInfoFunction = function(event) {
        setTimeout(function() {
            $('.mce-btn').on('click', function() {
                var bodyTop = $('body').offset().top;
                if (bodyTop < 0) {
                    setTimeout(function() {
                        var top = parseInt($('#mceu_50').css('top'));
                        var newTop = top / 2 - bodyTop - 30;
                        $('#mceu_50').css('top', newTop);
                        console.log(newTop);
                    }, 300);
                }
            });
        }, 300);
        $mdDialog.show({
            controller: ['$scope', '$mdDialog', DialogAddMoreInfoController],
            templateUrl: 'addMoreInfo.tmpl.html',
            parent: angular.element(document.body),
            targetEvent: event,
            clickOutsideToClose: true
        });
        };
        });
</code>```

`

Calculation can be corrected, let know if it helps

Body:
There is a top position calculation issue, It can be fixed adding below code in app.js file in
`

$scope.addMoreInfoFunction = function(event) {
        setTimeout(function() {
            $('.mce-btn').on('click', function() {
                var bodyTop = $('body').offset().top;
                if (bodyTop < 0) {
                    setTimeout(function() {
                        var top = parseInt($('#mceu_50').css('top'));
                        var newTop = top / 2 - bodyTop - 30;
                        $('#mceu_50').css('top', newTop);
                        console.log(newTop);
                    }, 300);
                }
            });
        }, 300);
        $mdDialog.show({
            controller: ['$scope', '$mdDialog', DialogAddMoreInfoController],
            templateUrl: 'addMoreInfo.tmpl.html',
            parent: angular.element(document.body),
            targetEvent: event,
            clickOutsideToClose: true
        });
        };
        });

`

Calculation can be corrected, let know if it helps


问:
Keras CONV training during data augmentation appears to be displaying the wrong batch size and number of training examples
I am learning how to implement data augmentation using Keras and the CIFAR-10 dataset. I am learning with the help of online tutorials and this book Deep learning with Keras.

The specific details of the code are here.

Here is my issue, and I am certain it relates to some misunderstanding on my part:

This is my CONV set up.

```<code> IMG_CHANNELS = 3
 IMG_ROWS = 32
 IMG_COLS = 32
 BATCH_SIZE = 128
 NB_EPOCH = 50
 NB_CLASSES = 10
 VERBOSE = 1
 VALIDATION_SPLIT = 0.2
 OPTIM = RMSprop()
</code>```

Load the dataset, convert to categorical, float and normalise:

```<code>(X_train, y_train), (X_test, y_test) = cifar10.load_data()
Y_train = np_utils.to_categorical(y_train, NB_CLASSES)
Y_test = np_utils.to_categorical(y_test, NB_CLASSES)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
</code>```

Create generator

```<code>datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        rotation_range=0,  # randomly rotate images in the range (degrees, 0 to 180)
        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
        horizontal_flip=True,  # randomly flip images
        vertical_flip=False)  # randomly flip images
 datagen.fit(X_train)
</code>```

Train the model (I haven't listed the model)

```<code>model.fit_generator(datagen.flow(X_train, Y_train,
                   batch_size=BATCH_SIZE),
                   samples_per_epoch=X_train.shape[0],
                   nb_epoch=NB_EPOCH,
                   verbose=VERBOSE)
</code>```

My issue is that as I train the following is displayed:

```<code> Epoch 1/40
 390/390 [==============================] - 199s - loss: 0.9751 - acc: 0.6588
</code>```

I cannot see why I am getting 390 examples. Samples_per_epoch is equal to X_train.shape[0] which is 50000 and batch size is 128 so I thought it should go up to 50000 in batches of 128.

答:
The progress-bar is not showing the number of samples but the number of steps or batches (When you use model.fit instead of model.fit_generator it will automatically display the samples). Each batch contains 128 samples and there are a total of 50,000 samples. 50,000/128 = 390.625. That's why you see 390 instead of 50,000.

Because you are using model.fit_generator it is not possible to show the total number of samples. Except if you set the batch_size to 1. The reason for this is that the generator is expected to loop over its data indefinitely until the steps_per_epochs or samples_per_epoch threshold is reached (*).

By the way, you are able to change this in model.fit with the callback ProgbarLogger, look here.

Body:
I am learning how to implement data augmentation using Keras and the CIFAR-10 dataset. I am learning with the help of online tutorials and this book Deep learning with Keras.

The specific details of the code are here.

Here is my issue, and I am certain it relates to some misunderstanding on my part:

This is my CONV set up.

 IMG_CHANNELS = 3
 IMG_ROWS = 32
 IMG_COLS = 32
 BATCH_SIZE = 128
 NB_EPOCH = 50
 NB_CLASSES = 10
 VERBOSE = 1
 VALIDATION_SPLIT = 0.2
 OPTIM = RMSprop()

Load the dataset, convert to categorical, float and normalise:

(X_train, y_train), (X_test, y_test) = cifar10.load_data()
Y_train = np_utils.to_categorical(y_train, NB_CLASSES)
Y_test = np_utils.to_categorical(y_test, NB_CLASSES)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

Create generator

datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        rotation_range=0,  # randomly rotate images in the range (degrees, 0 to 180)
        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
        horizontal_flip=True,  # randomly flip images
        vertical_flip=False)  # randomly flip images
 datagen.fit(X_train)

Train the model (I haven't listed the model)

model.fit_generator(datagen.flow(X_train, Y_train,
                   batch_size=BATCH_SIZE),
                   samples_per_epoch=X_train.shape[0],
                   nb_epoch=NB_EPOCH,
                   verbose=VERBOSE)

My issue is that as I train the following is displayed:

 Epoch 1/40
 390/390 [==============================] - 199s - loss: 0.9751 - acc: 0.6588

I cannot see why I am getting 390 examples. Samples_per_epoch is equal to X_train.shape[0] which is 50000 and batch size is 128 so I thought it should go up to 50000 in batches of 128.


问:
Which TortoiseGit command can overwrite local files?
I've installed TortoiseGit on Windows. I want to fetch all code from origin/master and all local files may be overwritten.
How can we do this with right clicking on the folder and which TortoiseGit method we should use with parameters?
Or do we always need to open a command prompt and enter the following commands:

```<code>git fetch --all
get reset --hard origin/master
</code>```

答:
TortoiseGit has almost all the same features are command line, so most of the time the command line is not needed.

```<code>git fetch --all
</code>```

Use the fetch dialog, when there are multiple remotes, then you could choose "- all -"

```<code> git reset --hard origin/master
</code>```

You need to go to the log, choose origin/master (on the left) and select reset in the contextmenu.

Body:
I've installed TortoiseGit on Windows. I want to fetch all code from origin/master and all local files may be overwritten.
How can we do this with right clicking on the folder and which TortoiseGit method we should use with parameters?
Or do we always need to open a command prompt and enter the following commands:

git fetch --all
get reset --hard origin/master

Body:
TortoiseGit has almost all the same features are command line, so most of the time the command line is not needed.

git fetch --all

Use the fetch dialog, when there are multiple remotes, then you could choose "- all -"

 git reset --hard origin/master

You need to go to the log, choose origin/master (on the left) and select reset in the contextmenu.


问:
Laravel Carbon, retrieve today's date with weekday?
I am using carbon to compare 2 dates with today's date, however I also have another field in a database called weekday which contains values like:

'MO'
'TU'
'WE'

So I don't only want to search and output by dates but also search by a weekday so:

```<code>public function show($id)
{
    $today = Carbon::now();
    $weekday = //whatever carbon or something else has to retrieve today's day
    $event = Event::with('businesses')
       ->where('startdate', '<', $today->format('Y-m-d'))
       ->where('endate', '>', $today->format('Y-m-d'))
       //or where ('weekday') = $weekday?
       ->get();
    return view('events.showEvent', compact('event'));
}
</code>```

答:
I'm not sure that Carbon has such formatting, but what you could do is get the wekkday from a map of days and the current week day constant:</p>

```<code>$weekMap = [
    0 => 'SU',
    1 => 'MO',
    2 => 'TU',
    3 => 'WE',
    4 => 'TH',
    5 => 'FR',
    6 => 'SA',
];
$dayOfTheWeek = Carbon::now()->dayOfWeek;
$weekday = $weekMap[$dayOfTheWeek];
</code>```

Body:
I am using carbon to compare 2 dates with today's date, however I also have another field in a database called weekday which contains values like:

'MO'
'TU'
'WE'

So I don't only want to search and output by dates but also search by a weekday so:

public function show($id)
{
    $today = Carbon::now();
    $weekday = //whatever carbon or something else has to retrieve today's day
    $event = Event::with('businesses')
       ->where('startdate', '<', $today->format('Y-m-d'))
       ->where('endate', '>', $today->format('Y-m-d'))
       //or where ('weekday') = $weekday?
       ->get();
    return view('events.showEvent', compact('event'));
}

Body:
I'm not sure that Carbon has such formatting, but what you could do is get the wekkday from a map of days and the current week day constant:

$weekMap = [
    0 => 'SU',
    1 => 'MO',
    2 => 'TU',
    3 => 'WE',
    4 => 'TH',
    5 => 'FR',
    6 => 'SA',
];
$dayOfTheWeek = Carbon::now()->dayOfWeek;
$weekday = $weekMap[$dayOfTheWeek];


问:
Forward arrow operator not found
I'm confused with the nature of ->, I cannot get its definition like I can with other operators and it doesn't behave like <-. See below:

```<code>print(`<-`) # .Primitive("<-")
print(`->`) # Error in print(`->`) : object '->' not found
</code>```

Also, I can't hijack it, though R won't fire any error if I try to :

```<code>`->` = `+`  # attempting to hijack `->`, no error
print(`->`) # function (e1, e2)  .Primitive("+"), seems like it worked
1 -> 3      # Error in 3 <- 1 : invalid (do_set) left-hand side to assignment
1 -> test1
print(test1) # 1, hijacking failed
`->`(1,3)   # 4, this works
</code>```

With <- (or any other operator I tried), I can do it:

```<code>`<-` = `+`
print(`<-`)
1 <- 3      # 4
1 <- test2  # Error: object 'test2' not found

rm(list=ls()) # back to sanity
</code>```

So what's going on ?

答:
```<code>> e <- quote(42 -> x)
> e
x <- 42
</code>```

There is only one assignment operator in R: <- (well, two: there's = but let's not complicate things). The parser interprets the symbol "->" as assignment, and creates the expression as if <- had been used.

Title: Forward arrow operator not found

Body:
I'm confused with the nature of ->, I cannot get its definition like I can with other operators and it doesn't behave like <-. See below:

print(`<-`) # .Primitive("<-")
print(`->`) # Error in print(`->`) : object '->' not found

Also, I can't hijack it, though R won't fire any error if I try to :

`->` = `+`  # attempting to hijack `->`, no error
print(`->`) # function (e1, e2)  .Primitive("+"), seems like it worked
1 -> 3      # Error in 3 <- 1 : invalid (do_set) left-hand side to assignment
1 -> test1
print(test1) # 1, hijacking failed
`->`(1,3)   # 4, this works

With <- (or any other operator I tried), I can do it:

`<-` = `+`
print(`<-`)
1 <- 3      # 4
1 <- test2  # Error: object 'test2' not found

rm(list=ls()) # back to sanity

So what's going on ?

Body:
> e <- quote(42 -> x)
> e
x <- 42

There is only one assignment operator in R: <- (well, two: there's = but let's not complicate things). The parser interprets the symbol "->" as assignment, and creates the expression as if <- had been used.


问:
How to perform actions on time basis in android?
In my application I want the user to auto log out after 10 PM and can login after 10 AM only .Now I am picking the current time but I don't know how to this for my scenario ,If the application is not in background then also it should work(I should work in background) .</p>

答:
Download the Sample by google itself, which gives all 3 types of repeating tasks example.

https://developer.android.com/training/scheduling/alarms.html


问:
Using Rails validation helpers :message but want it without listing the column name in message
Using Rails validation helpers-

```<code>validates_xxx_of :the_column, :message => "my message"
</code>```

will generate a validation message :

the_column my message

Is there a way to turn-off the inclusion of the column name?
(substitute xxx with any validation helper method)

答:
Why not simply use the @object.errors hash ?!

Change the messages as you with in the validate part:

validates_uniqueness_of :foobar, :message => "The foobar isn't unique."

And then,

@foo.errors.to_a

You get a nice array where the second entry is the error message itself.

Body:
Using Rails validation helpers-

validates_xxx_of :the_column, :message => "my message"

will generate a validation message :

the_column my message

Is there a way to turn-off the inclusion of the column name?
(substitute xxx with any validation helper method)


问:
Compare matrices in Python and store results
I would like to compare a 70x1 matrix with a 1000x3 matrix. What i want to do is compare the first column of the second matrix with the first matrix, find all the common values and then store the results in a new third matrix which is going to have all 3 columns.

I used np.intersect1d to find the common values between the two matrices but that is about it.

I can't find a way to import the other two columns of the second matrix to the new one.

Matrix1

```<code>[1.0

4.7

4.8

4.9

5.0

5.1]
</code>```

Matrix2

```<code>[[3.0, 1.8, -3.0]

[3.1, 2.2, -3.0]

[4.7, 2.4, -3.0]

[3.3, 2.8, -3.0]

[3.40, 3.0, -3.0]]
</code>```

Matrix3

```<code>[4.7, 2.4, -3.0]
</code>```

Body:
I would like to compare a 70x1 matrix with a 1000x3 matrix. What i want to do is compare the first column of the second matrix with the first matrix, find all the common values and then store the results in a new third matrix which is going to have all 3 columns.

I used np.intersect1d to find the common values between the two matrices but that is about it.

I can't find a way to import the other two columns of the second matrix to the new one.

Matrix1

[1.0

4.7

4.8

4.9

5.0

5.1]

Matrix2

[[3.0, 1.8, -3.0]

[3.1, 2.2, -3.0]

[4.7, 2.4, -3.0]

[3.3, 2.8, -3.0]

[3.40, 3.0, -3.0]]

Matrix3

[4.7, 2.4, -3.0]

Body:
You can use np.in1d:

a = numpy.array([1.0,4.7,4.8,4.9,5.0,5.1])
b = numpy.array([
    [3.0, 1.8, -3.0],
    [3.1, 2.2, -3.0],
    [4.7, 2.4, -3.0],
    [3.3, 2.8, -3.0],
    [3.40, 3.0, -3.0]
])

c = b[numpy.in1d(b[:, 0], a), :]
# array([[ 4.7,  2.4, -3. ]])


问:
Google maps V2 Location returning null
I'm getting a null pointer exception when calling location.getLatitude in the initCamera method. I've tried all the solutions on stack but none have worked. Below are my fragment code, manifest and dependencies I'm using:

Java code

```<code>public class MapFragment extends SupportMapFragment implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnInfoWindowClickListener,
        GoogleMap.OnMapLongClickListener,
        GoogleMap.OnMapClickListener,
        GoogleMap.OnMarkerClickListener {
    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;
    private LocationRequest mLocationRequest;

    private final int[] MAP_TYPES = { GoogleMap.MAP_TYPE_SATELLITE,
            GoogleMap.MAP_TYPE_NORMAL,
            GoogleMap.MAP_TYPE_HYBRID,
            GoogleMap.MAP_TYPE_TERRAIN,
            GoogleMap.MAP_TYPE_NONE };
    private int curMapTypeIndex = 0;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        setHasOptionsMenu(true);

        mGoogleApiClient = new GoogleApiClient.Builder( getActivity() )
                .addConnectionCallbacks( this )
                .addOnConnectionFailedListener( this )
                .addApi( LocationServices.API )
                .build();

        initListeners();
    }

    @Override
    public void onConnected(Bundle bundle) {

        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation( mGoogleApiClient );
        Log.d("mCurrentLocation",mCurrentLocation +"");
        initCamera( mCurrentLocation );

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        removeListeners();
    }

    private void initListeners() {
        getMap().setOnMarkerClickListener(this);
        getMap().setOnMapLongClickListener(this);
        getMap().setOnInfoWindowClickListener( this );
        getMap().setOnMapClickListener(this);
    }

    private void removeListeners() {
        if( getMap() != null ) {
            getMap().setOnMarkerClickListener( null );
            getMap().setOnMapLongClickListener(null);
            getMap().setOnInfoWindowClickListener(null);
            getMap().setOnMapClickListener(null);
        }
    }
    private void initCamera( Location location ) {
        if (location != null){
            CameraPosition position = CameraPosition.builder()
                    .target( new LatLng( location.getLatitude(), location.getLongitude() ) )
                    .zoom( 16f )
                    .bearing( 0.0f )
                    .tilt( 0.0f )
                    .build();

            getMap().animateCamera( CameraUpdateFactory.newCameraPosition( position ), null );

            getMap().setMapType( MAP_TYPES[curMapTypeIndex] );
            getMap().setTrafficEnabled( true );
            getMap().setMyLocationEnabled( true );
            getMap().getUiSettings().setZoomControlsEnabled( true );
        } else {
            Log.d("hello","hello");
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if( mGoogleApiClient != null && mGoogleApiClient.isConnected() ) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        //handle play services disconnecting if location is being constantly used
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //Create a default location if the Google API Client fails. Placing location at Googleplex
        mCurrentLocation = new Location( "" );
        mCurrentLocation.setLatitude( 37.422535 );
        mCurrentLocation.setLongitude( -122.084804 );
        initCamera(mCurrentLocation);
    }

}
</code>```

Manifest permission

```<code><uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

Dependencies

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:recyclerview-v7:22.2.0'
    compile 'com.google.android.gms:play-services-maps:7.8.0'
    compile 'com.google.android.gms:play-services-location:7.8.0'
}
</code>```

答:
It is a bug!!

You may find null values while fetching location data.

Firstly we need to make use of GoogleApiClient class.

Secondly we need to implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener

Third we need to override its onConnected() , onConnectionSuspended() and onConnectionFailed() method.

Beside above mentioned you need to make use of onLocationChanged()

You will get location data when ever it is available in onLocationChanged().

Hope it clarifies.

Title: Google maps V2 Location returning null

Body:
I'm getting a null pointer exception when calling location.getLatitude in the initCamera method. I've tried all the solutions on stack but none have worked. Below are my fragment code, manifest and dependencies I'm using:

Java code

public class MapFragment extends SupportMapFragment implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnInfoWindowClickListener,
        GoogleMap.OnMapLongClickListener,
        GoogleMap.OnMapClickListener,
        GoogleMap.OnMarkerClickListener {
    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;
    private LocationRequest mLocationRequest;

    private final int[] MAP_TYPES = { GoogleMap.MAP_TYPE_SATELLITE,
            GoogleMap.MAP_TYPE_NORMAL,
            GoogleMap.MAP_TYPE_HYBRID,
            GoogleMap.MAP_TYPE_TERRAIN,
            GoogleMap.MAP_TYPE_NONE };
    private int curMapTypeIndex = 0;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        setHasOptionsMenu(true);

        mGoogleApiClient = new GoogleApiClient.Builder( getActivity() )
                .addConnectionCallbacks( this )
                .addOnConnectionFailedListener( this )
                .addApi( LocationServices.API )
                .build();

        initListeners();
    }

    @Override
    public void onConnected(Bundle bundle) {

        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation( mGoogleApiClient );
        Log.d("mCurrentLocation",mCurrentLocation +"");
        initCamera( mCurrentLocation );

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        removeListeners();
    }

    private void initListeners() {
        getMap().setOnMarkerClickListener(this);
        getMap().setOnMapLongClickListener(this);
        getMap().setOnInfoWindowClickListener( this );
        getMap().setOnMapClickListener(this);
    }

    private void removeListeners() {
        if( getMap() != null ) {
            getMap().setOnMarkerClickListener( null );
            getMap().setOnMapLongClickListener(null);
            getMap().setOnInfoWindowClickListener(null);
            getMap().setOnMapClickListener(null);
        }
    }
    private void initCamera( Location location ) {
        if (location != null){
            CameraPosition position = CameraPosition.builder()
                    .target( new LatLng( location.getLatitude(), location.getLongitude() ) )
                    .zoom( 16f )
                    .bearing( 0.0f )
                    .tilt( 0.0f )
                    .build();

            getMap().animateCamera( CameraUpdateFactory.newCameraPosition( position ), null );

            getMap().setMapType( MAP_TYPES[curMapTypeIndex] );
            getMap().setTrafficEnabled( true );
            getMap().setMyLocationEnabled( true );
            getMap().getUiSettings().setZoomControlsEnabled( true );
        } else {
            Log.d("hello","hello");
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if( mGoogleApiClient != null && mGoogleApiClient.isConnected() ) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        //handle play services disconnecting if location is being constantly used
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //Create a default location if the Google API Client fails. Placing location at Googleplex
        mCurrentLocation = new Location( "" );
        mCurrentLocation.setLatitude( 37.422535 );
        mCurrentLocation.setLongitude( -122.084804 );
        initCamera(mCurrentLocation);
    }

}

Manifest permission

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Dependencies

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:recyclerview-v7:22.2.0'
    compile 'com.google.android.gms:play-services-maps:7.8.0'
    compile 'com.google.android.gms:play-services-location:7.8.0'
}


问:
How to set cache control in aws s3 object while uploading in java?
I tried the following options, but none of them will work

metadata.setCacheControl("max-age=604800, must-revalidate");

metadata.addUserMetadata("x-amz-meta-Cache-Control", "max-age=31536000, must-revalidate");

metadata.setHeader("x-amz-meta-Cache-Control", "max-age=31536000, must-revalidate");

metadata.addUserMetadata("Cache-Control", "max-age=31536000, must-revalidate");

Kindly help me to resolve this...

答:
First one is the correct approach, what i did wrong is, passed metadata via PutObjectRequest instead of TransferManager upload method. Need to pass metadata in TransferManager upload method.

metadata.setCacheControl("max-age=604800, must-revalidate");

Not Correct:

```<code>ObjectMetadata metadata = new ObjectMetadata();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, PREFIX + folderName + DELIMITER, null, metadata);
</code>```

correct :

```<code>ObjectMetadata metadata = new ObjectMetadata();
metadata.setCacheControl("max-age=31536000, must-revalidate");
Upload upload = transferManager.upload(bucketName, PREFIX + folderName + DELIMITER + fileName, fileStream, metadata);
</code>```

Now its working fine.

Body:
First one is the correct approach, what i did wrong is, passed metadata via PutObjectRequest instead of TransferManager upload method. Need to pass metadata in TransferManager upload method.

metadata.setCacheControl("max-age=604800, must-revalidate");

Not Correct:

ObjectMetadata metadata = new ObjectMetadata();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, PREFIX + folderName + DELIMITER, null, metadata);

correct :

ObjectMetadata metadata = new ObjectMetadata();
metadata.setCacheControl("max-age=31536000, must-revalidate");
Upload upload = transferManager.upload(bucketName, PREFIX + folderName + DELIMITER + fileName, fileStream, metadata);

Now its working fine.


问:
Unity C# Yield WaitForSeconds within For Loop Only Works Once
I am trying to use two yields within a coroutine loop (because I need to iterate out arrays with pauses between each loop).

The first loop works correctly, with all the yields working for the right amount of time. By the second loop, the yield return new WaitForSeconds() begins counting down right away, not waiting for the yield and code before it to complete (it seems). By the time of the third loop, the timing is all off.

I tried using a while loop instead of a for but got the same result.

TLDR: I need to loop out my arrays with pauses between each one. How can I use more than one yield past the first loop through in a coroutine?

```<code>public IEnumerator doPathfinding()
{
    for (int i = 0; i < waypoint.Length; i++)
    {

        // get first waypoint from array
        var _waypoint = waypoint[i];

        // get node on A* of cloest waypoint
        closestPointOnNavmesh = AstarPath.active.GetNearest(_waypoint.transform.position, NNConstraint.Default).clampedPosition;

        // Move towards destination
        ai.destination = closestPointOnNavmesh;

        // Wait until within X range of waypoint
        yield return new WaitUntil(() => distanceReached == true);

        // Agent is now at waypoint and automatically stops. Wait 5 seconds before looping to next waypoint.
        yield return new WaitForSeconds(5f);

    }

    Debug.Log("Loop End");
}

    public override void OnUpdate()
    {

        // Get current distance to the target. If distance is less than offset, then sent event.
        currentDistance = Vector3.Distance(go.transform.position, closestPointOnNavmesh);
        if(currentDistance <= arrivalOffset.Value)
        {
            distanceReached = true;
        }
        else
        {
            distanceReached = false;
        }

    }
</code>```

答:
The code inside the couroutine is fine, it works as intended.

Most probably, based on the issue you reported, you're calling more than once the coroutine at the same time.

Use a bool to check if the coroutine has already started or not, like this:

```<code>bool isDoPathFindingRunning = false;
IEnumerator = doPathFinding();

private void Awake() {
    pathFinding = doPathfinding();
}

private void WhereeverYouStartCoroutine() {
    if (!isDoPathFindingRunning)
        StartCoroutine(pathFinding);
}

public IEnumerator doPathfinding() {
    isDoPathFindingRunning = true;
    // Do your stuff
    isDoPathFindingRunning = false;
}
</code>```

Body:
I am trying to use two yields within a coroutine loop (because I need to iterate out arrays with pauses between each loop).

The first loop works correctly, with all the yields working for the right amount of time. By the second loop, the yield return new WaitForSeconds() begins counting down right away, not waiting for the yield and code before it to complete (it seems). By the time of the third loop, the timing is all off.

I tried using a while loop instead of a for but got the same result.

TLDR: I need to loop out my arrays with pauses between each one. How can I use more than one yield past the first loop through in a coroutine?

public IEnumerator doPathfinding()
{
    for (int i = 0; i < waypoint.Length; i++)
    {

        // get first waypoint from array
        var _waypoint = waypoint[i];

        // get node on A* of cloest waypoint
        closestPointOnNavmesh = AstarPath.active.GetNearest(_waypoint.transform.position, NNConstraint.Default).clampedPosition;

        // Move towards destination
        ai.destination = closestPointOnNavmesh;

        // Wait until within X range of waypoint
        yield return new WaitUntil(() => distanceReached == true);

        // Agent is now at waypoint and automatically stops. Wait 5 seconds before looping to next waypoint.
        yield return new WaitForSeconds(5f);

    }

    Debug.Log("Loop End");
}

    public override void OnUpdate()
    {

        // Get current distance to the target. If distance is less than offset, then sent event.
        currentDistance = Vector3.Distance(go.transform.position, closestPointOnNavmesh);
        if(currentDistance <= arrivalOffset.Value)
        {
            distanceReached = true;
        }
        else
        {
            distanceReached = false;
        }

    }

Body:
The code inside the couroutine is fine, it works as intended.

Most probably, based on the issue you reported, you're calling more than once the coroutine at the same time.

Use a bool to check if the coroutine has already started or not, like this:

bool isDoPathFindingRunning = false;
IEnumerator = doPathFinding();

private void Awake() {
    pathFinding = doPathfinding();
}

private void WhereeverYouStartCoroutine() {
    if (!isDoPathFindingRunning)
        StartCoroutine(pathFinding);
}

public IEnumerator doPathfinding() {
    isDoPathFindingRunning = true;
    // Do your stuff
    isDoPathFindingRunning = false;
}


问:
Could not load file or assembly 'Microsoft.SharePoint, Version=15.0.0.0
This is the code which I used.
And I have added Microsoft.SharePoint.dll .

```<code>using Microsoft.SharePoint.Client;
using System.Web.Script.Serialization;
using Microsoft.SharePoint;

    class
    {
      SPSite site = new SPSite(siteUrl);
    }
</code>```

The Error shows like this
:

```<code> Could not load file or assembly 'Microsoft.SharePoint, Version=15.0.0.0,
 Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies.
 The system cannot find the file specified.
</code>```

答:
1) Check references in your project. Is there a Microsoft.SharePoint reference?

2) If there is a reference and it's not corrupted, check the version by opening library properties.

2.1) If you have referenced a newer version, add an assembly binding with bindingRedirect in app config, for example:

```<code><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
  </dependentAssembly>
</assemblyBinding>
</code>```

3) Enable the Fusion log How to enable assembly bind failure logging (Fusion) in .NET and read the logs.

Body:
This is the code which I used.
And I have added Microsoft.SharePoint.dll .

using Microsoft.SharePoint.Client;
using System.Web.Script.Serialization;
using Microsoft.SharePoint;

    class
    {
      SPSite site = new SPSite(siteUrl);
    }

The Error shows like this
:

 Could not load file or assembly 'Microsoft.SharePoint, Version=15.0.0.0,
 Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies.
 The system cannot find the file specified.

Body:
1) Check references in your project. Is there a Microsoft.SharePoint reference?

2) If there is a reference and it's not corrupted, check the version by opening library properties.

2.1) If you have referenced a newer version, add an assembly binding with bindingRedirect in app config, for example:

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
  </dependentAssembly>
</assemblyBinding>

3) Enable the Fusion log How to enable assembly bind failure logging (Fusion) in .NET and read the logs.


问:
How to draw a shape of polygon dynamically on map in Angular
how to draw a shape of polygon dynamically(not predefined paths) and how to store lat long values of Polygon

I already refer AGMPolygon but it didn't solve my isuse

答:
Update 26 Apr 2018.

I am not sure but seems that the Angular Google Maps has already supported drawing polygon. You can check more.

Check the working demo:

Basic version (drawing polygon only) https://stackblitz.com/edit/angular-draw-polygon-google-maps

Updated version (drawing multiple polygon and intersect checking)  https://stackblitz.com/edit/angular-draw-polygon-intersect?file=src/main.ts

AGM is the best library for Angular 2 for now but It still needs to update more to reflect all the Google Maps API. So better we follow Google Maps doc and use it directly before the Angular community support it.

https://developers.google.com/maps/documentation/javascript/examples/drawing-tools

Please be noted that it is a very basic one which allows you to draw a polygon and get the coordinate once finishing. You might want to move all the map related code into service as well.

Also, better to wrap the whole code within zone.runOutsideAngular to prevent unnecessary change detection.

```<code>constructor(private zone: NgZone) {

}

ngOnInit() {
    this.zone.runOutsideAngular(() => {
      this.map = new google.maps.Map(document.getElementById('map'), {
          center: { lat: -34.397, lng: 150.644 },
          zoom: 8
      });

      this.drawingManager = new google.maps.drawing.DrawingManager({
          drawingMode: google.maps.drawing.OverlayType.POLYGON,
          drawingControl: true,
          drawingControlOptions: {
              position: google.maps.ControlPosition.TOP_CENTER,
              drawingModes: ['polygon']
          }
      });

      this.drawingManager.setMap(this.map);
      google.maps.event.addListener(this.drawingManager, 'overlaycomplete', (event) => {
          // Polygon drawn
          if (event.type === google.maps.drawing.OverlayType.POLYGON) {
            //this is the coordinate, you can assign it to a variable or pass into another function.
              alert(event.overlay.getPath().getArray());
          }
      });
    })
}
</code>```

Body:
Update 26 Apr 2018.

I am not sure but seems that the Angular Google Maps has already supported drawing polygon. You can check more.

Check the working demo:

Basic version (drawing polygon only) https://stackblitz.com/edit/angular-draw-polygon-google-maps

Updated version (drawing multiple polygon and intersect checking)  https://stackblitz.com/edit/angular-draw-polygon-intersect?file=src/main.ts

AGM is the best library for Angular 2 for now but It still needs to update more to reflect all the Google Maps API. So better we follow Google Maps doc and use it directly before the Angular community support it.

https://developers.google.com/maps/documentation/javascript/examples/drawing-tools

Please be noted that it is a very basic one which allows you to draw a polygon and get the coordinate once finishing. You might want to move all the map related code into service as well.

Also, better to wrap the whole code within zone.runOutsideAngular to prevent unnecessary change detection.

constructor(private zone: NgZone) {

}

ngOnInit() {
    this.zone.runOutsideAngular(() => {
      this.map = new google.maps.Map(document.getElementById('map'), {
          center: { lat: -34.397, lng: 150.644 },
          zoom: 8
      });

      this.drawingManager = new google.maps.drawing.DrawingManager({
          drawingMode: google.maps.drawing.OverlayType.POLYGON,
          drawingControl: true,
          drawingControlOptions: {
              position: google.maps.ControlPosition.TOP_CENTER,
              drawingModes: ['polygon']
          }
      });

      this.drawingManager.setMap(this.map);
      google.maps.event.addListener(this.drawingManager, 'overlaycomplete', (event) => {
          // Polygon drawn
          if (event.type === google.maps.drawing.OverlayType.POLYGON) {
            //this is the coordinate, you can assign it to a variable or pass into another function.
              alert(event.overlay.getPath().getArray());
          }
      });
    })
}


答:
As someone mentioned in comments

Check the time when user open the app, and if he should be logged out perform the logout and perform to the LogIn activity you probably implemented.

If I misunderstood something, let me know.

If you started coding this behaviour, you can provide some code snippets

Title: How to perform actions on time basis in android?

Body: In my application I want the user to auto log out after 10 PM and can login after 10 AM only .Now I am picking the current time but I don't know how to this for my scenario ,If the application is not in background then also it should work(I should work in background) .


问:
Different UI for different iPAD sizes
Our project runs for all iPAD's and we came across a problem as an example we have 8 buttons vertically sitting on a screen with constraints being added as vertical spacing they look fine on a iPAD 9.7 inch, but they look really big on iPAD 12.9, so the question is, is there any good way to actually use the screen space for something better, as in add an extra UIView if it is iPAD 12.9. I have looked into working with size classes, but I believe there is one size class for all iPADs, what I want is if there is a way to have different UI for different iPAD sizes using the Interface builder</p>

答:
You can use AutoLayout for this. You can assign aspect ratio base height to your buttons. Remember there is an option of setting ratio relationship to be 'equal to' or 'less than equal to.' You could use these instead of giving exact constraints. So this would cause button to adapt heights. Then in the code you could simply check if there is enough space remaining to draw an extra uiview or not. This will solve the 'Looking really big' problem also.

Check IB screenshot here to see what i am referring to:
Click on 'Relation' to see these settings

Title: Different UI for different iPAD sizes


问:
Angular escaping some of the css properties
I have webapp written in angular js. I am trying to load some HTML content in one of the div from my db. Following his how I told angular to trust HTML-

```<code>app = angular.module("######", ['ngRoute', 'ngSanitize', 'UserValidation', 'ui.select', 'textAngular', 'infinite-scroll']);

app.filter("trust", ['$sce', function ($sce) {
    return function (htmlCode) {
        return $sce.trustAsHtml(htmlCode);
    }
}]);
</code>```

HTML:

```<code><div class="summary" ng-bind-html="vm.portal.portalSummary | trust"></div>
</code>```

However some of the css properties from style attribute is getting escaped like position absolute, border.

1. The html is safe to be loaded, I too prohibit angular to escape these css styles?

2. Why angular is escaping these styles? What kind of security hazards are involved?

Thanks in advance!!

答: @Hitmands has suggested right thing in comment, its was not a issue of angularjs, properties were being stripped on server side</p>

Body:
I have webapp written in angular js. I am trying to load some HTML content in one of the div from my db. Following his how I told angular to trust HTML-

app = angular.module("######", ['ngRoute', 'ngSanitize', 'UserValidation', 'ui.select', 'textAngular', 'infinite-scroll']);

app.filter("trust", ['$sce', function ($sce) {
    return function (htmlCode) {
        return $sce.trustAsHtml(htmlCode);
    }
}]);

HTML:

However some of the css properties from style attribute is getting escaped like position absolute, border.

1. The html is safe to be loaded, I too prohibit angular to escape these css styles?

2. Why angular is escaping these styles? What kind of security hazards are involved?

Thanks in advance!!


问:
Is token still assigned to user when server shutdown?
As above, is token still assigned to user when server is shutting down?
Use case: user get token with 10 minutes expiration time, 30 seconds after user get authorized, server shutdowns. After 30 second server wakes up. Does user still authenticated with previously granted token ?

答: That completely depends on the Authorization Server's implementation of the requested token. If the token is a self-contained token like a JWT, it would still validate. If the token is a "by-reference-style" token then it may still validate if the Authorization Server uses persistent storage for its tokens, otherwise it would no longer validate.</p>


问:
Is it possible to update a generic property on an abstract base class via the constructor for all sub-classes?
This may represent poor design, but if you have a generic property in an abstract class that you wish to set via the constructor, can you set the type and value in not only a direct sub-class, but also sub-classes of the subclass?

```<code>public interface IFirst { }
public interface ISecond { }

public abstract class A<T> {
    public T SomeProperty { get; }

    protected A(T someProperty) {
        SomeProperty = someProperty;
    }
}

public class B : A<IFirst> {
    public B(IFirst someProperty) : base(someProperty) {
    }
}

public class C : B {
    public C(IFirst someProperty) : base(someProperty) {
        //What if I wanted to pass in ISecond as a type to SomeProperty by instantiating this class?
    }
}
</code>```

For all sub-classes of B, I'm locked into using IFirst as the type passed into the constructor.

Is there a design pattern or solution that solves this problem?

Thanks,

答:
You could use another interface to derive the two defined interfaces from:

```<code>public interface IBase {}
public interface IFirst : IBase { }
public interface ISecond : IBase { }

public abstract class A<T> {
    public T SomeProperty { get; }

    protected A(T someProperty) {
        SomeProperty = someProperty;
    }
}

public class B : A<IBase> {
    public B(IBase someProperty) : base(someProperty) {
    }
}

public class C : B {
    public C(ISecond someProperty) : base(someProperty) {
        //Works now
    }
}
</code>```

Body:
This may represent poor design, but if you have a generic property in an abstract class that you wish to set via the constructor, can you set the type and value in not only a direct sub-class, but also sub-classes of the subclass?

public interface IFirst { }
public interface ISecond { }

public abstract class A<T> {
    public T SomeProperty { get; }

    protected A(T someProperty) {
        SomeProperty = someProperty;
    }
}

public class B : A<IFirst> {
    public B(IFirst someProperty) : base(someProperty) {
    }
}

public class C : B {
    public C(IFirst someProperty) : base(someProperty) {
        //What if I wanted to pass in ISecond as a type to SomeProperty by instantiating this class?
    }
}

For all sub-classes of B, I'm locked into using IFirst as the type passed into the constructor.

Is there a design pattern or solution that solves this problem?

Thanks,

Body:
You could use another interface to derive the two defined interfaces from:

public interface IBase {}
public interface IFirst : IBase { }
public interface ISecond : IBase { }

public abstract class A<T> {
    public T SomeProperty { get; }

    protected A(T someProperty) {
        SomeProperty = someProperty;
    }
}

public class B : A<IBase> {
    public B(IBase someProperty) : base(someProperty) {
    }
}

public class C : B {
    public C(ISecond someProperty) : base(someProperty) {
        //Works now
    }
}


问:
Nodejs cpu profiling
I need to debug 100% cpu usage of my nodejs process. I found node --prof myapp.js is very helpful. Now I have another application that will fork child process and I need to debug that child process. here is how I was forking the process.

```<code>require('child_process').fork("childfile.js", ["arg1","arg2], {silent: true});
</code>```

Now my question is that, is it possible to profile child process, then how can I pass "--prof" option.

答:
```<code>require('child_process').fork("childfile.js", ["arg1","arg2], {silent: true,execArgv:["--prof"]});
</code>```

Title: Nodejs cpu profiling

Body:
I need to debug 100% cpu usage of my nodejs process. I found node --prof myapp.js is very helpful. Now I have another application that will fork child process and I need to debug that child process. here is how I was forking the process.

require('child_process').fork("childfile.js", ["arg1","arg2], {silent: true});

Now my question is that, is it possible to profile child process, then how can I pass "--prof" option.


问:
Real-time Linux (RTOS) for beagle bone
I am looking for a way to tailor a version of Ubuntu into a real-time OS, and then install it on Beagle Bone Black. I don't know where to start from.

What are the typical features one would look for in a real-time version of Ubuntu installed on a Beagle Bone Black?

If I want to start changing Beagle Bone's linux into a real-time version and building it, what is the exact procedure? Is there any guide for this?

How do I build and install this changed version of linux on Beagle Bone?

答:
Linux in itself is not real-time capable ("real-time tasks" = tasks which have a fixed, predictable timing behaviour).  However, there is a so called real-time-patch for Linux called "PREEMPT_RT" which addresses the most important real-time challenges.

To use PREEMPT_RT, you will have to patch and build your kernel.  Steps would be:

Get kernel source code for your target system

Get PREEMPT_RT patch from https://wiki.linuxfoundation.org/realtime/documentation/howto/applications/preemptrt_setup

Apply patch and install your own kernel

The PREEMPT_RT patch is available for kernel versions 2.6.22 up to 4.9.
See:

https://www.kernel.org/pub/linux/kernel/projects/rt/

Title: Real-time Linux (RTOS) for beagle bone


问:
Why is the following C++ code printing only the first character?
I am trying to convert a char string to a wchar string.

In more detail: I am trying to convert a char[] to a wchar[] first and then append " 1" to that string and the print it.

```<code>char src[256] = "c:\\user";

wchar_t temp_src[256];
mbtowc(temp_src, src, 256);

wchar_t path[256];

StringCbPrintf(path, 256, _T("%s 1"), temp_src);
wcout << path;
</code>```

But it prints just c

Is this the right way to convert from char to wchar? I have come to know of another way since. But I'd like to know why the above code works the way it does?

答:
L"Hello World"

the prefix L in front of the string makes it a wide char string.

Body:
I am trying to convert a char string to a wchar string.

In more detail: I am trying to convert a char[] to a wchar[] first and then append " 1" to that string and the print it.

char src[256] = "c:\\user";

wchar_t temp_src[256];
mbtowc(temp_src, src, 256);

wchar_t path[256];

StringCbPrintf(path, 256, _T("%s 1"), temp_src);
wcout << path;

But it prints just c

Is this the right way to convert from char to wchar? I have come to know of another way since. But I'd like to know why the above code works the way it does?


问:
What is tail recursion?
Whilst starting to learn lisp, I've come across the term tail-recursive. What does it mean exactly?

答:
This question has a lot of great answers... but I cannot help but chime in with an alternative take on how to define "tail recursion", or at least "proper tail recursion." Namely: should one look at it as a property of a particular expression in a program? Or should one look at it as a property of an implementation of a programming language?

For more on the latter view, there is a classic paper by Will Clinger, "Proper Tail Recursion and Space Efficiency" (PLDI 1998), that defined "proper tail recursion" as a property of a programming language implementation. The definition is constructed to allow one to ignore implementation details (such as whether the call stack is actually represented via the runtime stack or via a heap-allocated linked list of frames).

To accomplish this, it uses asymptotic analysis: not of program execution time as one usually sees, but rather of program space usage. This way, the space usage of a heap-allocated linked list vs a runtime call stack ends up being asymptotically equivalent; so one gets to ignore that programming language implementation detail (a detail which certainly matters quite a bit in practice, but can muddy the waters quite a bit when one attempts to determine whether a given implementation is satisfying the requirement to be "property tail recursive")

The paper is worth careful study for a number of reasons:

It gives an inductive definition of the tail expressions and tail calls of a program. (Such a definition, and why such calls are important, seems to be the subject of most of the other answers given here.)

Here are those definitions, just to provide a flavor of the text:

Definition 1 The tail expressions of a program written in Core Scheme are defined inductively as follows.

The body of a lambda expression is a tail expression

If (if E0 E1 E2) is a tail expression, then both E1 and E2 are tail expressions.

Nothing else is a tail expression.

Definition 2 A tail call is a tail expression that is a procedure call.

(a tail recursive call, or as the paper says, "self-tail call" is a special case of a tail call where the procedure is invoked itself.)

It provides formal definitions for six different "machines" for evaluating Core Scheme, where each machine has the same observable behavior except for the asymptotic space complexity class that each is in.

For example, after giving definitions for machines with respectively, 1. stack-based memory management, 2. garbage collection but no tail calls, 3. garbage collection and tail calls, the paper continues onward with even more advanced storage management strategies, such as 4. "evlis tail recursion", where the environment does not need to be preserved across the evaluation of the last sub-expression argument in a tail call, 5. reducing the environment of a closure to just the free variables of that closure, and 6. so-called "safe-for-space" semantics as defined by Appel and Shao.

In order to prove that the machines actually belong to six distinct space complexity classes, the paper, for each pair of machines under comparison, provides concrete examples of programs that will expose asymptotic space blowup on one machine but not the other.

(Reading over my answer now, I'm not sure if I'm managed to actually capture the crucial points of the Clinger paper. But, alas, I cannot devote more time to developing this answer right now.)

OwnerDisplayName: Ben Lever

Title: What is tail recursion?

LastEditorDisplayName: Adam Bellaire


问:
The different constructor ways
I have write little class, now i see different ways to call constructors. Which way is the correct way? (Or the better way)

SharedKeys.h

```<code>#ifndef SHAREDKEYS_H
    #define SHAREDKEYS_H

    class SharedKeys
    {
    private:
        char keyCode;

    public:
        SharedKeys(char keycode)
        {
            keyCode = keycode;
        }
        ~SharedKeys() {}

        char getKeyCode() { return keyCode; };

    };

    #endif
</code>```

Main.cpp

My constructor call way:

```<code>SharedKeys* SK;
SK = new SharedKeys(*cstr); //Call contructor
</code>```

Other constructor call way:

```<code>// SharedKeys constructor
SharedKeys::SharedKeys(*cstr)
{
    keyCode = keycode;
}
</code>```

I am open to any suggestions for improvement. Thank you.

Main.cpp

SK must be a pointer here or? (this code works)

```<code>SharedKeys* SK;

    vector<SharedKeys> StoreSharedKeys;

string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SK = new SharedKeys(*cstr);
StoreSharedKeys.push_back(*SK);
delete[] cstr;
</code>```

Did I understand you correctly?

```<code>cout << "Key: " <<  x << " loaded." << endl;
string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SharedKeys SK(*cstr);
StoreSharedKeys.push_back(SK);
delete[] cstr;
</code>```

if im see that correct then this contructor call is the right way. So i dont must delete the objects. Correct?

答:
Problem is probably in formule
you can write constructor without dynamic allocated memory

```<code>SharedKeys SK(*cstr);
</code>```

or with:

```<code>SK = new SharedKeys(*cstr);
</code>```

second thing which i see... you see to example

```<code>#include <iostream>
void function(char a, int lenght)
{
    std::cout << a << std::endl;
//  for (int i = 0; i < lenght; i++) printf("%c ", a[i]);
}
void function2(char *a, int lenght)
{
    for (int i = 0; i < lenght; i++) printf("%c ", a[i]);
}
int main()
{
    char tab[2]{ 'a','b' };
//  function(tab,2);
    function(*tab,2);
//  function2(tab,2);
//  function2(*tab,2);
    return 0;
}
</code>```

your line

```<code>SK = new SharedKeys(*cstr);
</code>```

this line give only first element array to constructor, i think it's not like you want. If you want give array char you should use formule from function2 (from example).

EDIT:
Yes, you must delete object,

```<code> delete[] cstr
</code>```

and

```<code>delete SK
</code>```

Title: The different constructor ways

Body:
I have write little class, now i see different ways to call constructors. Which way is the correct way? (Or the better way)

SharedKeys.h

#ifndef SHAREDKEYS_H
    #define SHAREDKEYS_H

    class SharedKeys
    {
    private:
        char keyCode;

    public:
        SharedKeys(char keycode)
        {
            keyCode = keycode;
        }
        ~SharedKeys() {}

        char getKeyCode() { return keyCode; };

    };

    #endif

Main.cpp

My constructor call way:

SharedKeys* SK;
SK = new SharedKeys(*cstr); //Call contructor

Other constructor call way:

// SharedKeys constructor
SharedKeys::SharedKeys(*cstr)
{
    keyCode = keycode;
}

I am open to any suggestions for improvement. Thank you.

Main.cpp

SK must be a pointer here or? (this code works)

SharedKeys* SK;

    vector<SharedKeys> StoreSharedKeys;

string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SK = new SharedKeys(*cstr);
StoreSharedKeys.push_back(*SK);
delete[] cstr;

Did I understand you correctly?

cout << "Key: " <<  x << " loaded." << endl;
string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SharedKeys SK(*cstr);
StoreSharedKeys.push_back(SK);
delete[] cstr;

if im see that correct then this contructor call is the right way. So i dont must delete the objects. Correct?

Body:
Problem is probably in formule
you can write constructor without dynamic allocated memory

SharedKeys SK(*cstr);

or with:

SK = new SharedKeys(*cstr);

second thing which i see... you see to example

#include <iostream>
void function(char a, int lenght)
{
    std::cout << a << std::endl;
//  for (int i = 0; i < lenght; i++) printf("%c ", a[i]);
}
void function2(char *a, int lenght)
{
    for (int i = 0; i < lenght; i++) printf("%c ", a[i]);
}
int main()
{
    char tab[2]{ 'a','b' };
//  function(tab,2);
    function(*tab,2);
//  function2(tab,2);
//  function2(*tab,2);
    return 0;
}

your line

SK = new SharedKeys(*cstr);

this line give only first element array to constructor, i think it's not like you want. If you want give array char you should use formule from function2 (from example).

EDIT:
Yes, you must delete object,

 delete[] cstr

and

delete SK