text:
import { Component, ChangeDetectionStrategy, ViewChild, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { HelperService } from '../../services/helper.service';
import { PharmacyService } from '../../services/pharmacy.service';
import { TransactionService } from '../../services/transaction.service';
import { TransactionProductService } from '../../services/transaction-product.service';
import { ProductService } from '../../services/product.service';
import { PrescriptionNumbertModel } from './prescription-number-model';
import { ProductModel } from './product-model';
import { PharmacyModel } from './pharmacy-model';
import { TransactionDateModel } from './transaction-date-model';
import { OwnerModel } from './owner-model';

import { FormControl } from '@angular/forms';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';

@Component({
	moduleId: module.id,
	selector: 'dash-cmp',
	templateUrl: 'dash.component.html',
	providers: [HelperService, PharmacyService, TransactionService, TransactionProductService, ProductService]
})

export class DashComponent implements OnInit {
	private intervalProcess:any = {};

	public transactionFeed:Array<Object> = [];
	public transactions:Array<Object> = [];
	public pharmacyProvinceCount:any;
	public transactionTrend:any = {
		current : [],
		previous : []
	};
	public pharmacies:Array<Object> = [];
	public isLoading:boolean = false;

	public prescriptionNumberList:Array<PrescriptionNumbertModel> = [];
	public lastTransactionList:Array<TransactionDateModel> = [];

	public pharmacyNameList:Array<PharmacyModel> = [];
	public productNameList:Array<ProductModel> = [];
	private ownerInfoList:Array<OwnerModel> = [];

	public transactionCount:number = 0;

	search        = '';
	searchControl = new FormControl();
	constructor(
		private router: Router,
		private _helperService : HelperService,
		private _pharmacyService : PharmacyService,
		private _transactionService : TransactionService,
		private _transactionProductService : TransactionProductService,
		private _productService : ProductService
	) {}

	public totalItems:number = 64;
	public currentPage:number = 4;

	public maxSize:number = 5;
	public bigTotalItems:number = 109;
	public bigCurrentPage:number = 1;

	private pageLimit:number = 10;

	public setPage(pageNo:number):void {
		this.currentPage = pageNo;
	};

	public pageChanged(event:any):void {
		this.currentPage = event.page;
		this._pharmacyService.find(this.pageLimit, this.search, this.currentPage, false, 'organization_branch')
		.subscribe(resPharmacyData => {
			this.transactions = resPharmacyData.result;
			this.parseTransactionData(resPharmacyData.result);
		});
	};

	public viewPharmacy(pharmacyId:any):void{
		this.router.navigate(['/dashboard/pharmacy-view', pharmacyId]);
	}

	private sortPharmacyProvince(data:any):any{
		data.sort(function(a, b) {
			return parseFloat(a.price) - parseFloat(b.price);
		});
	}

	private setPharmacyGraph(data:any):void {
		var pharmacyData = this.mapPharmacyArray(data.result);
		pharmacyData.sort(function(a, b) {
			return parseFloat(b.y) - parseFloat(a.y);
		});

		pharmacyData[0].selected = true;
		pharmacyData[0].sliced = true;

		var totalFruit: any = $('#total-fruit');
		totalFruit.highcharts({
			chart: {
				plotBackgroundColor: null,
				plotBorderWidth: null,
				plotShadow: false,
				type: 'pie'
			},
			title: {
				text: ''
			},
			tooltip: {
				pointFormat: '{series.name}: {point.percentage:.1f}%'
			},
			credits: {
				enabled: false
			},
			plotOptions: {
				pie: {
					allowPointSelect: true,
					cursor: 'pointer',
					dataLabels: {
						enabled: true,
						format: '{point.name}: {point.percentage:.1f} %',
						style: {
							color: 'black'
						}
					}
				}
			},
			series: [{
				name: 'Percentage',
				colorByPoint: true,
				data: pharmacyData
			}]
		});
	};

	private setTransactionTrendGraph(trendData:any):void {
		var transaction: any = $('#transaction-trend');
		transaction.highcharts({
			chart: {
				type: 'areaspline'
			},
			title: {
				text: ''
			},
			legend: {
				layout: 'vertical',
				align: 'left',
				verticalAlign: 'top',
				x: 150,
				y: 100,
				floating: true,
				borderWidth: 1,
				backgroundColor: '#FFFFFF'
			},
			xAxis: {
				categories: [
					"Sun",
					"Mon",
					"Tue",
					"Wed",
					"Thur",
					"Fri",
					"Sat"
				]
			},
			yAxis: {
				title: {
					text: 'Transactions'
				}
			},
			tooltip: {
				shared: true,
				valueSuffix: ' units'
			},
			credits: {
				enabled: false
			},
			plotOptions: {
				areaspline: {
					fillOpacity: 0.5
				}
			},
			series: [
				{
					name: 'Previous Week',
					data: [
						this.parseTrendData(trendData.previous[0]),
						this.parseTrendData(trendData.previous[1]),
						this.parseTrendData(trendData.previous[2]),
						this.parseTrendData(trendData.previous[3]),
						this.parseTrendData(trendData.previous[4]),
						this.parseTrendData(trendData.previous[5]),
						this.parseTrendData(trendData.previous[6])
					]
				},
				{
				name: 'Current Week',
					data: [
						this.parseTrendData(trendData.current[0]),
						this.parseTrendData(trendData.current[1]),
						this.parseTrendData(trendData.current[2]),
						this.parseTrendData(trendData.current[3]),
						this.parseTrendData(trendData.current[4]),
						this.parseTrendData(trendData.current[5]),
						this.parseTrendData(trendData.current[6])
					]
				}
			]
		});
	};

	private parseTrendData(data:any):number{
		var total_count = 0;

		if(data){
			total_count = data.total_prescription;
		}

		return total_count;
	}

	private mapPharmacyArray(data:any):any {
		var list = data;
		var total = 0;

		for (var i = 0; i < list.length; i++) {
			total = total + list[i].pharmacy_count;
			list[i].name = list[i]['province_name'];
			list[i].y = list[i]['pharmacy_count'];
			delete list[i].province_name;
			delete list[i].pharmacy_count;
		}

		for (var i = 0; i < list.length; i++) {
			list[i].y = (list[i].y / total) * 100;

		}
		return list;
	}

	private parseTransactionData(data:any):void{
		this.prescriptionNumberList = [];
		this.lastTransactionList = [];
		data.forEach(pharmacy => {
			this._helperService.getTransactionCountPerPharmacy(pharmacy.id)
			.subscribe(data => {
				if(data.result.length > 0){
					this.prescriptionNumberList.push(data.result[0]);
				}
			});
			this._transactionService.getByPharmacyId(pharmacy.id, 1, 10)
			.subscribe(data => {
				if(data.result.length > 0){
					this.lastTransactionList.push({
						id : pharmacy.id,
						date : data.result[0].dispense_date
					});
				}
			});
			this._helperService.getUserByOrganizationId(pharmacy.id)
			.subscribe(owner => {
				if(owner.result.length > 0){
					this.ownerInfoList.push(
						{
							id: pharmacy.id,
							name: owner.result[0].first_name + ' ' + owner.result[0].middle_name + ' ' + owner.result[0].last_name,
							email: owner.result[0].email,
							mobile : owner.result[0].mobile
						}
					);
				}
			});
		});
	}

	public formatDate(date:any, isTimeIncluded:boolean):string {
		var dateString = new Date(date).toUTCString();

		if(isTimeIncluded){
			dateString = dateString.split(' ').slice(0, 5).join(' ');
			} else {
				dateString = dateString.split(' ').slice(0, 4).join(' ');
			}

			return dateString;
	};

	public getPrescriptionNumber(id:number):string {
		var number = 'n/a';
		this.prescriptionNumberList.forEach(pharmacy => {
			if(pharmacy){
				if(id === pharmacy.id){
					number = pharmacy.total_prescription;
				}
			}
		});
		return number.toString();
	};

	public getProductName(data:any):string {

		var productName = 'Loading...';
		if(data){
			this.productNameList.forEach(product => {
				if(product){
					if(data.id === product.prescription_packaging_id){
						productName = product.name
					}else{
						productName = 'n/a';
					}
				}
			});
		}

		return productName;
	};

	public getPharmacyName(data:any):string {
		var pharmacyName = 'Loading...';
		if(data){
			this.pharmacyNameList.forEach(pharmacy => {
				if(pharmacy){
					if(data.id === pharmacy.prescription_packaging_id){
						pharmacyName = pharmacy.name
					}else{
						pharmacyName = 'n/a'
					}
			}
			});
		}

		return pharmacyName;
	};

	public getLastTransactionDate(id:number):string {
		var date = 'n/a';
		this.lastTransactionList.forEach(data => {
			if(data){
				if(id === data.id){
					date = this.formatDate(data.date, true)
				}
			}
		});

		return date;
	};

	public getOwnerInfo(id:number, type:string):string {
		var pharmacyName = 'n/a';
		this.ownerInfoList.forEach(pharmacy => {
			if(pharmacy){
				if(id === pharmacy.id){
					pharmacyName = pharmacy[type];
				}
			}
		});

		return pharmacyName;
	};

	private dateConvert(date:string, isCurrent:boolean):string{
		var dateObj = new Date();
		if(!isCurrent){
			dateObj = new Date(date);
		}

		var month = dateObj.getUTCMonth() + 1;
		var day = dateObj.getUTCDate() + 1;
		var year = dateObj.getUTCFullYear();

		return year + "-" + month + "-" + day;
	}

	private getCountWithFilters(isLicenseExpired: boolean, searchString: string, keySearch: string):void{
		/* This is a temporary dirty count. Need to Optimize via Backend API*/
		this._pharmacyService.find(1000, searchString, 1, isLicenseExpired, keySearch)
		.subscribe(data => {
			this.bigTotalItems = data.result.length;
		});
	}

	private checkUserRole():void{
		if(localStorage.getItem('roleId') !== 'admin' && localStorage.getItem('roleId') !== 'fda'){
			this.router.navigate(['/dashboard/pharmacy-view/' + localStorage.getItem('organizationId')]);
		}
	}

	ngOnInit(){
		var intervalCount = 1;

		this.isLoading = true;

		this.checkUserRole();

		this._helperService.getPharmacyCountPerProvince()
		.subscribe(data => {
			this.pharmacyProvinceCount = data.result;
			this.setPharmacyGraph(data);
		});

		this._helperService.getTransactionTrend()
		.subscribe(data => {
			this.transactionTrend = data.result
			this.setTransactionTrendGraph(data.result);
		});

		this._pharmacyService.getAll()
		.subscribe(data => {
			this.transactions = data.result;
			this.parseTransactionData(data.result);
			this.isLoading = false;
		});

		this._helperService.getAllPrescription(15, this.dateConvert(null, false), this.dateConvert(null, true))
		.subscribe(data => {
			this.transactionFeed = data.result;
		});

		this._pharmacyService.getCount()
		.subscribe(resPharmacyData => this.bigTotalItems = resPharmacyData.result[0].row_count);

		this.intervalProcess = setInterval(() => {
			var tmp = this.transactionFeed.shift();
			this.transactionFeed.push(tmp);
		}, 2000);

		this._transactionProductService.getAllCount()
		.subscribe(data => this.transactionCount = data.result[0].row_count);

		this.searchControl.valueChanges
		.debounceTime(250)
		.subscribe(newValue => {
			this.search = newValue;
			this.currentPage = 1;
			this.bigCurrentPage = 1;

			this._pharmacyService.find(this.pageLimit, this.search, this.currentPage, null, 'organization_branch')
			.subscribe(data => {
				this.transactions = data.result;
				this.getCountWithFilters(false, newValue, 'organization_branch');
				this.parseTransactionData(data.result);
			});
		});
	}

	ngOnDestroy() {
		if (this.intervalProcess) {
			clearInterval(this.intervalProcess);
		}
	}
}


text:
extern id bcPluginGlobal;

@implementation BCPlayerPlugin

#pragma mark - Cordova Initialization

-(CDVPlugin*) initWithWebView:(UIWebView*)theWebView
{
    self = (BCPlayerPlugin*)[super initWithWebView:theWebView];
    bcPluginGlobal = self;
    _backgroundMode = false;
    return self;
}

#pragma mark - Cordova Events

- (void) handlePlayEvent
{
    NSLog(@"Play video");

    [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('brightcovePlayer.play', {})"]];
}

- (void) handleLoadedEvent:(NSString*)duration
{
    NSLog(@"loaded video");
    [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('brightcovePlayer.loaded', {'duration': %@})", duration]];
}

- (void) handleProgressEvent:(NSString*)currentTime
{

    [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('brightcovePlayer.progress', {'currentTime': %@})", currentTime]];
}

- (void) handleRateEvent:(NSString*)rate
{

    [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('brightcovePlayer.rate', {'rate': %@})", rate]];
}

- (void) handlePauseEvent
{
    if(_backgroundMode){
        if(self.bCPlayerPluginController != nil){
            [self.bCPlayerPluginController play];
        }
        _backgroundMode = false;
    }

    [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('brightcovePlayer.pause', {})"]];
}

- (void) handleBackgroundMode
{
    _backgroundMode = true;
}

- (void) handleExitBackgroundMode
{
    _backgroundMode = false;
}

- (void) handleEndedEvent
{
    NSLog(@"ended video");

    [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('brightcovePlayer.end', {})"]];
}

- (void) handleErrorEvent
{
    NSLog(@"error video");

    [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('brightcovePlayer.error', {})"]];
}

- (void) handleLoadErrorEvent
{
    NSLog(@"load error video");

    [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('brightcovePlayer.error', {})"]];
}

#pragma mark - Cordova Methods

- (void)init:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;

    NSString *token = [command argumentAtIndex:0 withDefault:@"" andClass:[NSString class]];
    if (token != nil && [token length]) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Inited"];
    } else{
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Empty Brightcove token!"];
    }

    self.bCPlayerPluginController = [[BCPlayerPluginController alloc] initWithToken:self.webView.superview Token:token];
    self.bCPlayerPluginController.delegate = self;

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)reposition:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;

    NSString *xString = [command argumentAtIndex:0 withDefault:@"" andClass:[NSString class]];
    double x = 0;
    if (xString != nil && [xString length]) {
        x= [xString doubleValue];
    }

    NSString *yString = [command argumentAtIndex:1 withDefault:@"" andClass:[NSString class]];
    double y = 0;
    if (yString != nil && [yString length]) {
        y =[yString doubleValue];
    }

    NSString *widthString = [command argumentAtIndex:2 withDefault:@"" andClass:[NSString class]];
    double width = 0;
    if (widthString != nil && [widthString length]) {
        width =[widthString doubleValue];
    }

    NSString *heightString = [command argumentAtIndex:3 withDefault:@"" andClass:[NSString class]];
    double height = 0;
    if (heightString != nil && [heightString length]) {
        height =[heightString doubleValue];
    }

    CGRect viewRect = CGRectMake(x, y, width, height);

    [self.bCPlayerPluginController reposition:viewRect];
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:nil];

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)load:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;

    NSString *url = [command argumentAtIndex:0 withDefault:@"" andClass:[NSString class]];
    if (url != nil && [url length]) {
        [self.bCPlayerPluginController load:url];
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];
    }

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)seek:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;

    NSString *positionString = [command argumentAtIndex:0 withDefault:@"" andClass:[NSString class]];
    double position = 0;
    if (positionString != nil && [positionString length]) {
        position =[positionString doubleValue];
    }

    if (positionString != nil && [positionString length]) {
        [self.bCPlayerPluginController seek:position];
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];
    }

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)rate:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate runInBackground:^{
    CDVPluginResult* pluginResult = nil;

    NSString *rateString = [command argumentAtIndex:0 withDefault:@"" andClass:[NSString class]];
    float rate = 0;
    if (rateString != nil && [rateString length]) {
        rate =[rateString floatValue];
    }

    if (rateString != nil && [rateString length]) {
        [self.bCPlayerPluginController rate:rate];
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];
    }

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)play:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate runInBackground:^{
    CDVPluginResult* pluginResult = nil;

    [self.bCPlayerPluginController play];
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)pause:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate runInBackground:^{
        CDVPluginResult* pluginResult = nil;

    [self.bCPlayerPluginController pause];
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)hide:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;

    [self.bCPlayerPluginController hide];
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)show:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;

    [self.bCPlayerPluginController show];
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

