file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
contact-form.component.ts | import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlertsService } from '@jaspero/ng2-alerts';
import { AppStateService } from '../../../services/app-state.service';
import { ApiClient, Contact, Address, UpdateContactRequest, LookupEntry, Country } from '../../../services/incontrl-apiclient';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
import { LookupsService } from '../../../services/lookups.service';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['../forms.components.scss']
})
export class ContactFormComponent implements OnInit, OnDestroy {
countryCtrl: FormControl;
filteredCountries: Observable<any[]>;
subscription_key: any = null;
subscription_id: any = null;
private _bak: any = null;
private _model: any = null;
public readonly = true;
private busy = false;
public countries = [];
params_sub: any = null;
myControl: FormControl = new FormControl();
@Output() model_changed: EventEmitter<any> = new EventEmitter<any>();
@Input()
public set model(value: Contact) {
this._model = value;
}
public get model(): Contact { return this._model; }
constructor(private alertsService: AlertsService, private route: ActivatedRoute,
private appState: AppStateService,
private apiClient: ApiClient, private lookups: LookupsService) {
this.model = new Contact();
this.model.address = new Address();
this.countryCtrl = new FormControl();
this.filteredCountries = this.countryCtrl.valueChanges
.startWith(null)
.map(country => country ? this.filterCountries(country) : this.countries.slice());
}
filterCountries(name: string) {
return this.countries.filter(country =>
country.description.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
ngOnInit() {
this.lookups.countries.subscribe((items) => {
this.countries = items;
});
this.params_sub = this.route.parent.params.subscribe((params) => {
this.subscription_key = params['subscription-alias'];
this.appState.getSubscriptionByKey(this.subscription_key)
.subscribe((sub) => {
this.subscription_id = sub.id;
const contact = sub.data.contact.clone();
if (null == contact.address) {
contact.address = new Address();
}
this.model = contact;
});
});
}
ngOnDestroy() {
this.params_sub.unsubscribe();
}
toggle_edit_mode() {
this.readonly = !this.readonly;
if (!this.readonly) {
this.bak(this.model);
}
}
private bak(value: any) {
this._bak = value.clone();
}
cancel() {
this.readonly = true;
this.model = this._bak; | displayCountryFn(country: LookupEntry): string {
return country ? country.description : '';
}
save() {
this.readonly = true;
const request: UpdateContactRequest = new UpdateContactRequest();
request.firstName = this.model.firstName;
request.lastName = this.model.lastName;
request.email = this.model.email;
request.phone1 = this.model.phone1;
request.phone2 = this.model.phone2;
request.skype = this.model.skype;
request.notes = this.model.notes;
request.address = this.model.address;
this.apiClient.updateSubscriptionContact(this.subscription_id, request).subscribe((company) => {
// create a new backup copy
this.bak(this.model);
this.appState.getSubscriptionByKey(this.subscription_key).subscribe((sub) => {
sub.data.contact = this.model;
this.alertsService.create('success', 'Η αποθήκευση των αλλαγών σας έγινε με επιτυχία!');
});
}, (error) => {
console.log(error);
this.alertsService.create('error', 'Σφάλμα κατα την αποθήκευση! Μύνημα συστήματος: ' + error);
// keep on editing...
this.readonly = false;
});
}
} | }
| random_line_split |
contact-form.component.ts | import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlertsService } from '@jaspero/ng2-alerts';
import { AppStateService } from '../../../services/app-state.service';
import { ApiClient, Contact, Address, UpdateContactRequest, LookupEntry, Country } from '../../../services/incontrl-apiclient';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
import { LookupsService } from '../../../services/lookups.service';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['../forms.components.scss']
})
export class ContactFormComponent implements OnInit, OnDestroy {
countryCtrl: FormControl;
filteredCountries: Observable<any[]>;
subscription_key: any = null;
subscription_id: any = null;
private _bak: any = null;
private _model: any = null;
public readonly = true;
private busy = false;
public countries = [];
params_sub: any = null;
myControl: FormControl = new FormControl();
@Output() model_changed: EventEmitter<any> = new EventEmitter<any>();
@Input()
public set model(value: Contact) |
public get model(): Contact { return this._model; }
constructor(private alertsService: AlertsService, private route: ActivatedRoute,
private appState: AppStateService,
private apiClient: ApiClient, private lookups: LookupsService) {
this.model = new Contact();
this.model.address = new Address();
this.countryCtrl = new FormControl();
this.filteredCountries = this.countryCtrl.valueChanges
.startWith(null)
.map(country => country ? this.filterCountries(country) : this.countries.slice());
}
filterCountries(name: string) {
return this.countries.filter(country =>
country.description.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
ngOnInit() {
this.lookups.countries.subscribe((items) => {
this.countries = items;
});
this.params_sub = this.route.parent.params.subscribe((params) => {
this.subscription_key = params['subscription-alias'];
this.appState.getSubscriptionByKey(this.subscription_key)
.subscribe((sub) => {
this.subscription_id = sub.id;
const contact = sub.data.contact.clone();
if (null == contact.address) {
contact.address = new Address();
}
this.model = contact;
});
});
}
ngOnDestroy() {
this.params_sub.unsubscribe();
}
toggle_edit_mode() {
this.readonly = !this.readonly;
if (!this.readonly) {
this.bak(this.model);
}
}
private bak(value: any) {
this._bak = value.clone();
}
cancel() {
this.readonly = true;
this.model = this._bak;
}
displayCountryFn(country: LookupEntry): string {
return country ? country.description : '';
}
save() {
this.readonly = true;
const request: UpdateContactRequest = new UpdateContactRequest();
request.firstName = this.model.firstName;
request.lastName = this.model.lastName;
request.email = this.model.email;
request.phone1 = this.model.phone1;
request.phone2 = this.model.phone2;
request.skype = this.model.skype;
request.notes = this.model.notes;
request.address = this.model.address;
this.apiClient.updateSubscriptionContact(this.subscription_id, request).subscribe((company) => {
// create a new backup copy
this.bak(this.model);
this.appState.getSubscriptionByKey(this.subscription_key).subscribe((sub) => {
sub.data.contact = this.model;
this.alertsService.create('success', 'Η αποθήκευση των αλλαγών σας έγινε με επιτυχία!');
});
}, (error) => {
console.log(error);
this.alertsService.create('error', 'Σφάλμα κατα την αποθήκευση! Μύνημα συστήματος: ' + error);
// keep on editing...
this.readonly = false;
});
}
}
| {
this._model = value;
} | identifier_body |
contact-form.component.ts | import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlertsService } from '@jaspero/ng2-alerts';
import { AppStateService } from '../../../services/app-state.service';
import { ApiClient, Contact, Address, UpdateContactRequest, LookupEntry, Country } from '../../../services/incontrl-apiclient';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
import { LookupsService } from '../../../services/lookups.service';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['../forms.components.scss']
})
export class ContactFormComponent implements OnInit, OnDestroy {
countryCtrl: FormControl;
filteredCountries: Observable<any[]>;
subscription_key: any = null;
subscription_id: any = null;
private _bak: any = null;
private _model: any = null;
public readonly = true;
private busy = false;
public countries = [];
params_sub: any = null;
myControl: FormControl = new FormControl();
@Output() model_changed: EventEmitter<any> = new EventEmitter<any>();
@Input()
public set model(value: Contact) {
this._model = value;
}
public get model(): Contact { return this._model; }
constructor(private alertsService: AlertsService, private route: ActivatedRoute,
private appState: AppStateService,
private apiClient: ApiClient, private lookups: LookupsService) {
this.model = new Contact();
this.model.address = new Address();
this.countryCtrl = new FormControl();
this.filteredCountries = this.countryCtrl.valueChanges
.startWith(null)
.map(country => country ? this.filterCountries(country) : this.countries.slice());
}
filterCountries(name: string) {
return this.countries.filter(country =>
country.description.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
ngOnInit() {
this.lookups.countries.subscribe((items) => {
this.countries = items;
});
this.params_sub = this.route.parent.params.subscribe((params) => {
this.subscription_key = params['subscription-alias'];
this.appState.getSubscriptionByKey(this.subscription_key)
.subscribe((sub) => {
this.subscription_id = sub.id;
const contact = sub.data.contact.clone();
if (null == contact.address) {
contact.address = new Address();
}
this.model = contact;
});
});
}
ngOnDestroy() {
this.params_sub.unsubscribe();
}
toggle_edit_mode() {
this.readonly = !this.readonly;
if (!this.readonly) |
}
private bak(value: any) {
this._bak = value.clone();
}
cancel() {
this.readonly = true;
this.model = this._bak;
}
displayCountryFn(country: LookupEntry): string {
return country ? country.description : '';
}
save() {
this.readonly = true;
const request: UpdateContactRequest = new UpdateContactRequest();
request.firstName = this.model.firstName;
request.lastName = this.model.lastName;
request.email = this.model.email;
request.phone1 = this.model.phone1;
request.phone2 = this.model.phone2;
request.skype = this.model.skype;
request.notes = this.model.notes;
request.address = this.model.address;
this.apiClient.updateSubscriptionContact(this.subscription_id, request).subscribe((company) => {
// create a new backup copy
this.bak(this.model);
this.appState.getSubscriptionByKey(this.subscription_key).subscribe((sub) => {
sub.data.contact = this.model;
this.alertsService.create('success', 'Η αποθήκευση των αλλαγών σας έγινε με επιτυχία!');
});
}, (error) => {
console.log(error);
this.alertsService.create('error', 'Σφάλμα κατα την αποθήκευση! Μύνημα συστήματος: ' + error);
// keep on editing...
this.readonly = false;
});
}
}
| {
this.bak(this.model);
} | conditional_block |
unused-macro.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(decl_macro)]
#![deny(unused_macros)]
// Most simple case
macro unused { //~ ERROR: unused macro definition
() => {}
}
#[allow(unused_macros)]
mod bar {
// Test that putting the #[deny] close to the macro's definition
// works.
#[deny(unused_macros)]
macro unused { //~ ERROR: unused macro definition
() => {}
}
}
mod boo {
pub(crate) macro unused { //~ ERROR: unused macro definition
() => {}
}
}
fn main() | {} | identifier_body | |
unused-macro.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(decl_macro)]
#![deny(unused_macros)]
// Most simple case
macro unused { //~ ERROR: unused macro definition
() => {}
}
#[allow(unused_macros)]
mod bar {
// Test that putting the #[deny] close to the macro's definition
// works.
#[deny(unused_macros)]
macro unused { //~ ERROR: unused macro definition
() => {}
}
}
mod boo {
pub(crate) macro unused { //~ ERROR: unused macro definition
() => {}
}
}
fn | () {}
| main | identifier_name |
unused-macro.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(decl_macro)]
#![deny(unused_macros)]
// Most simple case
macro unused { //~ ERROR: unused macro definition
() => {}
}
#[allow(unused_macros)] | // Test that putting the #[deny] close to the macro's definition
// works.
#[deny(unused_macros)]
macro unused { //~ ERROR: unused macro definition
() => {}
}
}
mod boo {
pub(crate) macro unused { //~ ERROR: unused macro definition
() => {}
}
}
fn main() {} | mod bar { | random_line_split |
config.js | // Don't commit this file to your public repos. This config is for first-run
//
exports.creds = {
returnURL: 'http://localhost:3000/auth/openid/return',
identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration', // For using Microsoft you should never need to change this.
clientID: '02efe21f-6d15-4026-8872-9fcd7d789602', //this POC
clientSecret: 'VO474u6v5or+S4h=', //this POC
//clientID: '01d83438-0130-472a-a1db-28fffee476f9', //silverrockweb
//clientSecret: 'B3|$[N<-(b.0219T', //silverrockweb
skipUserProfile: true, // for AzureAD should be set to true.
responseType: 'id_token', // for login only flows use id_token. For accessing resources use `id_token code` | responseMode: 'form_post', // For login only flows we should have token passed back to us in a POST
//scope: ['email', 'profile'] // additional scopes you may wish to pass
tenantName: 'argoadb2ctest.onmicrosoft.com'
}; | random_line_split | |
Display.ts | import { AreasFaker } from "./Bootstrapping/AreasFaker";
import { IClassNames } from "./Bootstrapping/ClassNames";
import { ICreateElement } from "./Bootstrapping/CreateElement";
import { IGetAvailableContainerHeight } from "./Bootstrapping/GetAvailableContainerHeight";
import { IStyles } from "./Bootstrapping/Styles";
import { IUserWrappr } from "./IUserWrappr";
import { IMenuSchema } from "./Menus/MenuSchemas";
import { getAbsoluteSizeInContainer, IAbsoluteSizeSchema, IRelativeSizeSchema } from "./Sizing";
/**
* Creates contents for a size.
*
* @param size Bounding size to create contents in.
* @param userWrapper Containing IUserWrappr holding this display.
* @returns Contents at the size.
*/
export type ICreateContents = (size: IAbsoluteSizeSchema, userWrapper: IUserWrappr) => Element;
/**
* Menu and content elements, once creatd.
*/
interface ICreatedElements {
/**
* Contains the created contents.
*/
contentArea: HTMLElement;
/**
* Contains the real or fake menu elements.
*/
menuArea: HTMLElement;
}
/**
* Dependencies to initialize a new Display.
*/
export interface IDisplayDependencies {
/**
* Class names to use for display elements.
*/
classNames: IClassNames;
/**
* Container that will contain the contents and menus.
*/
container: HTMLElement;
/**
* Creates a new HTML element.
*/
createElement: ICreateElement;
/**
* Creates contents within a container.
*/
createContents: ICreateContents;
/**
* Gets how much height is available to size a container.
*/
getAvailableContainerHeight: IGetAvailableContainerHeight;
/**
* Menus to create inside of the view.
*/
menus: IMenuSchema[];
/**
* Styles to use for display elements.
*/
styles: IStyles;
/**
* Containing IUserWrappr holding this display.
*/
userWrapper: IUserWrappr;
}
/**
* Contains contents and menus within a container.
*/
export class Display {
/**
* Dependencies used for initialization.
*/
private readonly dependencies: IDisplayDependencies;
/**
* Creates placeholder menu titles before a real menu is created.
*/
private readonly areasFaker: AreasFaker;
/**
* Menu and content elements, once created.
*/
private createdElements: ICreatedElements | undefined;
/**
* Initializes a new instance of the Display class.
*
* @param dependencies Dependencies to be used for initialization.
*/
public constructor(dependencies: IDisplayDependencies) |
/**
* Creates initial contents and fake menus.
*
* @param requestedSize Size of the contents.
* @returns A Promise for the actual size of the contents.
*/
public async resetContents(requestedSize: IRelativeSizeSchema): Promise<IAbsoluteSizeSchema> {
if (this.createdElements !== undefined) {
this.dependencies.container.removeChild(this.createdElements.contentArea);
this.dependencies.container.removeChild(this.createdElements.menuArea);
}
const availableContainerSize: IAbsoluteSizeSchema = this.getAvailableContainerSize(this.dependencies.container);
const containerSize: IAbsoluteSizeSchema = getAbsoluteSizeInContainer(availableContainerSize, requestedSize);
const { menuArea, menuSize } = await this.areasFaker.createAndAppendMenuArea(containerSize);
const { contentSize, contentArea } = this.areasFaker.createContentArea(containerSize, menuSize);
this.dependencies.container.insertBefore(contentArea, menuArea);
contentArea.appendChild(this.dependencies.createContents(contentSize, this.dependencies.userWrapper));
this.createdElements = { contentArea, menuArea };
return containerSize;
}
/**
* @returns The container holding the contents and menus.
*/
public getContainer(): HTMLElement {
return this.dependencies.container;
}
/**
* Gets how much space is available to size a container.
*
* @param container Container element.
* @returns How much space is available to size the container.
*/
private getAvailableContainerSize(container: HTMLElement): IAbsoluteSizeSchema {
const availableHeight = this.dependencies.getAvailableContainerHeight();
return {
height: availableHeight - Math.round(container.offsetTop),
width: Math.round(container.clientWidth),
};
}
}
| {
this.dependencies = dependencies;
this.areasFaker = new AreasFaker(this.dependencies);
} | identifier_body |
Display.ts | import { AreasFaker } from "./Bootstrapping/AreasFaker";
import { IClassNames } from "./Bootstrapping/ClassNames";
import { ICreateElement } from "./Bootstrapping/CreateElement";
import { IGetAvailableContainerHeight } from "./Bootstrapping/GetAvailableContainerHeight";
import { IStyles } from "./Bootstrapping/Styles";
import { IUserWrappr } from "./IUserWrappr";
import { IMenuSchema } from "./Menus/MenuSchemas";
import { getAbsoluteSizeInContainer, IAbsoluteSizeSchema, IRelativeSizeSchema } from "./Sizing";
/**
* Creates contents for a size.
*
* @param size Bounding size to create contents in.
* @param userWrapper Containing IUserWrappr holding this display.
* @returns Contents at the size.
*/
export type ICreateContents = (size: IAbsoluteSizeSchema, userWrapper: IUserWrappr) => Element;
/**
* Menu and content elements, once creatd.
*/
interface ICreatedElements {
/**
* Contains the created contents.
*/
contentArea: HTMLElement;
/**
* Contains the real or fake menu elements.
*/
menuArea: HTMLElement;
}
/**
* Dependencies to initialize a new Display.
*/
export interface IDisplayDependencies {
/**
* Class names to use for display elements.
*/
classNames: IClassNames;
/**
* Container that will contain the contents and menus.
*/
container: HTMLElement;
/**
* Creates a new HTML element.
*/
createElement: ICreateElement;
/**
* Creates contents within a container.
*/
createContents: ICreateContents;
/**
* Gets how much height is available to size a container.
*/
getAvailableContainerHeight: IGetAvailableContainerHeight;
/**
* Menus to create inside of the view.
*/
menus: IMenuSchema[];
/**
* Styles to use for display elements.
*/
styles: IStyles;
/**
* Containing IUserWrappr holding this display.
*/
userWrapper: IUserWrappr;
}
/**
* Contains contents and menus within a container.
*/
export class | {
/**
* Dependencies used for initialization.
*/
private readonly dependencies: IDisplayDependencies;
/**
* Creates placeholder menu titles before a real menu is created.
*/
private readonly areasFaker: AreasFaker;
/**
* Menu and content elements, once created.
*/
private createdElements: ICreatedElements | undefined;
/**
* Initializes a new instance of the Display class.
*
* @param dependencies Dependencies to be used for initialization.
*/
public constructor(dependencies: IDisplayDependencies) {
this.dependencies = dependencies;
this.areasFaker = new AreasFaker(this.dependencies);
}
/**
* Creates initial contents and fake menus.
*
* @param requestedSize Size of the contents.
* @returns A Promise for the actual size of the contents.
*/
public async resetContents(requestedSize: IRelativeSizeSchema): Promise<IAbsoluteSizeSchema> {
if (this.createdElements !== undefined) {
this.dependencies.container.removeChild(this.createdElements.contentArea);
this.dependencies.container.removeChild(this.createdElements.menuArea);
}
const availableContainerSize: IAbsoluteSizeSchema = this.getAvailableContainerSize(this.dependencies.container);
const containerSize: IAbsoluteSizeSchema = getAbsoluteSizeInContainer(availableContainerSize, requestedSize);
const { menuArea, menuSize } = await this.areasFaker.createAndAppendMenuArea(containerSize);
const { contentSize, contentArea } = this.areasFaker.createContentArea(containerSize, menuSize);
this.dependencies.container.insertBefore(contentArea, menuArea);
contentArea.appendChild(this.dependencies.createContents(contentSize, this.dependencies.userWrapper));
this.createdElements = { contentArea, menuArea };
return containerSize;
}
/**
* @returns The container holding the contents and menus.
*/
public getContainer(): HTMLElement {
return this.dependencies.container;
}
/**
* Gets how much space is available to size a container.
*
* @param container Container element.
* @returns How much space is available to size the container.
*/
private getAvailableContainerSize(container: HTMLElement): IAbsoluteSizeSchema {
const availableHeight = this.dependencies.getAvailableContainerHeight();
return {
height: availableHeight - Math.round(container.offsetTop),
width: Math.round(container.clientWidth),
};
}
}
| Display | identifier_name |
Display.ts | import { AreasFaker } from "./Bootstrapping/AreasFaker";
import { IClassNames } from "./Bootstrapping/ClassNames";
import { ICreateElement } from "./Bootstrapping/CreateElement";
import { IGetAvailableContainerHeight } from "./Bootstrapping/GetAvailableContainerHeight";
import { IStyles } from "./Bootstrapping/Styles";
import { IUserWrappr } from "./IUserWrappr";
import { IMenuSchema } from "./Menus/MenuSchemas";
import { getAbsoluteSizeInContainer, IAbsoluteSizeSchema, IRelativeSizeSchema } from "./Sizing";
/**
* Creates contents for a size.
*
* @param size Bounding size to create contents in.
* @param userWrapper Containing IUserWrappr holding this display.
* @returns Contents at the size.
*/
export type ICreateContents = (size: IAbsoluteSizeSchema, userWrapper: IUserWrappr) => Element;
/**
* Menu and content elements, once creatd.
*/
interface ICreatedElements {
/**
* Contains the created contents.
*/
contentArea: HTMLElement;
/**
* Contains the real or fake menu elements.
*/
menuArea: HTMLElement;
}
/**
* Dependencies to initialize a new Display.
*/
export interface IDisplayDependencies {
/**
* Class names to use for display elements.
*/
classNames: IClassNames;
/**
* Container that will contain the contents and menus.
*/
container: HTMLElement;
/**
* Creates a new HTML element.
*/
createElement: ICreateElement;
/**
* Creates contents within a container.
*/
createContents: ICreateContents;
/**
* Gets how much height is available to size a container.
*/
getAvailableContainerHeight: IGetAvailableContainerHeight;
/**
* Menus to create inside of the view.
*/
menus: IMenuSchema[];
/**
* Styles to use for display elements.
*/
styles: IStyles;
/**
* Containing IUserWrappr holding this display.
*/
userWrapper: IUserWrappr;
}
/**
* Contains contents and menus within a container.
*/
export class Display {
/**
* Dependencies used for initialization.
*/
private readonly dependencies: IDisplayDependencies;
/**
* Creates placeholder menu titles before a real menu is created.
*/
private readonly areasFaker: AreasFaker;
/**
* Menu and content elements, once created.
*/
private createdElements: ICreatedElements | undefined;
/**
* Initializes a new instance of the Display class.
*
* @param dependencies Dependencies to be used for initialization.
*/
public constructor(dependencies: IDisplayDependencies) {
this.dependencies = dependencies;
this.areasFaker = new AreasFaker(this.dependencies);
}
/**
* Creates initial contents and fake menus.
*
* @param requestedSize Size of the contents.
* @returns A Promise for the actual size of the contents.
*/
public async resetContents(requestedSize: IRelativeSizeSchema): Promise<IAbsoluteSizeSchema> {
if (this.createdElements !== undefined) |
const availableContainerSize: IAbsoluteSizeSchema = this.getAvailableContainerSize(this.dependencies.container);
const containerSize: IAbsoluteSizeSchema = getAbsoluteSizeInContainer(availableContainerSize, requestedSize);
const { menuArea, menuSize } = await this.areasFaker.createAndAppendMenuArea(containerSize);
const { contentSize, contentArea } = this.areasFaker.createContentArea(containerSize, menuSize);
this.dependencies.container.insertBefore(contentArea, menuArea);
contentArea.appendChild(this.dependencies.createContents(contentSize, this.dependencies.userWrapper));
this.createdElements = { contentArea, menuArea };
return containerSize;
}
/**
* @returns The container holding the contents and menus.
*/
public getContainer(): HTMLElement {
return this.dependencies.container;
}
/**
* Gets how much space is available to size a container.
*
* @param container Container element.
* @returns How much space is available to size the container.
*/
private getAvailableContainerSize(container: HTMLElement): IAbsoluteSizeSchema {
const availableHeight = this.dependencies.getAvailableContainerHeight();
return {
height: availableHeight - Math.round(container.offsetTop),
width: Math.round(container.clientWidth),
};
}
}
| {
this.dependencies.container.removeChild(this.createdElements.contentArea);
this.dependencies.container.removeChild(this.createdElements.menuArea);
} | conditional_block |
Display.ts | import { AreasFaker } from "./Bootstrapping/AreasFaker";
import { IClassNames } from "./Bootstrapping/ClassNames";
import { ICreateElement } from "./Bootstrapping/CreateElement";
import { IGetAvailableContainerHeight } from "./Bootstrapping/GetAvailableContainerHeight";
import { IStyles } from "./Bootstrapping/Styles";
import { IUserWrappr } from "./IUserWrappr";
import { IMenuSchema } from "./Menus/MenuSchemas";
import { getAbsoluteSizeInContainer, IAbsoluteSizeSchema, IRelativeSizeSchema } from "./Sizing";
/**
* Creates contents for a size.
*
* @param size Bounding size to create contents in.
* @param userWrapper Containing IUserWrappr holding this display.
* @returns Contents at the size.
*/
export type ICreateContents = (size: IAbsoluteSizeSchema, userWrapper: IUserWrappr) => Element;
/**
* Menu and content elements, once creatd.
*/
interface ICreatedElements {
/**
* Contains the created contents.
*/
contentArea: HTMLElement;
/**
* Contains the real or fake menu elements.
*/
menuArea: HTMLElement;
}
/**
* Dependencies to initialize a new Display.
*/
export interface IDisplayDependencies {
/**
* Class names to use for display elements.
*/
classNames: IClassNames;
/**
* Container that will contain the contents and menus.
*/
container: HTMLElement;
/**
* Creates a new HTML element.
*/
createElement: ICreateElement;
/**
* Creates contents within a container.
*/
createContents: ICreateContents;
/**
* Gets how much height is available to size a container.
*/
getAvailableContainerHeight: IGetAvailableContainerHeight;
/**
* Menus to create inside of the view.
*/
menus: IMenuSchema[];
/**
* Styles to use for display elements.
*/ | * Containing IUserWrappr holding this display.
*/
userWrapper: IUserWrappr;
}
/**
* Contains contents and menus within a container.
*/
export class Display {
/**
* Dependencies used for initialization.
*/
private readonly dependencies: IDisplayDependencies;
/**
* Creates placeholder menu titles before a real menu is created.
*/
private readonly areasFaker: AreasFaker;
/**
* Menu and content elements, once created.
*/
private createdElements: ICreatedElements | undefined;
/**
* Initializes a new instance of the Display class.
*
* @param dependencies Dependencies to be used for initialization.
*/
public constructor(dependencies: IDisplayDependencies) {
this.dependencies = dependencies;
this.areasFaker = new AreasFaker(this.dependencies);
}
/**
* Creates initial contents and fake menus.
*
* @param requestedSize Size of the contents.
* @returns A Promise for the actual size of the contents.
*/
public async resetContents(requestedSize: IRelativeSizeSchema): Promise<IAbsoluteSizeSchema> {
if (this.createdElements !== undefined) {
this.dependencies.container.removeChild(this.createdElements.contentArea);
this.dependencies.container.removeChild(this.createdElements.menuArea);
}
const availableContainerSize: IAbsoluteSizeSchema = this.getAvailableContainerSize(this.dependencies.container);
const containerSize: IAbsoluteSizeSchema = getAbsoluteSizeInContainer(availableContainerSize, requestedSize);
const { menuArea, menuSize } = await this.areasFaker.createAndAppendMenuArea(containerSize);
const { contentSize, contentArea } = this.areasFaker.createContentArea(containerSize, menuSize);
this.dependencies.container.insertBefore(contentArea, menuArea);
contentArea.appendChild(this.dependencies.createContents(contentSize, this.dependencies.userWrapper));
this.createdElements = { contentArea, menuArea };
return containerSize;
}
/**
* @returns The container holding the contents and menus.
*/
public getContainer(): HTMLElement {
return this.dependencies.container;
}
/**
* Gets how much space is available to size a container.
*
* @param container Container element.
* @returns How much space is available to size the container.
*/
private getAvailableContainerSize(container: HTMLElement): IAbsoluteSizeSchema {
const availableHeight = this.dependencies.getAvailableContainerHeight();
return {
height: availableHeight - Math.round(container.offsetTop),
width: Math.round(container.clientWidth),
};
}
} | styles: IStyles;
/** | random_line_split |
server.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import logging, os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.gen
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
app_settings = {
"debug": True,
'static_path': os.path.join(base_dir, "static"),
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
tornado.web.url(r"/live", WebSocketHandler, name="websocket"),
], **app_settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
|
class WebSocketHandler(tornado.websocket.WebSocketHandler):
listenners = []
def check_origin(self, origin):
return True
@tornado.gen.engine
def open(self):
WebSocketHandler.listenners.append(self)
def on_close(self):
if self in WebSocketHandler.listenners:
WebSocketHandler.listenners.remove(self)
@tornado.gen.engine
def on_message(self, wsdata):
for listenner in WebSocketHandler.listenners:
listenner.write_message(wsdata)
@tornado.gen.coroutine
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(8888)
logging.info("application running on http://localhost:8888")
if __name__ == "__main__":
tornado.ioloop.IOLoop.current().run_sync(main)
tornado.ioloop.IOLoop.current().start()
| self.render('index.html') | identifier_body |
server.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import logging, os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.gen
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
app_settings = {
"debug": True,
'static_path': os.path.join(base_dir, "static"),
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
tornado.web.url(r"/live", WebSocketHandler, name="websocket"),
], **app_settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
class WebSocketHandler(tornado.websocket.WebSocketHandler):
listenners = []
def check_origin(self, origin):
return True
@tornado.gen.engine
def open(self):
WebSocketHandler.listenners.append(self)
def on_close(self):
if self in WebSocketHandler.listenners:
WebSocketHandler.listenners.remove(self)
@tornado.gen.engine
def on_message(self, wsdata):
for listenner in WebSocketHandler.listenners:
|
@tornado.gen.coroutine
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(8888)
logging.info("application running on http://localhost:8888")
if __name__ == "__main__":
tornado.ioloop.IOLoop.current().run_sync(main)
tornado.ioloop.IOLoop.current().start()
| listenner.write_message(wsdata) | conditional_block |
server.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import logging, os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.gen
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
app_settings = {
"debug": True,
'static_path': os.path.join(base_dir, "static"),
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
tornado.web.url(r"/live", WebSocketHandler, name="websocket"),
], **app_settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
class WebSocketHandler(tornado.websocket.WebSocketHandler):
listenners = []
def | (self, origin):
return True
@tornado.gen.engine
def open(self):
WebSocketHandler.listenners.append(self)
def on_close(self):
if self in WebSocketHandler.listenners:
WebSocketHandler.listenners.remove(self)
@tornado.gen.engine
def on_message(self, wsdata):
for listenner in WebSocketHandler.listenners:
listenner.write_message(wsdata)
@tornado.gen.coroutine
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(8888)
logging.info("application running on http://localhost:8888")
if __name__ == "__main__":
tornado.ioloop.IOLoop.current().run_sync(main)
tornado.ioloop.IOLoop.current().start()
| check_origin | identifier_name |
server.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import logging, os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.gen
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
app_settings = {
"debug": True,
'static_path': os.path.join(base_dir, "static"),
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
tornado.web.url(r"/live", WebSocketHandler, name="websocket"),
], **app_settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
class WebSocketHandler(tornado.websocket.WebSocketHandler):
listenners = []
def check_origin(self, origin):
return True
| WebSocketHandler.listenners.append(self)
def on_close(self):
if self in WebSocketHandler.listenners:
WebSocketHandler.listenners.remove(self)
@tornado.gen.engine
def on_message(self, wsdata):
for listenner in WebSocketHandler.listenners:
listenner.write_message(wsdata)
@tornado.gen.coroutine
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(8888)
logging.info("application running on http://localhost:8888")
if __name__ == "__main__":
tornado.ioloop.IOLoop.current().run_sync(main)
tornado.ioloop.IOLoop.current().start() | @tornado.gen.engine
def open(self): | random_line_split |
restfulhelpers.py | # -*- coding: utf-8 -*-
"""
Useful classes and methods to aid RESTful webservice development in Pyramid.
PythonPro Limited
2012-01-14
"""
import json
import httplib
import logging
import traceback
#from decorator import decorator
from pyramid.request import Response
def get_log(e=None):
return logging.getLogger("{0}.{1}".format(__name__, e) if e else __name__)
def json_result(view_callable):
"""Return a result dict for a response.
rc = {
"success": True | False,
"data": ...,
"message", "ok" | "..message explaining result=False..",
}
the data field will contain whatever is returned from the response
normal i.e. any valid type.
"""
#log = get_log('json_result')
def inner(request, *args):
"""Add the success status wrapper. exceptions will be
handled elsewhere.
"""
response = dict(success=True, data=None, message="ok")
response['data'] = view_callable(request, *args)
return response
return inner
def status_body(
success=True, data=None, message="", to_json=False, traceback='',
):
"""Create a JSON response body we will use for error and other situations.
:param success: Default True or False.
:param data: Default "" or given result.
:param message: Default "ok" or a user given message string.
:param to_json: Default True, return a JSON string or dict is False.
the to_json is used in situations where something else will take care
of to JSON conversion.
:returns: JSON status response body.
The default response is::
json.dumps(dict(
success=True | False,
data=...,
message="...",
))
"""
# TODO: switch tracebacks off for production
body = dict(
success=success,
data=data,
message=message,
)
if traceback:
body['traceback'] = traceback
if to_json:
body = json.dumps(body)
return body
def status_err(exc, tb):
""" Generate an error status response from an exception and traceback
"""
return status_body("error", str(exc), exc.__class__.__name__, tb,
to_json=False)
#@decorator
def status_wrapper(f, *args, **kw):
""" Decorate a view function to wrap up its response in the status_body
gumph from above, and handle all exceptions.
"""
try:
res = f(*args, **kw)
return status_body(message=res, to_json=False)
except Exception, e:
tb = traceback.format_exc()
get_log().exception(tb)
return status_err(e, tb)
def notfound_404_view(request):
"""A custom 404 view returning JSON error message body instead of HTML.
:returns: a JSON response with the body::
json.dumps(dict(error="URI Not Found '...'"))
"""
msg = str(request.exception.message)
get_log().info("notfound_404_view: URI '%s' not found!" % str(msg))
request.response.status = httplib.NOT_FOUND
request.response.content_type = "application/json"
body = status_body(
success=False,
message="URI Not Found '%s'" % msg,
)
return Response(body)
def xyz_handler(status):
"""A custom xyz view returning JSON error message body instead of HTML.
:returns: a JSON response with the body::
json.dumps(dict(error="URI Not Found '...'"))
"""
log = get_log()
def handler(request):
msg = str(request.exception.message)
log.info("xyz_handler (%s): %s" % (status, str(msg)))
#request.response.status = status
#request.response.content_type = "application/json"
body = status_body(
success=False,
message=msg,
to_json=True,
)
rc = Response(body)
rc.status = status
rc.content_type = "application/json"
return rc
return handler
# Reference:
# * http://zhuoqiang.me/a/restful-pyramid
#
class HttpMethodOverrideMiddleware(object):
'''WSGI middleware for overriding HTTP Request Method for RESTful support
'''
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
if 'POST' == environ['REQUEST_METHOD']:
|
return self.application(environ, start_response)
class JSONErrorHandler(object):
"""Capture exceptions usefully and return to aid the client side.
:returns: status_body set for an error.
E.g.::
rc = {
"success": True | False,
"data": ...,
"message", "ok" | "..message explaining result=False..",
}
the data field will contain whatever is returned from the response
normal i.e. any valid type.
"""
def __init__(self, application):
self.app = application
self.log = get_log("JSONErrorHandler")
def formatError(self):
"""Return a string representing the last traceback.
"""
exception, instance, tb = traceback.sys.exc_info()
error = "".join(traceback.format_tb(tb))
return error
def __call__(self, environ, start_response):
try:
return self.app(environ, start_response)
except Exception, e:
self.log.exception("error: ")
ctype = environ.get('CONTENT_TYPE')
if ctype == "application/json":
self.log.debug("Request was in JSON responding with JSON.")
errmsg = "%d %s" % (
httplib.INTERNAL_SERVER_ERROR,
httplib.responses[httplib.INTERNAL_SERVER_ERROR]
)
start_response(errmsg, [('Content-Type', 'application/json')])
message = str(e)
error = "%s" % (type(e).__name__)
self.log.error("%s: %s" % (error, message))
return status_body(
success=False,
# Should this be disabled on production?
data=self.formatError(),
message=message,
# I need to JSON encode it as the view never finished and
# the requestor is expecting a JSON response status.
to_json=True,
)
else:
raise
| override_method = ''
# First check the "_method" form parameter
# if 'form-urlencoded' in environ['CONTENT_TYPE']:
# from webob import Request
# request = Request(environ)
# override_method = request.str_POST.get('_method', '').upper()
# If not found, then look for "X-HTTP-Method-Override" header
if not override_method:
override_method = environ.get(
'HTTP_X_HTTP_METHOD_OVERRIDE', ''
).upper()
if override_method in ('PUT', 'DELETE', 'OPTIONS', 'PATCH'):
# Save the original HTTP method
method = environ['REQUEST_METHOD']
environ['http_method_override.original_method'] = method
# Override HTTP method
environ['REQUEST_METHOD'] = override_method | conditional_block |
restfulhelpers.py | # -*- coding: utf-8 -*-
"""
Useful classes and methods to aid RESTful webservice development in Pyramid.
PythonPro Limited
2012-01-14
"""
import json
import httplib
import logging
import traceback
#from decorator import decorator
from pyramid.request import Response
def get_log(e=None):
return logging.getLogger("{0}.{1}".format(__name__, e) if e else __name__)
def json_result(view_callable):
"""Return a result dict for a response.
rc = {
"success": True | False,
"data": ...,
"message", "ok" | "..message explaining result=False..",
}
the data field will contain whatever is returned from the response
normal i.e. any valid type.
"""
#log = get_log('json_result')
def inner(request, *args):
"""Add the success status wrapper. exceptions will be
handled elsewhere.
"""
response = dict(success=True, data=None, message="ok")
response['data'] = view_callable(request, *args)
return response
return inner
def status_body(
success=True, data=None, message="", to_json=False, traceback='',
):
"""Create a JSON response body we will use for error and other situations.
:param success: Default True or False.
:param data: Default "" or given result.
:param message: Default "ok" or a user given message string.
:param to_json: Default True, return a JSON string or dict is False.
the to_json is used in situations where something else will take care
of to JSON conversion.
:returns: JSON status response body.
The default response is::
json.dumps(dict(
success=True | False,
data=...,
message="...",
))
"""
# TODO: switch tracebacks off for production
body = dict(
success=success,
data=data,
message=message,
)
if traceback:
body['traceback'] = traceback
if to_json:
body = json.dumps(body)
return body
def status_err(exc, tb):
""" Generate an error status response from an exception and traceback
"""
return status_body("error", str(exc), exc.__class__.__name__, tb,
to_json=False)
#@decorator
def status_wrapper(f, *args, **kw):
""" Decorate a view function to wrap up its response in the status_body
gumph from above, and handle all exceptions.
"""
try:
res = f(*args, **kw)
return status_body(message=res, to_json=False)
except Exception, e:
tb = traceback.format_exc()
get_log().exception(tb)
return status_err(e, tb)
def notfound_404_view(request):
"""A custom 404 view returning JSON error message body instead of HTML.
:returns: a JSON response with the body::
json.dumps(dict(error="URI Not Found '...'"))
"""
msg = str(request.exception.message)
get_log().info("notfound_404_view: URI '%s' not found!" % str(msg))
request.response.status = httplib.NOT_FOUND
request.response.content_type = "application/json"
body = status_body(
success=False,
message="URI Not Found '%s'" % msg,
)
return Response(body)
def xyz_handler(status):
"""A custom xyz view returning JSON error message body instead of HTML.
:returns: a JSON response with the body::
json.dumps(dict(error="URI Not Found '...'"))
"""
log = get_log()
def handler(request):
msg = str(request.exception.message)
log.info("xyz_handler (%s): %s" % (status, str(msg)))
#request.response.status = status
#request.response.content_type = "application/json"
body = status_body(
success=False,
message=msg,
to_json=True,
)
rc = Response(body)
rc.status = status
rc.content_type = "application/json"
return rc
return handler
# Reference:
# * http://zhuoqiang.me/a/restful-pyramid
#
class HttpMethodOverrideMiddleware(object):
'''WSGI middleware for overriding HTTP Request Method for RESTful support
'''
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
if 'POST' == environ['REQUEST_METHOD']:
override_method = ''
# First check the "_method" form parameter
# if 'form-urlencoded' in environ['CONTENT_TYPE']:
# from webob import Request
# request = Request(environ)
# override_method = request.str_POST.get('_method', '').upper()
# If not found, then look for "X-HTTP-Method-Override" header
if not override_method:
override_method = environ.get(
'HTTP_X_HTTP_METHOD_OVERRIDE', ''
).upper()
if override_method in ('PUT', 'DELETE', 'OPTIONS', 'PATCH'):
# Save the original HTTP method
method = environ['REQUEST_METHOD']
environ['http_method_override.original_method'] = method
# Override HTTP method
environ['REQUEST_METHOD'] = override_method
return self.application(environ, start_response)
class JSONErrorHandler(object):
"""Capture exceptions usefully and return to aid the client side.
:returns: status_body set for an error.
E.g.::
rc = {
"success": True | False,
"data": ...,
"message", "ok" | "..message explaining result=False..",
}
the data field will contain whatever is returned from the response
normal i.e. any valid type.
"""
def __init__(self, application):
|
def formatError(self):
"""Return a string representing the last traceback.
"""
exception, instance, tb = traceback.sys.exc_info()
error = "".join(traceback.format_tb(tb))
return error
def __call__(self, environ, start_response):
try:
return self.app(environ, start_response)
except Exception, e:
self.log.exception("error: ")
ctype = environ.get('CONTENT_TYPE')
if ctype == "application/json":
self.log.debug("Request was in JSON responding with JSON.")
errmsg = "%d %s" % (
httplib.INTERNAL_SERVER_ERROR,
httplib.responses[httplib.INTERNAL_SERVER_ERROR]
)
start_response(errmsg, [('Content-Type', 'application/json')])
message = str(e)
error = "%s" % (type(e).__name__)
self.log.error("%s: %s" % (error, message))
return status_body(
success=False,
# Should this be disabled on production?
data=self.formatError(),
message=message,
# I need to JSON encode it as the view never finished and
# the requestor is expecting a JSON response status.
to_json=True,
)
else:
raise
| self.app = application
self.log = get_log("JSONErrorHandler") | identifier_body |
restfulhelpers.py | # -*- coding: utf-8 -*-
"""
Useful classes and methods to aid RESTful webservice development in Pyramid.
PythonPro Limited
2012-01-14
"""
import json
import httplib
import logging
import traceback
#from decorator import decorator
from pyramid.request import Response
def get_log(e=None):
return logging.getLogger("{0}.{1}".format(__name__, e) if e else __name__)
def json_result(view_callable):
"""Return a result dict for a response.
rc = {
"success": True | False,
"data": ...,
"message", "ok" | "..message explaining result=False..",
}
the data field will contain whatever is returned from the response
normal i.e. any valid type.
"""
#log = get_log('json_result')
def inner(request, *args):
"""Add the success status wrapper. exceptions will be
handled elsewhere.
"""
response = dict(success=True, data=None, message="ok")
response['data'] = view_callable(request, *args)
return response
return inner
def | (
success=True, data=None, message="", to_json=False, traceback='',
):
"""Create a JSON response body we will use for error and other situations.
:param success: Default True or False.
:param data: Default "" or given result.
:param message: Default "ok" or a user given message string.
:param to_json: Default True, return a JSON string or dict is False.
the to_json is used in situations where something else will take care
of to JSON conversion.
:returns: JSON status response body.
The default response is::
json.dumps(dict(
success=True | False,
data=...,
message="...",
))
"""
# TODO: switch tracebacks off for production
body = dict(
success=success,
data=data,
message=message,
)
if traceback:
body['traceback'] = traceback
if to_json:
body = json.dumps(body)
return body
def status_err(exc, tb):
""" Generate an error status response from an exception and traceback
"""
return status_body("error", str(exc), exc.__class__.__name__, tb,
to_json=False)
#@decorator
def status_wrapper(f, *args, **kw):
""" Decorate a view function to wrap up its response in the status_body
gumph from above, and handle all exceptions.
"""
try:
res = f(*args, **kw)
return status_body(message=res, to_json=False)
except Exception, e:
tb = traceback.format_exc()
get_log().exception(tb)
return status_err(e, tb)
def notfound_404_view(request):
"""A custom 404 view returning JSON error message body instead of HTML.
:returns: a JSON response with the body::
json.dumps(dict(error="URI Not Found '...'"))
"""
msg = str(request.exception.message)
get_log().info("notfound_404_view: URI '%s' not found!" % str(msg))
request.response.status = httplib.NOT_FOUND
request.response.content_type = "application/json"
body = status_body(
success=False,
message="URI Not Found '%s'" % msg,
)
return Response(body)
def xyz_handler(status):
"""A custom xyz view returning JSON error message body instead of HTML.
:returns: a JSON response with the body::
json.dumps(dict(error="URI Not Found '...'"))
"""
log = get_log()
def handler(request):
msg = str(request.exception.message)
log.info("xyz_handler (%s): %s" % (status, str(msg)))
#request.response.status = status
#request.response.content_type = "application/json"
body = status_body(
success=False,
message=msg,
to_json=True,
)
rc = Response(body)
rc.status = status
rc.content_type = "application/json"
return rc
return handler
# Reference:
# * http://zhuoqiang.me/a/restful-pyramid
#
class HttpMethodOverrideMiddleware(object):
'''WSGI middleware for overriding HTTP Request Method for RESTful support
'''
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
if 'POST' == environ['REQUEST_METHOD']:
override_method = ''
# First check the "_method" form parameter
# if 'form-urlencoded' in environ['CONTENT_TYPE']:
# from webob import Request
# request = Request(environ)
# override_method = request.str_POST.get('_method', '').upper()
# If not found, then look for "X-HTTP-Method-Override" header
if not override_method:
override_method = environ.get(
'HTTP_X_HTTP_METHOD_OVERRIDE', ''
).upper()
if override_method in ('PUT', 'DELETE', 'OPTIONS', 'PATCH'):
# Save the original HTTP method
method = environ['REQUEST_METHOD']
environ['http_method_override.original_method'] = method
# Override HTTP method
environ['REQUEST_METHOD'] = override_method
return self.application(environ, start_response)
class JSONErrorHandler(object):
"""Capture exceptions usefully and return to aid the client side.
:returns: status_body set for an error.
E.g.::
rc = {
"success": True | False,
"data": ...,
"message", "ok" | "..message explaining result=False..",
}
the data field will contain whatever is returned from the response
normal i.e. any valid type.
"""
def __init__(self, application):
self.app = application
self.log = get_log("JSONErrorHandler")
def formatError(self):
"""Return a string representing the last traceback.
"""
exception, instance, tb = traceback.sys.exc_info()
error = "".join(traceback.format_tb(tb))
return error
def __call__(self, environ, start_response):
try:
return self.app(environ, start_response)
except Exception, e:
self.log.exception("error: ")
ctype = environ.get('CONTENT_TYPE')
if ctype == "application/json":
self.log.debug("Request was in JSON responding with JSON.")
errmsg = "%d %s" % (
httplib.INTERNAL_SERVER_ERROR,
httplib.responses[httplib.INTERNAL_SERVER_ERROR]
)
start_response(errmsg, [('Content-Type', 'application/json')])
message = str(e)
error = "%s" % (type(e).__name__)
self.log.error("%s: %s" % (error, message))
return status_body(
success=False,
# Should this be disabled on production?
data=self.formatError(),
message=message,
# I need to JSON encode it as the view never finished and
# the requestor is expecting a JSON response status.
to_json=True,
)
else:
raise
| status_body | identifier_name |
restfulhelpers.py | # -*- coding: utf-8 -*-
"""
Useful classes and methods to aid RESTful webservice development in Pyramid.
PythonPro Limited
2012-01-14
"""
import json
import httplib
import logging
import traceback
#from decorator import decorator
from pyramid.request import Response
def get_log(e=None):
return logging.getLogger("{0}.{1}".format(__name__, e) if e else __name__)
def json_result(view_callable):
"""Return a result dict for a response.
rc = {
"success": True | False,
"data": ...,
"message", "ok" | "..message explaining result=False..",
}
the data field will contain whatever is returned from the response
normal i.e. any valid type.
"""
#log = get_log('json_result')
def inner(request, *args):
"""Add the success status wrapper. exceptions will be
handled elsewhere.
"""
response = dict(success=True, data=None, message="ok")
response['data'] = view_callable(request, *args)
return response
return inner
def status_body(
success=True, data=None, message="", to_json=False, traceback='',
):
"""Create a JSON response body we will use for error and other situations.
:param success: Default True or False.
:param data: Default "" or given result.
:param message: Default "ok" or a user given message string.
:param to_json: Default True, return a JSON string or dict is False.
the to_json is used in situations where something else will take care
of to JSON conversion.
:returns: JSON status response body.
The default response is::
json.dumps(dict(
success=True | False,
data=...,
message="...",
))
"""
# TODO: switch tracebacks off for production
body = dict(
success=success,
data=data,
message=message,
)
if traceback:
body['traceback'] = traceback
if to_json:
body = json.dumps(body)
return body
def status_err(exc, tb):
""" Generate an error status response from an exception and traceback
"""
return status_body("error", str(exc), exc.__class__.__name__, tb,
to_json=False)
#@decorator
def status_wrapper(f, *args, **kw):
""" Decorate a view function to wrap up its response in the status_body
gumph from above, and handle all exceptions.
"""
try:
res = f(*args, **kw)
return status_body(message=res, to_json=False)
except Exception, e:
tb = traceback.format_exc()
get_log().exception(tb)
return status_err(e, tb)
def notfound_404_view(request):
"""A custom 404 view returning JSON error message body instead of HTML.
:returns: a JSON response with the body::
json.dumps(dict(error="URI Not Found '...'"))
"""
msg = str(request.exception.message)
get_log().info("notfound_404_view: URI '%s' not found!" % str(msg))
request.response.status = httplib.NOT_FOUND
request.response.content_type = "application/json"
body = status_body(
success=False,
message="URI Not Found '%s'" % msg,
)
return Response(body)
def xyz_handler(status):
"""A custom xyz view returning JSON error message body instead of HTML.
:returns: a JSON response with the body::
json.dumps(dict(error="URI Not Found '...'"))
"""
log = get_log()
def handler(request):
msg = str(request.exception.message)
log.info("xyz_handler (%s): %s" % (status, str(msg)))
#request.response.status = status
#request.response.content_type = "application/json"
body = status_body(
success=False,
message=msg,
to_json=True,
)
rc = Response(body)
rc.status = status
rc.content_type = "application/json"
return rc
return handler
# Reference:
# * http://zhuoqiang.me/a/restful-pyramid
#
class HttpMethodOverrideMiddleware(object):
'''WSGI middleware for overriding HTTP Request Method for RESTful support
'''
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
if 'POST' == environ['REQUEST_METHOD']:
override_method = ''
# First check the "_method" form parameter
# if 'form-urlencoded' in environ['CONTENT_TYPE']:
# from webob import Request
# request = Request(environ)
# override_method = request.str_POST.get('_method', '').upper()
# If not found, then look for "X-HTTP-Method-Override" header
if not override_method:
override_method = environ.get(
'HTTP_X_HTTP_METHOD_OVERRIDE', ''
).upper()
if override_method in ('PUT', 'DELETE', 'OPTIONS', 'PATCH'):
# Save the original HTTP method
method = environ['REQUEST_METHOD'] | environ['http_method_override.original_method'] = method
# Override HTTP method
environ['REQUEST_METHOD'] = override_method
return self.application(environ, start_response)
class JSONErrorHandler(object):
"""Capture exceptions usefully and return to aid the client side.
:returns: status_body set for an error.
E.g.::
rc = {
"success": True | False,
"data": ...,
"message", "ok" | "..message explaining result=False..",
}
the data field will contain whatever is returned from the response
normal i.e. any valid type.
"""
def __init__(self, application):
self.app = application
self.log = get_log("JSONErrorHandler")
def formatError(self):
"""Return a string representing the last traceback.
"""
exception, instance, tb = traceback.sys.exc_info()
error = "".join(traceback.format_tb(tb))
return error
def __call__(self, environ, start_response):
try:
return self.app(environ, start_response)
except Exception, e:
self.log.exception("error: ")
ctype = environ.get('CONTENT_TYPE')
if ctype == "application/json":
self.log.debug("Request was in JSON responding with JSON.")
errmsg = "%d %s" % (
httplib.INTERNAL_SERVER_ERROR,
httplib.responses[httplib.INTERNAL_SERVER_ERROR]
)
start_response(errmsg, [('Content-Type', 'application/json')])
message = str(e)
error = "%s" % (type(e).__name__)
self.log.error("%s: %s" % (error, message))
return status_body(
success=False,
# Should this be disabled on production?
data=self.formatError(),
message=message,
# I need to JSON encode it as the view never finished and
# the requestor is expecting a JSON response status.
to_json=True,
)
else:
raise | random_line_split | |
RangeBackgrounds.spec.ts | import {test} from 'ava';
import {Sheet, SheetConfig} from 'excol';
import {Errors} from 'excol';
const DIMENSION = 20;
const cfg: SheetConfig = {
id: 0,
name: 'test lib',
numRows: DIMENSION,
numColumns: DIMENSION
};
test('should set array of backgrounds for range A2:B3', t => {
const sheet = new Sheet(cfg);
const range = sheet.getRange({A1: 'A2:B3'});
range.setBackgrounds([
['A2', 'B2'],
['A3', 'B3'],
]);
const bgs = range.getBackgrounds();
const bg = range.getBackground();
const expected = [
['A2', 'B2'], |
t.deepEqual(bgs, expected);
t.is(bg, 'A2');
});
/*
test.only('should throw error on bad colors types', t => {
const grid = new Sheet(cfg);
const range = grid.getRange({A1: 'A2:B3'});
const expectedErr = Errors.INCORRECT_SET_VALUES_PARAMETERS(typeof '');
const expectedErr2 = Errors.INCORRECT_SET_VALUES_PARAMETERS(typeof 0);
///* tslint:disable */
/*
const actual = t.throws(() => {
range.setBackgrounds('toto');
}, Error);
t.is(actual.message, expectedErr);
//expect(function(){range.setBackgrounds(0)}).to.throw(expectedErr2);
/* tslint:enable */
//}); | ['A3', 'B3']
]; | random_line_split |
NetGroup.ts | /**
* Copyright 2014 Mozilla Foundation
*
* 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.
*/
// Class: NetGroup
module Shumway.AVMX.AS.flash.net {
import notImplemented = Shumway.Debug.notImplemented;
import axCoerceString = Shumway.AVMX.axCoerceString;
export class NetGroup extends flash.events.EventDispatcher {
// Called whenever the class is initialized.
static classInitializer: any = null;
// List of static symbols to link.
static classSymbols: string [] = null; // [];
// List of instance symbols to link.
static instanceSymbols: string [] = null; // ["close", "replicationStrategy", "replicationStrategy", "addHaveObjects", "removeHaveObjects", "addWantObjects", "removeWantObjects", "writeRequestedObject", "denyRequestedObject", "estimatedMemberCount", "neighborCount", "receiveMode", "receiveMode", "post", "sendToNearest", "sendToNeighbor", "sendToAllNeighbors", "addNeighbor", "addMemberHint"];
constructor (connection: flash.net.NetConnection, groupspec: string) {
super();
connection = connection; groupspec = axCoerceString(groupspec);
}
// JS -> AS Bindings
close: () => void;
replicationStrategy: string;
addHaveObjects: (startIndex: number, endIndex: number) => void;
removeHaveObjects: (startIndex: number, endIndex: number) => void;
addWantObjects: (startIndex: number, endIndex: number) => void;
removeWantObjects: (startIndex: number, endIndex: number) => void;
writeRequestedObject: (requestID: number /*int*/, object: ASObject) => void; | post: (message: ASObject) => string;
sendToNearest: (message: ASObject, groupAddress: string) => string;
sendToNeighbor: (message: ASObject, sendMode: string) => string;
sendToAllNeighbors: (message: ASObject) => string;
addNeighbor: (peerID: string) => boolean;
addMemberHint: (peerID: string) => boolean;
// AS -> JS Bindings
// _replicationStrategy: string;
// _estimatedMemberCount: number;
// _neighborCount: number;
// _receiveMode: string;
// _info: flash.net.NetGroupInfo;
// _localCoverageFrom: string;
// _localCoverageTo: string;
get info(): flash.net.NetGroupInfo {
notImplemented("public flash.net.NetGroup::get info"); return;
// return this._info;
}
convertPeerIDToGroupAddress(peerID: string): string {
peerID = axCoerceString(peerID);
notImplemented("public flash.net.NetGroup::convertPeerIDToGroupAddress"); return;
}
get localCoverageFrom(): string {
notImplemented("public flash.net.NetGroup::get localCoverageFrom"); return;
// return this._localCoverageFrom;
}
get localCoverageTo(): string {
notImplemented("public flash.net.NetGroup::get localCoverageTo"); return;
// return this._localCoverageTo;
}
}
} | denyRequestedObject: (requestID: number /*int*/) => void;
estimatedMemberCount: number;
neighborCount: number;
receiveMode: string; | random_line_split |
NetGroup.ts | /**
* Copyright 2014 Mozilla Foundation
*
* 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.
*/
// Class: NetGroup
module Shumway.AVMX.AS.flash.net {
import notImplemented = Shumway.Debug.notImplemented;
import axCoerceString = Shumway.AVMX.axCoerceString;
export class NetGroup extends flash.events.EventDispatcher {
// Called whenever the class is initialized.
static classInitializer: any = null;
// List of static symbols to link.
static classSymbols: string [] = null; // [];
// List of instance symbols to link.
static instanceSymbols: string [] = null; // ["close", "replicationStrategy", "replicationStrategy", "addHaveObjects", "removeHaveObjects", "addWantObjects", "removeWantObjects", "writeRequestedObject", "denyRequestedObject", "estimatedMemberCount", "neighborCount", "receiveMode", "receiveMode", "post", "sendToNearest", "sendToNeighbor", "sendToAllNeighbors", "addNeighbor", "addMemberHint"];
constructor (connection: flash.net.NetConnection, groupspec: string) {
super();
connection = connection; groupspec = axCoerceString(groupspec);
}
// JS -> AS Bindings
close: () => void;
replicationStrategy: string;
addHaveObjects: (startIndex: number, endIndex: number) => void;
removeHaveObjects: (startIndex: number, endIndex: number) => void;
addWantObjects: (startIndex: number, endIndex: number) => void;
removeWantObjects: (startIndex: number, endIndex: number) => void;
writeRequestedObject: (requestID: number /*int*/, object: ASObject) => void;
denyRequestedObject: (requestID: number /*int*/) => void;
estimatedMemberCount: number;
neighborCount: number;
receiveMode: string;
post: (message: ASObject) => string;
sendToNearest: (message: ASObject, groupAddress: string) => string;
sendToNeighbor: (message: ASObject, sendMode: string) => string;
sendToAllNeighbors: (message: ASObject) => string;
addNeighbor: (peerID: string) => boolean;
addMemberHint: (peerID: string) => boolean;
// AS -> JS Bindings
// _replicationStrategy: string;
// _estimatedMemberCount: number;
// _neighborCount: number;
// _receiveMode: string;
// _info: flash.net.NetGroupInfo;
// _localCoverageFrom: string;
// _localCoverageTo: string;
get info(): flash.net.NetGroupInfo {
notImplemented("public flash.net.NetGroup::get info"); return;
// return this._info;
}
convertPeerIDToGroupAddress(peerID: string): string |
get localCoverageFrom(): string {
notImplemented("public flash.net.NetGroup::get localCoverageFrom"); return;
// return this._localCoverageFrom;
}
get localCoverageTo(): string {
notImplemented("public flash.net.NetGroup::get localCoverageTo"); return;
// return this._localCoverageTo;
}
}
}
| {
peerID = axCoerceString(peerID);
notImplemented("public flash.net.NetGroup::convertPeerIDToGroupAddress"); return;
} | identifier_body |
NetGroup.ts | /**
* Copyright 2014 Mozilla Foundation
*
* 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.
*/
// Class: NetGroup
module Shumway.AVMX.AS.flash.net {
import notImplemented = Shumway.Debug.notImplemented;
import axCoerceString = Shumway.AVMX.axCoerceString;
export class NetGroup extends flash.events.EventDispatcher {
// Called whenever the class is initialized.
static classInitializer: any = null;
// List of static symbols to link.
static classSymbols: string [] = null; // [];
// List of instance symbols to link.
static instanceSymbols: string [] = null; // ["close", "replicationStrategy", "replicationStrategy", "addHaveObjects", "removeHaveObjects", "addWantObjects", "removeWantObjects", "writeRequestedObject", "denyRequestedObject", "estimatedMemberCount", "neighborCount", "receiveMode", "receiveMode", "post", "sendToNearest", "sendToNeighbor", "sendToAllNeighbors", "addNeighbor", "addMemberHint"];
constructor (connection: flash.net.NetConnection, groupspec: string) {
super();
connection = connection; groupspec = axCoerceString(groupspec);
}
// JS -> AS Bindings
close: () => void;
replicationStrategy: string;
addHaveObjects: (startIndex: number, endIndex: number) => void;
removeHaveObjects: (startIndex: number, endIndex: number) => void;
addWantObjects: (startIndex: number, endIndex: number) => void;
removeWantObjects: (startIndex: number, endIndex: number) => void;
writeRequestedObject: (requestID: number /*int*/, object: ASObject) => void;
denyRequestedObject: (requestID: number /*int*/) => void;
estimatedMemberCount: number;
neighborCount: number;
receiveMode: string;
post: (message: ASObject) => string;
sendToNearest: (message: ASObject, groupAddress: string) => string;
sendToNeighbor: (message: ASObject, sendMode: string) => string;
sendToAllNeighbors: (message: ASObject) => string;
addNeighbor: (peerID: string) => boolean;
addMemberHint: (peerID: string) => boolean;
// AS -> JS Bindings
// _replicationStrategy: string;
// _estimatedMemberCount: number;
// _neighborCount: number;
// _receiveMode: string;
// _info: flash.net.NetGroupInfo;
// _localCoverageFrom: string;
// _localCoverageTo: string;
get info(): flash.net.NetGroupInfo {
notImplemented("public flash.net.NetGroup::get info"); return;
// return this._info;
}
convertPeerIDToGroupAddress(peerID: string): string {
peerID = axCoerceString(peerID);
notImplemented("public flash.net.NetGroup::convertPeerIDToGroupAddress"); return;
}
get | (): string {
notImplemented("public flash.net.NetGroup::get localCoverageFrom"); return;
// return this._localCoverageFrom;
}
get localCoverageTo(): string {
notImplemented("public flash.net.NetGroup::get localCoverageTo"); return;
// return this._localCoverageTo;
}
}
}
| localCoverageFrom | identifier_name |
gist-article.service.spec.ts | /**
* @author Cristian Moreno <khriztianmoreno@gmail.com>
*/
import { TestBed, getTestBed, async, inject } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import {
ResponseOptions,
BaseRequestOptions,
Response,
HttpModule,
Http,
XHRBackend,
RequestMethod
} from '@angular/http';
import { GistArticleService } from './gist-article.service';
describe('GistArticleService', () => {
let mockBackend: MockBackend;
const userName = 'khriztianmoreno';
const idGist = '172e201db07617a1feacae8d145f8cf0';
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
GistArticleService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory:
(backend: XHRBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
}
}
],
imports: [
HttpModule
]
}); | mockBackend = getTestBed().get(MockBackend);
}));
describe('When I request gists API services', () => {
it('if i do a GET api.github.com/users/:username/gists it should fetch gists list',
async(inject([GistArticleService], (appService) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
expect(connection.request.url).toContain(`https://api.github.com/users/${userName}/gists`);
expect(connection.request.method).toEqual(RequestMethod.Get);
connection.mockRespond(new Response(
new ResponseOptions({
body: [{
id: idGist
}]
})));
});
appService.fetchGists(userName).subscribe(
(data) => {
expect(data.length).toBeDefined();
expect(data.length).toEqual(1);
expect(data[0].id).toEqual(idGist);
});
})));
it('if i do a GET api.github.com/gists/:id it should fetch single gist',
async(inject([GistArticleService], (appService) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
expect(connection.request.url).toContain(`https://api.github.com/gists/${idGist}`);
expect(connection.request.method).toEqual(RequestMethod.Get);
connection.mockRespond(new Response(
new ResponseOptions({
body: { id: idGist }
})));
});
appService.fetchSingleGist(idGist).subscribe(
(data) => {
expect(data).toBeDefined();
expect(data.id).toEqual(idGist);
});
})));
});
}); | random_line_split | |
policy.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# All Rights Reserved.
#
# 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.
"""Policy Engine For Glance"""
import json
import os.path
from glance.common import cfg
from glance.common import exception
from glance.common import policy
class Enforcer(object):
"""Responsible for loading and enforcing rules"""
policy_opts = (
cfg.StrOpt('policy_file', default=None),
cfg.StrOpt('policy_default_rule', default='default'),
)
def __init__(self, conf):
for opt in self.policy_opts:
conf.register_opt(opt)
self.default_rule = conf.policy_default_rule
self.policy_path = self._find_policy_file(conf)
self.policy_file_mtime = None
self.policy_file_contents = None
def set_rules(self, rules):
"""Create a new Brain based on the provided dict of rules"""
brain = policy.Brain(rules, self.default_rule)
policy.set_brain(brain)
def load_rules(self):
"""Set the rules found in the json file on disk"""
rules = self._read_policy_file()
self.set_rules(rules)
@staticmethod
def _find_policy_file(conf):
"""Locate the policy json data file"""
if conf.policy_file:
return conf.policy_file
matches = cfg.find_config_files('glance', 'policy', 'json')
try:
return matches[0]
except IndexError:
raise cfg.ConfigFilesNotFoundError(('policy.json',))
def _read_policy_file(self):
"""Read contents of the policy file
This re-caches policy data if the file has been changed.
"""
mtime = os.path.getmtime(self.policy_path)
if not self.policy_file_contents or mtime != self.policy_file_mtime:
with open(self.policy_path) as fap:
raw_contents = fap.read()
self.policy_file_contents = json.loads(raw_contents)
self.policy_file_mtime = mtime
return self.policy_file_contents
def enforce(self, context, action, target):
| """Verifies that the action is valid on the target in this context.
:param context: Glance request context
:param action: String representing the action to be checked
:param object: Dictionary representing the object of the action.
:raises: `glance.common.exception.NotAuthorized`
:returns: None
"""
self.load_rules()
match_list = ('rule:%s' % action,)
credentials = {
'roles': context.roles,
'user': context.user,
'tenant': context.tenant,
}
try:
policy.enforce(match_list, target, credentials)
except policy.NotAuthorized:
raise exception.NotAuthorized(action=action) | identifier_body | |
policy.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# All Rights Reserved.
#
# 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.
"""Policy Engine For Glance"""
import json
import os.path
from glance.common import cfg
from glance.common import exception
from glance.common import policy
class Enforcer(object):
"""Responsible for loading and enforcing rules"""
policy_opts = (
cfg.StrOpt('policy_file', default=None),
cfg.StrOpt('policy_default_rule', default='default'),
)
def __init__(self, conf):
for opt in self.policy_opts:
conf.register_opt(opt)
self.default_rule = conf.policy_default_rule
self.policy_path = self._find_policy_file(conf)
self.policy_file_mtime = None
self.policy_file_contents = None
def set_rules(self, rules):
"""Create a new Brain based on the provided dict of rules"""
brain = policy.Brain(rules, self.default_rule)
policy.set_brain(brain)
def load_rules(self):
"""Set the rules found in the json file on disk"""
rules = self._read_policy_file()
self.set_rules(rules)
@staticmethod
def _find_policy_file(conf):
"""Locate the policy json data file"""
if conf.policy_file:
return conf.policy_file
matches = cfg.find_config_files('glance', 'policy', 'json')
try:
return matches[0]
except IndexError:
raise cfg.ConfigFilesNotFoundError(('policy.json',))
def _read_policy_file(self):
"""Read contents of the policy file
This re-caches policy data if the file has been changed.
"""
mtime = os.path.getmtime(self.policy_path)
if not self.policy_file_contents or mtime != self.policy_file_mtime:
|
return self.policy_file_contents
def enforce(self, context, action, target):
"""Verifies that the action is valid on the target in this context.
:param context: Glance request context
:param action: String representing the action to be checked
:param object: Dictionary representing the object of the action.
:raises: `glance.common.exception.NotAuthorized`
:returns: None
"""
self.load_rules()
match_list = ('rule:%s' % action,)
credentials = {
'roles': context.roles,
'user': context.user,
'tenant': context.tenant,
}
try:
policy.enforce(match_list, target, credentials)
except policy.NotAuthorized:
raise exception.NotAuthorized(action=action)
| with open(self.policy_path) as fap:
raw_contents = fap.read()
self.policy_file_contents = json.loads(raw_contents)
self.policy_file_mtime = mtime | conditional_block |
policy.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# All Rights Reserved.
#
# 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.
"""Policy Engine For Glance"""
import json
import os.path
from glance.common import cfg
from glance.common import exception
from glance.common import policy
class Enforcer(object):
"""Responsible for loading and enforcing rules"""
policy_opts = (
cfg.StrOpt('policy_file', default=None),
cfg.StrOpt('policy_default_rule', default='default'),
)
def __init__(self, conf):
for opt in self.policy_opts:
conf.register_opt(opt)
self.default_rule = conf.policy_default_rule
self.policy_path = self._find_policy_file(conf)
self.policy_file_mtime = None
self.policy_file_contents = None
def set_rules(self, rules):
"""Create a new Brain based on the provided dict of rules"""
brain = policy.Brain(rules, self.default_rule)
policy.set_brain(brain)
def load_rules(self):
"""Set the rules found in the json file on disk"""
rules = self._read_policy_file()
self.set_rules(rules)
@staticmethod
def _find_policy_file(conf):
"""Locate the policy json data file"""
if conf.policy_file:
return conf.policy_file
matches = cfg.find_config_files('glance', 'policy', 'json')
try: | except IndexError:
raise cfg.ConfigFilesNotFoundError(('policy.json',))
def _read_policy_file(self):
"""Read contents of the policy file
This re-caches policy data if the file has been changed.
"""
mtime = os.path.getmtime(self.policy_path)
if not self.policy_file_contents or mtime != self.policy_file_mtime:
with open(self.policy_path) as fap:
raw_contents = fap.read()
self.policy_file_contents = json.loads(raw_contents)
self.policy_file_mtime = mtime
return self.policy_file_contents
def enforce(self, context, action, target):
"""Verifies that the action is valid on the target in this context.
:param context: Glance request context
:param action: String representing the action to be checked
:param object: Dictionary representing the object of the action.
:raises: `glance.common.exception.NotAuthorized`
:returns: None
"""
self.load_rules()
match_list = ('rule:%s' % action,)
credentials = {
'roles': context.roles,
'user': context.user,
'tenant': context.tenant,
}
try:
policy.enforce(match_list, target, credentials)
except policy.NotAuthorized:
raise exception.NotAuthorized(action=action) | return matches[0] | random_line_split |
policy.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# All Rights Reserved.
#
# 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.
"""Policy Engine For Glance"""
import json
import os.path
from glance.common import cfg
from glance.common import exception
from glance.common import policy
class Enforcer(object):
"""Responsible for loading and enforcing rules"""
policy_opts = (
cfg.StrOpt('policy_file', default=None),
cfg.StrOpt('policy_default_rule', default='default'),
)
def __init__(self, conf):
for opt in self.policy_opts:
conf.register_opt(opt)
self.default_rule = conf.policy_default_rule
self.policy_path = self._find_policy_file(conf)
self.policy_file_mtime = None
self.policy_file_contents = None
def set_rules(self, rules):
"""Create a new Brain based on the provided dict of rules"""
brain = policy.Brain(rules, self.default_rule)
policy.set_brain(brain)
def | (self):
"""Set the rules found in the json file on disk"""
rules = self._read_policy_file()
self.set_rules(rules)
@staticmethod
def _find_policy_file(conf):
"""Locate the policy json data file"""
if conf.policy_file:
return conf.policy_file
matches = cfg.find_config_files('glance', 'policy', 'json')
try:
return matches[0]
except IndexError:
raise cfg.ConfigFilesNotFoundError(('policy.json',))
def _read_policy_file(self):
"""Read contents of the policy file
This re-caches policy data if the file has been changed.
"""
mtime = os.path.getmtime(self.policy_path)
if not self.policy_file_contents or mtime != self.policy_file_mtime:
with open(self.policy_path) as fap:
raw_contents = fap.read()
self.policy_file_contents = json.loads(raw_contents)
self.policy_file_mtime = mtime
return self.policy_file_contents
def enforce(self, context, action, target):
"""Verifies that the action is valid on the target in this context.
:param context: Glance request context
:param action: String representing the action to be checked
:param object: Dictionary representing the object of the action.
:raises: `glance.common.exception.NotAuthorized`
:returns: None
"""
self.load_rules()
match_list = ('rule:%s' % action,)
credentials = {
'roles': context.roles,
'user': context.user,
'tenant': context.tenant,
}
try:
policy.enforce(match_list, target, credentials)
except policy.NotAuthorized:
raise exception.NotAuthorized(action=action)
| load_rules | identifier_name |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot::RwLockUpgradableReadGuard;
use crate::CacheStats;
use crate::IoTimeSeries;
use crate::ProgressBar;
/// Data needed to render render multi-line progress.
///
/// There are 2 kinds of data:
/// - I/O time series. (ex. "Network [▁▂▄█▇▅▃▆] 3MB/s")
/// - Ordinary progress bars with "position" and "total".
/// (ex. "fetching files 123/456")
#[derive(Default, Clone, Debug)]
pub struct Registry {
render_cond: Arc<(Mutex<bool>, Condvar)>,
inner: Arc<RwLock<Inner>>,
}
macro_rules! impl_model {
{
$( $field:ident: $type:ty, )*
} => {
paste::paste! {
#[derive(Default, Debug)]
struct Inner {
$( $field: Vec<Arc<$type>>, )*
}
impl Registry {
$(
/// Register a model.
pub fn [< register_ $field >](&self, model: &Arc<$type>) {
tracing::debug!("registering {} {}", stringify!($type), model.topic());
let mut inner = self.inner.write();
inner.$field.push(model.clone());
}
/// List models registered.
pub fn [< list_ $field >](&self) -> Vec<Arc<$type>> {
self.inner.read().$field.clone()
}
/// Remove models that were dropped externally.
pub fn [< remove_orphan_ $field >](&self) -> usize {
let inner = self.inner.upgradable_read();
let orphan_count = inner
.$field
.iter()
.filter(|b| Arc::strong_count(b) == 1)
.count();
if orphan_count > 0 {
tracing::debug!(
"removing {} orphan {}",
orphan_count,
stringify!($type)
);
let mut inner = RwLockUpgradableReadGuard::upgrade(inner);
inner.$field = inner
.$field
.drain(..)
.filter(|b| Arc::strong_count(b) > 1)
.collect();
}
orphan_count
}
)*
/// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )*
}
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::new(|| {
tracing::debug!("main progress Registry initialized");
Registry {
render_cond: Arc::new((Mutex::new(false), Condvar::new())),
..Default::default()
}
});
®ISTRY
}
/// step/wait provide a mechanism for tests to step through
/// rendering/handling of the registry in a controlled manner. The
/// test calls step() which unblocks the wait()er. Then step()
/// waits for the next wait() call, ensuring that the registry
/// processing loop finished its iteration.
pub fn step(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
*ready = true;
var.notify_one();
// Wait for wait() to notify us that it completed an iteration.
var.wait(&mut ready);
}
/// See step().
pub fn wait(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
if *ready {
// | for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let registry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let bar2 = {
let bar = ProgressBar::new(topic.to_string(), 200, "bytes");
bar.increase_position(100);
bar.set_message("a.txt".to_string());
registry.register_progress_bar(&bar);
bar
};
assert_eq!(registry.remove_orphan_progress_bar(), 0);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 100/200 bytes a.txt]"
);
drop(bar2);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(format!("{:?}", registry.list_progress_bar()), "[]");
}
#[test]
fn test_time_series() {
let registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq!(
format!("{:?}", registry.list_io_time_series()),
"[Net [0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0], Disk [0|0|0, 5000|300|1, 20000|1200|2, 45000|2700|3, 80000|4800|4, 125000|7500|5, 180000|10800|6, 245000|14700|7, 320000|19200|8, 405000|24300|9, 500000|30000|10, 605000|36300|11, 720000|43200|12, 845000|50700|13, 980000|58800|14, 1125000|67500|15]]"
);
drop(series1);
drop(series2);
assert_eq!(registry.remove_orphan_io_time_series(), 2);
assert_eq!(format!("{:?}", registry.list_io_time_series()), "[]");
}
}
| We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait | conditional_block |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot::RwLockUpgradableReadGuard;
use crate::CacheStats;
use crate::IoTimeSeries;
use crate::ProgressBar;
/// Data needed to render render multi-line progress.
///
/// There are 2 kinds of data:
/// - I/O time series. (ex. "Network [▁▂▄█▇▅▃▆] 3MB/s")
/// - Ordinary progress bars with "position" and "total".
/// (ex. "fetching files 123/456")
#[derive(Default, Clone, Debug)]
pub struct Registry {
render_cond: Arc<(Mutex<bool>, Condvar)>,
inner: Arc<RwLock<Inner>>,
}
macro_rules! impl_model {
{
$( $field:ident: $type:ty, )*
} => {
paste::paste! {
#[derive(Default, Debug)]
struct Inner {
$( $field: Vec<Arc<$type>>, )*
}
impl Registry {
$(
/// Register a model.
pub fn [< register_ $field >](&self, model: &Arc<$type>) {
tracing::debug!("registering {} {}", stringify!($type), model.topic());
let mut inner = self.inner.write();
inner.$field.push(model.clone());
}
/// List models registered.
pub fn [< list_ $field >](&self) -> Vec<Arc<$type>> {
self.inner.read().$field.clone()
}
/// Remove models that were dropped externally.
pub fn [< remove_orphan_ $field >](&self) -> usize {
let inner = self.inner.upgradable_read();
let orphan_count = inner
.$field
.iter()
.filter(|b| Arc::strong_count(b) == 1)
.count();
if orphan_count > 0 {
tracing::debug!(
"removing {} orphan {}",
orphan_count,
stringify!($type)
);
let mut inner = RwLockUpgradableReadGuard::upgrade(inner);
inner.$field = inner
.$field
.drain(..)
.filter(|b| Arc::strong_count(b) > 1)
.collect();
}
orphan_count
}
)*
| }
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::new(|| {
tracing::debug!("main progress Registry initialized");
Registry {
render_cond: Arc::new((Mutex::new(false), Condvar::new())),
..Default::default()
}
});
®ISTRY
}
/// step/wait provide a mechanism for tests to step through
/// rendering/handling of the registry in a controlled manner. The
/// test calls step() which unblocks the wait()er. Then step()
/// waits for the next wait() call, ensuring that the registry
/// processing loop finished its iteration.
pub fn step(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
*ready = true;
var.notify_one();
// Wait for wait() to notify us that it completed an iteration.
var.wait(&mut ready);
}
/// See step().
pub fn wait(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
if *ready {
// We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let registry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let bar2 = {
let bar = ProgressBar::new(topic.to_string(), 200, "bytes");
bar.increase_position(100);
bar.set_message("a.txt".to_string());
registry.register_progress_bar(&bar);
bar
};
assert_eq!(registry.remove_orphan_progress_bar(), 0);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 100/200 bytes a.txt]"
);
drop(bar2);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(format!("{:?}", registry.list_progress_bar()), "[]");
}
#[test]
fn test_time_series() {
let registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq!(
format!("{:?}", registry.list_io_time_series()),
"[Net [0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0], Disk [0|0|0, 5000|300|1, 20000|1200|2, 45000|2700|3, 80000|4800|4, 125000|7500|5, 180000|10800|6, 245000|14700|7, 320000|19200|8, 405000|24300|9, 500000|30000|10, 605000|36300|11, 720000|43200|12, 845000|50700|13, 980000|58800|14, 1125000|67500|15]]"
);
drop(series1);
drop(series2);
assert_eq!(registry.remove_orphan_io_time_series(), 2);
assert_eq!(format!("{:?}", registry.list_io_time_series()), "[]");
}
} | /// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )* | random_line_split |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot::RwLockUpgradableReadGuard;
use crate::CacheStats;
use crate::IoTimeSeries;
use crate::ProgressBar;
/// Data needed to render render multi-line progress.
///
/// There are 2 kinds of data:
/// - I/O time series. (ex. "Network [▁▂▄█▇▅▃▆] 3MB/s")
/// - Ordinary progress bars with "position" and "total".
/// (ex. "fetching files 123/456")
#[derive(Default, Clone, Debug)]
pub struct Registry {
render_cond: Arc<(Mutex<bool>, Condvar)>,
inner: Arc<RwLock<Inner>>,
}
macro_rules! impl_model {
{
$( $field:ident: $type:ty, )*
} => {
paste::paste! {
#[derive(Default, Debug)]
struct Inner {
$( $field: Vec<Arc<$type>>, )*
}
impl Registry {
$(
/// Register a model.
pub fn [< register_ $field >](&self, model: &Arc<$type>) {
tracing::debug!("registering {} {}", stringify!($type), model.topic());
let mut inner = self.inner.write();
inner.$field.push(model.clone());
}
/// List models registered.
pub fn [< list_ $field >](&self) -> Vec<Arc<$type>> {
self.inner.read().$field.clone()
}
/// Remove models that were dropped externally.
pub fn [< remove_orphan_ $field >](&self) -> usize {
let inner = self.inner.upgradable_read();
let orphan_count = inner
.$field
.iter()
.filter(|b| Arc::strong_count(b) == 1)
.count();
if orphan_count > 0 {
tracing::debug!(
"removing {} orphan {}",
orphan_count,
stringify!($type)
);
let mut inner = RwLockUpgradableReadGuard::upgrade(inner);
inner.$field = inner
.$field
.drain(..)
.filter(|b| Arc::strong_count(b) > 1)
.collect();
}
orphan_count
}
)*
/// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )*
}
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::new(|| {
tracing::debug!("main progress Registry initialized");
Registry {
render_cond: Arc::new((Mutex::new(false), Condvar::new())),
..Default::default()
}
});
®ISTRY
}
/// step/wait provide a mechanism for tests to step through
/// rendering/handling of the registry in a controlled manner. The
/// test calls step() which unblocks the wait()er. Then step()
/// waits for the next wait() call, ensuring that the registry
/// processing loop finished its iteration.
pub fn step(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
*ready = true;
var.notify_one();
// Wait for wait() to notify us that it completed an iteration.
var.wait(&mut ready);
}
/// See step().
pub fn wait(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
if *ready {
// We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let re | fn test_time_series() {
let registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq!(
format!("{:?}", registry.list_io_time_series()),
"[Net [0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0], Disk [0|0|0, 5000|300|1, 20000|1200|2, 45000|2700|3, 80000|4800|4, 125000|7500|5, 180000|10800|6, 245000|14700|7, 320000|19200|8, 405000|24300|9, 500000|30000|10, 605000|36300|11, 720000|43200|12, 845000|50700|13, 980000|58800|14, 1125000|67500|15]]"
);
drop(series1);
drop(series2);
assert_eq!(registry.remove_orphan_io_time_series(), 2);
assert_eq!(format!("{:?}", registry.list_io_time_series()), "[]");
}
}
| gistry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let bar2 = {
let bar = ProgressBar::new(topic.to_string(), 200, "bytes");
bar.increase_position(100);
bar.set_message("a.txt".to_string());
registry.register_progress_bar(&bar);
bar
};
assert_eq!(registry.remove_orphan_progress_bar(), 0);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 100/200 bytes a.txt]"
);
drop(bar2);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(format!("{:?}", registry.list_progress_bar()), "[]");
}
#[test]
| identifier_body |
registry.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use once_cell::sync::Lazy;
use parking_lot::Condvar;
use parking_lot::Mutex;
use parking_lot::RwLock;
use parking_lot::RwLockUpgradableReadGuard;
use crate::CacheStats;
use crate::IoTimeSeries;
use crate::ProgressBar;
/// Data needed to render render multi-line progress.
///
/// There are 2 kinds of data:
/// - I/O time series. (ex. "Network [▁▂▄█▇▅▃▆] 3MB/s")
/// - Ordinary progress bars with "position" and "total".
/// (ex. "fetching files 123/456")
#[derive(Default, Clone, Debug)]
pub struct Registry {
render_cond: Arc<(Mutex<bool>, Condvar)>,
inner: Arc<RwLock<Inner>>,
}
macro_rules! impl_model {
{
$( $field:ident: $type:ty, )*
} => {
paste::paste! {
#[derive(Default, Debug)]
struct Inner {
$( $field: Vec<Arc<$type>>, )*
}
impl Registry {
$(
/// Register a model.
pub fn [< register_ $field >](&self, model: &Arc<$type>) {
tracing::debug!("registering {} {}", stringify!($type), model.topic());
let mut inner = self.inner.write();
inner.$field.push(model.clone());
}
/// List models registered.
pub fn [< list_ $field >](&self) -> Vec<Arc<$type>> {
self.inner.read().$field.clone()
}
/// Remove models that were dropped externally.
pub fn [< remove_orphan_ $field >](&self) -> usize {
let inner = self.inner.upgradable_read();
let orphan_count = inner
.$field
.iter()
.filter(|b| Arc::strong_count(b) == 1)
.count();
if orphan_count > 0 {
tracing::debug!(
"removing {} orphan {}",
orphan_count,
stringify!($type)
);
let mut inner = RwLockUpgradableReadGuard::upgrade(inner);
inner.$field = inner
.$field
.drain(..)
.filter(|b| Arc::strong_count(b) > 1)
.collect();
}
orphan_count
}
)*
/// Remove all registered models that are dropped externally.
pub fn remove_orphan_models(&self) {
$( self.[< remove_orphan_ $field >](); )*
}
}
}
};
}
impl_model! {
cache_stats: CacheStats,
io_time_series: IoTimeSeries,
progress_bar: ProgressBar,
}
impl Registry {
/// The "main" progress registry in this process.
pub fn main() -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::new(|| {
tracing::debug!("main progress Registry initialized");
Registry {
render_cond: Arc::new((Mutex::new(false), Condvar::new())),
..Default::default()
}
});
®ISTRY
}
/// step/wait provide a mechanism for tests to step through
/// rendering/handling of the registry in a controlled manner. The
/// test calls step() which unblocks the wait()er. Then step()
/// waits for the next wait() call, ensuring that the registry
/// processing loop finished its iteration.
pub fn step(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
*ready = true;
var.notify_one();
// Wait for wait() to notify us that it completed an iteration.
var.wait(&mut ready);
}
/// See step().
pub fn wait(&self) {
let &(ref lock, ref var) = &*self.render_cond;
let mut ready = lock.lock();
if *ready {
// We've come around to the next iteration's wait() call -
// notify step() that we finished an iteration.
*ready = false;
var.notify_one();
}
// Wait for next step() call.
var.wait(&mut ready);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_bar() {
let registry = Registry::default();
let topic = "fetching files";
// Add 2 progress bars.
let bar1 = {
let bar = ProgressBar::new(topic.to_string(), 100, "files");
bar.set_position(50);
registry.register_progress_bar(&bar);
bar
};
let bar2 = {
let bar = ProgressBar::new(topic.to_string(), 200, "bytes");
bar.increase_position(100);
bar.set_message("a.txt".to_string());
registry.register_progress_bar(&bar);
bar
};
assert_eq!(registry.remove_orphan_progress_bar(), 0);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 50/100 files, [fetching files 100/200 bytes a.txt]"
);
// Dropping a bar marks it as "completed" and affects aggregated_bars.
drop(bar1);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(
format!("{:?}", registry.list_progress_bar()),
"[[fetching files 100/200 bytes a.txt]"
);
drop(bar2);
assert_eq!(registry.remove_orphan_progress_bar(), 1);
assert_eq!(format!("{:?}", registry.list_progress_bar()), "[]");
}
#[test]
fn test_time_series | registry = Registry::default();
let series1 = IoTimeSeries::new("Net", "requests");
registry.register_io_time_series(&series1);
let series2 = IoTimeSeries::new("Disk", "files");
series2.populate_test_samples(1, 1, 1);
registry.register_io_time_series(&series2);
assert_eq!(
format!("{:?}", registry.list_io_time_series()),
"[Net [0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0, 0|0|0], Disk [0|0|0, 5000|300|1, 20000|1200|2, 45000|2700|3, 80000|4800|4, 125000|7500|5, 180000|10800|6, 245000|14700|7, 320000|19200|8, 405000|24300|9, 500000|30000|10, 605000|36300|11, 720000|43200|12, 845000|50700|13, 980000|58800|14, 1125000|67500|15]]"
);
drop(series1);
drop(series2);
assert_eq!(registry.remove_orphan_io_time_series(), 2);
assert_eq!(format!("{:?}", registry.list_io_time_series()), "[]");
}
}
| () {
let | identifier_name |
Success.js | import PropTypes from "prop-types";
import { Link } from "react-router"; |
<h4 className="text-center push-ends">
Welcome{person.nickName ? ` ${(person.nickName || person.firstName)}` : ""}!
</h4>
<p className="text-left">
Congratulations on setting up your NewSpring account!
This account will help us to serve you better in your walk with Jesus.
To help us make sure the information we have is accurate and up to date,
we would love if you could complete your profile.
</p>
<Link to="/profile/settings" className="one-whole btn push-ends" >
Complete Profile Now
</Link>
<button className="btn--thin btn--small btn--dark-tertiary one-whole " onClick={onExit}>
Complete Later
</button>
</div>
);
Success.propTypes = {
person: PropTypes.object, // eslint-disable-line
onExit: PropTypes.func,
};
export default Success; |
const Success = ({ person, onExit }) => (
<div className="soft soft-double-ends one-whole text-center"> | random_line_split |
task_18.py | #!/usr/bin/python3
from pyrob.api import *
@task
def task_8_28():
if wall_is_above() != True: | while(wall_is_on_the_right() != True and wall_is_beneath() and wall_is_above()):
move_right()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while(wall_is_on_the_left() != True):
move_left()
while (wall_is_on_the_left() != True and wall_is_beneath() and wall_is_above()):
move_left()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left()
if __name__ == '__main__':
run_tasks() | while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left()
| random_line_split |
task_18.py | #!/usr/bin/python3
from pyrob.api import *
@task
def task_8_28():
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
|
while(wall_is_on_the_right() != True and wall_is_beneath() and wall_is_above()):
move_right()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while(wall_is_on_the_left() != True):
move_left()
while (wall_is_on_the_left() != True and wall_is_beneath() and wall_is_above()):
move_left()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left()
if __name__ == '__main__':
run_tasks() | move_left() | conditional_block |
task_18.py | #!/usr/bin/python3
from pyrob.api import *
@task
def | ():
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left()
while(wall_is_on_the_right() != True and wall_is_beneath() and wall_is_above()):
move_right()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while(wall_is_on_the_left() != True):
move_left()
while (wall_is_on_the_left() != True and wall_is_beneath() and wall_is_above()):
move_left()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left()
if __name__ == '__main__':
run_tasks() | task_8_28 | identifier_name |
task_18.py | #!/usr/bin/python3
from pyrob.api import *
@task
def task_8_28():
|
if __name__ == '__main__':
run_tasks() | if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left()
while(wall_is_on_the_right() != True and wall_is_beneath() and wall_is_above()):
move_right()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while(wall_is_on_the_left() != True):
move_left()
while (wall_is_on_the_left() != True and wall_is_beneath() and wall_is_above()):
move_left()
if wall_is_above() != True:
while (wall_is_above() != True):
move_up()
while (wall_is_on_the_left() != True):
move_left() | identifier_body |
app.component.ts | import {Component, Inject} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES, Router} from '@angular/router';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {DialogDemoComponent} from './dialog/dialog-demo.component';
import {TabsDemoComponent} from './tabs/tabs-demo.component';
import {TooltipDemoComponent} from './tooltip/tooltip-demo.component';
import {Select2DemoComponent} from './select2/select2-demo.component';
import {LogService, LogLevel} from '../src/common/services/log.service.ts';
import {IS_DEV_MODE} from './constants';
import {RadioButtonGroupDemoComponent} from './radio-button-group/radio-button-group-demo.component';
@Component({
selector: 'auiNgDemoApp',
directives: [...ROUTER_DIRECTIVES],
styles: [`
.aui-ng-page {
height: 100vh;
width: 100vw;
padding: 15px;
}
.aui-ng-nav {
max-width: 150px;
min-width: 150px;
vertical-align: top;
padding-top: 25px;
border-right: 1px solid #ccc;
}
.aui-ng-content {
vertical-align: top;
padding-left: 15px;
}
`],
template: `
<table class="aui-ng-page">
<tr>
<td class="aui-ng-nav" width="15%">
<ul>
<li router-active>
<a [routerLink]="['/dialog'] ">Dialog</a>
</li>
<li router-active>
<a [routerLink]=" ['/tabs'] ">Tabs</a>
</li>
<li router-active>
<a [routerLink]=" ['/tooltip']">Tooltips</a>
</li>
<li router-active>
<a [routerLink]=" ['/select2']">Select2</a>
</li>
<li router-active>
<a [routerLink]=" ['/radio-button-group']">Radio button group</a>
</li>
</ul>
</td>
<td class="aui-ng-content" width="85%">
<router-outlet></router-outlet>
</td>
</tr>
</table>
`
})
@Routes([
{path: '/', component: DialogDemoComponent}, // remove this entry as soon as useAsDefault is implemented
{path: '/dialog', component: DialogDemoComponent}, // add {useAsDefault: true}
{path: '/tabs', component: TabsDemoComponent},
{path: '/tooltip', component: TooltipDemoComponent},
{path: '/select2', component: Select2DemoComponent},
{path: '/radio-button-group', component: RadioButtonGroupDemoComponent},
])
export class AuiNgDemoAppComponent {
constructor(
private router: Router,
private logService: LogService,
@Inject(IS_DEV_MODE) private isDevMode: string,
translate : TranslateService
) |
}
| {
if (isDevMode) {
this.logService.setLogLevel(LogLevel.DEBUG);
}
translate.setTranslation('en', Object.assign({}, require('../src/assets/i18n/en.json'), require('./assets/i18n/en.json')));
translate.setTranslation('de', Object.assign({}, require('../src/assets/i18n/de.json'), require('./assets/i18n/de.json')));
translate.use('en');
} | identifier_body |
app.component.ts | import {Component, Inject} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES, Router} from '@angular/router';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {DialogDemoComponent} from './dialog/dialog-demo.component';
import {TabsDemoComponent} from './tabs/tabs-demo.component';
import {TooltipDemoComponent} from './tooltip/tooltip-demo.component';
import {Select2DemoComponent} from './select2/select2-demo.component';
import {LogService, LogLevel} from '../src/common/services/log.service.ts';
import {IS_DEV_MODE} from './constants';
import {RadioButtonGroupDemoComponent} from './radio-button-group/radio-button-group-demo.component';
@Component({
selector: 'auiNgDemoApp',
directives: [...ROUTER_DIRECTIVES],
styles: [`
.aui-ng-page {
height: 100vh;
width: 100vw;
padding: 15px;
}
.aui-ng-nav {
max-width: 150px;
min-width: 150px;
vertical-align: top;
padding-top: 25px;
border-right: 1px solid #ccc;
}
.aui-ng-content {
vertical-align: top;
padding-left: 15px;
}
`],
template: `
<table class="aui-ng-page">
<tr>
<td class="aui-ng-nav" width="15%">
<ul>
<li router-active>
<a [routerLink]="['/dialog'] ">Dialog</a>
</li>
<li router-active>
<a [routerLink]=" ['/tabs'] ">Tabs</a>
</li>
<li router-active>
<a [routerLink]=" ['/tooltip']">Tooltips</a>
</li>
<li router-active>
<a [routerLink]=" ['/select2']">Select2</a>
</li>
<li router-active>
<a [routerLink]=" ['/radio-button-group']">Radio button group</a>
</li>
</ul>
</td>
<td class="aui-ng-content" width="85%">
<router-outlet></router-outlet>
</td>
</tr>
</table>
`
})
@Routes([
{path: '/', component: DialogDemoComponent}, // remove this entry as soon as useAsDefault is implemented
{path: '/dialog', component: DialogDemoComponent}, // add {useAsDefault: true}
{path: '/tabs', component: TabsDemoComponent},
{path: '/tooltip', component: TooltipDemoComponent},
{path: '/select2', component: Select2DemoComponent},
{path: '/radio-button-group', component: RadioButtonGroupDemoComponent},
])
export class AuiNgDemoAppComponent {
constructor(
private router: Router,
private logService: LogService,
@Inject(IS_DEV_MODE) private isDevMode: string,
translate : TranslateService
) {
if (isDevMode) |
translate.setTranslation('en', Object.assign({}, require('../src/assets/i18n/en.json'), require('./assets/i18n/en.json')));
translate.setTranslation('de', Object.assign({}, require('../src/assets/i18n/de.json'), require('./assets/i18n/de.json')));
translate.use('en');
}
}
| {
this.logService.setLogLevel(LogLevel.DEBUG);
} | conditional_block |
app.component.ts | import {Component, Inject} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES, Router} from '@angular/router';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {DialogDemoComponent} from './dialog/dialog-demo.component';
import {TabsDemoComponent} from './tabs/tabs-demo.component';
import {TooltipDemoComponent} from './tooltip/tooltip-demo.component';
import {Select2DemoComponent} from './select2/select2-demo.component';
import {LogService, LogLevel} from '../src/common/services/log.service.ts';
import {IS_DEV_MODE} from './constants';
import {RadioButtonGroupDemoComponent} from './radio-button-group/radio-button-group-demo.component';
@Component({
selector: 'auiNgDemoApp',
directives: [...ROUTER_DIRECTIVES],
styles: [`
.aui-ng-page {
height: 100vh;
width: 100vw;
padding: 15px;
}
.aui-ng-nav {
max-width: 150px;
min-width: 150px;
vertical-align: top;
padding-top: 25px;
border-right: 1px solid #ccc;
}
.aui-ng-content {
vertical-align: top;
padding-left: 15px;
}
`],
template: `
<table class="aui-ng-page">
<tr>
<td class="aui-ng-nav" width="15%">
<ul>
<li router-active>
<a [routerLink]="['/dialog'] ">Dialog</a>
</li>
<li router-active>
<a [routerLink]=" ['/tabs'] ">Tabs</a>
</li>
<li router-active>
<a [routerLink]=" ['/tooltip']">Tooltips</a>
</li>
<li router-active>
<a [routerLink]=" ['/select2']">Select2</a>
</li>
<li router-active>
<a [routerLink]=" ['/radio-button-group']">Radio button group</a>
</li>
</ul>
</td>
<td class="aui-ng-content" width="85%">
<router-outlet></router-outlet>
</td>
</tr>
</table>
| {path: '/tabs', component: TabsDemoComponent},
{path: '/tooltip', component: TooltipDemoComponent},
{path: '/select2', component: Select2DemoComponent},
{path: '/radio-button-group', component: RadioButtonGroupDemoComponent},
])
export class AuiNgDemoAppComponent {
constructor(
private router: Router,
private logService: LogService,
@Inject(IS_DEV_MODE) private isDevMode: string,
translate : TranslateService
) {
if (isDevMode) {
this.logService.setLogLevel(LogLevel.DEBUG);
}
translate.setTranslation('en', Object.assign({}, require('../src/assets/i18n/en.json'), require('./assets/i18n/en.json')));
translate.setTranslation('de', Object.assign({}, require('../src/assets/i18n/de.json'), require('./assets/i18n/de.json')));
translate.use('en');
}
} | `
})
@Routes([
{path: '/', component: DialogDemoComponent}, // remove this entry as soon as useAsDefault is implemented
{path: '/dialog', component: DialogDemoComponent}, // add {useAsDefault: true} | random_line_split |
app.component.ts | import {Component, Inject} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES, Router} from '@angular/router';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {DialogDemoComponent} from './dialog/dialog-demo.component';
import {TabsDemoComponent} from './tabs/tabs-demo.component';
import {TooltipDemoComponent} from './tooltip/tooltip-demo.component';
import {Select2DemoComponent} from './select2/select2-demo.component';
import {LogService, LogLevel} from '../src/common/services/log.service.ts';
import {IS_DEV_MODE} from './constants';
import {RadioButtonGroupDemoComponent} from './radio-button-group/radio-button-group-demo.component';
@Component({
selector: 'auiNgDemoApp',
directives: [...ROUTER_DIRECTIVES],
styles: [`
.aui-ng-page {
height: 100vh;
width: 100vw;
padding: 15px;
}
.aui-ng-nav {
max-width: 150px;
min-width: 150px;
vertical-align: top;
padding-top: 25px;
border-right: 1px solid #ccc;
}
.aui-ng-content {
vertical-align: top;
padding-left: 15px;
}
`],
template: `
<table class="aui-ng-page">
<tr>
<td class="aui-ng-nav" width="15%">
<ul>
<li router-active>
<a [routerLink]="['/dialog'] ">Dialog</a>
</li>
<li router-active>
<a [routerLink]=" ['/tabs'] ">Tabs</a>
</li>
<li router-active>
<a [routerLink]=" ['/tooltip']">Tooltips</a>
</li>
<li router-active>
<a [routerLink]=" ['/select2']">Select2</a>
</li>
<li router-active>
<a [routerLink]=" ['/radio-button-group']">Radio button group</a>
</li>
</ul>
</td>
<td class="aui-ng-content" width="85%">
<router-outlet></router-outlet>
</td>
</tr>
</table>
`
})
@Routes([
{path: '/', component: DialogDemoComponent}, // remove this entry as soon as useAsDefault is implemented
{path: '/dialog', component: DialogDemoComponent}, // add {useAsDefault: true}
{path: '/tabs', component: TabsDemoComponent},
{path: '/tooltip', component: TooltipDemoComponent},
{path: '/select2', component: Select2DemoComponent},
{path: '/radio-button-group', component: RadioButtonGroupDemoComponent},
])
export class | {
constructor(
private router: Router,
private logService: LogService,
@Inject(IS_DEV_MODE) private isDevMode: string,
translate : TranslateService
) {
if (isDevMode) {
this.logService.setLogLevel(LogLevel.DEBUG);
}
translate.setTranslation('en', Object.assign({}, require('../src/assets/i18n/en.json'), require('./assets/i18n/en.json')));
translate.setTranslation('de', Object.assign({}, require('../src/assets/i18n/de.json'), require('./assets/i18n/de.json')));
translate.use('en');
}
}
| AuiNgDemoAppComponent | identifier_name |
deployments.py | # Copyright (c) 2013 Mirantis, Inc.
#
# 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.
from sqlalchemy import desc
from webob import exc
from murano.api.v1 import request_statistics
from murano.common import policy
from murano.common import utils
from murano.db import models
from murano.db import session as db_session
from murano.openstack.common.gettextutils import _ # noqa
from murano.openstack.common import log as logging
from murano.openstack.common import wsgi
LOG = logging.getLogger(__name__)
API_NAME = 'Deployments'
class Controller(object):
@request_statistics.stats_count(API_NAME, 'Index')
def index(self, request, environment_id):
target = {"environment_id": environment_id}
policy.check("list_deployments", request.context, target)
unit = db_session.get_session()
verify_and_get_env(unit, environment_id, request)
query = unit.query(models.Deployment) \
.filter_by(environment_id=environment_id) \
.order_by(desc(models.Deployment.created))
result = query.all()
deployments = [set_dep_state(deployment, unit).to_dict() for deployment
in result]
return {'deployments': deployments}
@request_statistics.stats_count(API_NAME, 'Statuses')
def statuses(self, request, environment_id, deployment_id):
target = {"environment_id": environment_id,
"deployment_id": deployment_id}
policy.check("statuses_deployments", request.context, target)
unit = db_session.get_session()
query = unit.query(models.Status) \
.filter_by(deployment_id=deployment_id) \
.order_by(models.Status.created)
deployment = verify_and_get_deployment(unit, environment_id,
deployment_id)
if 'service_id' in request.GET:
service_id_set = set(request.GET.getall('service_id'))
environment = deployment.description
entity_ids = []
for service in environment.get('services', []):
if service['?']['id'] in service_id_set:
id_map = utils.build_entity_map(service)
entity_ids = entity_ids + id_map.keys()
if entity_ids:
query = query.filter(models.Status.entity_id.in_(entity_ids))
else:
return {'reports': []}
result = query.all()
return {'reports': [status.to_dict() for status in result]}
def verify_and_get_env(db_session, environment_id, request):
|
def _patch_description(description):
description['services'] = description.get('applications', [])
del description['applications']
def verify_and_get_deployment(db_session, environment_id, deployment_id):
deployment = db_session.query(models.Deployment).get(deployment_id)
if not deployment:
LOG.info(_('Deployment with id {0} not found').format(deployment_id))
raise exc.HTTPNotFound
if deployment.environment_id != environment_id:
LOG.info(_('Deployment with id {0} not found'
' in environment {1}').format(deployment_id,
environment_id))
raise exc.HTTPBadRequest
_patch_description(deployment.description)
return deployment
def create_resource():
return wsgi.Resource(Controller())
def set_dep_state(deployment, unit):
num_errors = unit.query(models.Status).filter_by(
level='error',
deployment_id=deployment.id).count()
num_warnings = unit.query(models.Status).filter_by(
level='warning',
deployment_id=deployment.id).count()
if deployment.finished:
if num_errors:
deployment.state = 'completed_w_errors'
elif num_warnings:
deployment.state = 'completed_w_warnings'
else:
deployment.state = 'success'
else:
if num_errors:
deployment.state = 'running_w_errors'
elif num_warnings:
deployment.state = 'running_w_warnings'
else:
deployment.state = 'running'
_patch_description(deployment.description)
return deployment
| environment = db_session.query(models.Environment).get(environment_id)
if not environment:
LOG.info(_('Environment with id {0} not found').format(environment_id))
raise exc.HTTPNotFound
if environment.tenant_id != request.context.tenant:
LOG.info(_('User is not authorized to access this tenant resources.'))
raise exc.HTTPUnauthorized
return environment | identifier_body |
deployments.py | # Copyright (c) 2013 Mirantis, Inc.
#
# 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.
from sqlalchemy import desc
from webob import exc
from murano.api.v1 import request_statistics
from murano.common import policy
from murano.common import utils
from murano.db import models
from murano.db import session as db_session
from murano.openstack.common.gettextutils import _ # noqa
from murano.openstack.common import log as logging
from murano.openstack.common import wsgi
LOG = logging.getLogger(__name__)
API_NAME = 'Deployments'
class Controller(object):
@request_statistics.stats_count(API_NAME, 'Index')
def index(self, request, environment_id):
target = {"environment_id": environment_id}
policy.check("list_deployments", request.context, target)
unit = db_session.get_session()
verify_and_get_env(unit, environment_id, request)
query = unit.query(models.Deployment) \
.filter_by(environment_id=environment_id) \
.order_by(desc(models.Deployment.created))
result = query.all()
deployments = [set_dep_state(deployment, unit).to_dict() for deployment
in result]
return {'deployments': deployments}
@request_statistics.stats_count(API_NAME, 'Statuses')
def statuses(self, request, environment_id, deployment_id):
target = {"environment_id": environment_id,
"deployment_id": deployment_id}
policy.check("statuses_deployments", request.context, target)
unit = db_session.get_session()
query = unit.query(models.Status) \
.filter_by(deployment_id=deployment_id) \
.order_by(models.Status.created)
deployment = verify_and_get_deployment(unit, environment_id,
deployment_id)
if 'service_id' in request.GET:
service_id_set = set(request.GET.getall('service_id'))
environment = deployment.description
entity_ids = []
for service in environment.get('services', []):
if service['?']['id'] in service_id_set:
id_map = utils.build_entity_map(service)
entity_ids = entity_ids + id_map.keys()
if entity_ids:
query = query.filter(models.Status.entity_id.in_(entity_ids))
else:
return {'reports': []}
result = query.all()
return {'reports': [status.to_dict() for status in result]}
def verify_and_get_env(db_session, environment_id, request):
environment = db_session.query(models.Environment).get(environment_id)
if not environment:
LOG.info(_('Environment with id {0} not found').format(environment_id))
raise exc.HTTPNotFound
if environment.tenant_id != request.context.tenant:
LOG.info(_('User is not authorized to access this tenant resources.'))
raise exc.HTTPUnauthorized
return environment
def | (description):
description['services'] = description.get('applications', [])
del description['applications']
def verify_and_get_deployment(db_session, environment_id, deployment_id):
deployment = db_session.query(models.Deployment).get(deployment_id)
if not deployment:
LOG.info(_('Deployment with id {0} not found').format(deployment_id))
raise exc.HTTPNotFound
if deployment.environment_id != environment_id:
LOG.info(_('Deployment with id {0} not found'
' in environment {1}').format(deployment_id,
environment_id))
raise exc.HTTPBadRequest
_patch_description(deployment.description)
return deployment
def create_resource():
return wsgi.Resource(Controller())
def set_dep_state(deployment, unit):
num_errors = unit.query(models.Status).filter_by(
level='error',
deployment_id=deployment.id).count()
num_warnings = unit.query(models.Status).filter_by(
level='warning',
deployment_id=deployment.id).count()
if deployment.finished:
if num_errors:
deployment.state = 'completed_w_errors'
elif num_warnings:
deployment.state = 'completed_w_warnings'
else:
deployment.state = 'success'
else:
if num_errors:
deployment.state = 'running_w_errors'
elif num_warnings:
deployment.state = 'running_w_warnings'
else:
deployment.state = 'running'
_patch_description(deployment.description)
return deployment
| _patch_description | identifier_name |
deployments.py | # Copyright (c) 2013 Mirantis, Inc.
#
# 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.
from sqlalchemy import desc
from webob import exc
from murano.api.v1 import request_statistics
from murano.common import policy
from murano.common import utils
from murano.db import models
from murano.db import session as db_session
from murano.openstack.common.gettextutils import _ # noqa
from murano.openstack.common import log as logging
from murano.openstack.common import wsgi
LOG = logging.getLogger(__name__)
API_NAME = 'Deployments'
class Controller(object):
@request_statistics.stats_count(API_NAME, 'Index')
def index(self, request, environment_id):
target = {"environment_id": environment_id}
policy.check("list_deployments", request.context, target)
unit = db_session.get_session()
verify_and_get_env(unit, environment_id, request)
query = unit.query(models.Deployment) \
.filter_by(environment_id=environment_id) \
.order_by(desc(models.Deployment.created))
result = query.all()
deployments = [set_dep_state(deployment, unit).to_dict() for deployment
in result]
return {'deployments': deployments}
@request_statistics.stats_count(API_NAME, 'Statuses')
def statuses(self, request, environment_id, deployment_id):
target = {"environment_id": environment_id,
"deployment_id": deployment_id}
policy.check("statuses_deployments", request.context, target)
unit = db_session.get_session()
query = unit.query(models.Status) \
.filter_by(deployment_id=deployment_id) \
.order_by(models.Status.created)
deployment = verify_and_get_deployment(unit, environment_id,
deployment_id)
if 'service_id' in request.GET:
service_id_set = set(request.GET.getall('service_id'))
environment = deployment.description
entity_ids = []
for service in environment.get('services', []):
if service['?']['id'] in service_id_set:
id_map = utils.build_entity_map(service)
entity_ids = entity_ids + id_map.keys()
if entity_ids:
query = query.filter(models.Status.entity_id.in_(entity_ids))
else:
return {'reports': []}
result = query.all()
return {'reports': [status.to_dict() for status in result]}
def verify_and_get_env(db_session, environment_id, request):
environment = db_session.query(models.Environment).get(environment_id)
if not environment:
LOG.info(_('Environment with id {0} not found').format(environment_id))
raise exc.HTTPNotFound
if environment.tenant_id != request.context.tenant:
LOG.info(_('User is not authorized to access this tenant resources.'))
raise exc.HTTPUnauthorized
return environment
def _patch_description(description):
description['services'] = description.get('applications', [])
del description['applications']
def verify_and_get_deployment(db_session, environment_id, deployment_id):
deployment = db_session.query(models.Deployment).get(deployment_id)
if not deployment:
LOG.info(_('Deployment with id {0} not found').format(deployment_id))
raise exc.HTTPNotFound
if deployment.environment_id != environment_id:
LOG.info(_('Deployment with id {0} not found'
' in environment {1}').format(deployment_id,
environment_id))
raise exc.HTTPBadRequest
_patch_description(deployment.description)
return deployment
def create_resource():
return wsgi.Resource(Controller())
| num_errors = unit.query(models.Status).filter_by(
level='error',
deployment_id=deployment.id).count()
num_warnings = unit.query(models.Status).filter_by(
level='warning',
deployment_id=deployment.id).count()
if deployment.finished:
if num_errors:
deployment.state = 'completed_w_errors'
elif num_warnings:
deployment.state = 'completed_w_warnings'
else:
deployment.state = 'success'
else:
if num_errors:
deployment.state = 'running_w_errors'
elif num_warnings:
deployment.state = 'running_w_warnings'
else:
deployment.state = 'running'
_patch_description(deployment.description)
return deployment | def set_dep_state(deployment, unit): | random_line_split |
deployments.py | # Copyright (c) 2013 Mirantis, Inc.
#
# 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.
from sqlalchemy import desc
from webob import exc
from murano.api.v1 import request_statistics
from murano.common import policy
from murano.common import utils
from murano.db import models
from murano.db import session as db_session
from murano.openstack.common.gettextutils import _ # noqa
from murano.openstack.common import log as logging
from murano.openstack.common import wsgi
LOG = logging.getLogger(__name__)
API_NAME = 'Deployments'
class Controller(object):
@request_statistics.stats_count(API_NAME, 'Index')
def index(self, request, environment_id):
target = {"environment_id": environment_id}
policy.check("list_deployments", request.context, target)
unit = db_session.get_session()
verify_and_get_env(unit, environment_id, request)
query = unit.query(models.Deployment) \
.filter_by(environment_id=environment_id) \
.order_by(desc(models.Deployment.created))
result = query.all()
deployments = [set_dep_state(deployment, unit).to_dict() for deployment
in result]
return {'deployments': deployments}
@request_statistics.stats_count(API_NAME, 'Statuses')
def statuses(self, request, environment_id, deployment_id):
target = {"environment_id": environment_id,
"deployment_id": deployment_id}
policy.check("statuses_deployments", request.context, target)
unit = db_session.get_session()
query = unit.query(models.Status) \
.filter_by(deployment_id=deployment_id) \
.order_by(models.Status.created)
deployment = verify_and_get_deployment(unit, environment_id,
deployment_id)
if 'service_id' in request.GET:
service_id_set = set(request.GET.getall('service_id'))
environment = deployment.description
entity_ids = []
for service in environment.get('services', []):
if service['?']['id'] in service_id_set:
id_map = utils.build_entity_map(service)
entity_ids = entity_ids + id_map.keys()
if entity_ids:
query = query.filter(models.Status.entity_id.in_(entity_ids))
else:
return {'reports': []}
result = query.all()
return {'reports': [status.to_dict() for status in result]}
def verify_and_get_env(db_session, environment_id, request):
environment = db_session.query(models.Environment).get(environment_id)
if not environment:
LOG.info(_('Environment with id {0} not found').format(environment_id))
raise exc.HTTPNotFound
if environment.tenant_id != request.context.tenant:
LOG.info(_('User is not authorized to access this tenant resources.'))
raise exc.HTTPUnauthorized
return environment
def _patch_description(description):
description['services'] = description.get('applications', [])
del description['applications']
def verify_and_get_deployment(db_session, environment_id, deployment_id):
deployment = db_session.query(models.Deployment).get(deployment_id)
if not deployment:
|
if deployment.environment_id != environment_id:
LOG.info(_('Deployment with id {0} not found'
' in environment {1}').format(deployment_id,
environment_id))
raise exc.HTTPBadRequest
_patch_description(deployment.description)
return deployment
def create_resource():
return wsgi.Resource(Controller())
def set_dep_state(deployment, unit):
num_errors = unit.query(models.Status).filter_by(
level='error',
deployment_id=deployment.id).count()
num_warnings = unit.query(models.Status).filter_by(
level='warning',
deployment_id=deployment.id).count()
if deployment.finished:
if num_errors:
deployment.state = 'completed_w_errors'
elif num_warnings:
deployment.state = 'completed_w_warnings'
else:
deployment.state = 'success'
else:
if num_errors:
deployment.state = 'running_w_errors'
elif num_warnings:
deployment.state = 'running_w_warnings'
else:
deployment.state = 'running'
_patch_description(deployment.description)
return deployment
| LOG.info(_('Deployment with id {0} not found').format(deployment_id))
raise exc.HTTPNotFound | conditional_block |
where-clauses-cross-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:where_clauses_xc.rs
extern crate where_clauses_xc;
use where_clauses_xc::{Equal, equal}; | println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} |
fn main() {
println!("{}", equal(&1, &2)); | random_line_split |
where-clauses-cross-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:where_clauses_xc.rs
extern crate where_clauses_xc;
use where_clauses_xc::{Equal, equal};
fn | () {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
}
| main | identifier_name |
where-clauses-cross-crate.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:where_clauses_xc.rs
extern crate where_clauses_xc;
use where_clauses_xc::{Equal, equal};
fn main() | {
println!("{}", equal(&1, &2));
println!("{}", equal(&1, &1));
println!("{}", "hello".equal(&"hello"));
println!("{}", "hello".equals::<isize,&str>(&1, &1, &"foo", &"bar"));
} | identifier_body | |
jshighlight.core-v1.0.0.src.js | JSHL.language = JSHL.language || {};
JSHL.language.javascript = {
//文档注释 --> 普通注释 --> 字符串 --> 关键字--> 变量 --> 内置对象-->数字-->boolean-->操作符
//cls : ['js-doc','js-com','js-str','js-key'/*,'js-var'*/,'js-obj','js-num','js-bol','js-ope'],
reg : {
'doc' : /.?(\/\*{2}[\s\S]*?\*\/)/, //文档注释
'com' : /(\/\*(?!\*)[\s\S]*?\*\/|\/\/.*)/, //普通注释
'str' : /('(?:(?:\\'|[^'\r\n])*?)'|"(?:(?:\\"|[^"\r\n])*?)")/, //字符串
'key' : /(?:[^\$_@\w])(break|delete|function|return|typeof|arguments|case|do|if|switch|var|catch|else|in|this|void|continue|instanceof|throw|while|debugger|finally|new|with|default|for|null|try)(?![$_@\w])/, //关键字
'obj' : /(?:[^\$_@\w])(Array|String|Date|Math|Boolean|Number|Function|Global|Error|RegExp|Object|window|document)(?:[^$_@\w])/, //内置对象
'num' : /\b(\d+(?:\.\d+)?(?:[Ee][-+]?(?:\d)+)?|NaN|Infinity)\b/, //数字
'bol' : /(?:[^$_@\w])(true|false)(?:[^$_@\w])/, //布尔值
'ope' : /(==|=|===|\+|-|\+=|-=|\*=|\\=|%=|<|<=|>|>=)/ //操作符
}
}
JSHL.language.html = {
cls : ['com','mrk','attr','val'],
reg : {
'com' : /(<\!--[\s\S]*?-->)/, //注释
'mrk' : /(<\/?\w+(?:.*?)>)/ //标签
},
markup : true // markup support
,
include : [
{
lang : 'javascript',
wrapper : /<script>([\s\S]*?)<\/script>/g
},
{
lang : 'css',
wrapper : /<style>([\s\S]*?)<\/style>/g
}
]
}
JSHL.language.css = { | reg : {
'com' : /(\/\*[\s\S]*?\*\/)/, //注释
//'key' : /((?:\.|#)?(?:\w+(?:[,\s:#\w\.]+)?)+){/, //选择器
'key' : /([^{\n\$\|]*?){/, //选择器
'obj' : /(?:([\w-]+?)\s*\:([\w\s"',\-\#]*))/ //属性名:属性值
}
}
JSHL.extendLanguage = function(langName, langObj){
JSHL.language[langName] = langObj;
if(langObj.wrapper){
JSHL.language[langObj.wrapper].include.push(langObj.content);
}
JSHL(langName);
}
function JSHL(langName){
var pres = document.getElementsByTagName('pre'),
len = pres.length,
pre = null,
index = 0,
lang = 'javascript',
html,outer;
function parseHTML(html){
return html.replace(/</g,'<').replace(/>/g,'>').replace(/(\r?\n)$/g,'');
}
function addLineNumber(nums){
var html = ['<div class="','jshl-linenum','">'], i=1;
for(; i< nums; i+=1) html.push(i+'.<br/>');
html.push(nums,'.</div>');
return html.join('')
}
/**
* 根据语言高亮代码
* @param {String} html
* @param {String} lang
* @param {Boolean} findParent
* @returns {*}
*/
function hlbylanguage(html, lang, findParent){
//var ln = addLineNumber(html.split('\n').length);
//console.log(lang,html);
if(!(lang in JSHL.language))
return html + (findParent ? addLineNumber(html.split('\n').length) : '')
var l = JSHL.language[lang];
if(findParent && l.wrapper) l = JSHL.language[l.wrapper];
if(!l) return html + (findParent ? addLineNumber(html.split('\n').length) : '')
html = '|'+html+'|';
var ln = /(<div class="jshl-linenum">(?:.*?)<\/div>)/g;
if(ln.test(html)){ //已经加入了行号
html = html.replace(ln,'{@jshl-linenum@}');
}
var //start = new Date(),
pattern = l.reg,
markup = l.markup,
cls = l.cls || [],
defaultCls = (cls.length === 0),
inc = l.include,
olanghl=[],placeholder=[],pl='',wrapper,
//console.log(lang +' start...');
// 文档注释 --> com --> mrk --> 关键字-->vars -->内置对象-->数字-->boolean-->操作符
type = ['doc','com','mrk','str','key','var','obj','num','bol','ope'],
p = [], len = type.length, i = 0;
/*if(cls.length === 0 || pattern.length === 0){
return
}*/
for(; i< len; i+=1){
if(pattern[type[i]]){
p.push(pattern[type[i]].source); //正则表达式
defaultCls && cls.push(type[i]); //对应的类名
}
}
pattern = new RegExp(p.join("|"),'g');
//提取其他语言的代码
if(inc && inc.length > 0){
for(i=0; i< inc.length; i+=1){
wrapper = new RegExp(inc[i].wrapper.source.replace(/</g,'<').replace(/>/g,'>'),'gi');
html = html.replace(wrapper,function($0,$1){
//console.log("$0:",$0,"$1",$1);
pl = '{@'+Math.random()+'@}';
placeholder.push(pl);
olanghl.push(hlbylanguage($1,inc[i].lang, false))
return $0.replace($1,pl);
});
}
}
html = html.replace(pattern,function(){
//console.log(arguments)
var args = Array.prototype.slice.call(arguments,0),
currArg1 = null,
currArg = null,
len = args.length - 2,
index = len;
for(; index > 0; index-=1){
currArg = args[index];
if(currArg){
if(markup && cls[index-1] === 'mrk'){
currArg1 = currArg.replace(
/(\w+)=(".*?")/g,
'<span class="'+JSHL.language.html.cls[2]+
'">$1</span>=<span class="'+JSHL.language.html.cls[3]+'">$2</span>'
)
}
args[0] = args[0].replace(currArg,'<span class="'+cls[index-1]+'">'+(currArg1 !== null ?currArg1:currArg)+'</span>')
}
}
return args[0];
});
for(i=0; i< placeholder.length; i++){ //高亮包含的其他语言
html = html.replace(new RegExp('{@.*?'+placeholder[i].replace(/[{@}]/g,'')+'.*?@}','g'),placeholder[i])
.replace(placeholder[i], olanghl[i]);
}
return html.replace(/^(\|)|(\|)$/g,'').replace('{@jshl-linenum@}','') + (findParent ? addLineNumber(html.split('\n').length) : '');
}
for(; index < len; index += 1){
pre = pres[index];
lang = pre.getAttribute('data-language').toLowerCase() || lang;
if(typeof langName !== 'undefined' && lang !== langName){
continue
}
html = parseHTML(pre.innerHTML);
if(pre.outerHTML){
outer = pre.outerHTML.match(/<\w+\s*(.*?)>/)[1];
pre.outerHTML = '<pre '+outer+'>'+ hlbylanguage(html,lang,true) + '</pre>';
}else{
pre.innerHTML = hlbylanguage(html,lang,true);
}
}
}
JSHL(); | cls : ['com','attr','key','val'], | random_line_split |
jshighlight.core-v1.0.0.src.js | JSHL.language = JSHL.language || {};
JSHL.language.javascript = {
//文档注释 --> 普通注释 --> 字符串 --> 关键字--> 变量 --> 内置对象-->数字-->boolean-->操作符
//cls : ['js-doc','js-com','js-str','js-key'/*,'js-var'*/,'js-obj','js-num','js-bol','js-ope'],
reg : {
'doc' : /.?(\/\*{2}[\s\S]*?\*\/)/, //文档注释
'com' : /(\/\*(?!\*)[\s\S]*?\*\/|\/\/.*)/, //普通注释
'str' : /('(?:(?:\\'|[^'\r\n])*?)'|"(?:(?:\\"|[^"\r\n])*?)")/, //字符串
'key' : /(?:[^\$_@\w])(break|delete|function|return|typeof|arguments|case|do|if|switch|var|catch|else|in|this|void|continue|instanceof|throw|while|debugger|finally|new|with|default|for|null|try)(?![$_@\w])/, //关键字
'obj' : /(?:[^\$_@\w])(Array|String|Date|Math|Boolean|Number|Function|Global|Error|RegExp|Object|window|document)(?:[^$_@\w])/, //内置对象
'num' : /\b(\d+(?:\.\d+)?(?:[Ee][-+]?(?:\d)+)?|NaN|Infinity)\b/, //数字
'bol' : /(?:[^$_@\w])(true|false)(?:[^$_@\w])/, //布尔值
'ope' : /(==|=|===|\+|-|\+=|-=|\*=|\\=|%=|<|<=|>|>=)/ //操作符
}
}
JSHL.language.html = {
cls : ['com','mrk','attr','val'],
reg : {
'com' : /(<\!--[\s\S]*?-->)/, //注释
'mrk' : /(<\/?\w+(?:.*?)>)/ //标签
},
markup : true // markup support
,
include : [
{
lang : 'javascript',
wrapper : /<script>([\s\S]*?)<\/script>/g
},
{
lang : 'css',
wrapper : /<style>([\s\S]*?)<\/style>/g
}
]
}
JSHL.language.css = {
cls : ['com','attr','key','val'],
reg : {
'com' : /(\/\*[\s\S]*?\*\/)/, //注释
//'key' : /((?:\.|#)?(?:\w+(?:[,\s:#\w\.]+)?)+){/, //选择器
'key' : /([^{\n\$\|]*?){/, //选择器
'obj' : /(?:([\w-]+?)\s*\:([\w\s"',\-\#]*))/ //属性名:属性值
}
}
JSHL.extendLanguage = function(langName, langObj){
JSHL.language[langName] = langObj;
if(langObj.wrapper){
JSHL.language[langObj.wrapper].include.push(langObj.content);
}
JSHL(langName);
}
function JSHL(langName){
var pres = document.getElementsByTagName('pre'),
len = pres.length,
pre = null,
index = 0,
lang = 'jav | ascript',
html,outer;
function parseHTML(html){
return html.replace(/</g,'<').replace(/>/g,'>').replace(/(\r?\n)$/g,'');
}
function addLineNumber(nums){
var html = ['<div class="','jshl-linenum','">'], i=1;
for(; i< nums; i+=1) html.push(i+'.<br/>');
html.push(nums,'.</div>');
return html.join('')
}
/**
* 根据语言高亮代码
* @param {String} html
* @param {String} lang
* @param {Boolean} findParent
* @returns {*}
*/
function hlbylanguage(html, lang, findParent){
//var ln = addLineNumber(html.split('\n').length);
//console.log(lang,html);
if(!(lang in JSHL.language))
return html + (findParent ? addLineNumber(html.split('\n').length) : '')
var l = JSHL.language[lang];
if(findParent && l.wrapper) l = JSHL.language[l.wrapper];
if(!l) return html + (findParent ? addLineNumber(html.split('\n').length) : '')
html = '|'+html+'|';
var ln = /(<div class="jshl-linenum">(?:.*?)<\/div>)/g;
if(ln.test(html)){ //已经加入了行号
html = html.replace(ln,'{@jshl-linenum@}');
}
var //start = new Date(),
pattern = l.reg,
markup = l.markup,
cls = l.cls || [],
defaultCls = (cls.length === 0),
inc = l.include,
olanghl=[],placeholder=[],pl='',wrapper,
//console.log(lang +' start...');
// 文档注释 --> com --> mrk --> 关键字-->vars -->内置对象-->数字-->boolean-->操作符
type = ['doc','com','mrk','str','key','var','obj','num','bol','ope'],
p = [], len = type.length, i = 0;
/*if(cls.length === 0 || pattern.length === 0){
return
}*/
for(; i< len; i+=1){
if(pattern[type[i]]){
p.push(pattern[type[i]].source); //正则表达式
defaultCls && cls.push(type[i]); //对应的类名
}
}
pattern = new RegExp(p.join("|"),'g');
//提取其他语言的代码
if(inc && inc.length > 0){
for(i=0; i< inc.length; i+=1){
wrapper = new RegExp(inc[i].wrapper.source.replace(/</g,'<').replace(/>/g,'>'),'gi');
html = html.replace(wrapper,function($0,$1){
//console.log("$0:",$0,"$1",$1);
pl = '{@'+Math.random()+'@}';
placeholder.push(pl);
olanghl.push(hlbylanguage($1,inc[i].lang, false))
return $0.replace($1,pl);
});
}
}
html = html.replace(pattern,function(){
//console.log(arguments)
var args = Array.prototype.slice.call(arguments,0),
currArg1 = null,
currArg = null,
len = args.length - 2,
index = len;
for(; index > 0; index-=1){
currArg = args[index];
if(currArg){
if(markup && cls[index-1] === 'mrk'){
currArg1 = currArg.replace(
/(\w+)=(".*?")/g,
'<span class="'+JSHL.language.html.cls[2]+
'">$1</span>=<span class="'+JSHL.language.html.cls[3]+'">$2</span>'
)
}
args[0] = args[0].replace(currArg,'<span class="'+cls[index-1]+'">'+(currArg1 !== null ?currArg1:currArg)+'</span>')
}
}
return args[0];
});
for(i=0; i< placeholder.length; i++){ //高亮包含的其他语言
html = html.replace(new RegExp('{@.*?'+placeholder[i].replace(/[{@}]/g,'')+'.*?@}','g'),placeholder[i])
.replace(placeholder[i], olanghl[i]);
}
return html.replace(/^(\|)|(\|)$/g,'').replace('{@jshl-linenum@}','') + (findParent ? addLineNumber(html.split('\n').length) : '');
}
for(; index < len; index += 1){
pre = pres[index];
lang = pre.getAttribute('data-language').toLowerCase() || lang;
if(typeof langName !== 'undefined' && lang !== langName){
continue
}
html = parseHTML(pre.innerHTML);
if(pre.outerHTML){
outer = pre.outerHTML.match(/<\w+\s*(.*?)>/)[1];
pre.outerHTML = '<pre '+outer+'>'+ hlbylanguage(html,lang,true) + '</pre>';
}else{
pre.innerHTML = hlbylanguage(html,lang,true);
}
}
}
JSHL(); | identifier_body | |
jshighlight.core-v1.0.0.src.js | JSHL.language = JSHL.language || {};
JSHL.language.javascript = {
//文档注释 --> 普通注释 --> 字符串 --> 关键字--> 变量 --> 内置对象-->数字-->boolean-->操作符
//cls : ['js-doc','js-com','js-str','js-key'/*,'js-var'*/,'js-obj','js-num','js-bol','js-ope'],
reg : {
'doc' : /.?(\/\*{2}[\s\S]*?\*\/)/, //文档注释
'com' : /(\/\*(?!\*)[\s\S]*?\*\/|\/\/.*)/, //普通注释
'str' : /('(?:(?:\\'|[^'\r\n])*?)'|"(?:(?:\\"|[^"\r\n])*?)")/, //字符串
'key' : /(?:[^\$_@\w])(break|delete|function|return|typeof|arguments|case|do|if|switch|var|catch|else|in|this|void|continue|instanceof|throw|while|debugger|finally|new|with|default|for|null|try)(?![$_@\w])/, //关键字
'obj' : /(?:[^\$_@\w])(Array|String|Date|Math|Boolean|Number|Function|Global|Error|RegExp|Object|window|document)(?:[^$_@\w])/, //内置对象
'num' : /\b(\d+(?:\.\d+)?(?:[Ee][-+]?(?:\d)+)?|NaN|Infinity)\b/, //数字
'bol' : /(?:[^$_@\w])(true|false)(?:[^$_@\w])/, //布尔值
'ope' : /(==|=|===|\+|-|\+=|-=|\*=|\\=|%=|<|<=|>|>=)/ //操作符
}
}
JSHL.language.html = {
cls : ['com','mrk','attr','val'],
reg : {
'com' : /(<\!--[\s\S]*?-->)/, //注释
'mrk' : /(<\/?\w+(?:.*?)>)/ //标签
},
markup : true // markup support
,
include : [
{
lang : 'javascript',
wrapper : /<script>([\s\S]*?)<\/script>/g
},
{
lang : 'css',
wrapper : /<style>([\s\S]*?)<\/style>/g
}
]
}
JSHL.language.css = {
cls : ['com','attr','key','val'],
reg : {
'com' : /(\/\*[\s\S]*?\*\/)/, //注释
//'key' : /((?:\.|#)?(?:\w+(?:[,\s:#\w\.]+)?)+){/, //选择器
'key' : /([^{\n\$\|]*?){/, //选择器
'obj' : /(?:([\w-]+?)\s*\:([\w\s"',\-\#]*))/ //属性名:属性值
}
}
JSHL.extendLanguage = function(langName, langObj){
JSHL.language[langName] = langObj;
if(langObj.wrapper){
JSHL.language[langObj.wrapper].include.push(langObj.content);
}
JSHL(langName);
}
function JSHL(langName){
var pres = document.getElementsByTagName('pre'),
len = pres.length,
pre = null,
index = 0,
| ang = 'javascript',
html,outer;
function parseHTML(html){
return html.replace(/</g,'<').replace(/>/g,'>').replace(/(\r?\n)$/g,'');
}
function addLineNumber(nums){
var html = ['<div class="','jshl-linenum','">'], i=1;
for(; i< nums; i+=1) html.push(i+'.<br/>');
html.push(nums,'.</div>');
return html.join('')
}
/**
* 根据语言高亮代码
* @param {String} html
* @param {String} lang
* @param {Boolean} findParent
* @returns {*}
*/
function hlbylanguage(html, lang, findParent){
//var ln = addLineNumber(html.split('\n').length);
//console.log(lang,html);
if(!(lang in JSHL.language))
return html + (findParent ? addLineNumber(html.split('\n').length) : '')
var l = JSHL.language[lang];
if(findParent && l.wrapper) l = JSHL.language[l.wrapper];
if(!l) return html + (findParent ? addLineNumber(html.split('\n').length) : '')
html = '|'+html+'|';
var ln = /(<div class="jshl-linenum">(?:.*?)<\/div>)/g;
if(ln.test(html)){ //已经加入了行号
html = html.replace(ln,'{@jshl-linenum@}');
}
var //start = new Date(),
pattern = l.reg,
markup = l.markup,
cls = l.cls || [],
defaultCls = (cls.length === 0),
inc = l.include,
olanghl=[],placeholder=[],pl='',wrapper,
//console.log(lang +' start...');
// 文档注释 --> com --> mrk --> 关键字-->vars -->内置对象-->数字-->boolean-->操作符
type = ['doc','com','mrk','str','key','var','obj','num','bol','ope'],
p = [], len = type.length, i = 0;
/*if(cls.length === 0 || pattern.length === 0){
return
}*/
for(; i< len; i+=1){
if(pattern[type[i]]){
p.push(pattern[type[i]].source); //正则表达式
defaultCls && cls.push(type[i]); //对应的类名
}
}
pattern = new RegExp(p.join("|"),'g');
//提取其他语言的代码
if(inc && inc.length > 0){
for(i=0; i< inc.length; i+=1){
wrapper = new RegExp(inc[i].wrapper.source.replace(/</g,'<').replace(/>/g,'>'),'gi');
html = html.replace(wrapper,function($0,$1){
//console.log("$0:",$0,"$1",$1);
pl = '{@'+Math.random()+'@}';
placeholder.push(pl);
olanghl.push(hlbylanguage($1,inc[i].lang, false))
return $0.replace($1,pl);
});
}
}
html = html.replace(pattern,function(){
//console.log(arguments)
var args = Array.prototype.slice.call(arguments,0),
currArg1 = null,
currArg = null,
len = args.length - 2,
index = len;
for(; index > 0; index-=1){
currArg = args[index];
if(currArg){
if(markup && cls[index-1] === 'mrk'){
currArg1 = currArg.replace(
/(\w+)=(".*?")/g,
'<span class="'+JSHL.language.html.cls[2]+
'">$1</span>=<span class="'+JSHL.language.html.cls[3]+'">$2</span>'
)
}
args[0] = args[0].replace(currArg,'<span class="'+cls[index-1]+'">'+(currArg1 !== null ?currArg1:currArg)+'</span>')
}
}
return args[0];
});
for(i=0; i< placeholder.length; i++){ //高亮包含的其他语言
html = html.replace(new RegExp('{@.*?'+placeholder[i].replace(/[{@}]/g,'')+'.*?@}','g'),placeholder[i])
.replace(placeholder[i], olanghl[i]);
}
return html.replace(/^(\|)|(\|)$/g,'').replace('{@jshl-linenum@}','') + (findParent ? addLineNumber(html.split('\n').length) : '');
}
for(; index < len; index += 1){
pre = pres[index];
lang = pre.getAttribute('data-language').toLowerCase() || lang;
if(typeof langName !== 'undefined' && lang !== langName){
continue
}
html = parseHTML(pre.innerHTML);
if(pre.outerHTML){
outer = pre.outerHTML.match(/<\w+\s*(.*?)>/)[1];
pre.outerHTML = '<pre '+outer+'>'+ hlbylanguage(html,lang,true) + '</pre>';
}else{
pre.innerHTML = hlbylanguage(html,lang,true);
}
}
}
JSHL(); | l | identifier_name |
rowNodeSorter.ts | import { Column } from "../entities/column";
import { RowNode } from "../entities/rowNode";
import { Autowired, Bean } from "../context/context";
import { GridOptionsWrapper } from "../gridOptionsWrapper";
import { ValueService } from "../valueService/valueService";
import { _ } from "../utils";
import { Constants } from "../constants/constants";
export interface SortOption {
sort: string;
column: Column;
}
export interface SortedRowNode {
currentPos: number;
rowNode: RowNode;
}
// this logic is used by both SSRM and CSRM
@Bean('rowNodeSorter')
export class RowNodeSorter {
@Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
@Autowired('valueService') private valueService: ValueService;
public doFullSort(rowNodes: RowNode[], sortOptions: SortOption[]): RowNode[] {
const mapper = (rowNode: RowNode, pos: number) => ({currentPos: pos, rowNode: rowNode});
const sortedRowNodes: SortedRowNode[] = rowNodes.map(mapper);
sortedRowNodes.sort(this.compareRowNodes.bind(this, sortOptions));
return sortedRowNodes.map(item => item.rowNode);
}
public compareRowNodes(sortOptions: SortOption[], sortedNodeA: SortedRowNode, sortedNodeB: SortedRowNode): number |
private getValue(nodeA: RowNode, column: Column): string {
return this.valueService.getValue(column, nodeA);
}
} | {
const nodeA: RowNode = sortedNodeA.rowNode;
const nodeB: RowNode = sortedNodeB.rowNode;
// Iterate columns, return the first that doesn't match
for (let i = 0, len = sortOptions.length; i < len; i++) {
const sortOption = sortOptions[i];
// let compared = compare(nodeA, nodeB, sortOption.column, sortOption.inverter === -1);
const isInverted = sortOption.sort === Constants.SORT_DESC;
const valueA: any = this.getValue(nodeA, sortOption.column);
const valueB: any = this.getValue(nodeB, sortOption.column);
let comparatorResult: number;
const providedComparator = sortOption.column.getColDef().comparator;
if (providedComparator) {
//if comparator provided, use it
comparatorResult = providedComparator(valueA, valueB, nodeA, nodeB, isInverted);
} else {
//otherwise do our own comparison
comparatorResult = _.defaultComparator(valueA, valueB, this.gridOptionsWrapper.isAccentedSort());
}
if (comparatorResult !== 0) {
return sortOption.sort === Constants.SORT_ASC ? comparatorResult : comparatorResult * -1;
}
}
// All matched, we make is so that the original sort order is kept:
return sortedNodeA.currentPos - sortedNodeB.currentPos;
} | identifier_body |
rowNodeSorter.ts | import { Column } from "../entities/column";
import { RowNode } from "../entities/rowNode";
import { Autowired, Bean } from "../context/context";
import { GridOptionsWrapper } from "../gridOptionsWrapper";
import { ValueService } from "../valueService/valueService";
import { _ } from "../utils";
import { Constants } from "../constants/constants";
export interface SortOption {
sort: string;
column: Column;
}
export interface SortedRowNode {
currentPos: number;
rowNode: RowNode;
}
// this logic is used by both SSRM and CSRM
@Bean('rowNodeSorter')
export class | {
@Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
@Autowired('valueService') private valueService: ValueService;
public doFullSort(rowNodes: RowNode[], sortOptions: SortOption[]): RowNode[] {
const mapper = (rowNode: RowNode, pos: number) => ({currentPos: pos, rowNode: rowNode});
const sortedRowNodes: SortedRowNode[] = rowNodes.map(mapper);
sortedRowNodes.sort(this.compareRowNodes.bind(this, sortOptions));
return sortedRowNodes.map(item => item.rowNode);
}
public compareRowNodes(sortOptions: SortOption[], sortedNodeA: SortedRowNode, sortedNodeB: SortedRowNode): number {
const nodeA: RowNode = sortedNodeA.rowNode;
const nodeB: RowNode = sortedNodeB.rowNode;
// Iterate columns, return the first that doesn't match
for (let i = 0, len = sortOptions.length; i < len; i++) {
const sortOption = sortOptions[i];
// let compared = compare(nodeA, nodeB, sortOption.column, sortOption.inverter === -1);
const isInverted = sortOption.sort === Constants.SORT_DESC;
const valueA: any = this.getValue(nodeA, sortOption.column);
const valueB: any = this.getValue(nodeB, sortOption.column);
let comparatorResult: number;
const providedComparator = sortOption.column.getColDef().comparator;
if (providedComparator) {
//if comparator provided, use it
comparatorResult = providedComparator(valueA, valueB, nodeA, nodeB, isInverted);
} else {
//otherwise do our own comparison
comparatorResult = _.defaultComparator(valueA, valueB, this.gridOptionsWrapper.isAccentedSort());
}
if (comparatorResult !== 0) {
return sortOption.sort === Constants.SORT_ASC ? comparatorResult : comparatorResult * -1;
}
}
// All matched, we make is so that the original sort order is kept:
return sortedNodeA.currentPos - sortedNodeB.currentPos;
}
private getValue(nodeA: RowNode, column: Column): string {
return this.valueService.getValue(column, nodeA);
}
} | RowNodeSorter | identifier_name |
rowNodeSorter.ts | import { Column } from "../entities/column";
import { RowNode } from "../entities/rowNode";
import { Autowired, Bean } from "../context/context";
import { GridOptionsWrapper } from "../gridOptionsWrapper";
import { ValueService } from "../valueService/valueService";
import { _ } from "../utils";
import { Constants } from "../constants/constants";
export interface SortOption {
sort: string;
column: Column;
}
export interface SortedRowNode {
currentPos: number;
rowNode: RowNode;
}
| // this logic is used by both SSRM and CSRM
@Bean('rowNodeSorter')
export class RowNodeSorter {
@Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
@Autowired('valueService') private valueService: ValueService;
public doFullSort(rowNodes: RowNode[], sortOptions: SortOption[]): RowNode[] {
const mapper = (rowNode: RowNode, pos: number) => ({currentPos: pos, rowNode: rowNode});
const sortedRowNodes: SortedRowNode[] = rowNodes.map(mapper);
sortedRowNodes.sort(this.compareRowNodes.bind(this, sortOptions));
return sortedRowNodes.map(item => item.rowNode);
}
public compareRowNodes(sortOptions: SortOption[], sortedNodeA: SortedRowNode, sortedNodeB: SortedRowNode): number {
const nodeA: RowNode = sortedNodeA.rowNode;
const nodeB: RowNode = sortedNodeB.rowNode;
// Iterate columns, return the first that doesn't match
for (let i = 0, len = sortOptions.length; i < len; i++) {
const sortOption = sortOptions[i];
// let compared = compare(nodeA, nodeB, sortOption.column, sortOption.inverter === -1);
const isInverted = sortOption.sort === Constants.SORT_DESC;
const valueA: any = this.getValue(nodeA, sortOption.column);
const valueB: any = this.getValue(nodeB, sortOption.column);
let comparatorResult: number;
const providedComparator = sortOption.column.getColDef().comparator;
if (providedComparator) {
//if comparator provided, use it
comparatorResult = providedComparator(valueA, valueB, nodeA, nodeB, isInverted);
} else {
//otherwise do our own comparison
comparatorResult = _.defaultComparator(valueA, valueB, this.gridOptionsWrapper.isAccentedSort());
}
if (comparatorResult !== 0) {
return sortOption.sort === Constants.SORT_ASC ? comparatorResult : comparatorResult * -1;
}
}
// All matched, we make is so that the original sort order is kept:
return sortedNodeA.currentPos - sortedNodeB.currentPos;
}
private getValue(nodeA: RowNode, column: Column): string {
return this.valueService.getValue(column, nodeA);
}
} | random_line_split | |
rowNodeSorter.ts | import { Column } from "../entities/column";
import { RowNode } from "../entities/rowNode";
import { Autowired, Bean } from "../context/context";
import { GridOptionsWrapper } from "../gridOptionsWrapper";
import { ValueService } from "../valueService/valueService";
import { _ } from "../utils";
import { Constants } from "../constants/constants";
export interface SortOption {
sort: string;
column: Column;
}
export interface SortedRowNode {
currentPos: number;
rowNode: RowNode;
}
// this logic is used by both SSRM and CSRM
@Bean('rowNodeSorter')
export class RowNodeSorter {
@Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
@Autowired('valueService') private valueService: ValueService;
public doFullSort(rowNodes: RowNode[], sortOptions: SortOption[]): RowNode[] {
const mapper = (rowNode: RowNode, pos: number) => ({currentPos: pos, rowNode: rowNode});
const sortedRowNodes: SortedRowNode[] = rowNodes.map(mapper);
sortedRowNodes.sort(this.compareRowNodes.bind(this, sortOptions));
return sortedRowNodes.map(item => item.rowNode);
}
public compareRowNodes(sortOptions: SortOption[], sortedNodeA: SortedRowNode, sortedNodeB: SortedRowNode): number {
const nodeA: RowNode = sortedNodeA.rowNode;
const nodeB: RowNode = sortedNodeB.rowNode;
// Iterate columns, return the first that doesn't match
for (let i = 0, len = sortOptions.length; i < len; i++) {
const sortOption = sortOptions[i];
// let compared = compare(nodeA, nodeB, sortOption.column, sortOption.inverter === -1);
const isInverted = sortOption.sort === Constants.SORT_DESC;
const valueA: any = this.getValue(nodeA, sortOption.column);
const valueB: any = this.getValue(nodeB, sortOption.column);
let comparatorResult: number;
const providedComparator = sortOption.column.getColDef().comparator;
if (providedComparator) | else {
//otherwise do our own comparison
comparatorResult = _.defaultComparator(valueA, valueB, this.gridOptionsWrapper.isAccentedSort());
}
if (comparatorResult !== 0) {
return sortOption.sort === Constants.SORT_ASC ? comparatorResult : comparatorResult * -1;
}
}
// All matched, we make is so that the original sort order is kept:
return sortedNodeA.currentPos - sortedNodeB.currentPos;
}
private getValue(nodeA: RowNode, column: Column): string {
return this.valueService.getValue(column, nodeA);
}
} | {
//if comparator provided, use it
comparatorResult = providedComparator(valueA, valueB, nodeA, nodeB, isInverted);
} | conditional_block |
test2.js | var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var multer = require('multer');
var fs = require('fs')
var exec = require('child_process').exec;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(__dirname + '/public'));
app.listen(8888,function(){
console.log("2333");
})
var wenjian = multer({ dest: './public/wz/' })
var wenjian_img = multer({ dest: './public/wz/tx/' })
app.post('/update', wenjian_img, function (req, res) { | var cmdStr = 'rm '+req.files.tupian.path;
exec(cmdStr, function (err, stdout, stderr) {
console.log(stdout)
})
})
}) | console.log(req.files);
var cmdStr = 'mv '+req.files.tupian.path+" "+"public/wz/tx/233/";
exec(cmdStr, function (err, stdout, stderr) { | random_line_split |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Intern {
Intern { vec: Vec::new() }
}
pub fn add(&mut self, string: &CStr) -> *const c_char {
fn e | s1: &CStr, s2: &CStr) -> bool {
s1 == s2
}
for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let mut intern = Intern::new();
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null());
assert!(!bar_ptr.is_null());
assert!(foo_ptr != bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr != intern.add(cstr(b"fo\0")));
assert!(foo_ptr != intern.add(cstr(b"fool\0")));
assert!(foo_ptr != intern.add(cstr(b"not foo\0")));
}
}
| q( | identifier_name |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Intern {
Intern { vec: Vec::new() }
}
pub fn add(&mut self, string: &CStr) -> *const c_char {
fn eq(s1: &CStr, s2: &CStr) -> bool { | for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let mut intern = Intern::new();
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null());
assert!(!bar_ptr.is_null());
assert!(foo_ptr != bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr != intern.add(cstr(b"fo\0")));
assert!(foo_ptr != intern.add(cstr(b"fool\0")));
assert!(foo_ptr != intern.add(cstr(b"not foo\0")));
}
}
|
s1 == s2
}
| identifier_body |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Intern {
Intern { vec: Vec::new() }
}
pub fn add(&mut self, string: &CStr) -> *const c_char {
fn eq(s1: &CStr, s2: &CStr) -> bool {
s1 == s2
}
for s in &self.vec {
if eq(s, string) { | }
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let mut intern = Intern::new();
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null());
assert!(!bar_ptr.is_null());
assert!(foo_ptr != bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr != intern.add(cstr(b"fo\0")));
assert!(foo_ptr != intern.add(cstr(b"fool\0")));
assert!(foo_ptr != intern.add(cstr(b"not foo\0")));
}
}
|
return s.as_ptr();
}
| conditional_block |
intern.rs | // Copyright © 2017-2018 Mozilla Foundation
//
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug)]
pub struct Intern {
vec: Vec<CString>,
}
impl Intern {
pub fn new() -> Intern {
Intern { vec: Vec::new() }
}
pub fn add(&mut self, string: &CStr) -> *const c_char {
fn eq(s1: &CStr, s2: &CStr) -> bool {
s1 == s2
}
for s in &self.vec {
if eq(s, string) {
return s.as_ptr();
}
}
self.vec.push(string.to_owned());
self.vec.last().unwrap().as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::Intern;
use std::ffi::CStr;
#[test]
fn intern() {
fn cstr(str: &[u8]) -> &CStr {
CStr::from_bytes_with_nul(str).unwrap()
}
let mut intern = Intern::new(); | assert!(!bar_ptr.is_null());
assert!(foo_ptr != bar_ptr);
assert!(foo_ptr == intern.add(cstr(b"foo\0")));
assert!(foo_ptr != intern.add(cstr(b"fo\0")));
assert!(foo_ptr != intern.add(cstr(b"fool\0")));
assert!(foo_ptr != intern.add(cstr(b"not foo\0")));
}
} |
let foo_ptr = intern.add(cstr(b"foo\0"));
let bar_ptr = intern.add(cstr(b"bar\0"));
assert!(!foo_ptr.is_null()); | random_line_split |
ds_reference.py | print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist is just another name pointing to the same object!
mylist = shoplist
# I purchased the first item, so I remove it from the list
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
# Notice that both shoplist and mylist both print
# the same list without the 'apple' confirming that
# they point to the same object
print('Copy by making a full slice')
# Make a copy by doing a full slice
mylist = shoplist[:]
mylist1 = shoplist.copy()
# Remove first item
del mylist[0] | del mylist1[1]
print('shoplist is', shoplist)
print('mylist is', mylist1) |
print('shoplist is', shoplist)
print('mylist is', mylist)
| random_line_split |
biblivre.z3950.search.js | /**
* Este arquivo é parte do Biblivre5.
*
* Biblivre5 é um software livre; você pode redistribuí-lo e/ou
* modificá-lo dentro dos termos da Licença Pública Geral GNU como
* publicada pela Fundação do Software Livre (FSF); na versão 3 da
* Licença, ou (caso queira) qualquer versão posterior.
*
* Este programa é distribuído na esperança de que possa ser útil,
* mas SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
* MERCANTIBILIDADE OU ADEQUAÇÃO PARA UM FIM PARTICULAR. Veja a
* Licença Pública Geral GNU para maiores detalhes.
*
* Você deve ter recebido uma cópia da Licença Pública Geral GNU junto
* com este programa, Se não, veja em <http://www.gnu.org/licenses/>.
*
* @author Alberto Wagner <alberto@biblivre.org.br>
* @author Danniel Willian <danniel@biblivre.org.br>
*
*/
var Z3950SearchClass = $.extend(CatalogingSearchClass, {
initialize: function() {
var me = this;
this.prefix = this.type = 'z3950';
this.root = $('body');
this.root.find('.search_results').setTemplateElement(this.root.find('.search_results_template'));
$.History.bind(function(trigger) {
return me.historyRead(trigger);
});
me.switchToSimpleSearch();
},
afterHistoryRead: function(trigger) {
var query = Core.historyCheckAndSet(trigger, 'query');
var attribute = Core.historyCheckAndSet(trigger, 'attribute');
var server = Core.historyCheckAndSet(trigger, 'server');
if (query.changed || attribute.changed || server.changed) {
if (query.value !== n | ction(keepOrderingBar) {
Core.trigger(this.prefix + 'clear-search');
if (!keepOrderingBar) {
Core.removeMsg();
}
},
simpleSearch: function() {
var query = this.root.find('.search_box .simple_search :input[name=query]').val();
var attribute = this.root.find('.search_box .simple_search :input[name=attribute]').val();
if (!query) {
return; //TODO mensagem
}
var server = [];
this.root.find('.search_box .distributed_servers :checkbox[name=server]:checked').each(function() {
server.push($(this).val());
});
if (server.length == 0) {
var el = this.root.find('.search_box .distributed_servers :checkbox[name=server]:first');
el.prop('checked', true);
server.push(el.val());
}
serverList = server.join(',');
var searchParameters = {
query: query,
attribute: attribute,
server: serverList
};
Core.historyTrigger({
query: query,
attribute: attribute,
server: serverList
});
this.submit(searchParameters);
},
afterDisplayResult: function() {
// Empty function to override CatalogingSearch
},
searchTerm: function(obj) {
var query = $("<div />").html(obj.query).text();
this.root.find('.search_box .simple_search :input[name=query]').val(query);
this.root.find('.search_box .simple_search :input[name=attribute]').trigger('setvalue', obj.attribute);
var server = (obj.server || '').split(',');
this.root.find('.search_box .distributed_servers :checkbox[name=server]').each(function() {
$(this).prop("checked", ($.inArray($(this).val(), server) != -1));
});
this.root.find('.search_box .main_button:visible').trigger('click');
},
loadRecordExtraParams: function() {
return {
search_id: this.lastPagingParameters.search_id
};
},
getSearchResult: function(record_id) {
var result = this.lastSearchResult[record_id] || {};
return $.extend({}, result, result.record);
}
}); | ull) {
this.searchTerm({
query: query.value,
attribute: attribute.value,
server: server.value
});
}
}
},
clearResults: fun | conditional_block |
biblivre.z3950.search.js | /**
* Este arquivo é parte do Biblivre5.
*
* Biblivre5 é um software livre; você pode redistribuí-lo e/ou
* modificá-lo dentro dos termos da Licença Pública Geral GNU como
* publicada pela Fundação do Software Livre (FSF); na versão 3 da
* Licença, ou (caso queira) qualquer versão posterior.
*
* Este programa é distribuído na esperança de que possa ser útil, | * Você deve ter recebido uma cópia da Licença Pública Geral GNU junto
* com este programa, Se não, veja em <http://www.gnu.org/licenses/>.
*
* @author Alberto Wagner <alberto@biblivre.org.br>
* @author Danniel Willian <danniel@biblivre.org.br>
*
*/
var Z3950SearchClass = $.extend(CatalogingSearchClass, {
initialize: function() {
var me = this;
this.prefix = this.type = 'z3950';
this.root = $('body');
this.root.find('.search_results').setTemplateElement(this.root.find('.search_results_template'));
$.History.bind(function(trigger) {
return me.historyRead(trigger);
});
me.switchToSimpleSearch();
},
afterHistoryRead: function(trigger) {
var query = Core.historyCheckAndSet(trigger, 'query');
var attribute = Core.historyCheckAndSet(trigger, 'attribute');
var server = Core.historyCheckAndSet(trigger, 'server');
if (query.changed || attribute.changed || server.changed) {
if (query.value !== null) {
this.searchTerm({
query: query.value,
attribute: attribute.value,
server: server.value
});
}
}
},
clearResults: function(keepOrderingBar) {
Core.trigger(this.prefix + 'clear-search');
if (!keepOrderingBar) {
Core.removeMsg();
}
},
simpleSearch: function() {
var query = this.root.find('.search_box .simple_search :input[name=query]').val();
var attribute = this.root.find('.search_box .simple_search :input[name=attribute]').val();
if (!query) {
return; //TODO mensagem
}
var server = [];
this.root.find('.search_box .distributed_servers :checkbox[name=server]:checked').each(function() {
server.push($(this).val());
});
if (server.length == 0) {
var el = this.root.find('.search_box .distributed_servers :checkbox[name=server]:first');
el.prop('checked', true);
server.push(el.val());
}
serverList = server.join(',');
var searchParameters = {
query: query,
attribute: attribute,
server: serverList
};
Core.historyTrigger({
query: query,
attribute: attribute,
server: serverList
});
this.submit(searchParameters);
},
afterDisplayResult: function() {
// Empty function to override CatalogingSearch
},
searchTerm: function(obj) {
var query = $("<div />").html(obj.query).text();
this.root.find('.search_box .simple_search :input[name=query]').val(query);
this.root.find('.search_box .simple_search :input[name=attribute]').trigger('setvalue', obj.attribute);
var server = (obj.server || '').split(',');
this.root.find('.search_box .distributed_servers :checkbox[name=server]').each(function() {
$(this).prop("checked", ($.inArray($(this).val(), server) != -1));
});
this.root.find('.search_box .main_button:visible').trigger('click');
},
loadRecordExtraParams: function() {
return {
search_id: this.lastPagingParameters.search_id
};
},
getSearchResult: function(record_id) {
var result = this.lastSearchResult[record_id] || {};
return $.extend({}, result, result.record);
}
}); | * mas SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
* MERCANTIBILIDADE OU ADEQUAÇÃO PARA UM FIM PARTICULAR. Veja a
* Licença Pública Geral GNU para maiores detalhes.
* | random_line_split |
main.rs | #![feature(associated_consts)]
#![feature(slice_patterns)]
#![feature(const_fn)]
//#![deny(missing_docs)]
//#![deny(warnings)]
extern crate sdl2;
extern crate nuklear_rust as nk;
use nk::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Difficulty {
Easy,
Hard
}
#[derive(Debug, Default, Copy, Clone, PartialEq)]
#[repr(C, packed)]
struct GuiVertex {
position: [f32; 2],
uv: [f32; 2],
color: [u8; 4]
}
use std::mem::size_of;
impl GuiVertex {
const OFFSETOF_POSITION: usize = 0;
const OFFSETOF_UV: usize = 8;
const OFFSETOF_COLOR: usize = 16;
}
const MAX_VERTEX_BUFFER: usize = 512 * 1024;
const MAX_ELEMENT_BUFFER: usize = 128 * 1024;
struct App<'a> {
sdl2: sdl2::Sdl,
rdr: sdl2::render::Renderer<'a>,
nk: nk::NkContext,
property: i32,
op: Difficulty,
aa: NkAntiAliasing,
}
enum AppEventHandling {
Quit,
Unhandled,
}
trait IntoNkKey {
fn to_nk_key(&self) -> NkKey;
}
use sdl2::keyboard::Keycode;
use sdl2::keyboard::Keycode::*;
use NkKey::*;
impl IntoNkKey for Keycode {
fn to_nk_key(&self) -> NkKey {
match self {
&Up => NK_KEY_UP,
_ => NK_KEY_NONE,
}
}
}
impl<'a> App<'a> {
fn new() -> Self {
let sdl2 = sdl2::init().expect("Could not initialize SDL2");
let sdl2_video = sdl2.video().expect("Could not initialize video subsystem");
let window = sdl2_video.window("Foo", 800, 600).build().unwrap();
let rdr =
window.renderer().accelerated().present_vsync().build().unwrap();
use std::fs::File;
use std::io::Read;
let mut buf = Vec::<u8>::new();
let mut file = File::open("/home/yoon/.local/share/fonts/basis33.ttf").unwrap();
file.read_to_end(&mut buf).unwrap();
drop(file);
let mut atlas = NkFontAtlas::new(&mut NkAllocator::new_vec());
atlas.begin();
let mut font = atlas.add_font_with_bytes(&buf, 16f32).unwrap();
let _ = atlas.bake(NkFontAtlasFormat::NK_FONT_ATLAS_RGBA32);
atlas.end(NkHandle::from_ptr(std::ptr::null_mut()), None);
let mut nk = NkContext::new(&mut NkAllocator::new_vec(), &font.handle());
nk.style_set_font(&font.handle());
App {
sdl2, rdr, nk, property: 0, op: Difficulty::Easy, aa: NkAntiAliasing::NK_ANTI_ALIASING_OFF
}
}
fn handle_event(&mut self, e: &sdl2::event::Event) -> Result<(), AppEventHandling> {
use sdl2::event::Event;
self.nk.input_begin();
let out = match e {
&Event::MouseMotion { x, y, .. } => {
println!("Mouse at {:?}", (x, y));
Ok(())
},
&Event::KeyDown { keycode, .. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), true);
println!("Key {:?} is down", keycode);
Ok(())
},
&Event::KeyUp { keycode, .. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), false);
println!("Key {:?} is up", keycode);
Ok(())
},
&Event::TextInput {..} => Ok(()),
&Event::MouseButtonDown { mouse_btn, .. } => {
println!("Mouse {:?} is down", mouse_btn);
Ok(())
},
&Event::MouseButtonUp { mouse_btn, .. } => {
println!("Mouse {:?} is up", mouse_btn);
Ok(())
},
&Event::MouseWheel { direction, y, .. } => {
println!("Mouse scroll: {} ({:?})", y, direction);
Ok(())
},
&Event::Window {..} => Ok(()),
&Event::Quit {..} => Err(AppEventHandling::Quit),
_ => Err(AppEventHandling::Unhandled),
};
self.nk.input_end();
out
}
fn gui(&mut self) {
let nk = &mut self.nk;
let title = NkString::from("Foo");
let rect = NkRect {x:20f32, y:30f32, w:200f32, h:200f32};
use NkPanelFlags::*;
let flags = NK_WINDOW_MOVABLE as u32
| NK_WINDOW_SCALABLE as u32
| NK_WINDOW_CLOSABLE as u32
| NK_WINDOW_MINIMIZABLE as u32
| NK_WINDOW_TITLE as u32;
if nk.begin(title, rect, flags) {
use NkTextAlignment::*;
nk.menubar_begin();
nk.layout_row_begin(NkLayoutFormat::NK_STATIC, 25f32, 2);
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("FILE"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("OPEN"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("EDIT"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("CUT"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("COPY"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_end();
nk.menubar_end();
nk.layout_row_static(30f32, 80, 1);
if nk.button_label(NkString::from("button")) {
println!("Button pressed!");
}
use Difficulty::*;
nk.layout_row_dynamic(30f32, 2);
if nk.option_label(NkString::from("Easy"), self.op == Easy) {
self.op = Easy;
}
if nk.option_label(NkString::from("Hard"), self.op == Hard) {
self.op = Hard;
}
nk.layout_row_dynamic(25f32, 1);
nk.property_int(NkString::from("Compression:"), 0, &mut self.property, 100, 10, 1f32);
}
nk.end();
}
fn render_gui(&mut self) {
let nk = &mut self.nk;
const MAX_CMDS_BUFFER: usize = MAX_VERTEX_BUFFER;
let mut cmd_mem = [0u8; MAX_CMDS_BUFFER];
let mut cmds = NkBuffer::with_fixed(&mut cmd_mem);
use NkDrawVertexLayoutFormat::*;
use NkDrawVertexLayoutAttribute::*;
let vlayout = NkDrawVertexLayoutElements::new(&[
(NK_VERTEX_POSITION, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_POSITION as u32),
(NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_UV as u32),
(NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, GuiVertex::OFFSETOF_COLOR as u32),
// è_é
(NK_VERTEX_ATTRIBUTE_COUNT, NK_FORMAT_COUNT, 0),
]);
let mut config = NkConvertConfig::default();
config.set_vertex_layout(&vlayout);
config.set_vertex_size(size_of::<GuiVertex>());
config.set_null(NkDrawNullTexture::default());
config.set_circle_segment_count(22);
config.set_curve_segment_count(22);
config.set_arc_segment_count(22);
config.set_global_alpha(1f32);
config.set_shape_aa(self.aa);
config.set_line_aa(self.aa);
/*
use std::slice::from_raw_parts_mut as frpm;
let mut vmem = [0u8; MAX_VERTEX_BUFFER];
let mut emem = [0u8; MAX_ELEMENT_BUFFER];
let vertices = unsafe { frpm(vmem.as_mut_ptr() as *mut GuiVertex, MAX_VERTEX_BUFFER/size_of::<GuiVertex>()) };
let elements = unsafe { frpm(emem.as_mut_ptr() as *mut u16, MAX_ELEMENT_BUFFER/size_of::<u16>()) };
let mut vbuf = NkBuffer::with_fixed(&mut vmem);
let mut ebuf = NkBuffer::with_fixed(&mut emem);
nk.convert(&mut cmds, &mut ebuf, &mut vbuf, &config);
let mut offset = 0;
for cmd in nk.draw_command_iterator(&cmds) {
let elem_count = cmd.elem_count();
if elem_count <= 0 {
continue;
}
for i in offset..(offset+elem_count) {
let e = elements[i as usize] as usize;
println!("i: {}", e);
let v = vertices[e];
let [x,y] = v.position;
let [r,g,b,a] = v.color;
let (w,h) = self.rdr.window().unwrap().size();
let x = (w as f32*(x+1f32)/2f32) as i32;
let y = -(h as f32*(y+1f32)/2f32) as i32;
self.rdr.set_draw_color(sdl2::pixels::Color::RGBA(r,g,b,a));
self.rdr.draw_point(sdl2::rect::Point::new(x,y)).unwrap();
}
offset += elem_count;
}
*/
for cmd in nk.command_iterator() {
println!("cmd: {:?}", cmd);
}
nk.clear();
}
}
fn ma | {
std::env::set_var("RUST_BACKTRACE", "1");
let mut app = App::new();
let mut event_pump = app.sdl2.event_pump().unwrap();
'running: loop {
for e in event_pump.poll_iter() {
use AppEventHandling::*;
match app.handle_event(&e) {
Ok(_) => (),
Err(Quit) => break 'running,
Err(Unhandled) => println!("Unhandled event: {:?}", &e),
};
}
use sdl2::pixels::Color::*;
use sdl2::rect::Rect;
app.rdr.set_draw_color(RGB(255, 255, 0));
app.rdr.clear();
app.rdr.set_draw_color(RGB(0, 255, 255));
app.rdr.draw_rect(Rect::new(20, 20, 50, 50)).unwrap();
app.gui();
app.render_gui();
app.rdr.present();
}
}
| in() | identifier_name |
main.rs | #![feature(associated_consts)]
#![feature(slice_patterns)]
#![feature(const_fn)]
//#![deny(missing_docs)]
//#![deny(warnings)]
extern crate sdl2;
extern crate nuklear_rust as nk;
use nk::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Difficulty {
Easy,
Hard
}
#[derive(Debug, Default, Copy, Clone, PartialEq)]
#[repr(C, packed)]
struct GuiVertex {
position: [f32; 2],
uv: [f32; 2],
color: [u8; 4]
}
use std::mem::size_of;
impl GuiVertex {
const OFFSETOF_POSITION: usize = 0;
const OFFSETOF_UV: usize = 8;
const OFFSETOF_COLOR: usize = 16;
}
const MAX_VERTEX_BUFFER: usize = 512 * 1024;
const MAX_ELEMENT_BUFFER: usize = 128 * 1024;
struct App<'a> {
sdl2: sdl2::Sdl,
rdr: sdl2::render::Renderer<'a>,
nk: nk::NkContext,
property: i32,
op: Difficulty,
aa: NkAntiAliasing,
}
enum AppEventHandling {
Quit,
Unhandled,
}
trait IntoNkKey {
fn to_nk_key(&self) -> NkKey;
}
use sdl2::keyboard::Keycode;
use sdl2::keyboard::Keycode::*;
use NkKey::*;
impl IntoNkKey for Keycode {
fn to_nk_key(&self) -> NkKey {
match self {
&Up => NK_KEY_UP,
_ => NK_KEY_NONE,
}
}
}
impl<'a> App<'a> {
fn new() -> Self {
let sdl2 = sdl2::init().expect("Could not initialize SDL2");
let sdl2_video = sdl2.video().expect("Could not initialize video subsystem");
let window = sdl2_video.window("Foo", 800, 600).build().unwrap();
let rdr =
window.renderer().accelerated().present_vsync().build().unwrap();
use std::fs::File;
use std::io::Read;
let mut buf = Vec::<u8>::new();
let mut file = File::open("/home/yoon/.local/share/fonts/basis33.ttf").unwrap();
file.read_to_end(&mut buf).unwrap();
drop(file);
let mut atlas = NkFontAtlas::new(&mut NkAllocator::new_vec());
atlas.begin();
let mut font = atlas.add_font_with_bytes(&buf, 16f32).unwrap();
let _ = atlas.bake(NkFontAtlasFormat::NK_FONT_ATLAS_RGBA32);
atlas.end(NkHandle::from_ptr(std::ptr::null_mut()), None);
let mut nk = NkContext::new(&mut NkAllocator::new_vec(), &font.handle());
nk.style_set_font(&font.handle());
App {
sdl2, rdr, nk, property: 0, op: Difficulty::Easy, aa: NkAntiAliasing::NK_ANTI_ALIASING_OFF
}
}
fn handle_event(&mut self, e: &sdl2::event::Event) -> Result<(), AppEventHandling> {
use sdl2::event::Event;
self.nk.input_begin();
let out = match e {
&Event::MouseMotion { x, y, .. } => {
println!("Mouse at {:?}", (x, y));
Ok(())
},
&Event::KeyDown { keycode, .. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), true);
println!("Key {:?} is down", keycode);
Ok(())
},
&Event::KeyUp { keycode, .. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), false);
println!("Key {:?} is up", keycode);
Ok(())
},
&Event::TextInput {..} => Ok(()),
&Event::MouseButtonDown { mouse_btn, .. } => {
println!("Mouse {:?} is down", mouse_btn);
Ok(())
},
&Event::MouseButtonUp { mouse_btn, .. } => {
println!("Mouse {:?} is up", mouse_btn);
Ok(())
},
&Event::MouseWheel { direction, y, .. } => {
println!("Mouse scroll: {} ({:?})", y, direction);
Ok(())
},
&Event::Window {..} => Ok(()),
&Event::Quit {..} => Err(AppEventHandling::Quit),
_ => Err(AppEventHandling::Unhandled),
};
self.nk.input_end();
out
}
fn gui(&mut self) {
let nk = &mut self.nk;
let title = NkString::from("Foo");
let rect = NkRect {x:20f32, y:30f32, w:200f32, h:200f32};
use NkPanelFlags::*;
let flags = NK_WINDOW_MOVABLE as u32
| NK_WINDOW_SCALABLE as u32
| NK_WINDOW_CLOSABLE as u32
| NK_WINDOW_MINIMIZABLE as u32
| NK_WINDOW_TITLE as u32;
if nk.begin(title, rect, flags) {
use NkTextAlignment::*;
nk.menubar_begin();
nk.layout_row_begin(NkLayoutFormat::NK_STATIC, 25f32, 2);
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("FILE"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("OPEN"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("EDIT"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("CUT"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("COPY"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_end();
nk.menubar_end();
nk.layout_row_static(30f32, 80, 1);
if nk.button_label(NkString::from("button")) {
println!("Button pressed!");
}
use Difficulty::*;
nk.layout_row_dynamic(30f32, 2);
if nk.option_label(NkString::from("Easy"), self.op == Easy) {
self.op = Easy;
}
if nk.option_label(NkString::from("Hard"), self.op == Hard) {
self.op = Hard;
}
nk.layout_row_dynamic(25f32, 1);
nk.property_int(NkString::from("Compression:"), 0, &mut self.property, 100, 10, 1f32);
}
nk.end();
}
fn render_gui(&mut self) {
let nk = &mut self.nk;
const MAX_CMDS_BUFFER: usize = MAX_VERTEX_BUFFER;
let mut cmd_mem = [0u8; MAX_CMDS_BUFFER];
let mut cmds = NkBuffer::with_fixed(&mut cmd_mem);
use NkDrawVertexLayoutFormat::*;
use NkDrawVertexLayoutAttribute::*;
let vlayout = NkDrawVertexLayoutElements::new(&[
(NK_VERTEX_POSITION, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_POSITION as u32),
(NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_UV as u32),
(NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, GuiVertex::OFFSETOF_COLOR as u32),
// è_é
(NK_VERTEX_ATTRIBUTE_COUNT, NK_FORMAT_COUNT, 0),
]);
let mut config = NkConvertConfig::default();
config.set_vertex_layout(&vlayout);
config.set_vertex_size(size_of::<GuiVertex>());
config.set_null(NkDrawNullTexture::default());
config.set_circle_segment_count(22);
config.set_curve_segment_count(22);
config.set_arc_segment_count(22);
config.set_global_alpha(1f32);
config.set_shape_aa(self.aa);
config.set_line_aa(self.aa);
/*
use std::slice::from_raw_parts_mut as frpm;
let mut vmem = [0u8; MAX_VERTEX_BUFFER];
let mut emem = [0u8; MAX_ELEMENT_BUFFER];
let vertices = unsafe { frpm(vmem.as_mut_ptr() as *mut GuiVertex, MAX_VERTEX_BUFFER/size_of::<GuiVertex>()) };
let elements = unsafe { frpm(emem.as_mut_ptr() as *mut u16, MAX_ELEMENT_BUFFER/size_of::<u16>()) };
let mut vbuf = NkBuffer::with_fixed(&mut vmem);
let mut ebuf = NkBuffer::with_fixed(&mut emem);
nk.convert(&mut cmds, &mut ebuf, &mut vbuf, &config);
let mut offset = 0;
for cmd in nk.draw_command_iterator(&cmds) {
let elem_count = cmd.elem_count();
if elem_count <= 0 {
continue;
}
for i in offset..(offset+elem_count) {
let e = elements[i as usize] as usize;
println!("i: {}", e);
let v = vertices[e];
let [x,y] = v.position;
let [r,g,b,a] = v.color;
let (w,h) = self.rdr.window().unwrap().size(); | self.rdr.set_draw_color(sdl2::pixels::Color::RGBA(r,g,b,a));
self.rdr.draw_point(sdl2::rect::Point::new(x,y)).unwrap();
}
offset += elem_count;
}
*/
for cmd in nk.command_iterator() {
println!("cmd: {:?}", cmd);
}
nk.clear();
}
}
fn main() {
std::env::set_var("RUST_BACKTRACE", "1");
let mut app = App::new();
let mut event_pump = app.sdl2.event_pump().unwrap();
'running: loop {
for e in event_pump.poll_iter() {
use AppEventHandling::*;
match app.handle_event(&e) {
Ok(_) => (),
Err(Quit) => break 'running,
Err(Unhandled) => println!("Unhandled event: {:?}", &e),
};
}
use sdl2::pixels::Color::*;
use sdl2::rect::Rect;
app.rdr.set_draw_color(RGB(255, 255, 0));
app.rdr.clear();
app.rdr.set_draw_color(RGB(0, 255, 255));
app.rdr.draw_rect(Rect::new(20, 20, 50, 50)).unwrap();
app.gui();
app.render_gui();
app.rdr.present();
}
} | let x = (w as f32*(x+1f32)/2f32) as i32;
let y = -(h as f32*(y+1f32)/2f32) as i32; | random_line_split |
main.rs | #![feature(associated_consts)]
#![feature(slice_patterns)]
#![feature(const_fn)]
//#![deny(missing_docs)]
//#![deny(warnings)]
extern crate sdl2;
extern crate nuklear_rust as nk;
use nk::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Difficulty {
Easy,
Hard
}
#[derive(Debug, Default, Copy, Clone, PartialEq)]
#[repr(C, packed)]
struct GuiVertex {
position: [f32; 2],
uv: [f32; 2],
color: [u8; 4]
}
use std::mem::size_of;
impl GuiVertex {
const OFFSETOF_POSITION: usize = 0;
const OFFSETOF_UV: usize = 8;
const OFFSETOF_COLOR: usize = 16;
}
const MAX_VERTEX_BUFFER: usize = 512 * 1024;
const MAX_ELEMENT_BUFFER: usize = 128 * 1024;
struct App<'a> {
sdl2: sdl2::Sdl,
rdr: sdl2::render::Renderer<'a>,
nk: nk::NkContext,
property: i32,
op: Difficulty,
aa: NkAntiAliasing,
}
enum AppEventHandling {
Quit,
Unhandled,
}
trait IntoNkKey {
fn to_nk_key(&self) -> NkKey;
}
use sdl2::keyboard::Keycode;
use sdl2::keyboard::Keycode::*;
use NkKey::*;
impl IntoNkKey for Keycode {
fn to_nk_key(&self) -> NkKey {
match self {
&Up => NK_KEY_UP,
_ => NK_KEY_NONE,
}
}
}
impl<'a> App<'a> {
fn new() -> Self {
let sdl2 = sdl2::init().expect("Could not initialize SDL2");
let sdl2_video = sdl2.video().expect("Could not initialize video subsystem");
let window = sdl2_video.window("Foo", 800, 600).build().unwrap();
let rdr =
window.renderer().accelerated().present_vsync().build().unwrap();
use std::fs::File;
use std::io::Read;
let mut buf = Vec::<u8>::new();
let mut file = File::open("/home/yoon/.local/share/fonts/basis33.ttf").unwrap();
file.read_to_end(&mut buf).unwrap();
drop(file);
let mut atlas = NkFontAtlas::new(&mut NkAllocator::new_vec());
atlas.begin();
let mut font = atlas.add_font_with_bytes(&buf, 16f32).unwrap();
let _ = atlas.bake(NkFontAtlasFormat::NK_FONT_ATLAS_RGBA32);
atlas.end(NkHandle::from_ptr(std::ptr::null_mut()), None);
let mut nk = NkContext::new(&mut NkAllocator::new_vec(), &font.handle());
nk.style_set_font(&font.handle());
App {
sdl2, rdr, nk, property: 0, op: Difficulty::Easy, aa: NkAntiAliasing::NK_ANTI_ALIASING_OFF
}
}
fn handle_event(&mut self, e: &sdl2::event::Event) -> Result<(), AppEventHandling> {
use sdl2::event::Event;
self.nk.input_begin();
let out = match e {
&Event::MouseMotion { x, y, .. } => {
println!("Mouse at {:?}", (x, y));
Ok(())
},
&Event::KeyDown { keycode, .. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), true);
println!("Key {:?} is down", keycode);
Ok(())
},
&Event::KeyUp { keycode, .. } => {
self.nk.input_key(keycode.unwrap().to_nk_key(), false);
println!("Key {:?} is up", keycode);
Ok(())
},
&Event::TextInput {..} => Ok(()),
&Event::MouseButtonDown { mouse_btn, .. } => {
println!("Mouse {:?} is down", mouse_btn);
Ok(())
},
&Event::MouseButtonUp { mouse_btn, .. } => | ,
&Event::MouseWheel { direction, y, .. } => {
println!("Mouse scroll: {} ({:?})", y, direction);
Ok(())
},
&Event::Window {..} => Ok(()),
&Event::Quit {..} => Err(AppEventHandling::Quit),
_ => Err(AppEventHandling::Unhandled),
};
self.nk.input_end();
out
}
fn gui(&mut self) {
let nk = &mut self.nk;
let title = NkString::from("Foo");
let rect = NkRect {x:20f32, y:30f32, w:200f32, h:200f32};
use NkPanelFlags::*;
let flags = NK_WINDOW_MOVABLE as u32
| NK_WINDOW_SCALABLE as u32
| NK_WINDOW_CLOSABLE as u32
| NK_WINDOW_MINIMIZABLE as u32
| NK_WINDOW_TITLE as u32;
if nk.begin(title, rect, flags) {
use NkTextAlignment::*;
nk.menubar_begin();
nk.layout_row_begin(NkLayoutFormat::NK_STATIC, 25f32, 2);
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("FILE"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("OPEN"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_push(45f32);
if nk.menu_begin_label(NkString::from("EDIT"), NK_TEXT_LEFT as u32, NkVec2 { x:120f32, y:200f32 }) {
nk.layout_row_dynamic(30f32, 1);
nk.menu_item_label(NkString::from("CUT"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("COPY"), NK_TEXT_LEFT as u32);
nk.menu_item_label(NkString::from("CLOSE"), NK_TEXT_LEFT as u32);
nk.menu_end();
}
nk.layout_row_end();
nk.menubar_end();
nk.layout_row_static(30f32, 80, 1);
if nk.button_label(NkString::from("button")) {
println!("Button pressed!");
}
use Difficulty::*;
nk.layout_row_dynamic(30f32, 2);
if nk.option_label(NkString::from("Easy"), self.op == Easy) {
self.op = Easy;
}
if nk.option_label(NkString::from("Hard"), self.op == Hard) {
self.op = Hard;
}
nk.layout_row_dynamic(25f32, 1);
nk.property_int(NkString::from("Compression:"), 0, &mut self.property, 100, 10, 1f32);
}
nk.end();
}
fn render_gui(&mut self) {
let nk = &mut self.nk;
const MAX_CMDS_BUFFER: usize = MAX_VERTEX_BUFFER;
let mut cmd_mem = [0u8; MAX_CMDS_BUFFER];
let mut cmds = NkBuffer::with_fixed(&mut cmd_mem);
use NkDrawVertexLayoutFormat::*;
use NkDrawVertexLayoutAttribute::*;
let vlayout = NkDrawVertexLayoutElements::new(&[
(NK_VERTEX_POSITION, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_POSITION as u32),
(NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, GuiVertex::OFFSETOF_UV as u32),
(NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, GuiVertex::OFFSETOF_COLOR as u32),
// è_é
(NK_VERTEX_ATTRIBUTE_COUNT, NK_FORMAT_COUNT, 0),
]);
let mut config = NkConvertConfig::default();
config.set_vertex_layout(&vlayout);
config.set_vertex_size(size_of::<GuiVertex>());
config.set_null(NkDrawNullTexture::default());
config.set_circle_segment_count(22);
config.set_curve_segment_count(22);
config.set_arc_segment_count(22);
config.set_global_alpha(1f32);
config.set_shape_aa(self.aa);
config.set_line_aa(self.aa);
/*
use std::slice::from_raw_parts_mut as frpm;
let mut vmem = [0u8; MAX_VERTEX_BUFFER];
let mut emem = [0u8; MAX_ELEMENT_BUFFER];
let vertices = unsafe { frpm(vmem.as_mut_ptr() as *mut GuiVertex, MAX_VERTEX_BUFFER/size_of::<GuiVertex>()) };
let elements = unsafe { frpm(emem.as_mut_ptr() as *mut u16, MAX_ELEMENT_BUFFER/size_of::<u16>()) };
let mut vbuf = NkBuffer::with_fixed(&mut vmem);
let mut ebuf = NkBuffer::with_fixed(&mut emem);
nk.convert(&mut cmds, &mut ebuf, &mut vbuf, &config);
let mut offset = 0;
for cmd in nk.draw_command_iterator(&cmds) {
let elem_count = cmd.elem_count();
if elem_count <= 0 {
continue;
}
for i in offset..(offset+elem_count) {
let e = elements[i as usize] as usize;
println!("i: {}", e);
let v = vertices[e];
let [x,y] = v.position;
let [r,g,b,a] = v.color;
let (w,h) = self.rdr.window().unwrap().size();
let x = (w as f32*(x+1f32)/2f32) as i32;
let y = -(h as f32*(y+1f32)/2f32) as i32;
self.rdr.set_draw_color(sdl2::pixels::Color::RGBA(r,g,b,a));
self.rdr.draw_point(sdl2::rect::Point::new(x,y)).unwrap();
}
offset += elem_count;
}
*/
for cmd in nk.command_iterator() {
println!("cmd: {:?}", cmd);
}
nk.clear();
}
}
fn main() {
std::env::set_var("RUST_BACKTRACE", "1");
let mut app = App::new();
let mut event_pump = app.sdl2.event_pump().unwrap();
'running: loop {
for e in event_pump.poll_iter() {
use AppEventHandling::*;
match app.handle_event(&e) {
Ok(_) => (),
Err(Quit) => break 'running,
Err(Unhandled) => println!("Unhandled event: {:?}", &e),
};
}
use sdl2::pixels::Color::*;
use sdl2::rect::Rect;
app.rdr.set_draw_color(RGB(255, 255, 0));
app.rdr.clear();
app.rdr.set_draw_color(RGB(0, 255, 255));
app.rdr.draw_rect(Rect::new(20, 20, 50, 50)).unwrap();
app.gui();
app.render_gui();
app.rdr.present();
}
}
| {
println!("Mouse {:?} is up", mouse_btn);
Ok(())
} | conditional_block |
nginx.py | """
fabcloudkit
Functions for managing Nginx.
This module provides functions that check for installation, install, and manage an
installation of, Nginx.
/etc/init.d/nginx:
The "init-script" that allows Nginx to be run automatically at system startup.
The existence of this file is verified, but it's assumed that the script is
installed by the package manager that installed Nginx.
/etc/nginx/nginx.conf:
The main or root Nginx configuration file. This file is loaded by Nginx when
it launches. The file contains an include directive that tells Nginx to
load additional configurations from a different directory.
Currently, this code writes a very basic nginx.conf file.
/etc/nginx/conf.d/:
The directory marked by the include directive in the nginx root configuration
file. Individual server configurations are stored in files in this folder.
/etc/nginx/conf.g/*.conf:
Individual server configuration files.
<deploy_root>/<name>/logs/ngaccess.log, ngerror.log:
Default location of the access (ngaccess.log) and error (ngerror.log) log files
for a specific server configuration. This location can be overridden in the call
to write_server_config().
For more information on Nginx check out: http://nginx.org, http://wiki.nginx.org
:copyright: (c) 2013 by Rick Bohrer.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
# standard
import posixpath as path
# pypi
from fabric.operations import run, sudo
# package
from fabcloudkit import cfg, put_string
from ..internal import *
from ..toolbase import Tool, SimpleTool
class NginxTool(Tool):
def __init__(self):
super(NginxTool,self).__init__()
self._simple = SimpleTool.create('nginx')
def check(self, **kwargs):
|
def install(self, **kwargs):
# install Nginx using the package manager.
self._simple.install()
start_msg('----- Configuring "Nginx":')
# verify that there's an init-script.
result = run('test -f /etc/init.d/nginx')
if result.failed:
raise HaltError('Uh oh. Package manager did not install an Nginx init-script.')
# write nginx.conf file.
dest = path.join(cfg().nginx_conf, 'nginx.conf')
message('Writing "nginx.conf"')
put_string(_NGINX_CONF, dest, use_sudo=True)
# the Amazon Linux AMI uses chkconfig; the init.d script won't do the job by itself.
# set Nginx so it can be managed by chkconfig; and turn on boot startup.
result = run('which chkconfig')
if result.succeeded:
message('System has chkconfig; configuring.')
result = sudo('chkconfig --add nginx')
if result.failed:
raise HaltError('"chkconfig --add nginx" failed.')
result = sudo('chkconfig nginx on')
if result.failed:
raise HaltError('"chkconfig nginx on" failed.')
succeed_msg('Successfully installed and configured "Nginx".')
return self
def write_config(self, name, server_names, proxy_pass, static_locations='', log_root=None, listen=80):
"""
Writes an Nginx server configuration file.
This function writes a specific style of configuration, that seems to be somewhat common, where
Nginx is used as a reverse-proxy for a locally-running (e.g., WSGI) server.
:param name: identifies the server name; used to name the configuration file.
:param server_names:
:param proxy_pass: identifies the local proxy to which Nginx will pass requests.
"""
start_msg('----- Writing Nginx server configuration for "{0}":'.format(name))
# be sure the log directory exists.
if log_root is None:
log_root = path.join(cfg().deploy_root, name, 'logs')
result = sudo('mkdir -p {0}'.format(log_root))
if result.failed:
raise HaltError('Unable to create log directory: "{0}"'.format(log_root))
# generate and write the configuration file.
server_config = _NGINX_SERVER_CONF.format(**locals())
dest = path.join(cfg().nginx_include_conf, '{name}.conf'.format(**locals()))
message('Writing to file: "{0}"'.format(dest))
put_string(server_config, dest, use_sudo=True)
succeed_msg('Wrote conf file for "{0}".'.format(name))
return self
def delete_config(self, name):
start_msg('----- Deleting server configuration for "{0}":'.format(name))
# delete the file, but ignore any errors.
config_name = '{name}.conf'.format(**locals())
result = sudo('rm -f {0}'.format(path.join(cfg().nginx_include_conf, config_name)))
if result.failed:
failed_msg('Ignoring failed attempt to delete configuration "{0}"'.format(config_name))
else:
succeed_msg('Successfully deleted configuration "{0}".'.format(config_name))
return self
def reload(self):
start_msg('----- Telling "Nginx" to reload configuration:')
result = sudo('/etc/init.d/nginx reload')
if result.failed:
raise HaltError('"Nginx" configuration reload failed ({0})'.format(result))
succeed_msg('Successfully reloaded.')
return self
# register.
Tool.__tools__['nginx'] = NginxTool
_NGINX_SERVER_CONF = """
server {{
listen {listen};
server_name {server_names};
access_log {log_root}/ngaccess.log;
error_log {log_root}/ngerror.log;
location / {{
proxy_pass {proxy_pass};
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}}
{static_locations}
}}
""".lstrip()
_NGINX_CONF = """
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
""".lstrip()
| return self._simple.check() | identifier_body |
nginx.py | """
fabcloudkit
Functions for managing Nginx.
This module provides functions that check for installation, install, and manage an
installation of, Nginx.
/etc/init.d/nginx:
The "init-script" that allows Nginx to be run automatically at system startup.
The existence of this file is verified, but it's assumed that the script is
installed by the package manager that installed Nginx.
/etc/nginx/nginx.conf:
The main or root Nginx configuration file. This file is loaded by Nginx when
it launches. The file contains an include directive that tells Nginx to
load additional configurations from a different directory.
Currently, this code writes a very basic nginx.conf file.
/etc/nginx/conf.d/:
The directory marked by the include directive in the nginx root configuration
file. Individual server configurations are stored in files in this folder.
/etc/nginx/conf.g/*.conf:
Individual server configuration files.
<deploy_root>/<name>/logs/ngaccess.log, ngerror.log:
Default location of the access (ngaccess.log) and error (ngerror.log) log files
for a specific server configuration. This location can be overridden in the call
to write_server_config().
For more information on Nginx check out: http://nginx.org, http://wiki.nginx.org
:copyright: (c) 2013 by Rick Bohrer.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
# standard
import posixpath as path
# pypi
from fabric.operations import run, sudo
# package
from fabcloudkit import cfg, put_string
from ..internal import *
from ..toolbase import Tool, SimpleTool
class NginxTool(Tool):
def __init__(self):
super(NginxTool,self).__init__()
self._simple = SimpleTool.create('nginx')
def check(self, **kwargs):
return self._simple.check()
def install(self, **kwargs):
# install Nginx using the package manager.
self._simple.install()
start_msg('----- Configuring "Nginx":')
# verify that there's an init-script.
result = run('test -f /etc/init.d/nginx')
if result.failed:
|
# write nginx.conf file.
dest = path.join(cfg().nginx_conf, 'nginx.conf')
message('Writing "nginx.conf"')
put_string(_NGINX_CONF, dest, use_sudo=True)
# the Amazon Linux AMI uses chkconfig; the init.d script won't do the job by itself.
# set Nginx so it can be managed by chkconfig; and turn on boot startup.
result = run('which chkconfig')
if result.succeeded:
message('System has chkconfig; configuring.')
result = sudo('chkconfig --add nginx')
if result.failed:
raise HaltError('"chkconfig --add nginx" failed.')
result = sudo('chkconfig nginx on')
if result.failed:
raise HaltError('"chkconfig nginx on" failed.')
succeed_msg('Successfully installed and configured "Nginx".')
return self
def write_config(self, name, server_names, proxy_pass, static_locations='', log_root=None, listen=80):
"""
Writes an Nginx server configuration file.
This function writes a specific style of configuration, that seems to be somewhat common, where
Nginx is used as a reverse-proxy for a locally-running (e.g., WSGI) server.
:param name: identifies the server name; used to name the configuration file.
:param server_names:
:param proxy_pass: identifies the local proxy to which Nginx will pass requests.
"""
start_msg('----- Writing Nginx server configuration for "{0}":'.format(name))
# be sure the log directory exists.
if log_root is None:
log_root = path.join(cfg().deploy_root, name, 'logs')
result = sudo('mkdir -p {0}'.format(log_root))
if result.failed:
raise HaltError('Unable to create log directory: "{0}"'.format(log_root))
# generate and write the configuration file.
server_config = _NGINX_SERVER_CONF.format(**locals())
dest = path.join(cfg().nginx_include_conf, '{name}.conf'.format(**locals()))
message('Writing to file: "{0}"'.format(dest))
put_string(server_config, dest, use_sudo=True)
succeed_msg('Wrote conf file for "{0}".'.format(name))
return self
def delete_config(self, name):
start_msg('----- Deleting server configuration for "{0}":'.format(name))
# delete the file, but ignore any errors.
config_name = '{name}.conf'.format(**locals())
result = sudo('rm -f {0}'.format(path.join(cfg().nginx_include_conf, config_name)))
if result.failed:
failed_msg('Ignoring failed attempt to delete configuration "{0}"'.format(config_name))
else:
succeed_msg('Successfully deleted configuration "{0}".'.format(config_name))
return self
def reload(self):
start_msg('----- Telling "Nginx" to reload configuration:')
result = sudo('/etc/init.d/nginx reload')
if result.failed:
raise HaltError('"Nginx" configuration reload failed ({0})'.format(result))
succeed_msg('Successfully reloaded.')
return self
# register.
Tool.__tools__['nginx'] = NginxTool
_NGINX_SERVER_CONF = """
server {{
listen {listen};
server_name {server_names};
access_log {log_root}/ngaccess.log;
error_log {log_root}/ngerror.log;
location / {{
proxy_pass {proxy_pass};
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}}
{static_locations}
}}
""".lstrip()
_NGINX_CONF = """
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
""".lstrip()
| raise HaltError('Uh oh. Package manager did not install an Nginx init-script.') | conditional_block |
nginx.py | """
fabcloudkit
Functions for managing Nginx.
This module provides functions that check for installation, install, and manage an
installation of, Nginx.
/etc/init.d/nginx:
The "init-script" that allows Nginx to be run automatically at system startup.
The existence of this file is verified, but it's assumed that the script is
installed by the package manager that installed Nginx.
/etc/nginx/nginx.conf:
The main or root Nginx configuration file. This file is loaded by Nginx when
it launches. The file contains an include directive that tells Nginx to
load additional configurations from a different directory.
Currently, this code writes a very basic nginx.conf file.
/etc/nginx/conf.d/:
The directory marked by the include directive in the nginx root configuration
file. Individual server configurations are stored in files in this folder.
/etc/nginx/conf.g/*.conf:
Individual server configuration files.
<deploy_root>/<name>/logs/ngaccess.log, ngerror.log:
Default location of the access (ngaccess.log) and error (ngerror.log) log files
for a specific server configuration. This location can be overridden in the call
to write_server_config().
For more information on Nginx check out: http://nginx.org, http://wiki.nginx.org
:copyright: (c) 2013 by Rick Bohrer.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
# standard
import posixpath as path
# pypi
from fabric.operations import run, sudo
# package
from fabcloudkit import cfg, put_string
from ..internal import *
from ..toolbase import Tool, SimpleTool
class NginxTool(Tool):
def __init__(self):
super(NginxTool,self).__init__()
self._simple = SimpleTool.create('nginx')
def check(self, **kwargs):
return self._simple.check()
def install(self, **kwargs):
# install Nginx using the package manager.
self._simple.install()
start_msg('----- Configuring "Nginx":')
# verify that there's an init-script.
result = run('test -f /etc/init.d/nginx')
if result.failed:
raise HaltError('Uh oh. Package manager did not install an Nginx init-script.')
# write nginx.conf file.
dest = path.join(cfg().nginx_conf, 'nginx.conf')
message('Writing "nginx.conf"')
put_string(_NGINX_CONF, dest, use_sudo=True)
# the Amazon Linux AMI uses chkconfig; the init.d script won't do the job by itself.
# set Nginx so it can be managed by chkconfig; and turn on boot startup.
result = run('which chkconfig')
if result.succeeded:
message('System has chkconfig; configuring.')
result = sudo('chkconfig --add nginx')
if result.failed:
raise HaltError('"chkconfig --add nginx" failed.')
result = sudo('chkconfig nginx on')
if result.failed:
raise HaltError('"chkconfig nginx on" failed.')
succeed_msg('Successfully installed and configured "Nginx".')
return self
def | (self, name, server_names, proxy_pass, static_locations='', log_root=None, listen=80):
"""
Writes an Nginx server configuration file.
This function writes a specific style of configuration, that seems to be somewhat common, where
Nginx is used as a reverse-proxy for a locally-running (e.g., WSGI) server.
:param name: identifies the server name; used to name the configuration file.
:param server_names:
:param proxy_pass: identifies the local proxy to which Nginx will pass requests.
"""
start_msg('----- Writing Nginx server configuration for "{0}":'.format(name))
# be sure the log directory exists.
if log_root is None:
log_root = path.join(cfg().deploy_root, name, 'logs')
result = sudo('mkdir -p {0}'.format(log_root))
if result.failed:
raise HaltError('Unable to create log directory: "{0}"'.format(log_root))
# generate and write the configuration file.
server_config = _NGINX_SERVER_CONF.format(**locals())
dest = path.join(cfg().nginx_include_conf, '{name}.conf'.format(**locals()))
message('Writing to file: "{0}"'.format(dest))
put_string(server_config, dest, use_sudo=True)
succeed_msg('Wrote conf file for "{0}".'.format(name))
return self
def delete_config(self, name):
start_msg('----- Deleting server configuration for "{0}":'.format(name))
# delete the file, but ignore any errors.
config_name = '{name}.conf'.format(**locals())
result = sudo('rm -f {0}'.format(path.join(cfg().nginx_include_conf, config_name)))
if result.failed:
failed_msg('Ignoring failed attempt to delete configuration "{0}"'.format(config_name))
else:
succeed_msg('Successfully deleted configuration "{0}".'.format(config_name))
return self
def reload(self):
start_msg('----- Telling "Nginx" to reload configuration:')
result = sudo('/etc/init.d/nginx reload')
if result.failed:
raise HaltError('"Nginx" configuration reload failed ({0})'.format(result))
succeed_msg('Successfully reloaded.')
return self
# register.
Tool.__tools__['nginx'] = NginxTool
_NGINX_SERVER_CONF = """
server {{
listen {listen};
server_name {server_names};
access_log {log_root}/ngaccess.log;
error_log {log_root}/ngerror.log;
location / {{
proxy_pass {proxy_pass};
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}}
{static_locations}
}}
""".lstrip()
_NGINX_CONF = """
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
""".lstrip()
| write_config | identifier_name |
nginx.py | """
fabcloudkit
Functions for managing Nginx.
This module provides functions that check for installation, install, and manage an
installation of, Nginx.
/etc/init.d/nginx:
The "init-script" that allows Nginx to be run automatically at system startup.
The existence of this file is verified, but it's assumed that the script is
installed by the package manager that installed Nginx.
/etc/nginx/nginx.conf:
The main or root Nginx configuration file. This file is loaded by Nginx when
it launches. The file contains an include directive that tells Nginx to
load additional configurations from a different directory.
Currently, this code writes a very basic nginx.conf file.
/etc/nginx/conf.d/:
The directory marked by the include directive in the nginx root configuration
file. Individual server configurations are stored in files in this folder.
/etc/nginx/conf.g/*.conf:
Individual server configuration files.
<deploy_root>/<name>/logs/ngaccess.log, ngerror.log:
Default location of the access (ngaccess.log) and error (ngerror.log) log files
for a specific server configuration. This location can be overridden in the call
to write_server_config().
For more information on Nginx check out: http://nginx.org, http://wiki.nginx.org
:copyright: (c) 2013 by Rick Bohrer.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
# standard
import posixpath as path
# pypi
from fabric.operations import run, sudo
# package
from fabcloudkit import cfg, put_string
from ..internal import *
from ..toolbase import Tool, SimpleTool
class NginxTool(Tool):
def __init__(self):
super(NginxTool,self).__init__()
self._simple = SimpleTool.create('nginx')
def check(self, **kwargs):
return self._simple.check()
def install(self, **kwargs):
# install Nginx using the package manager.
self._simple.install()
start_msg('----- Configuring "Nginx":')
# verify that there's an init-script.
result = run('test -f /etc/init.d/nginx')
if result.failed:
raise HaltError('Uh oh. Package manager did not install an Nginx init-script.')
# write nginx.conf file.
dest = path.join(cfg().nginx_conf, 'nginx.conf') | # set Nginx so it can be managed by chkconfig; and turn on boot startup.
result = run('which chkconfig')
if result.succeeded:
message('System has chkconfig; configuring.')
result = sudo('chkconfig --add nginx')
if result.failed:
raise HaltError('"chkconfig --add nginx" failed.')
result = sudo('chkconfig nginx on')
if result.failed:
raise HaltError('"chkconfig nginx on" failed.')
succeed_msg('Successfully installed and configured "Nginx".')
return self
def write_config(self, name, server_names, proxy_pass, static_locations='', log_root=None, listen=80):
"""
Writes an Nginx server configuration file.
This function writes a specific style of configuration, that seems to be somewhat common, where
Nginx is used as a reverse-proxy for a locally-running (e.g., WSGI) server.
:param name: identifies the server name; used to name the configuration file.
:param server_names:
:param proxy_pass: identifies the local proxy to which Nginx will pass requests.
"""
start_msg('----- Writing Nginx server configuration for "{0}":'.format(name))
# be sure the log directory exists.
if log_root is None:
log_root = path.join(cfg().deploy_root, name, 'logs')
result = sudo('mkdir -p {0}'.format(log_root))
if result.failed:
raise HaltError('Unable to create log directory: "{0}"'.format(log_root))
# generate and write the configuration file.
server_config = _NGINX_SERVER_CONF.format(**locals())
dest = path.join(cfg().nginx_include_conf, '{name}.conf'.format(**locals()))
message('Writing to file: "{0}"'.format(dest))
put_string(server_config, dest, use_sudo=True)
succeed_msg('Wrote conf file for "{0}".'.format(name))
return self
def delete_config(self, name):
start_msg('----- Deleting server configuration for "{0}":'.format(name))
# delete the file, but ignore any errors.
config_name = '{name}.conf'.format(**locals())
result = sudo('rm -f {0}'.format(path.join(cfg().nginx_include_conf, config_name)))
if result.failed:
failed_msg('Ignoring failed attempt to delete configuration "{0}"'.format(config_name))
else:
succeed_msg('Successfully deleted configuration "{0}".'.format(config_name))
return self
def reload(self):
start_msg('----- Telling "Nginx" to reload configuration:')
result = sudo('/etc/init.d/nginx reload')
if result.failed:
raise HaltError('"Nginx" configuration reload failed ({0})'.format(result))
succeed_msg('Successfully reloaded.')
return self
# register.
Tool.__tools__['nginx'] = NginxTool
_NGINX_SERVER_CONF = """
server {{
listen {listen};
server_name {server_names};
access_log {log_root}/ngaccess.log;
error_log {log_root}/ngerror.log;
location / {{
proxy_pass {proxy_pass};
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}}
{static_locations}
}}
""".lstrip()
_NGINX_CONF = """
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
""".lstrip() | message('Writing "nginx.conf"')
put_string(_NGINX_CONF, dest, use_sudo=True)
# the Amazon Linux AMI uses chkconfig; the init.d script won't do the job by itself. | random_line_split |
pages.py | from __future__ import absolute_import
import os
from robot.libraries.BuiltIn import BuiltIn
HOST = "http://localhost:8000"
BROWSER = os.environ.get('BROWSER', 'firefox')
def _get_variable_value(variable):
return BuiltIn().replace_variables('${%s}' % variable)
class Page(object):
def __init__(self, path):
self.path = path
@property
def url(self):
return "%s%s" % (_get_variable_value('HOST'), self.path)
@classmethod
def of(klass, model_instance):
if isinstance(model_instance, basestring):
model_instance = _get_variable_value(model_instance)
return klass(model_instance.get_absolute_url())
class Element(object):
def __init__(self, locator):
self.locator = locator
@property
def is_css(self):
return self.locator.startswith('css=')
@property
def is_xpath(self):
return self.locator.startswith('//')
def __getitem__(self, index):
if self.locator.startswith('css='):
|
elif self.locator.startswith('//'):
suffix = '[%s]' % (index + 1)
return Element(self.locator + suffix)
def in_(self, other):
other = _get_variable_value(other)
assert self.is_css == other.is_css, "Both locators must be of same type"
if self.is_css:
return Element(other.locator + " " + self.locator[len('css='):])
elif self.is_xpath:
return Element(other.locator + self.locator) # FIXME might fail for advanced xpath
# pages
add_talk_page = Page('/talks/new')
talk_page = Page('/talks/id/') # TODO this should be a regex
login_page = Page('/admin/login/')
add_series_page = Page('/talks/series/new')
series_page = Page('/talks/series/id/')
# dynamic pages
edit_talk_page = lambda slug: Page('/talks/id/%s/edit' % slug)
show_talk_page = lambda slug: Page('/talks/id/%s/' % slug)
# elements
body = Element('//body')
abstract_field = Element('css=#id_event-description')
title_field = Element('css=#id_event-title')
start_field = Element('css=#id_event-start')
end_field = Element('css=#id_event-end')
group_field = Element('css=#id_event-group')
venue_field = Element('css=#id_event-location_suggest')
button_done = Element('//button[text()="Done"]')
button_save_add_another = Element('css=#btn-save-add-another')
checkbox_in_group_section = Element('css=#id_event-group-enabled')
error_message = Element('//*[contains(@class, "alert-warning")]')
success_message = Element('//*[contains(@class, "alert-success")]')
create_group_button = Element("//a[text()='New series']")
suggestion_list = Element('css=.js-suggestion')
suggestion_popup = Element('css=.tt-suggestions')
modal_dialog = Element('//*[@id="form-modal"]')
modal_dialog_title = Element('//*[@id="form-modal-label"]')
modal_dialog_submit_button = Element('//*[@id="form-modal"]//input[@type="submit"]')
datetimepicker = Element('css=.bootstrap-datetimepicker-widget')
datetimepicker_current_day = Element('css=.datepicker-days')
datetimepicker_time = Element('css=.timepicker-picker')
button_login = Element('//input[@type="submit"]')
username_field = Element('css=#id_username')
password_field = Element('css=#id_password')
reveal_create_speaker_link = Element('//*[@person-type="speakers"]//*[@class="js-create-person"]')
speaker_name_field = Element('//*[@person-type="speakers"]//*[@id="id_name"]')
speaker_bio_field = Element('//*[@person-type="speakers"]//*[@id="id_bio"]')
add_speaker_button = Element('//*[@person-type="speakers"]//*[contains(@class, "js-submit-person")]')
series_title_field = Element('css=#id_title')
series_description_field = Element('css=#id_description')
series_occurence_field = Element('css=#id_occurence')
series_create_person = Element('css=.js-create-person')
series_create_person_name = Element('css=#id_name')
series_create_person_bio = Element('css=#id_bio')
series_create_person_submit = Element('css=.js-submit-person')
series_organisers_list = Element('css=')
# dynamic elements
field = lambda label: Element('//*[@id=//label[text()="%s"]/@for]' % label)
modal_dialog_field = lambda label: Element('//*[@id=//*[@id="form-modal"]//label[text()="%s"]/@for]' % label)
suggested_item = lambda label: Element('//a[contains(text(), "%s")][contains(@class, "js-suggestion")]' % label)
suggestion_popup_item = lambda label: Element('//*[contains(., "%s")][@class="tt-suggestion"]' % label)
list_group_item = lambda label: Element('//*[contains(@class, "list-group-item")][contains(text(), "%s")]' % label)
remove_item = lambda label: Element('//input[@name="%s"]/following-sibling::div/a' % label)
| raise NotImplementedError("indexing not supported for css selectors") | conditional_block |
pages.py | from __future__ import absolute_import
import os
from robot.libraries.BuiltIn import BuiltIn
HOST = "http://localhost:8000"
BROWSER = os.environ.get('BROWSER', 'firefox')
def _get_variable_value(variable):
return BuiltIn().replace_variables('${%s}' % variable)
class Page(object):
def __init__(self, path):
self.path = path
@property
def url(self):
return "%s%s" % (_get_variable_value('HOST'), self.path)
@classmethod
def of(klass, model_instance):
if isinstance(model_instance, basestring):
model_instance = _get_variable_value(model_instance)
return klass(model_instance.get_absolute_url())
class Element(object):
def __init__(self, locator):
self.locator = locator
@property
def is_css(self):
return self.locator.startswith('css=')
@property
def is_xpath(self):
|
def __getitem__(self, index):
if self.locator.startswith('css='):
raise NotImplementedError("indexing not supported for css selectors")
elif self.locator.startswith('//'):
suffix = '[%s]' % (index + 1)
return Element(self.locator + suffix)
def in_(self, other):
other = _get_variable_value(other)
assert self.is_css == other.is_css, "Both locators must be of same type"
if self.is_css:
return Element(other.locator + " " + self.locator[len('css='):])
elif self.is_xpath:
return Element(other.locator + self.locator) # FIXME might fail for advanced xpath
# pages
add_talk_page = Page('/talks/new')
talk_page = Page('/talks/id/') # TODO this should be a regex
login_page = Page('/admin/login/')
add_series_page = Page('/talks/series/new')
series_page = Page('/talks/series/id/')
# dynamic pages
edit_talk_page = lambda slug: Page('/talks/id/%s/edit' % slug)
show_talk_page = lambda slug: Page('/talks/id/%s/' % slug)
# elements
body = Element('//body')
abstract_field = Element('css=#id_event-description')
title_field = Element('css=#id_event-title')
start_field = Element('css=#id_event-start')
end_field = Element('css=#id_event-end')
group_field = Element('css=#id_event-group')
venue_field = Element('css=#id_event-location_suggest')
button_done = Element('//button[text()="Done"]')
button_save_add_another = Element('css=#btn-save-add-another')
checkbox_in_group_section = Element('css=#id_event-group-enabled')
error_message = Element('//*[contains(@class, "alert-warning")]')
success_message = Element('//*[contains(@class, "alert-success")]')
create_group_button = Element("//a[text()='New series']")
suggestion_list = Element('css=.js-suggestion')
suggestion_popup = Element('css=.tt-suggestions')
modal_dialog = Element('//*[@id="form-modal"]')
modal_dialog_title = Element('//*[@id="form-modal-label"]')
modal_dialog_submit_button = Element('//*[@id="form-modal"]//input[@type="submit"]')
datetimepicker = Element('css=.bootstrap-datetimepicker-widget')
datetimepicker_current_day = Element('css=.datepicker-days')
datetimepicker_time = Element('css=.timepicker-picker')
button_login = Element('//input[@type="submit"]')
username_field = Element('css=#id_username')
password_field = Element('css=#id_password')
reveal_create_speaker_link = Element('//*[@person-type="speakers"]//*[@class="js-create-person"]')
speaker_name_field = Element('//*[@person-type="speakers"]//*[@id="id_name"]')
speaker_bio_field = Element('//*[@person-type="speakers"]//*[@id="id_bio"]')
add_speaker_button = Element('//*[@person-type="speakers"]//*[contains(@class, "js-submit-person")]')
series_title_field = Element('css=#id_title')
series_description_field = Element('css=#id_description')
series_occurence_field = Element('css=#id_occurence')
series_create_person = Element('css=.js-create-person')
series_create_person_name = Element('css=#id_name')
series_create_person_bio = Element('css=#id_bio')
series_create_person_submit = Element('css=.js-submit-person')
series_organisers_list = Element('css=')
# dynamic elements
field = lambda label: Element('//*[@id=//label[text()="%s"]/@for]' % label)
modal_dialog_field = lambda label: Element('//*[@id=//*[@id="form-modal"]//label[text()="%s"]/@for]' % label)
suggested_item = lambda label: Element('//a[contains(text(), "%s")][contains(@class, "js-suggestion")]' % label)
suggestion_popup_item = lambda label: Element('//*[contains(., "%s")][@class="tt-suggestion"]' % label)
list_group_item = lambda label: Element('//*[contains(@class, "list-group-item")][contains(text(), "%s")]' % label)
remove_item = lambda label: Element('//input[@name="%s"]/following-sibling::div/a' % label)
| return self.locator.startswith('//') | identifier_body |
pages.py | from __future__ import absolute_import
import os
from robot.libraries.BuiltIn import BuiltIn
HOST = "http://localhost:8000"
BROWSER = os.environ.get('BROWSER', 'firefox')
def _get_variable_value(variable):
return BuiltIn().replace_variables('${%s}' % variable)
class Page(object):
def __init__(self, path):
self.path = path
@property
def url(self):
return "%s%s" % (_get_variable_value('HOST'), self.path)
@classmethod
def of(klass, model_instance):
if isinstance(model_instance, basestring):
model_instance = _get_variable_value(model_instance)
return klass(model_instance.get_absolute_url())
class Element(object):
def __init__(self, locator):
self.locator = locator
@property
def | (self):
return self.locator.startswith('css=')
@property
def is_xpath(self):
return self.locator.startswith('//')
def __getitem__(self, index):
if self.locator.startswith('css='):
raise NotImplementedError("indexing not supported for css selectors")
elif self.locator.startswith('//'):
suffix = '[%s]' % (index + 1)
return Element(self.locator + suffix)
def in_(self, other):
other = _get_variable_value(other)
assert self.is_css == other.is_css, "Both locators must be of same type"
if self.is_css:
return Element(other.locator + " " + self.locator[len('css='):])
elif self.is_xpath:
return Element(other.locator + self.locator) # FIXME might fail for advanced xpath
# pages
add_talk_page = Page('/talks/new')
talk_page = Page('/talks/id/') # TODO this should be a regex
login_page = Page('/admin/login/')
add_series_page = Page('/talks/series/new')
series_page = Page('/talks/series/id/')
# dynamic pages
edit_talk_page = lambda slug: Page('/talks/id/%s/edit' % slug)
show_talk_page = lambda slug: Page('/talks/id/%s/' % slug)
# elements
body = Element('//body')
abstract_field = Element('css=#id_event-description')
title_field = Element('css=#id_event-title')
start_field = Element('css=#id_event-start')
end_field = Element('css=#id_event-end')
group_field = Element('css=#id_event-group')
venue_field = Element('css=#id_event-location_suggest')
button_done = Element('//button[text()="Done"]')
button_save_add_another = Element('css=#btn-save-add-another')
checkbox_in_group_section = Element('css=#id_event-group-enabled')
error_message = Element('//*[contains(@class, "alert-warning")]')
success_message = Element('//*[contains(@class, "alert-success")]')
create_group_button = Element("//a[text()='New series']")
suggestion_list = Element('css=.js-suggestion')
suggestion_popup = Element('css=.tt-suggestions')
modal_dialog = Element('//*[@id="form-modal"]')
modal_dialog_title = Element('//*[@id="form-modal-label"]')
modal_dialog_submit_button = Element('//*[@id="form-modal"]//input[@type="submit"]')
datetimepicker = Element('css=.bootstrap-datetimepicker-widget')
datetimepicker_current_day = Element('css=.datepicker-days')
datetimepicker_time = Element('css=.timepicker-picker')
button_login = Element('//input[@type="submit"]')
username_field = Element('css=#id_username')
password_field = Element('css=#id_password')
reveal_create_speaker_link = Element('//*[@person-type="speakers"]//*[@class="js-create-person"]')
speaker_name_field = Element('//*[@person-type="speakers"]//*[@id="id_name"]')
speaker_bio_field = Element('//*[@person-type="speakers"]//*[@id="id_bio"]')
add_speaker_button = Element('//*[@person-type="speakers"]//*[contains(@class, "js-submit-person")]')
series_title_field = Element('css=#id_title')
series_description_field = Element('css=#id_description')
series_occurence_field = Element('css=#id_occurence')
series_create_person = Element('css=.js-create-person')
series_create_person_name = Element('css=#id_name')
series_create_person_bio = Element('css=#id_bio')
series_create_person_submit = Element('css=.js-submit-person')
series_organisers_list = Element('css=')
# dynamic elements
field = lambda label: Element('//*[@id=//label[text()="%s"]/@for]' % label)
modal_dialog_field = lambda label: Element('//*[@id=//*[@id="form-modal"]//label[text()="%s"]/@for]' % label)
suggested_item = lambda label: Element('//a[contains(text(), "%s")][contains(@class, "js-suggestion")]' % label)
suggestion_popup_item = lambda label: Element('//*[contains(., "%s")][@class="tt-suggestion"]' % label)
list_group_item = lambda label: Element('//*[contains(@class, "list-group-item")][contains(text(), "%s")]' % label)
remove_item = lambda label: Element('//input[@name="%s"]/following-sibling::div/a' % label)
| is_css | identifier_name |
pages.py | from __future__ import absolute_import
import os
from robot.libraries.BuiltIn import BuiltIn
HOST = "http://localhost:8000"
BROWSER = os.environ.get('BROWSER', 'firefox')
def _get_variable_value(variable):
return BuiltIn().replace_variables('${%s}' % variable)
class Page(object):
def __init__(self, path):
self.path = path
@property
def url(self):
return "%s%s" % (_get_variable_value('HOST'), self.path)
@classmethod
def of(klass, model_instance):
if isinstance(model_instance, basestring):
model_instance = _get_variable_value(model_instance)
return klass(model_instance.get_absolute_url())
class Element(object):
def __init__(self, locator):
self.locator = locator
@property
def is_css(self):
return self.locator.startswith('css=')
@property
def is_xpath(self):
return self.locator.startswith('//')
def __getitem__(self, index):
if self.locator.startswith('css='):
raise NotImplementedError("indexing not supported for css selectors")
elif self.locator.startswith('//'):
suffix = '[%s]' % (index + 1)
return Element(self.locator + suffix)
def in_(self, other):
other = _get_variable_value(other)
assert self.is_css == other.is_css, "Both locators must be of same type"
if self.is_css:
return Element(other.locator + " " + self.locator[len('css='):]) |
add_talk_page = Page('/talks/new')
talk_page = Page('/talks/id/') # TODO this should be a regex
login_page = Page('/admin/login/')
add_series_page = Page('/talks/series/new')
series_page = Page('/talks/series/id/')
# dynamic pages
edit_talk_page = lambda slug: Page('/talks/id/%s/edit' % slug)
show_talk_page = lambda slug: Page('/talks/id/%s/' % slug)
# elements
body = Element('//body')
abstract_field = Element('css=#id_event-description')
title_field = Element('css=#id_event-title')
start_field = Element('css=#id_event-start')
end_field = Element('css=#id_event-end')
group_field = Element('css=#id_event-group')
venue_field = Element('css=#id_event-location_suggest')
button_done = Element('//button[text()="Done"]')
button_save_add_another = Element('css=#btn-save-add-another')
checkbox_in_group_section = Element('css=#id_event-group-enabled')
error_message = Element('//*[contains(@class, "alert-warning")]')
success_message = Element('//*[contains(@class, "alert-success")]')
create_group_button = Element("//a[text()='New series']")
suggestion_list = Element('css=.js-suggestion')
suggestion_popup = Element('css=.tt-suggestions')
modal_dialog = Element('//*[@id="form-modal"]')
modal_dialog_title = Element('//*[@id="form-modal-label"]')
modal_dialog_submit_button = Element('//*[@id="form-modal"]//input[@type="submit"]')
datetimepicker = Element('css=.bootstrap-datetimepicker-widget')
datetimepicker_current_day = Element('css=.datepicker-days')
datetimepicker_time = Element('css=.timepicker-picker')
button_login = Element('//input[@type="submit"]')
username_field = Element('css=#id_username')
password_field = Element('css=#id_password')
reveal_create_speaker_link = Element('//*[@person-type="speakers"]//*[@class="js-create-person"]')
speaker_name_field = Element('//*[@person-type="speakers"]//*[@id="id_name"]')
speaker_bio_field = Element('//*[@person-type="speakers"]//*[@id="id_bio"]')
add_speaker_button = Element('//*[@person-type="speakers"]//*[contains(@class, "js-submit-person")]')
series_title_field = Element('css=#id_title')
series_description_field = Element('css=#id_description')
series_occurence_field = Element('css=#id_occurence')
series_create_person = Element('css=.js-create-person')
series_create_person_name = Element('css=#id_name')
series_create_person_bio = Element('css=#id_bio')
series_create_person_submit = Element('css=.js-submit-person')
series_organisers_list = Element('css=')
# dynamic elements
field = lambda label: Element('//*[@id=//label[text()="%s"]/@for]' % label)
modal_dialog_field = lambda label: Element('//*[@id=//*[@id="form-modal"]//label[text()="%s"]/@for]' % label)
suggested_item = lambda label: Element('//a[contains(text(), "%s")][contains(@class, "js-suggestion")]' % label)
suggestion_popup_item = lambda label: Element('//*[contains(., "%s")][@class="tt-suggestion"]' % label)
list_group_item = lambda label: Element('//*[contains(@class, "list-group-item")][contains(text(), "%s")]' % label)
remove_item = lambda label: Element('//input[@name="%s"]/following-sibling::div/a' % label) | elif self.is_xpath:
return Element(other.locator + self.locator) # FIXME might fail for advanced xpath
# pages | random_line_split |
online.py | from typing import (
Dict,
Optional,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
get_jit_arguments,
)
def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]):
"""
Generate a numba jitted groupby ewma function specified by values
from engine_kwargs.
Parameters
----------
engine_kwargs : dict
dictionary of arguments to be passed into numba.jit
Returns
-------
Numba function
"""
nopython, nogil, parallel = get_jit_arguments(engine_kwargs)
cache_key = (lambda x: x, "online_ewma")
if cache_key in NUMBA_FUNC_CACHE:
return NUMBA_FUNC_CACHE[cache_key]
numba = import_optional_dependency("numba")
@numba.jit(nopython=nopython, nogil=nogil, parallel=parallel)
def online_ewma(
values: np.ndarray,
deltas: np.ndarray,
minimum_periods: int,
old_wt_factor: float,
new_wt: float,
old_wt: np.ndarray,
adjust: bool,
ignore_na: bool,
):
"""
Compute online exponentially weighted mean per column over 2D values.
Takes the first observation as is, then computes the subsequent
exponentially weighted mean accounting minimum periods.
"""
result = np.empty(values.shape)
weighted_avg = values[0]
nobs = (~np.isnan(weighted_avg)).astype(np.int64)
result[0] = np.where(nobs >= minimum_periods, weighted_avg, np.nan)
for i in range(1, len(values)):
cur = values[i]
is_observations = ~np.isnan(cur)
nobs += is_observations.astype(np.int64)
for j in numba.prange(len(cur)):
if not np.isnan(weighted_avg[j]):
if is_observations[j] or not ignore_na:
# note that len(deltas) = len(vals) - 1 and deltas[i] is to be
# used in conjunction with vals[i+1]
old_wt[j] *= old_wt_factor ** deltas[j - 1]
if is_observations[j]:
# avoid numerical errors on constant series
if weighted_avg[j] != cur[j]:
weighted_avg[j] = (
(old_wt[j] * weighted_avg[j]) + (new_wt * cur[j])
) / (old_wt[j] + new_wt)
if adjust:
old_wt[j] += new_wt
else:
old_wt[j] = 1.0
elif is_observations[j]:
weighted_avg[j] = cur[j]
result[i] = np.where(nobs >= minimum_periods, weighted_avg, np.nan)
return result, old_wt
return online_ewma
class EWMMeanState:
def __init__(self, com, adjust, ignore_na, axis, shape):
|
def run_ewm(self, weighted_avg, deltas, min_periods, ewm_func):
result, old_wt = ewm_func(
weighted_avg,
deltas,
min_periods,
self.old_wt_factor,
self.new_wt,
self.old_wt,
self.adjust,
self.ignore_na,
)
self.old_wt = old_wt
self.last_ewm = result[-1]
return result
def reset(self):
self.old_wt = np.ones(self.shape[self.axis - 1])
self.last_ewm = None
| alpha = 1.0 / (1.0 + com)
self.axis = axis
self.shape = shape
self.adjust = adjust
self.ignore_na = ignore_na
self.new_wt = 1.0 if adjust else alpha
self.old_wt_factor = 1.0 - alpha
self.old_wt = np.ones(self.shape[self.axis - 1])
self.last_ewm = None | identifier_body |
online.py | from typing import (
Dict,
Optional,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
get_jit_arguments,
)
def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]):
"""
Generate a numba jitted groupby ewma function specified by values
from engine_kwargs.
Parameters
----------
engine_kwargs : dict
dictionary of arguments to be passed into numba.jit
Returns
-------
Numba function
"""
nopython, nogil, parallel = get_jit_arguments(engine_kwargs)
cache_key = (lambda x: x, "online_ewma")
if cache_key in NUMBA_FUNC_CACHE:
return NUMBA_FUNC_CACHE[cache_key]
numba = import_optional_dependency("numba")
@numba.jit(nopython=nopython, nogil=nogil, parallel=parallel)
def online_ewma(
values: np.ndarray,
deltas: np.ndarray,
minimum_periods: int,
old_wt_factor: float,
new_wt: float,
old_wt: np.ndarray,
adjust: bool,
ignore_na: bool,
):
"""
Compute online exponentially weighted mean per column over 2D values.
Takes the first observation as is, then computes the subsequent
exponentially weighted mean accounting minimum periods.
"""
result = np.empty(values.shape)
weighted_avg = values[0]
nobs = (~np.isnan(weighted_avg)).astype(np.int64)
result[0] = np.where(nobs >= minimum_periods, weighted_avg, np.nan)
for i in range(1, len(values)):
cur = values[i]
is_observations = ~np.isnan(cur)
nobs += is_observations.astype(np.int64)
for j in numba.prange(len(cur)):
if not np.isnan(weighted_avg[j]):
if is_observations[j] or not ignore_na:
# note that len(deltas) = len(vals) - 1 and deltas[i] is to be
# used in conjunction with vals[i+1]
old_wt[j] *= old_wt_factor ** deltas[j - 1]
if is_observations[j]:
# avoid numerical errors on constant series
if weighted_avg[j] != cur[j]:
weighted_avg[j] = (
(old_wt[j] * weighted_avg[j]) + (new_wt * cur[j])
) / (old_wt[j] + new_wt)
if adjust:
|
else:
old_wt[j] = 1.0
elif is_observations[j]:
weighted_avg[j] = cur[j]
result[i] = np.where(nobs >= minimum_periods, weighted_avg, np.nan)
return result, old_wt
return online_ewma
class EWMMeanState:
def __init__(self, com, adjust, ignore_na, axis, shape):
alpha = 1.0 / (1.0 + com)
self.axis = axis
self.shape = shape
self.adjust = adjust
self.ignore_na = ignore_na
self.new_wt = 1.0 if adjust else alpha
self.old_wt_factor = 1.0 - alpha
self.old_wt = np.ones(self.shape[self.axis - 1])
self.last_ewm = None
def run_ewm(self, weighted_avg, deltas, min_periods, ewm_func):
result, old_wt = ewm_func(
weighted_avg,
deltas,
min_periods,
self.old_wt_factor,
self.new_wt,
self.old_wt,
self.adjust,
self.ignore_na,
)
self.old_wt = old_wt
self.last_ewm = result[-1]
return result
def reset(self):
self.old_wt = np.ones(self.shape[self.axis - 1])
self.last_ewm = None
| old_wt[j] += new_wt | conditional_block |
online.py | from typing import (
Dict,
Optional,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
get_jit_arguments,
)
def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]):
"""
Generate a numba jitted groupby ewma function specified by values
from engine_kwargs.
Parameters
----------
engine_kwargs : dict
dictionary of arguments to be passed into numba.jit
Returns
-------
Numba function
"""
nopython, nogil, parallel = get_jit_arguments(engine_kwargs)
cache_key = (lambda x: x, "online_ewma")
if cache_key in NUMBA_FUNC_CACHE:
return NUMBA_FUNC_CACHE[cache_key]
numba = import_optional_dependency("numba")
@numba.jit(nopython=nopython, nogil=nogil, parallel=parallel)
def online_ewma( | old_wt_factor: float,
new_wt: float,
old_wt: np.ndarray,
adjust: bool,
ignore_na: bool,
):
"""
Compute online exponentially weighted mean per column over 2D values.
Takes the first observation as is, then computes the subsequent
exponentially weighted mean accounting minimum periods.
"""
result = np.empty(values.shape)
weighted_avg = values[0]
nobs = (~np.isnan(weighted_avg)).astype(np.int64)
result[0] = np.where(nobs >= minimum_periods, weighted_avg, np.nan)
for i in range(1, len(values)):
cur = values[i]
is_observations = ~np.isnan(cur)
nobs += is_observations.astype(np.int64)
for j in numba.prange(len(cur)):
if not np.isnan(weighted_avg[j]):
if is_observations[j] or not ignore_na:
# note that len(deltas) = len(vals) - 1 and deltas[i] is to be
# used in conjunction with vals[i+1]
old_wt[j] *= old_wt_factor ** deltas[j - 1]
if is_observations[j]:
# avoid numerical errors on constant series
if weighted_avg[j] != cur[j]:
weighted_avg[j] = (
(old_wt[j] * weighted_avg[j]) + (new_wt * cur[j])
) / (old_wt[j] + new_wt)
if adjust:
old_wt[j] += new_wt
else:
old_wt[j] = 1.0
elif is_observations[j]:
weighted_avg[j] = cur[j]
result[i] = np.where(nobs >= minimum_periods, weighted_avg, np.nan)
return result, old_wt
return online_ewma
class EWMMeanState:
def __init__(self, com, adjust, ignore_na, axis, shape):
alpha = 1.0 / (1.0 + com)
self.axis = axis
self.shape = shape
self.adjust = adjust
self.ignore_na = ignore_na
self.new_wt = 1.0 if adjust else alpha
self.old_wt_factor = 1.0 - alpha
self.old_wt = np.ones(self.shape[self.axis - 1])
self.last_ewm = None
def run_ewm(self, weighted_avg, deltas, min_periods, ewm_func):
result, old_wt = ewm_func(
weighted_avg,
deltas,
min_periods,
self.old_wt_factor,
self.new_wt,
self.old_wt,
self.adjust,
self.ignore_na,
)
self.old_wt = old_wt
self.last_ewm = result[-1]
return result
def reset(self):
self.old_wt = np.ones(self.shape[self.axis - 1])
self.last_ewm = None | values: np.ndarray,
deltas: np.ndarray,
minimum_periods: int, | random_line_split |
online.py | from typing import (
Dict,
Optional,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
get_jit_arguments,
)
def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]):
"""
Generate a numba jitted groupby ewma function specified by values
from engine_kwargs.
Parameters
----------
engine_kwargs : dict
dictionary of arguments to be passed into numba.jit
Returns
-------
Numba function
"""
nopython, nogil, parallel = get_jit_arguments(engine_kwargs)
cache_key = (lambda x: x, "online_ewma")
if cache_key in NUMBA_FUNC_CACHE:
return NUMBA_FUNC_CACHE[cache_key]
numba = import_optional_dependency("numba")
@numba.jit(nopython=nopython, nogil=nogil, parallel=parallel)
def online_ewma(
values: np.ndarray,
deltas: np.ndarray,
minimum_periods: int,
old_wt_factor: float,
new_wt: float,
old_wt: np.ndarray,
adjust: bool,
ignore_na: bool,
):
"""
Compute online exponentially weighted mean per column over 2D values.
Takes the first observation as is, then computes the subsequent
exponentially weighted mean accounting minimum periods.
"""
result = np.empty(values.shape)
weighted_avg = values[0]
nobs = (~np.isnan(weighted_avg)).astype(np.int64)
result[0] = np.where(nobs >= minimum_periods, weighted_avg, np.nan)
for i in range(1, len(values)):
cur = values[i]
is_observations = ~np.isnan(cur)
nobs += is_observations.astype(np.int64)
for j in numba.prange(len(cur)):
if not np.isnan(weighted_avg[j]):
if is_observations[j] or not ignore_na:
# note that len(deltas) = len(vals) - 1 and deltas[i] is to be
# used in conjunction with vals[i+1]
old_wt[j] *= old_wt_factor ** deltas[j - 1]
if is_observations[j]:
# avoid numerical errors on constant series
if weighted_avg[j] != cur[j]:
weighted_avg[j] = (
(old_wt[j] * weighted_avg[j]) + (new_wt * cur[j])
) / (old_wt[j] + new_wt)
if adjust:
old_wt[j] += new_wt
else:
old_wt[j] = 1.0
elif is_observations[j]:
weighted_avg[j] = cur[j]
result[i] = np.where(nobs >= minimum_periods, weighted_avg, np.nan)
return result, old_wt
return online_ewma
class EWMMeanState:
def | (self, com, adjust, ignore_na, axis, shape):
alpha = 1.0 / (1.0 + com)
self.axis = axis
self.shape = shape
self.adjust = adjust
self.ignore_na = ignore_na
self.new_wt = 1.0 if adjust else alpha
self.old_wt_factor = 1.0 - alpha
self.old_wt = np.ones(self.shape[self.axis - 1])
self.last_ewm = None
def run_ewm(self, weighted_avg, deltas, min_periods, ewm_func):
result, old_wt = ewm_func(
weighted_avg,
deltas,
min_periods,
self.old_wt_factor,
self.new_wt,
self.old_wt,
self.adjust,
self.ignore_na,
)
self.old_wt = old_wt
self.last_ewm = result[-1]
return result
def reset(self):
self.old_wt = np.ones(self.shape[self.axis - 1])
self.last_ewm = None
| __init__ | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
from collections import OrderedDict
from typing import Dict, Type
from .base import DataCatalogTransport |
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[DataCatalogTransport]]
_transport_registry["grpc"] = DataCatalogGrpcTransport
_transport_registry["grpc_asyncio"] = DataCatalogGrpcAsyncIOTransport
__all__ = (
"DataCatalogTransport",
"DataCatalogGrpcTransport",
"DataCatalogGrpcAsyncIOTransport",
) | from .grpc import DataCatalogGrpcTransport
from .grpc_asyncio import DataCatalogGrpcAsyncIOTransport | random_line_split |
authcodes.js | module.exports = function(app) {
var _env = app.get('env');
var _log = app.lib.logger;
var _mongoose = app.core.mongo.mongoose;
var _group = 'MODEL:oauth.authcodes';
var Schema = {
authCode : {type: String, required: true, unique: true, alias: 'authCode'},
clientId : {type: String, alias: 'clientId'},
userId : {type: String, required: true, alias: 'userId'},
expires : {type: Date, alias: 'expires'}
};
var AuthCodesSchema = app.core.mongo.db.Schema(Schema); | });
AuthCodesSchema.method('saveAuthCode', function(code, clientId, expires, userId, cb) {
var AuthCodes = _mongoose.model('Oauth_AuthCodes');
if (userId.id)
userId = userId.id;
var fields = {
clientId : clientId,
userId : userId,
expires : expires
};
AuthCodes.update({authCode: code}, fields, {upsert: true}, function(err) {
if (err)
_log.error(_group, err);
cb(err);
});
});
return _mongoose.model('Oauth_AuthCodes', AuthCodesSchema);
}; |
// statics
AuthCodesSchema.method('getAuthCode', function(authCode, cb) {
var AuthCodes = _mongoose.model('Oauth_AuthCodes');
AuthCodes.findOne({authCode: authCode}, cb); | random_line_split |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> { | fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
height: Some(15),
left: Some(15),
right: Some(15),
valign: Align::Center,
..Default::default()
}),
);
}
}
}
fn main() {
let mut term = Terminal::new();
let mut scene = Scene::empty();
scene.add(App::new());
term.set_scene(scene);
while term.running() {
term.poll();
term.draw();
thread::sleep(Duration::from_millis(1000 / 30));
}
} | Some(&self.layout)
}
| random_line_split |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn | () -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> {
Some(&self.layout)
}
fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
height: Some(15),
left: Some(15),
right: Some(15),
valign: Align::Center,
..Default::default()
}),
);
}
}
}
fn main() {
let mut term = Terminal::new();
let mut scene = Scene::empty();
scene.add(App::new());
term.set_scene(scene);
while term.running() {
term.poll();
term.draw();
thread::sleep(Duration::from_millis(1000 / 30));
}
}
| new | identifier_name |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> {
Some(&self.layout)
}
fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() |
}
}
fn main() {
let mut term = Terminal::new();
let mut scene = Scene::empty();
scene.add(App::new());
term.set_scene(scene);
while term.running() {
term.poll();
term.draw();
thread::sleep(Duration::from_millis(1000 / 30));
}
}
| {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
height: Some(15),
left: Some(15),
right: Some(15),
valign: Align::Center,
..Default::default()
}),
);
} | conditional_block |
hello.rs | extern crate log;
extern crate tuitui;
use tuitui::widgets::Panel;
use tuitui::{Align, Layout, NodeId, Scene, Terminal, Widget, WidgetAdded};
use std::any::Any;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
struct App {
id: NodeId,
layout: Layout,
}
impl App {
fn new() -> App {
App {
id: 0,
layout: Layout::fill(),
}
}
}
impl Widget for App {
fn layout(&self) -> Option<&Layout> {
Some(&self.layout)
}
fn layout_mut(&mut self) -> Option<&mut Layout> {
Some(&mut self.layout)
}
fn reduce(&mut self, id: NodeId, action: &Box<Any>, scene: &mut Scene) |
}
fn main() {
let mut term = Terminal::new();
let mut scene = Scene::empty();
scene.add(App::new());
term.set_scene(scene);
while term.running() {
term.poll();
term.draw();
thread::sleep(Duration::from_millis(1000 / 30));
}
}
| {
if let Some(payload) = action.downcast_ref::<WidgetAdded>() {
if payload.0 != id {
return;
}
scene.add_child(
id,
Panel::new(Layout {
left: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
right: Some(0),
top: Some(0),
bottom: Some(0),
width: Some(30),
..Default::default()
}),
);
scene.add_child(
id,
Panel::new(Layout {
height: Some(15),
left: Some(15),
right: Some(15),
valign: Align::Center,
..Default::default()
}),
);
}
} | identifier_body |
__init__.py | NAME = 'django-adminactions'
VERSION = __version__ = (0, 4, 0, 'final', 0)
__author__ = 'sax'
import subprocess
import datetime
import os
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
git_changeset = get_git_changeset()
if git_changeset:
sub = '.a%s' % git_changeset
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return main + sub
def get_git_changeset():
| """Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S') | identifier_body | |
__init__.py | NAME = 'django-adminactions'
VERSION = __version__ = (0, 4, 0, 'final', 0)
__author__ = 'sax'
import subprocess
import datetime
import os
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
git_changeset = get_git_changeset()
if git_changeset:
sub = '.a%s' % git_changeset
elif version[3] != 'final':
|
return main + sub
def get_git_changeset():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S')
| mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4]) | conditional_block |
__init__.py | NAME = 'django-adminactions'
VERSION = __version__ = (0, 4, 0, 'final', 0)
__author__ = 'sax'
import subprocess
import datetime
import os
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
git_changeset = get_git_changeset()
if git_changeset:
sub = '.a%s' % git_changeset
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return main + sub
def | ():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S')
| get_git_changeset | identifier_name |
__init__.py | NAME = 'django-adminactions'
VERSION = __version__ = (0, 4, 0, 'final', 0)
__author__ = 'sax'
import subprocess
import datetime
import os
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
git_changeset = get_git_changeset()
if git_changeset:
sub = '.a%s' % git_changeset
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
| """Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S') | return main + sub
def get_git_changeset(): | random_line_split |
test.js | if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
nitpick.perform("Text Entity topMargin", Script.resolvePath("."), "secondary", undefined, function(testType) {
Script.include(nitpick.getUtilsRootPath() + "test_stage.js");
var LIFETIME = 200;
// Add the test Cases
var initData = {
flags: {
hasKeyLight: true,
hasAmbientLight: true
},
lifetime: LIFETIME,
originFrame: nitpick.getOriginFrame()
};
var createdEntities = setupStage(initData);
var posOri = getStagePosOriAt(0, 0, 0);
function getPos(col, row) {
var center = posOri.pos;
return Vec3.sum(Vec3.sum(center, Vec3.multiply(Quat.getRight(MyAvatar.orientation), col)),
Vec3.multiply(Quat.getUp(MyAvatar.orientation), row));
}
createdEntities.push(Entities.addEntity({
type: "Text",
position: getPos(-0.5, 1),
dimensions: 1.0,
text: "test",
lineHeight: 0.3,
topMargin: 0.0,
lifetime: LIFETIME
}));
createdEntities.push(Entities.addEntity({
type: "Text",
position: getPos(0.5, 1),
dimensions: 1.0,
text: "test",
lineHeight: 0.3,
topMargin: 0.2,
lifetime: LIFETIME
}));
nitpick.addStepSnapshot("Take snapshot");
nitpick.addStep("Clean up after test", function () {
for (var i = 0; i < createdEntities.length; i++) |
});
var result = nitpick.runTest(testType);
}); | {
Entities.deleteEntity(createdEntities[i]);
} | conditional_block |
test.js | if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
|
// Add the test Cases
var initData = {
flags: {
hasKeyLight: true,
hasAmbientLight: true
},
lifetime: LIFETIME,
originFrame: nitpick.getOriginFrame()
};
var createdEntities = setupStage(initData);
var posOri = getStagePosOriAt(0, 0, 0);
function getPos(col, row) {
var center = posOri.pos;
return Vec3.sum(Vec3.sum(center, Vec3.multiply(Quat.getRight(MyAvatar.orientation), col)),
Vec3.multiply(Quat.getUp(MyAvatar.orientation), row));
}
createdEntities.push(Entities.addEntity({
type: "Text",
position: getPos(-0.5, 1),
dimensions: 1.0,
text: "test",
lineHeight: 0.3,
topMargin: 0.0,
lifetime: LIFETIME
}));
createdEntities.push(Entities.addEntity({
type: "Text",
position: getPos(0.5, 1),
dimensions: 1.0,
text: "test",
lineHeight: 0.3,
topMargin: 0.2,
lifetime: LIFETIME
}));
nitpick.addStepSnapshot("Take snapshot");
nitpick.addStep("Clean up after test", function () {
for (var i = 0; i < createdEntities.length; i++) {
Entities.deleteEntity(createdEntities[i]);
}
});
var result = nitpick.runTest(testType);
}); | nitpick.perform("Text Entity topMargin", Script.resolvePath("."), "secondary", undefined, function(testType) {
Script.include(nitpick.getUtilsRootPath() + "test_stage.js");
var LIFETIME = 200;
| random_line_split |
test.js | if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
nitpick.perform("Text Entity topMargin", Script.resolvePath("."), "secondary", undefined, function(testType) {
Script.include(nitpick.getUtilsRootPath() + "test_stage.js");
var LIFETIME = 200;
// Add the test Cases
var initData = {
flags: {
hasKeyLight: true,
hasAmbientLight: true
},
lifetime: LIFETIME,
originFrame: nitpick.getOriginFrame()
};
var createdEntities = setupStage(initData);
var posOri = getStagePosOriAt(0, 0, 0);
function | (col, row) {
var center = posOri.pos;
return Vec3.sum(Vec3.sum(center, Vec3.multiply(Quat.getRight(MyAvatar.orientation), col)),
Vec3.multiply(Quat.getUp(MyAvatar.orientation), row));
}
createdEntities.push(Entities.addEntity({
type: "Text",
position: getPos(-0.5, 1),
dimensions: 1.0,
text: "test",
lineHeight: 0.3,
topMargin: 0.0,
lifetime: LIFETIME
}));
createdEntities.push(Entities.addEntity({
type: "Text",
position: getPos(0.5, 1),
dimensions: 1.0,
text: "test",
lineHeight: 0.3,
topMargin: 0.2,
lifetime: LIFETIME
}));
nitpick.addStepSnapshot("Take snapshot");
nitpick.addStep("Clean up after test", function () {
for (var i = 0; i < createdEntities.length; i++) {
Entities.deleteEntity(createdEntities[i]);
}
});
var result = nitpick.runTest(testType);
}); | getPos | identifier_name |
test.js | if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
nitpick.perform("Text Entity topMargin", Script.resolvePath("."), "secondary", undefined, function(testType) {
Script.include(nitpick.getUtilsRootPath() + "test_stage.js");
var LIFETIME = 200;
// Add the test Cases
var initData = {
flags: {
hasKeyLight: true,
hasAmbientLight: true
},
lifetime: LIFETIME,
originFrame: nitpick.getOriginFrame()
};
var createdEntities = setupStage(initData);
var posOri = getStagePosOriAt(0, 0, 0);
function getPos(col, row) |
createdEntities.push(Entities.addEntity({
type: "Text",
position: getPos(-0.5, 1),
dimensions: 1.0,
text: "test",
lineHeight: 0.3,
topMargin: 0.0,
lifetime: LIFETIME
}));
createdEntities.push(Entities.addEntity({
type: "Text",
position: getPos(0.5, 1),
dimensions: 1.0,
text: "test",
lineHeight: 0.3,
topMargin: 0.2,
lifetime: LIFETIME
}));
nitpick.addStepSnapshot("Take snapshot");
nitpick.addStep("Clean up after test", function () {
for (var i = 0; i < createdEntities.length; i++) {
Entities.deleteEntity(createdEntities[i]);
}
});
var result = nitpick.runTest(testType);
}); | {
var center = posOri.pos;
return Vec3.sum(Vec3.sum(center, Vec3.multiply(Quat.getRight(MyAvatar.orientation), col)),
Vec3.multiply(Quat.getUp(MyAvatar.orientation), row));
} | identifier_body |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window-System-Interaction.html
mod ffi {
use gdk_sys::{GdkDisplay, GdkWindow};
use x11::xlib::{Display, Window};
extern "C" {
pub fn gdk_x11_get_default_xdisplay() -> *mut Display;
pub fn gdk_x11_get_default_root_xwindow() -> Window;
pub fn gdk_x11_window_foreign_new_for_display(
display: *mut GdkDisplay,
window: Window,
) -> *mut GdkWindow;
}
}
/// Gets the default GTK+ display.
///
/// # Returns
///
/// the Xlib Display* for the display specified in the `--display`
/// command line option or the `DISPLAY` environment variable.
pub fn gdk_x11_get_default_xdisplay() -> *mut Display {
unsafe {
return ffi::gdk_x11_get_default_xdisplay();
}
}
/// Gets the root window of the default screen (see `gdk_x11_get_default_screen()`).
///
/// # Returns
///
/// an Xlib Window.
pub fn gdk_x11_get_default_root_xwindow() -> Window |
/// Wraps a native window in a GdkWindow. The function will try to look up the
/// window using `gdk_x11_window_lookup_for_display()` first. If it does not find
/// it there, it will create a new window.
///
/// This may fail if the window has been destroyed. If the window was already
/// known to GDK, a new reference to the existing GdkWindow is returned.
/// ## `display`
/// the GdkDisplay where the window handle comes from.
/// ## ` window`
/// an Xlib Window
///
/// # Returns
///
/// a GdkWindow wrapper for the native window, or `None` if the window has been
/// destroyed. The wrapper will be newly created, if one doesn’t exist already.
pub fn gdk_x11_window_foreign_new_for_display(
gdk_display: &mut gdk::Display,
xwindow: Window,
) -> Option<gdk::Window> {
unsafe {
let display: *mut GdkDisplay =
mut_override(gdk_display.to_glib_none().0);
return from_glib_full(ffi::gdk_x11_window_foreign_new_for_display(
display,
xwindow,
));
}
}
| {
unsafe {
return ffi::gdk_x11_get_default_root_xwindow();
}
} | identifier_body |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window-System-Interaction.html
mod ffi {
use gdk_sys::{GdkDisplay, GdkWindow};
use x11::xlib::{Display, Window};
extern "C" {
pub fn gdk_x11_get_default_xdisplay() -> *mut Display;
pub fn gdk_x11_get_default_root_xwindow() -> Window;
pub fn gdk_x11_window_foreign_new_for_display(
display: *mut GdkDisplay,
window: Window,
) -> *mut GdkWindow;
}
}
/// Gets the default GTK+ display.
///
/// # Returns
///
/// the Xlib Display* for the display specified in the `--display`
/// command line option or the `DISPLAY` environment variable.
pub fn gdk_x11_get_default_xdisplay() -> *mut Display {
unsafe {
return ffi::gdk_x11_get_default_xdisplay();
}
}
/// Gets the root window of the default screen (see `gdk_x11_get_default_screen()`).
///
/// # Returns
///
/// an Xlib Window.
pub fn gdk_x11_get_default_root_xwindow() -> Window {
unsafe {
return ffi::gdk_x11_get_default_root_xwindow();
}
}
/// Wraps a native window in a GdkWindow. The function will try to look up the
/// window using `gdk_x11_window_lookup_for_display()` first. If it does not find
/// it there, it will create a new window.
///
/// This may fail if the window has been destroyed. If the window was already
/// known to GDK, a new reference to the existing GdkWindow is returned.
/// ## `display`
/// the GdkDisplay where the window handle comes from.
/// ## ` window`
/// an Xlib Window
///
/// # Returns
///
/// a GdkWindow wrapper for the native window, or `None` if the window has been
/// destroyed. The wrapper will be newly created, if one doesn’t exist already.
pub fn gd | gdk_display: &mut gdk::Display,
xwindow: Window,
) -> Option<gdk::Window> {
unsafe {
let display: *mut GdkDisplay =
mut_override(gdk_display.to_glib_none().0);
return from_glib_full(ffi::gdk_x11_window_foreign_new_for_display(
display,
xwindow,
));
}
}
| k_x11_window_foreign_new_for_display(
| identifier_name |
gdk_x11.rs | //! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window-System-Interaction.html
mod ffi {
use gdk_sys::{GdkDisplay, GdkWindow};
use x11::xlib::{Display, Window};
extern "C" {
pub fn gdk_x11_get_default_xdisplay() -> *mut Display;
pub fn gdk_x11_get_default_root_xwindow() -> Window;
pub fn gdk_x11_window_foreign_new_for_display(
display: *mut GdkDisplay,
window: Window,
) -> *mut GdkWindow;
}
} |
/// Gets the default GTK+ display.
///
/// # Returns
///
/// the Xlib Display* for the display specified in the `--display`
/// command line option or the `DISPLAY` environment variable.
pub fn gdk_x11_get_default_xdisplay() -> *mut Display {
unsafe {
return ffi::gdk_x11_get_default_xdisplay();
}
}
/// Gets the root window of the default screen (see `gdk_x11_get_default_screen()`).
///
/// # Returns
///
/// an Xlib Window.
pub fn gdk_x11_get_default_root_xwindow() -> Window {
unsafe {
return ffi::gdk_x11_get_default_root_xwindow();
}
}
/// Wraps a native window in a GdkWindow. The function will try to look up the
/// window using `gdk_x11_window_lookup_for_display()` first. If it does not find
/// it there, it will create a new window.
///
/// This may fail if the window has been destroyed. If the window was already
/// known to GDK, a new reference to the existing GdkWindow is returned.
/// ## `display`
/// the GdkDisplay where the window handle comes from.
/// ## ` window`
/// an Xlib Window
///
/// # Returns
///
/// a GdkWindow wrapper for the native window, or `None` if the window has been
/// destroyed. The wrapper will be newly created, if one doesn’t exist already.
pub fn gdk_x11_window_foreign_new_for_display(
gdk_display: &mut gdk::Display,
xwindow: Window,
) -> Option<gdk::Window> {
unsafe {
let display: *mut GdkDisplay =
mut_override(gdk_display.to_glib_none().0);
return from_glib_full(ffi::gdk_x11_window_foreign_new_for_display(
display,
xwindow,
));
}
} | random_line_split | |
access.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// An exclusive access primitive
///
/// This primitive is used to gain exclusive access to read() and write() in uv.
/// It is assumed that all invocations of this struct happen on the same thread
/// (the uv event loop).
use std::cell::UnsafeCell;
use std::mem;
use std::rt::local::Local;
use std::rt::task::{BlockedTask, Task};
use std::sync::Arc;
use homing::HomingMissile;
pub struct Access<T> {
inner: Arc<UnsafeCell<Inner<T>>>,
}
pub struct Guard<'a, T: 'a> {
access: &'a mut Access<T>,
missile: Option<HomingMissile>,
}
struct Inner<T> {
queue: Vec<(BlockedTask, uint)>,
held: bool,
closed: bool,
data: T,
}
impl<T: Send> Access<T> {
pub fn new(data: T) -> Access<T> {
Access {
inner: Arc::new(UnsafeCell::new(Inner {
queue: vec![],
held: false,
closed: false,
data: data,
}))
}
}
pub fn grant<'a>(&'a mut self, token: uint,
missile: HomingMissile) -> Guard<'a, T> {
// This unsafety is actually OK because the homing missile argument
// guarantees that we're on the same event loop as all the other objects
// attempting to get access granted.
let inner = unsafe { &mut *self.inner.get() };
if inner.held {
let t: Box<Task> = Local::take();
t.deschedule(1, |task| {
inner.queue.push((task, token));
Ok(())
});
assert!(inner.held);
} else {
inner.held = true;
}
Guard { access: self, missile: Some(missile) }
}
pub fn unsafe_get(&self) -> *mut T {
unsafe { &mut (*self.inner.get()).data as *mut _ }
}
// Safe version which requires proof that you are on the home scheduler.
pub fn get_mut<'a>(&'a mut self, _missile: &HomingMissile) -> &'a mut T {
unsafe { &mut *self.unsafe_get() }
}
pub fn close(&self, _missile: &HomingMissile) {
// This unsafety is OK because with a homing missile we're guaranteed to
// be the only task looking at the `closed` flag (and are therefore
// allowed to modify it). Additionally, no atomics are necessary because
// everyone's running on the same thread and has already done the
// necessary synchronization to be running on this thread.
unsafe { (*self.inner.get()).closed = true; }
}
// Dequeue a blocked task with a specified token. This is unsafe because it
// is only safe to invoke while on the home event loop, and there is no
// guarantee that this i being invoked on the home event loop.
pub unsafe fn dequeue(&mut self, token: uint) -> Option<BlockedTask> {
let inner = &mut *self.inner.get();
match inner.queue.iter().position(|&(_, t)| t == token) {
Some(i) => Some(inner.queue.remove(i).unwrap().val0()),
None => None,
}
}
/// Test whether this access is closed, using a homing missile to prove
/// that it's safe
pub fn is_closed(&self, _missile: &HomingMissile) -> bool {
unsafe { (*self.inner.get()).closed }
}
}
impl<T: Send> Clone for Access<T> {
fn clone(&self) -> Access<T> {
Access { inner: self.inner.clone() }
}
}
impl<'a, T: Send> Guard<'a, T> {
pub fn | (&self) -> bool {
// See above for why this unsafety is ok, it just applies to the read
// instead of the write.
unsafe { (*self.access.inner.get()).closed }
}
}
impl<'a, T: Send> Deref<T> for Guard<'a, T> {
fn deref<'a>(&'a self) -> &'a T {
// A guard represents exclusive access to a piece of data, so it's safe
// to hand out shared and mutable references
unsafe { &(*self.access.inner.get()).data }
}
}
impl<'a, T: Send> DerefMut<T> for Guard<'a, T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut (*self.access.inner.get()).data }
}
}
#[unsafe_destructor]
impl<'a, T: Send> Drop for Guard<'a, T> {
fn drop(&mut self) {
// This guard's homing missile is still armed, so we're guaranteed to be
// on the same I/O event loop, so this unsafety should be ok.
assert!(self.missile.is_some());
let inner: &mut Inner<T> = unsafe {
mem::transmute(self.access.inner.get())
};
match inner.queue.remove(0) {
// Here we have found a task that was waiting for access, and we
// current have the "access lock" we need to relinquish access to
// this sleeping task.
//
// To do so, we first drop out homing missile and we then reawaken
// the task. In reawakening the task, it will be immediately
// scheduled on this scheduler. Because we might be woken up on some
// other scheduler, we drop our homing missile before we reawaken
// the task.
Some((task, _)) => {
drop(self.missile.take());
task.reawaken();
}
None => { inner.held = false; }
}
}
}
#[unsafe_destructor]
impl<T> Drop for Inner<T> {
fn drop(&mut self) {
assert!(!self.held);
assert_eq!(self.queue.len(), 0);
}
}
| is_closed | identifier_name |
access.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// An exclusive access primitive
///
/// This primitive is used to gain exclusive access to read() and write() in uv.
/// It is assumed that all invocations of this struct happen on the same thread | use std::cell::UnsafeCell;
use std::mem;
use std::rt::local::Local;
use std::rt::task::{BlockedTask, Task};
use std::sync::Arc;
use homing::HomingMissile;
pub struct Access<T> {
inner: Arc<UnsafeCell<Inner<T>>>,
}
pub struct Guard<'a, T: 'a> {
access: &'a mut Access<T>,
missile: Option<HomingMissile>,
}
struct Inner<T> {
queue: Vec<(BlockedTask, uint)>,
held: bool,
closed: bool,
data: T,
}
impl<T: Send> Access<T> {
pub fn new(data: T) -> Access<T> {
Access {
inner: Arc::new(UnsafeCell::new(Inner {
queue: vec![],
held: false,
closed: false,
data: data,
}))
}
}
pub fn grant<'a>(&'a mut self, token: uint,
missile: HomingMissile) -> Guard<'a, T> {
// This unsafety is actually OK because the homing missile argument
// guarantees that we're on the same event loop as all the other objects
// attempting to get access granted.
let inner = unsafe { &mut *self.inner.get() };
if inner.held {
let t: Box<Task> = Local::take();
t.deschedule(1, |task| {
inner.queue.push((task, token));
Ok(())
});
assert!(inner.held);
} else {
inner.held = true;
}
Guard { access: self, missile: Some(missile) }
}
pub fn unsafe_get(&self) -> *mut T {
unsafe { &mut (*self.inner.get()).data as *mut _ }
}
// Safe version which requires proof that you are on the home scheduler.
pub fn get_mut<'a>(&'a mut self, _missile: &HomingMissile) -> &'a mut T {
unsafe { &mut *self.unsafe_get() }
}
pub fn close(&self, _missile: &HomingMissile) {
// This unsafety is OK because with a homing missile we're guaranteed to
// be the only task looking at the `closed` flag (and are therefore
// allowed to modify it). Additionally, no atomics are necessary because
// everyone's running on the same thread and has already done the
// necessary synchronization to be running on this thread.
unsafe { (*self.inner.get()).closed = true; }
}
// Dequeue a blocked task with a specified token. This is unsafe because it
// is only safe to invoke while on the home event loop, and there is no
// guarantee that this i being invoked on the home event loop.
pub unsafe fn dequeue(&mut self, token: uint) -> Option<BlockedTask> {
let inner = &mut *self.inner.get();
match inner.queue.iter().position(|&(_, t)| t == token) {
Some(i) => Some(inner.queue.remove(i).unwrap().val0()),
None => None,
}
}
/// Test whether this access is closed, using a homing missile to prove
/// that it's safe
pub fn is_closed(&self, _missile: &HomingMissile) -> bool {
unsafe { (*self.inner.get()).closed }
}
}
impl<T: Send> Clone for Access<T> {
fn clone(&self) -> Access<T> {
Access { inner: self.inner.clone() }
}
}
impl<'a, T: Send> Guard<'a, T> {
pub fn is_closed(&self) -> bool {
// See above for why this unsafety is ok, it just applies to the read
// instead of the write.
unsafe { (*self.access.inner.get()).closed }
}
}
impl<'a, T: Send> Deref<T> for Guard<'a, T> {
fn deref<'a>(&'a self) -> &'a T {
// A guard represents exclusive access to a piece of data, so it's safe
// to hand out shared and mutable references
unsafe { &(*self.access.inner.get()).data }
}
}
impl<'a, T: Send> DerefMut<T> for Guard<'a, T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut (*self.access.inner.get()).data }
}
}
#[unsafe_destructor]
impl<'a, T: Send> Drop for Guard<'a, T> {
fn drop(&mut self) {
// This guard's homing missile is still armed, so we're guaranteed to be
// on the same I/O event loop, so this unsafety should be ok.
assert!(self.missile.is_some());
let inner: &mut Inner<T> = unsafe {
mem::transmute(self.access.inner.get())
};
match inner.queue.remove(0) {
// Here we have found a task that was waiting for access, and we
// current have the "access lock" we need to relinquish access to
// this sleeping task.
//
// To do so, we first drop out homing missile and we then reawaken
// the task. In reawakening the task, it will be immediately
// scheduled on this scheduler. Because we might be woken up on some
// other scheduler, we drop our homing missile before we reawaken
// the task.
Some((task, _)) => {
drop(self.missile.take());
task.reawaken();
}
None => { inner.held = false; }
}
}
}
#[unsafe_destructor]
impl<T> Drop for Inner<T> {
fn drop(&mut self) {
assert!(!self.held);
assert_eq!(self.queue.len(), 0);
}
} | /// (the uv event loop).
| random_line_split |
index.js | /**
@file Export all functions in yuv-video to user
@author Gilson Varghese<gilsonvarghese7@gmail.com>
@date 13 Oct, 2016
**/
/**
Module includes
*/
var frameReader = require(./lib/framereader);
var frameWriter = require(./lib/framewriter);
var frameConverter = require(./lib/frameconverter);
/**
Global variables
*/
var version = "1.0.0";
/**
Export all the functions to global namespace
*/
module.exports = {
/**
Test function to test the reader
*/
version: function() {
return version;
},
/**
Frame reader to read frame according to the given options
*/
frameReader: frameReader,
/**
Frame Writer to write frame according to the options
*/
frameWrite: frameWriter,
/**
Frame Converter to conver frame into various formats
Currently only YV21 and V210 are supported | */
frameConverter: frameConverter
}; | random_line_split | |
index.ts | import Module from 'ringcentral-integration/lib/di/decorators/module';
import RcUIModule from '../../lib/RcUIModule';
@Module({
name: 'ConnectivityBadgeUI',
deps: ['Locale', 'ConnectivityManager'],
})
export default class ConnectivityBadgeUI extends RcUIModule {
_locale: any;
_connectivityManager: any;
constructor({ locale, connectivityManager, ...options }) {
super({
...options,
});
this._locale = locale; | getUIProps() {
return {
currentLocale: this._locale.currentLocale,
mode:
(this._connectivityManager.ready && this._connectivityManager.mode) ||
null,
webphoneConnecting:
this._connectivityManager.ready &&
this._connectivityManager.webphoneConnecting,
hasLimitedStatusError:
this._connectivityManager.ready &&
this._connectivityManager.hasLimitedStatusError,
};
}
getUIFunctions() {
const connectivityManager = this._connectivityManager;
return {
onClick() {
if (connectivityManager.isWebphoneUnavailableMode) {
connectivityManager.checkWebphoneAndConnect();
} else if (connectivityManager.hasLimitedStatusError) {
connectivityManager.checkStatus();
} else {
connectivityManager.showConnectivityAlert();
}
},
showBadgeAlert() {
connectivityManager.showConnectivityAlert();
},
};
}
} | this._connectivityManager = connectivityManager;
}
| random_line_split |
index.ts | import Module from 'ringcentral-integration/lib/di/decorators/module';
import RcUIModule from '../../lib/RcUIModule';
@Module({
name: 'ConnectivityBadgeUI',
deps: ['Locale', 'ConnectivityManager'],
})
export default class ConnectivityBadgeUI extends RcUIModule {
_locale: any;
_connectivityManager: any;
constructor({ locale, connectivityManager, ...options }) {
super({
...options,
});
this._locale = locale;
this._connectivityManager = connectivityManager;
}
getUIProps() {
return {
currentLocale: this._locale.currentLocale,
mode:
(this._connectivityManager.ready && this._connectivityManager.mode) ||
null,
webphoneConnecting:
this._connectivityManager.ready &&
this._connectivityManager.webphoneConnecting,
hasLimitedStatusError:
this._connectivityManager.ready &&
this._connectivityManager.hasLimitedStatusError,
};
}
getUIFunctions() {
const connectivityManager = this._connectivityManager;
return {
| () {
if (connectivityManager.isWebphoneUnavailableMode) {
connectivityManager.checkWebphoneAndConnect();
} else if (connectivityManager.hasLimitedStatusError) {
connectivityManager.checkStatus();
} else {
connectivityManager.showConnectivityAlert();
}
},
showBadgeAlert() {
connectivityManager.showConnectivityAlert();
},
};
}
}
| onClick | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.