#pragma mark - Helper Methods

@end

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.serviceconsumermanagement.v1.model;

/**
 * `QuotaLimit` defines a specific limit that applies over a specified duration for a limit type.
 * There can be at most one limit for a duration and limit type combination defined within a
 * `QuotaGroup`.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Service Consumer Management API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class QuotaLimit extends com.google.api.client.json.GenericJson {

  /**
   * Default number of tokens that can be consumed during the specified duration. This is the number
   * of tokens assigned when a client application developer activates the service for his/her
   * project. Specifying a value of 0 will block all requests. This can be used if you are
   * provisioning quota to selected consumers and blocking others. Similarly, a value of -1 will
   * indicate an unlimited quota. No other negative values are allowed. Used by group-based quotas
   * only.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long defaultLimit;

  /**
   * Optional. User-visible, extended description for this quota limit. Should be used only when
   * more context is needed to understand this limit than provided by the limit's display name (see:
   * `display_name`).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String description;

  /**
   * User-visible display name for this limit. Optional. If not set, the UI will provide a default
   * display name based on the quota configuration. This field can be used to override the default
   * display name generated from the configuration.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String displayName;

  /**
   * Duration of this limit in textual notation. Must be "100s" or "1d". Used by group-based quotas
   * only.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String duration;

  /**
   * Free tier value displayed in the Developers Console for this limit. The free tier is the number
   * of tokens that will be subtracted from the billed amount when billing is enabled. This field
   * can only be set on a limit with duration "1d", in a billable group; it is invalid on any other
   * limit. If this field is not set, it defaults to 0, indicating that there is no free tier for
   * this service. Used by group-based quotas only.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long freeTier;

  /**
   * Maximum number of tokens that can be consumed during the specified duration. Client application
   * developers can override the default limit up to this maximum. If specified, this value cannot
   * be set to a value less than the default limit. If not specified, it is set to the default
   * limit. To allow clients to apply overrides with no upper bound, set this to -1, indicating
   * unlimited maximum quota. Used by group-based quotas only.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long maxLimit;

  /**
   * The name of the metric this quota limit applies to. The quota limits with the same metric will
   * be checked together during runtime. The metric must be defined within the service config.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String metric;

  /**
   * Name of the quota limit. The name must be provided, and it must be unique within the service.
   * The name can only include alphanumeric characters as well as '-'. The maximum length of the
   * limit name is 64 characters.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * Specify the unit of the quota limit. It uses the same syntax as Metric.unit. The supported unit
   * kinds are determined by the quota backend system. Here are some examples: * "1/min/{project}"
   * for quota per minute per project. Note: the order of unit components is insignificant. The "1"
   * at the beginning is required to follow the metric unit syntax.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String unit;

  /**
   * Tiered limit values. You must specify this as a key:value pair, with an integer value that is
   * the maximum number of requests allowed for the specified unit. Currently only STANDARD is
   * supported.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.util.Map<String, java.lang.Long> values;

  /**
   * Default number of tokens that can be consumed during the specified duration. This is the number
   * of tokens assigned when a client application developer activates the service for his/her
   * project. Specifying a value of 0 will block all requests. This can be used if you are
   * provisioning quota to selected consumers and blocking others. Similarly, a value of -1 will
   * indicate an unlimited quota. No other negative values are allowed. Used by group-based quotas
   * only.
   * @return value or {@code null} for none
   */
  public java.lang.Long getDefaultLimit() {
    return defaultLimit;
  }

  /**
   * Default number of tokens that can be consumed during the specified duration. This is the number
   * of tokens assigned when a client application developer activates the service for his/her
   * project. Specifying a value of 0 will block all requests. This can be used if you are
   * provisioning quota to selected consumers and blocking others. Similarly, a value of -1 will
   * indicate an unlimited quota. No other negative values are allowed. Used by group-based quotas
   * only.
   * @param defaultLimit defaultLimit or {@code null} for none
   */
  public QuotaLimit setDefaultLimit(java.lang.Long defaultLimit) {
    this.defaultLimit = defaultLimit;
    return this;
  }

  /**
   * Optional. User-visible, extended description for this quota limit. Should be used only when
   * more context is needed to understand this limit than provided by the limit's display name (see:
   * `display_name`).
   * @return value or {@code null} for none
   */
  public java.lang.String getDescription() {
    return description;
  }

  /**
   * Optional. User-visible, extended description for this quota limit. Should be used only when
   * more context is needed to understand this limit than provided by the limit's display name (see:
   * `display_name`).
   * @param description description or {@code null} for none
   */
  public QuotaLimit setDescription(java.lang.String description) {
    this.description = description;
    return this;
  }

  /**
   * User-visible display name for this limit. Optional. If not set, the UI will provide a default
   * display name based on the quota configuration. This field can be used to override the default
   * display name generated from the configuration.
   * @return value or {@code null} for none
   */
  public java.lang.String getDisplayName() {
    return displayName;
  }

  /**
   * User-visible display name for this limit. Optional. If not set, the UI will provide a default
   * display name based on the quota configuration. This field can be used to override the default
   * display name generated from the configuration.
   * @param displayName displayName or {@code null} for none
   */
  public QuotaLimit setDisplayName(java.lang.String displayName) {
    this.displayName = displayName;
    return this;
  }

  /**
   * Duration of this limit in textual notation. Must be "100s" or "1d". Used by group-based quotas
   * only.
   * @return value or {@code null} for none
   */
  public java.lang.String getDuration() {
    return duration;
  }

  /**
   * Duration of this limit in textual notation. Must be "100s" or "1d". Used by group-based quotas
   * only.
   * @param duration duration or {@code null} for none
   */
  public QuotaLimit setDuration(java.lang.String duration) {
    this.duration = duration;
    return this;
  }

  /**
   * Free tier value displayed in the Developers Console for this limit. The free tier is the number
   * of tokens that will be subtracted from the billed amount when billing is enabled. This field
   * can only be set on a limit with duration "1d", in a billable group; it is invalid on any other
   * limit. If this field is not set, it defaults to 0, indicating that there is no free tier for
   * this service. Used by group-based quotas only.
   * @return value or {@code null} for none
   */
  public java.lang.Long getFreeTier() {
    return freeTier;
  }

  /**
   * Free tier value displayed in the Developers Console for this limit. The free tier is the number
   * of tokens that will be subtracted from the billed amount when billing is enabled. This field
   * can only be set on a limit with duration "1d", in a billable group; it is invalid on any other
   * limit. If this field is not set, it defaults to 0, indicating that there is no free tier for
   * this service. Used by group-based quotas only.
   * @param freeTier freeTier or {@code null} for none
   */
  public QuotaLimit setFreeTier(java.lang.Long freeTier) {
    this.freeTier = freeTier;
    return this;
  }

  /**
   * Maximum number of tokens that can be consumed during the specified duration. Client application
   * developers can override the default limit up to this maximum. If specified, this value cannot
   * be set to a value less than the default limit. If not specified, it is set to the default
   * limit. To allow clients to apply overrides with no upper bound, set this to -1, indicating
   * unlimited maximum quota. Used by group-based quotas only.
   * @return value or {@code null} for none
   */
  public java.lang.Long getMaxLimit() {
    return maxLimit;
  }

  /**
   * Maximum number of tokens that can be consumed during the specified duration. Client application
   * developers can override the default limit up to this maximum. If specified, this value cannot
   * be set to a value less than the default limit. If not specified, it is set to the default
   * limit. To allow clients to apply overrides with no upper bound, set this to -1, indicating
   * unlimited maximum quota. Used by group-based quotas only.
   * @param maxLimit maxLimit or {@code null} for none
   */
  public QuotaLimit setMaxLimit(java.lang.Long maxLimit) {
    this.maxLimit = maxLimit;
    return this;
  }

  /**
   * The name of the metric this quota limit applies to. The quota limits with the same metric will
   * be checked together during runtime. The metric must be defined within the service config.
   * @return value or {@code null} for none
   */
  public java.lang.String getMetric() {
    return metric;
  }

  /**
   * The name of the metric this quota limit applies to. The quota limits with the same metric will
   * be checked together during runtime. The metric must be defined within the service config.
   * @param metric metric or {@code null} for none
   */
  public QuotaLimit setMetric(java.lang.String metric) {
    this.metric = metric;
    return this;
  }

  /**
   * Name of the quota limit. The name must be provided, and it must be unique within the service.
   * The name can only include alphanumeric characters as well as '-'. The maximum length of the
   * limit name is 64 characters.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * Name of the quota limit. The name must be provided, and it must be unique within the service.
   * The name can only include alphanumeric characters as well as '-'. The maximum length of the
   * limit name is 64 characters.
   * @param name name or {@code null} for none
   */
  public QuotaLimit setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * Specify the unit of the quota limit. It uses the same syntax as Metric.unit. The supported unit
   * kinds are determined by the quota backend system. Here are some examples: * "1/min/{project}"
   * for quota per minute per project. Note: the order of unit components is insignificant. The "1"
   * at the beginning is required to follow the metric unit syntax.
   * @return value or {@code null} for none
   */
  public java.lang.String getUnit() {
    return unit;
  }

  /**
   * Specify the unit of the quota limit. It uses the same syntax as Metric.unit. The supported unit
   * kinds are determined by the quota backend system. Here are some examples: * "1/min/{project}"
   * for quota per minute per project. Note: the order of unit components is insignificant. The "1"
   * at the beginning is required to follow the metric unit syntax.
   * @param unit unit or {@code null} for none
   */
  public QuotaLimit setUnit(java.lang.String unit) {
    this.unit = unit;
    return this;
  }

  /**
   * Tiered limit values. You must specify this as a key:value pair, with an integer value that is
   * the maximum number of requests allowed for the specified unit. Currently only STANDARD is
   * supported.
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.Long> getValues() {
    return values;
  }

  /**
   * Tiered limit values. You must specify this as a key:value pair, with an integer value that is
   * the maximum number of requests allowed for the specified unit. Currently only STANDARD is
   * supported.
   * @param values values or {@code null} for none
   */
  public QuotaLimit setValues(java.util.Map<String, java.lang.Long> values) {
    this.values = values;
    return this;
  }

  @Override
  public QuotaLimit set(String fieldName, Object value) {
    return (QuotaLimit) super.set(fieldName, value);
  }

  @Override
  public QuotaLimit clone() {
    return (QuotaLimit) super.clone();
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 52(5): 955 (1974)

#### Original name
Pesavis Elsik & Janson.

### Remarks
null


text:
package org.usfirst.frc.team2875.robot.autocommands;

import org.usfirst.frc.team2875.robot.Robot;
import org.usfirst.frc.team2875.robot.commands.DriveXFeet;
import org.usfirst.frc.team2875.robot.commands.LiftArmsAuto;
import org.usfirst.frc.team2875.robot.commands.LowerArmsAuto;
import org.usfirst.frc.team2875.robot.commands.TimeOut;
import org.usfirst.frc.team2875.robot.commands.TurnTo;
import org.usfirst.frc.team2875.robot.util.Direction;

import edu.wpi.first.wpilibj.command.CommandGroup;

public class ChevalAuto extends CommandGroup {

	public ChevalAuto()
	{
		addSequential(new DriveXFeet(3.3,0.5D));
		addSequential(new LowerArmsAuto());
		//TEST CODE
		//addSequential(new TimeOut(3));
		//
		addSequential(new DriveXFeet(1, 0.3D));
		addParallel(new LiftArmsAuto());
		addParallel(new DriveXFeet(4, 0.4D));
		if(Robot.gyroscope.get_heading_neg() > 0.0D){
			addSequential(new TurnTo(0.0D, Direction.LEFT));
		}else{
			addSequential(new TurnTo(0.0D, Direction.RIGHT));
		}
	}
}


text:
var config = require("./config/dev");
var mongoose = require("mongoose");
var server = require("./server");

// start DB
mongoose.connect(config.db.url);
var db = mongoose.connection;
db.on("error", console.error.bind(console, "Connection error:"));

server.start(config.port);
console.log("Started server: DEVELOPMENT");


text:
package com.zuoxiaolong.blog.service;

import com.zuoxiaolong.blog.dao.DictionaryRepository;
import com.zuoxiaolong.blog.entity.Dictionary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DictionaryService {

    @Resource
    private DictionaryRepository dictionaryRepository;

    public List<Map<String, String>> getDictionariesByType(final String type) {
        List<Dictionary> dictionaries = dictionaryRepository.findByType(type);
        if (dictionaries != null) {
            return dictionaries.stream().map(dictionary -> transfer(dictionary)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    public String getName(final Integer id) {
        Optional<Dictionary> dictionary = dictionaryRepository.findById(id);
        if (dictionary.isPresent()) {
            return dictionary.get().getName();
        }
        return null;
    }

    public Map<String, String> transfer(Dictionary dictionary) {
        Map<String, String> diactionaryMap = new HashMap<String, String>();
        diactionaryMap.put("id", String.valueOf(dictionary.getId()));
        diactionaryMap.put("name", dictionary.getName());
        return diactionaryMap;
    }

}


text:
package com.alperez.bt_microphone.bluetoorh.connector.data;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.annotation.NonNull;

import com.alperez.bt_microphone.bluetoorh.BtUtils;
import com.alperez.bt_microphone.bluetoorh.connector.BtConnector;
import com.alperez.bt_microphone.bluetoorh.connector.OnConnectionStatusListener;
import com.alperez.bt_microphone.utils.ThreadLog;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;

/**
 * Created by stanislav.perchenko on 3/17/2017.
 */

public class BtDataTransceiverImpl implements BtDataTransceiver {
    public static final String TAG = "BtTrans";

    //--- Connection entry point ---
    private BluetoothDevice device;
    private UUID serviceUUID;

    //---  Exit condition ---
    private volatile boolean released;

    //--- Connection-related objects ---
    /**
     * Anyone who wants to work with connection must acquire this lock!
     */
    private final Object connectorLock = new Object();
    private BluetoothSocket socket;
    private InputStream iStream;
    private OutputStream oStream;
    private volatile boolean dataConnectionReady;
    private volatile int numConnectionTry;

    //---  Transmission-related section  ----
    private final TransmissionThread transmThread;

    /**
     * Anyone who wants to work with data transmission must acquire this lock!
     */
    private final Queue<String> transmissionQueue = new LinkedList<>();

    //----  Receiver-related section  ----
    private final ReceivingThread rcvThread;

    private final Set<OnTextDataReceivedListener> rcvListeners = Collections.synchronizedSet(new HashSet<>());

    //----  Transceiver status notification section ---
    private final Set<OnConnectionStatusListener> statusListeners = Collections.synchronizedSet(new HashSet<>());

    /**********************************  Public API section  **************************************/

    public BtDataTransceiverImpl(@NonNull BluetoothDevice device, @NonNull UUID serviceUUID) {
        if (device == null) throw new IllegalArgumentException("BluetoothDevice cannot be null");
        if (serviceUUID == null) throw new IllegalArgumentException("Service UUID cannot be null");
        this.device = device;
        this.serviceUUID = serviceUUID;

        ThreadLog.d(TAG, "=====  Transceiver created  =======");

        transmThread = new TransmissionThread(getClass().getSimpleName()+": transmission thread");
        rcvThread = new ReceivingThread(getClass().getSimpleName()+": receiving thread");
        transmThread.start();
        rcvThread.start();

        openConnectionAsync(75);
    }

    @Override
    public BtDataTransceiver addOnTextDataReceivedListener(@NonNull OnTextDataReceivedListener l) {
        this.rcvListeners.add(l);
        return this;
    }

    @Override
    public boolean removeOnTextDataReceivedListener(@NonNull OnTextDataReceivedListener l) {
        return rcvListeners.remove(l);
    }

    @Override
    public BtDataTransceiver addOnTransceiverStatusListener(@NonNull OnConnectionStatusListener l) {
        statusListeners.add(l);
        return this;
    }

    @Override
    public boolean removeOnTransceiverStatusListener(@NonNull OnConnectionStatusListener l) {
        return statusListeners.remove(l);
    }

    /**
     * Submits new data to the transmission queue. If data String does not end with the "\r\n" sequence,
     * these bytes are added before transmission.
     * @param data
     */
    @Override
    public void sendDataNonBlocked(String data) {
        synchronized (transmissionQueue) {
            ThreadLog.d(TAG, "Request send data - "+data);
            transmissionQueue.add(data);
            transmissionQueue.notify();
        }
    }

    /**
     * An instance of the BtDataTransceiverImpl cannot be used after release
     */
    @Override
    public void release() {
        if (!released) {
            synchronized (connectorLock) {
                if (!released) {
                    ThreadLog.e(TAG, "~~~~~~~~  Release transceiver  ~~~~~~~~~~~~");
                    released = true;
                    rcvThread.interrupt();
                    transmThread.interrupt();
                    closeConnectionSilently();
                }
            }
        }
    }

    /*********************  Managing Connection section  ******************************************/

    private void openConnectionAsync(int initDelay) {
        if (!dataConnectionReady && !released) {
            synchronized (connectorLock) {
                if (!dataConnectionReady && !released) {
                    numConnectionTry ++;

                    ThreadLog.d(TAG, String.format("---->> Open connection async with initial delay %d ms, Ntry = %d", initDelay, numConnectionTry));

                    BtConnector.forDevice(device, serviceUUID)
                            .preConnectionDelay(initDelay)
                            .connectAsync(new BtConnector.OnDeviceConnectListener() {
                                @Override
                                public void onConnected(BluetoothSocket socket, InputStream iStream, OutputStream oStream) {
                                    // Instantiate connection data. Released condition is checked inside
                                    setConnection(socket, iStream, oStream);
                                }

                                @Override
                                public void onConnectionFailure(Throwable reason) {
                                    //---  Notify status listener  ---
                                    synchronized (statusListeners) {
                                        for (OnConnectionStatusListener sl : statusListeners) {
                                            sl.onConnectionAttemptFailed(numConnectionTry);
                                        }
                                    }

                                    ThreadLog.e(TAG, "~~~~~~>>  onConnectionFailed() - "+reason.getMessage());

                                    //--- Try again with delay. Released condition is checked inside ---
                                    openConnectionAsync(750);
                                }
                            });
                }
            }
        }
    }

    private void setConnection(BluetoothSocket socket, InputStream iStream, OutputStream oStream) {
        boolean connReady = false;
        if (!dataConnectionReady && !released) {
            synchronized (connectorLock) {
                if (!dataConnectionReady && !released) {
                    ThreadLog.d(TAG, "=======>> Set new opened connection!");
                    dataConnectionReady = true;
                    this.socket = socket;
                    this.iStream = iStream;
                    this.oStream = oStream;
                    connReady = true;
                    connectorLock.notifyAll();

                    //---  Notify status listener  ---
                    synchronized (statusListeners) {
                        for (OnConnectionStatusListener sl : statusListeners) {
                            sl.onConnectionRestorted(numConnectionTry);
                        }
                    }

                }
            }
        }

        if (connReady) {
            synchronized (transmissionQueue) {
                transmissionQueue.notify();
            }
            //TODO Notify receiver thread!
        }
    }

    private void closeConnectionSilently() {
        if (dataConnectionReady) {
            synchronized (connectorLock) {
                if (dataConnectionReady) {
                    ThreadLog.e(TAG, "!!!!  Close connection silently !!!!");
                    dataConnectionReady = false;
                    BtUtils.silentlyCloseCloseable(iStream);
                    BtUtils.silentlyCloseCloseable(oStream);
                    BtUtils.silentlyCloseCloseable(socket);
                    iStream = null;
                    oStream = null;
                    socket = null;
                }
            }
        }
    }

    /**
     * This method must be called either from transmit or receiver Thread in case of exception over
     * data streams.
     * @param failedThreadName
     * @param failureReason
     */
    private synchronized void reconnectAfterFailure(String failedThreadName, Throwable failureReason) {
        if (!dataConnectionReady) {
            ThreadLog.e(TAG, "Reconnect after failure -> Process already started");
            return;
        }

        ThreadLog.d(TAG, "===> Reconnect after failure");

        closeConnectionSilently();

        synchronized (statusListeners) {
            for (OnConnectionStatusListener sl : statusListeners) {
                sl.onConnectionBroken(failedThreadName, failureReason);
            }
        }

        openConnectionAsync(50);
    }

    /********************************  Data transmit section  *************************************/
    private class TransmissionThread extends Thread {

        public TransmissionThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            ThreadLog.d(TAG, "---------- Thread started -----------");
            String textToSend = null; //TODO Remove this after testing
            byte[] data = null;
            OutputStream localOS = null;

            while (!released) {

                //--- Wait for data to transmit ---
                if (data == null) {
                    synchronized (transmissionQueue) {
                        while(transmissionQueue.isEmpty()) {
                            try {
                                transmissionQueue.wait();
                            } catch (InterruptedException e) {
                                if (released) {
                                    ThreadLog.e(TAG, "Transmission - thread was interrupted and released");
                                    Thread.currentThread().interrupt();
                                    break;
                                }
                            }
                        }
                        if (released) {
                            ThreadLog.e(TAG, "Transmission - leave thread early on release (1)");
                            break;
                        }
                        data = BtUtils.prepareDataToTransmit(textToSend = transmissionQueue.remove());
                    }
                }

                ThreadLog.d(TAG, "Transmission - got data to send: "+textToSend);

                if (released) {
                    ThreadLog.e(TAG, "Transmission - leave thread early on release (2)");
                    break;
                }

                //--- get OutputStream safely ---
                if (localOS == null) {
                    synchronized (connectorLock) {
                        while (!dataConnectionReady) {
                            try {
                                connectorLock.wait();
                            } catch (InterruptedException e) {
                                if (released) {
                                    Thread.currentThread().interrupt();
                                    break;
                                }
                            }
                        }
                        localOS = oStream;
                    }
                }

                ThreadLog.d(TAG, "Transmission - got OutputStream");

                if (data != null && localOS != null && !released) {
                    try {
                        localOS.write(data);
                        localOS.flush();
                        data = null;

                        ThreadLog.d(TAG, "Transmission - Data sent OK");

                        Thread.sleep(450);

                    } catch (IOException e) {
                        ThreadLog.e(TAG, "Transmission - Data sent ERROR - "+e.getMessage()+".   Try reconnect");
                        //---  RECONNECT!!!  ---
                        localOS = null; //Reset connection!
                        reconnectAfterFailure(Thread.currentThread().getName(), e);
                    } catch (InterruptedException ignore) {
                        Thread.currentThread().interrupt();
                    }
                }

            }// Top-level thread cycle

            ThreadLog.e(TAG, "---------- Thread finished -----------");

        }//run()
    }

    private class ReceivingThread extends Thread {

        public ReceivingThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            ThreadLog.d(TAG, "---------- Thread started -----------");
            InputStream localIS = null;
            while(!released) {

                //--- get OutputStream safely ---
                if (localIS == null) {
                    synchronized (connectorLock) {
                        while (!dataConnectionReady) {
                            try {
                                connectorLock.wait();
                            } catch (InterruptedException e) {
                                if (released) {
                                    Thread.currentThread().interrupt();
                                    break;
                                }
                            }
                        }
                        localIS = iStream;
                    }
                }

                /*if (localIS != null && !released) {
                    byte[] buffer = new byte[16];
                    int nBytes;
                    while(true) {
                        try {
                            nBytes = localIS.read(buffer);
                            ThreadLog.d(TAG, nBytes+" bytes received");
                        } catch (IOException e) {

                            ThreadLog.e(TAG, "Receiving - Data sent ERROR - "+e.getMessage()+".   Try reconnect");
                            localIS = null;
                            reconnectAfterFailure(Thread.currentThread().getName(), e);
                            break;
                        }
                    }
                }*/

                if (localIS != null && !released) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);

                    try {
                        int symb;
                        byte b_1=0, b_2=0;
                        while ((symb = localIS.read()) >= 0 && !released) {
                            //ThreadLog.e(TAG, "Got character - "+(char)symb);
                            b_2 = b_1;
                            b_1 = (byte)symb;
                            bos.write(symb);
                            if ((b_2 == 0x0D && b_1 == 0x0A)) {
                                byte[] data = bos.toByteArray();
                                String textData = new String(data, 0, data.length-2);
                                bos.reset();
                                synchronized (rcvListeners) {
                                    for (OnTextDataReceivedListener rsl : rcvListeners) {
                                        rsl.onReceive(textData);
                                    }
                                }
                            }
                        }
                        if (!released) {
                            throw new IOException("Input thread ends");
                        }
                    } catch (IOException e) {
                        ThreadLog.e(TAG, "Receiving - Data sent ERROR - "+e.getMessage()+".   Try reconnect");
                        localIS = null;
                        reconnectAfterFailure(Thread.currentThread().getName(), e);
                    } finally {
                        BtUtils.silentlyCloseCloseable(bos);
                    }

                }

            }
            ThreadLog.e(TAG, "---------- Thread finished -----------");
        }
    }

}


text:
This is an ever-changing time-suck that I use for experiments and such.

Built with plain ol' HTML and CSS (which, btw was a breath of fresh air...).


text:
var domActions = {
    fill: function (opts) {
        return this.sendKeys(opts.selector, opts.text, {reset: true});
    },
    click: function (opts) {
        return this.click(opts.selector);
    }
};

module.exports = function (params, timeoutDuration) {
    log('dom action', params.do, params.selector, 'INFO_BAR');
    if (params.selector && params.do) {
        var timeout = params.timeout !== undefined ?
            params.timeout : timeoutDuration;

        log('waiting for', params.selector, 'INFO_BAR');
        return this.waitUntilVisible(params.selector, function () {
            log('got', params.selector, 'SUCCESS');

            if (domActions[params.do]) {
                return domActions[params.do].call(this, params);
            }
            log('no dom action found for ' + params.do, 'ERROR');
            throw new Error('no dom action');

        }, function () {
            log('timeout, can\'t load dom', params.selector, 'WARNING');
        }, timeout);
    }
    throw new Error('missing params');
};


text:
require 'spec_helper'

describe "sessions/new.html.erb" do
  before(:each) do
    assign(:session, stub_model(Session,
      :new_record? => true
    ))
  end

  it "renders new session form" do
    render

    rendered.should have_selector("form", :action => sessions_path, :method => "post") do |form|
    end
  end
end


text:
var log4js = require('log4js');

module.exports = function(name) {
  var name = name || 'default';

  return log4js.getLogger(name);
}


text:
/*
VULKAN_SAMPLE_SHORT_DESCRIPTION
enumerate physical devices
*/

#include <cassert>
#include <cstdlib>
#include <util_init.hpp>

int sample_main(int argc, char *argv[]) {
    struct sample_info info = {};
    init_global_layer_properties(info);
    init_instance(info, "vulkansamples_enumerate");

    /* VULKAN_KEY_START */

    uint32_t gpu_count = 1;
    VkResult U_ASSERT_ONLY res =
        vkEnumeratePhysicalDevices(info.inst, &gpu_count, NULL);
    assert(gpu_count);
    info.gpus.resize(gpu_count);
    res = vkEnumeratePhysicalDevices(info.inst, &gpu_count, info.gpus.data());
    assert(!res && gpu_count >= 1);

    /* VULKAN_KEY_END */

    vkDestroyInstance(info.inst, NULL);

    return 0;
}


text:
//Apache2, 2017, WinterDev
//Apache2, 2009, griffm, FO.NET
namespace Fonet.Fo.Properties
{
    internal class VerticalAlign
    {
        public const int BASELINE = Constants.BASELINE;

        public const int MIDDLE = Constants.MIDDLE;

        public const int SUB = Constants.SUB;

        public const int SUPER = Constants.SUPER;

        public const int TEXT_TOP = Constants.TEXT_TOP;

        public const int TEXT_BOTTOM = Constants.TEXT_BOTTOM;

        public const int TOP = Constants.TOP;

        public const int BOTTOM = Constants.BOTTOM;

    }
}


text:
package disk

import (
	"strings"

	bosherr "github.com/cloudfoundry/bosh-agent/internal/github.com/cloudfoundry/bosh-utils/errors"
	boshsys "github.com/cloudfoundry/bosh-agent/internal/github.com/cloudfoundry/bosh-utils/system"
)

type procMountsSearcher struct {
	fs boshsys.FileSystem
}

func NewProcMountsSearcher(fs boshsys.FileSystem) MountsSearcher {
	return procMountsSearcher{fs}
}

func (s procMountsSearcher) SearchMounts() ([]Mount, error) {
	var mounts []Mount

	mountInfo, err := s.fs.ReadFileString("/proc/mounts")
	if err != nil {
		return mounts, bosherr.WrapError(err, "Reading /proc/mounts")
	}

	for _, mountEntry := range strings.Split(mountInfo, "\n") {
		if mountEntry == "" {
			continue
		}

		mountFields := strings.Fields(mountEntry)

		mounts = append(mounts, Mount{
			PartitionPath: mountFields[0],
			MountPoint:    mountFields[1],
		})
	}

	return mounts, nil
}


text:
<?php namespace controllers;
use core\view as View,
    \core\Model as Model;

class Product extends \core\controller{

    private $productModel;

	public function __construct(Model $productModel){
		parent::__construct();
        $this->productModel = $productModel;
	}

	public function index(){
	    var_dump($this->getProducts());
	}

	public function getProducts(){
		return $this->productModel->getProducts();
	}

}


text:
package org.apache.olingo.server.core.uri.parser;

/** Exception thrown during URI parsing in cases where an URI part is invalid according to the Entity Data Model. */
public class UriParserSemanticException extends UriParserException {

  private static final long serialVersionUID = 3850285860949809622L;

  public static enum MessageKeys implements MessageKey {
    /** parameters: function-import name, function parameters */
    FUNCTION_NOT_FOUND,
    /** parameter: resource part */
    RESOURCE_PART_ONLY_FOR_TYPED_PARTS,
    /** parameter: resource part */
    RESOURCE_PART_MUST_BE_PRECEDED_BY_STRUCTURAL_TYPE,
    /** parameter: property name */
    PROPERTY_AFTER_COLLECTION,
    /** parameters: type name, property name */
    PROPERTY_NOT_IN_TYPE,
    /** parameters: type name, property name */
    EXPRESSION_PROPERTY_NOT_IN_TYPE,
    /** parameter: property name */
    UNKNOWN_PROPERTY_TYPE,
    /** parameter: type filter */
    INCOMPATIBLE_TYPE_FILTER,
    /** parameters: previous type filter, last type filter */
    TYPE_FILTER_NOT_CHAINABLE,
    /** parameter: type filter */
    PREVIOUS_PART_NOT_TYPED,
    /** parameter: type */
    FUNCTION_PARAMETERS_EXPECTED,
    /** parameter: resource part */
    UNKNOWN_PART,
    /** parameter: expression */
    ONLY_FOR_TYPED_PARTS,
    /** parameter: entity type name */
    UNKNOWN_ENTITY_TYPE,
    /** parameter: expression */
    ONLY_FOR_COLLECTIONS,
    /** parameter: expression */
    ONLY_FOR_ENTITY_TYPES,
    /** parameter: expression */
    ONLY_FOR_STRUCTURAL_TYPES,
    /** parameter: expression */
    ONLY_FOR_TYPED_PROPERTIES,
    /** parameter: value */
    INVALID_KEY_VALUE,
    PARAMETERS_LIST_ONLY_FOR_TYPED_PARTS,
    /** parameters: expected number, actual number */
    WRONG_NUMBER_OF_KEY_PROPERTIES,
    NOT_ENOUGH_REFERENTIAL_CONSTRAINTS,
    KEY_NOT_ALLOWED,
    RESOURCE_PATH_NOT_TYPED,
    ONLY_SIMPLE_AND_COMPLEX_PROPERTIES_IN_SELECT,
    COMPLEX_PROPERTY_OF_ENTITY_TYPE_EXPECTED,
    NOT_FOR_ENTITY_TYPE,
    PREVIOUS_PART_TYPED,
    /** parameter: resource_name */
    RESOURCE_NOT_FOUND;

    @Override
    public String getKey() {
      return name();
    }
  }

  public UriParserSemanticException(final String developmentMessage, final MessageKey messageKey,
      final String... parameters) {
    super(developmentMessage, messageKey, parameters);
  }

  public UriParserSemanticException(final String developmentMessage, final Throwable cause,
      final MessageKey messageKey,
      final String... parameters) {
    super(developmentMessage, cause, messageKey, parameters);
  }
}


text:
package com.ashish.anylist;

import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class ListElementActivity extends ListActivity
{

	private ArrayAdapter<ListElement> listElement;
	private DBHelper db;
	private Context context;
	private int list_id;
	private String list_name;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setTitle("Any List");
		overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_left);
		setContentView(R.layout.activity_list_element);
		context=this;

		list_id = getIntent().getExtras().getInt("list_id");
		list_name = getIntent().getExtras().getString("list_name");

		TextView text = (TextView) findViewById(R.id.listname);
		text.setText(list_name);

		db = new DBHelper(getApplicationContext());
        listElement = new ArrayAdapter<ListElement>(this, android.R.layout.simple_list_item_1,
                android.R.id.text1, db.fetchAllListElements(list_id));
        setListAdapter(listElement);
        db.close();

        ListView listView = getListView();
        // Create a ListView-specific touch listener. ListViews are given special treatment because
        // by default they handle touches for their list items... i.e. they're in charge of drawing
        // the pressed state (the list selector), handling list item clicks, etc.
        SwipeDismissListViewTouchListener touchListener =
                new SwipeDismissListViewTouchListener(
                        listView,
                        new SwipeDismissListViewTouchListener.DismissCallbacks()
                        {
                            @Override
                            public boolean canDismiss(int position)
                            {
                                return true;
                            }

                            @Override
                            public void onDismiss(ListView listView, int[] reverseSortedPositions)
                            {
                            	//Delete list element on swipe
                            	String temp ="";
                                for (int position : reverseSortedPositions) {
                                	db=new DBHelper(context);
                                	db.deleteListElement(listElement.getItem(position).get_id());
                                	temp = listElement.getItem(position).get_element();
                                }
                                listElement.clear();
                                listElement.addAll(db.fetchAllListElements(list_id));
                                listElement.notifyDataSetChanged();
                                db.close();
                	            Toast.makeText(context,"Deleted list element " + temp,Toast.LENGTH_SHORT).show();
                            }
                        });
        listView.setOnTouchListener(touchListener);
        // Setting this scroll listener is required to ensure that during ListView scrolling,
        // we don't look for swipes.
        listView.setOnScrollListener(touchListener.makeScrollListener());

        this.getListView().setLongClickable(true);
        this.getListView().setOnItemLongClickListener(new OnItemLongClickListener()
        {
             public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id)
             {
            	 //On long press open alert box to modify list element name
            	 final ListElement le = (ListElement)getListAdapter().getItem(position);
                 final EditText input = new EditText(context);
                 input.setText(le.toString());

         		new AlertDialog.Builder(context)
         	    .setTitle("Modify List Element")
         	    .setMessage("")
         	    .setView(input)
         	    .setPositiveButton("Ok", new DialogInterface.OnClickListener()
         	    {
         	        public void onClick(DialogInterface dialog, int whichButton)
         	        {
         	            Editable name = input.getText();
         	            le.set_elem(name.toString());
         	            db = new DBHelper(context);
         	            db.updateListElement(le);
         	            listElement.clear();
         	            listElement.addAll(db.fetchAllListElements(list_id));
         	            listElement.notifyDataSetChanged();
         	            db.close();
         	            Toast.makeText(context,"Updated element name to " + name.toString(),Toast.LENGTH_SHORT).show();
         	        }
         	    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener()
         	    {
         	        public void onClick(DialogInterface dialog, int whichButton)
         	        {
         	            // Do nothing.
         	        }
         	    }).show();
                 return true;
             }
         });

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.list_element, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
	    // Handle presses on the action bar items
	    switch (item.getItemId())
	    {
	        case R.id.action_add:
	            openAddListElement();
	            return true;

	        case R.id.action_home:
	        	Intent i = new Intent(getApplicationContext(), MainListActivity.class);
	            startActivity(i);
	            return true;

	        case R.id.action_about:
	        	Intent j = new Intent(getApplicationContext(), AboutActivity.class);
	            startActivity(j);
	            return true;

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

	public void openAddListElement()
	{
		//Open alert box to add new list element
		final EditText input = new EditText(this);

		new AlertDialog.Builder(this)
	    .setTitle("Enter List Element")
	    .setMessage("")
	    .setView(input)
	    .setPositiveButton("Ok", new DialogInterface.OnClickListener()
	    {
	        public void onClick(DialogInterface dialog, int whichButton)
	        {
	            Editable name = input.getText();
	            db = new DBHelper(getApplicationContext());
	            ListElement le = new ListElement(name.toString());
	            le.set_list_id(list_id);
	            db.createListElement(le);
	            listElement.clear();
	            listElement.addAll(db.fetchAllListElements(list_id));
	            listElement.notifyDataSetChanged();
	            db.close();
	            Toast.makeText(context,"Added new list element " + name.toString(),Toast.LENGTH_SHORT).show();
	        }
	    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener()
	    {
	        public void onClick(DialogInterface dialog, int whichButton)
	        {
	            // Do nothing.
	        }
	    }).show();
	}
}


text:
/**
 * Элемент пути.
 *
 * @author dew1983@mail.ru <Suvorov Andrey M.>
 */

Ext.define(
	'FBEditor.view.panel.main.props.body.path.el.El',
	{
		extend: 'Ext.Component',
		requires: [
			'FBEditor.view.panel.main.props.body.path.el.ElController'
		],

		controller: 'panel.props.body.path.el',
		xtype: 'panel-props-body-path-el',
		cls: 'panel-props-body-path-el',

		listeners: {
			click: {
				element: 'el',
				fn: 'onClick'
			}
		},

		/**
		 * @private
		 * @property {FBEditor.editor.element.AbstractElement} Модель элемента пути.
		 */
		focusEl: null,

		/**
		 * @private
		 * @property {FBEditor.view.panel.main.props.body.Body} Панель свойств.
		 */
		panelProps: null,

		constructor: function (data)
		{
			var me = this,
				focusEl = data.focusEl,
				name = focusEl.getName();

			me.focusEl = focusEl;
			me.html = '<span>' + name.toUpperCase() + '</span>';

			me.callParent(arguments);
		},

		/**
		 * Возвращает модель элемента пути.
		 * @return {FBEditor.editor.element.AbstractElement} Модель элемента пути.
		 */
		getFocusEl: function ()
		{
			return this.focusEl;
		},

		/**
		 * Возвращает панель свойств редактора текста.
		 * @return {FBEditor.view.panel.main.props.body.Body}
		 */
		getPanelProps: function ()
		{
			var me = this,
				panelProps;

			panelProps = me.panelProps || Ext.getCmp('panel-props-body');
			me.panelProps = panelProps;

			return panelProps
		}
	}
);


text:
<?php

namespace tests\codeception\frontend\functional;

use common\models\User;
use tests\codeception\frontend\FunctionalTester;
use tests\codeception\common\_pages\LoginPage;

/* @var $scenario \Codeception\Scenario */

$I = new \tests\codeception\frontend\Step\Functional\OperatorSteps($scenario);

$I->wantTo('ensure user management works');

$admin = $I->asAnAdmin();
$I->amGoingTo('create an user');
$I->visit('user/create');
$I->expectTo('see user form');
$user = $I->submitUserCreationForm();
$I->expectTo('see user was created successfully');
$I->see('User created successfully');
$I->seeUserInDatabase($user);
$user = $user->lastInserted();

$I->amGoingTo('see that the new user can login');
$I->logout();
$I->seeAmOnPage('site/login');
$I->login($user);
$I->expectTo('see tradeins page');
$I->see('Tradeins','h1');

$I->logout();
$I->asAnAdmin($admin);
$I->amGoingTo('change user password');
$newPass = 'asdf123';
$I->visit('user');
$I->click('a[href="/index-test.php?r=user%2Fupdate&id=' . $user->id . '"]');
$I->submitChangePasswordForm($newPass);
$I->click('#logout-link');
$I->amGoingTo('try to login with new password');
$I->login($user, $newPass);
$I->expectTo('see that user is logged');
$I->see($user->username);
$I->dontSeeLink('Login');

$I->amGoingTo('delete a user');
$I->logout();
$I->asAnAdmin();
$I->visit('user');
$I->see($user->username);
$I->click('a[href="/index-test.php?r=user%2Fdelete&id=' . $user->id . '"]');
$I->dontSee($user->username);


text:
package ErrorUtiles

import (
	"errors"
	"runtime/debug"
)

var (
	OUTPUT_STACK_ON_ERROR = false
)

type PanicError struct {
	error
	stack []byte
}

func (p *PanicError) Error() string {
	if p.stack == nil {
		return p.error.Error()
	}
	return p.error.Error() + "\n" + (string)(p.stack)
}

func NewPanicError(err error) error {
	if !OUTPUT_STACK_ON_ERROR {
		return &PanicError{
			err,
			nil,
		}
	}
	return &PanicError{
		err,
		debug.Stack(),
	}
}

func NewError(err string) error {
	if !OUTPUT_STACK_ON_ERROR {
		return &PanicError{
			errors.New(err),
			nil,
		}
	}
	return &PanicError{
		errors.New(err),
		debug.Stack(),
	}
}


text:
import {assertThrows} from './helpers.js';

contract('PatronageRegistry', function(accounts) {
  it("should not allow default sends", async function() {
    const registry = PatronageRegistry.deployed();
    const registrar = await registry.registrar();
    const other = accounts.find(function(a) { return a != registrar });
    const startingBalance = web3.eth.getBalance(registrar);
    await assertThrows(async () => {
      await web3.eth.sendTransaction({from: patron, to: address, value: donationAmount});
    });
    const endingBalance = web3.eth.getBalance(registrar);
    assert.equal(startingBalance.toString(), endingBalance.toString());
  });

  it("should allow the registrar to update registrar", async function() {
    const registry = PatronageRegistry.deployed();
    const originalRegistrar = await registry.registrar();
    const newRegistrar = accounts.find(function(a) { return a != originalRegistrar });
    await registry.updateRegistrar(newRegistrar, {from: originalRegistrar});
    assert.equal(newRegistrar, await registry.registrar());
  });

  it("shouldn't allow others to update the registrar", async function() {
    const registry = PatronageRegistry.deployed();
    const originalRegistrar = await registry.registrar();
    const newRegistrar = accounts.find(function(a) { return a != originalRegistrar });
    await assertThrows(async () => {
      await registry.updateRegistrar(newRegistrar, {from: newRegistrar});
    });
    assert.equal(originalRegistrar, await registry.registrar());
  });

  it("should allow the registrar to register a new name", async function() {
    const registry = PatronageRegistry.deployed();
    const username = 'user' + Math.floor(10000 * Math.random());
    const registrar = await registry.registrar();
    const payoutAddress = accounts.find(function(a) { return a != registrar; });
    await registry.registerUsername(username, payoutAddress, {from: registrar});
    const contractAddress = await registry.patronageContractForUsername.call(username);
    const patronage = Patronage.at(contractAddress);
    assert.equal(payoutAddress, await patronage.payoutAddress());
  });

  it("shouldn't allow a non-registrar to register a name", async function() {
    const registry = PatronageRegistry.deployed();
    const username = 'user' + Math.floor(10000 * Math.random());
    const registrar = await registry.registrar();
    const other = accounts.find(function(a) { return a != registrar });
    await assertThrows(async () => {
      await registry.registerUsername(username, other, {from: other});
    });
  });

  it("shouldn't allow the same name to be registered twice", async function() {
    const registry = PatronageRegistry.deployed();
    const username = 'user' + Math.floor(10000 * Math.random());
    const registrar = await registry.registrar();
    const payoutAddress = accounts.find(function(a) { return a != registrar; });
    await registry.registerUsername(username, payoutAddress, {from: registrar});
    const patronageAddress = await registry.patronageContractForUsername.call(username);
    const patronage = Patronage.at(patronageAddress);
    assert.equal(payoutAddress, await patronage.payoutAddress());
    const other = accounts.find(function(a) { return [registrar, payoutAddress].indexOf(a) == -1; });
    await assertThrows(async () => {
      await registry.registerUsername(username, other, {from: registrar});
    });
    assert.equal(payoutAddress, await patronage.payoutAddress());
  });

  it("should allow patronage owners to update payout address", async function() {
    const registry = PatronageRegistry.deployed();
    const username = 'user' + Math.floor(10000 * Math.random());
    const registrar = await registry.registrar();
    const payoutAddress = accounts.find(function(a) { return a != registrar; });
    await registry.registerUsername(username, payoutAddress, {from: registrar});
    const patronageAddress = await registry.patronageContractForUsername.call(username);
    const patronage = Patronage.at(patronageAddress);
    assert.equal(payoutAddress, await patronage.payoutAddress());
    const newPayoutAddress = accounts.find(function(a) {
      return [registrar, payoutAddress].indexOf(a) == -1;
    });
    await patronage.updatePayoutAddress(newPayoutAddress, {from: payoutAddress});
    assert.equal(newPayoutAddress, await patronage.payoutAddress());
  });

  it("shouldn't allow others to update payout address", async function() {
    const registry = PatronageRegistry.deployed();
    const username = 'user' + Math.floor(10000 * Math.random());
    const registrar = await registry.registrar();
    const payoutAddress = accounts.find(function(a) { return a != registrar; });
    await registry.registerUsername(username, payoutAddress, {from: registrar});
    const patronageAddress = await registry.patronageContractForUsername.call(username);
    const patronage = Patronage.at(patronageAddress);
    assert.equal(payoutAddress, await patronage.payoutAddress());
    const other = accounts.find(function(a) {
      return [registrar, payoutAddress].indexOf(a) == -1;
    });
    await assertThrows(async () => {
      await patronage.updatePayoutAddress(other, {from: registrar});
    });
    assert.equal(payoutAddress, await patronage.payoutAddress());
  });

  it("should not allow withdrawals if balance is zero", async function() {
    const registry = PatronageRegistry.deployed();
    const username = 'user' + Math.floor(10000 * Math.random());
    const registrar =  await registry.registrar();
    const payoutAddress = accounts.find(function(a) { return a != registrar; });
    await registry.registerUsername(username, payoutAddress, {from: registrar});
    const patronageAddress = await registry.patronageContractForUsername.call(username);
    const patronage = Patronage.at(patronageAddress);
    await assertThrows(async () => patronage.withdrawal());
  });

  it("should pay balance to shareholders and owner", async function() {
    const registry = PatronageRegistry.deployed();
    const username = 'user' + Math.floor(10000 * Math.random());
    const donationAmount = 10000;
    const registrar = await registry.registrar();
    const shareholders = await registry.shareholders();
    const payoutAddress = accounts.find(function(a) {
      return a != registrar && a != shareholders;
    });
    const payoutBalance = web3.eth.getBalance(payoutAddress);
    const shareholderBalance = web3.eth.getBalance(shareholders);
    await registry.registerUsername(username, payoutAddress, {from: registrar});
    const patronageAddress = await registry.patronageContractForUsername.call(username);
    const patronage = Patronage.at(patronageAddress);
    const patron = accounts.find(function(a) {
      return [registrar, payoutAddress, shareholders].indexOf(a) == -1;
    });
    await web3.eth.sendTransaction({from: patron, to: patronageAddress, value: donationAmount});
    assert.equal(donationAmount, web3.eth.getBalance(patronageAddress).toNumber());
    await patronage.withdrawal({from: registrar});
    assert.equal(0, web3.eth.getBalance(patronageAddress).toNumber());
    assert.equal(payoutBalance.add(9000).toString(), web3.eth.getBalance(payoutAddress).toString());
    assert.equal(shareholderBalance.add(1000).toString(), web3.eth.getBalance(shareholders).toString());
  });
});


text:
A simple, no setup required, secure tool for interacting with the unofficial PokemonGo API.

Right now it's in heavy development, so there isn't a pre-built version yet.


text:
package org.spongepowered.api.block.tileentity;

import org.spongepowered.api.data.manipulator.mutable.tileentity.EndGatewayData;

/**
 * Represents an End Gateway.
 *
 * @see EndGatewayData
 */
public interface EndGateway extends TileEntity {

    /**
     * Gets a copy of the {@link EndGatewayData} containing all available
     * data this {@link EndGateway} has.
     *
     * @return A copy of the end gateway data
     */
    default EndGatewayData getEndGatewayData() {
        return this.get(EndGatewayData.class).get();
    }

}