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 |
|---|---|---|---|---|
portal-directives.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
ComponentFactoryResolver,
ComponentRef,
Directive,
EmbeddedViewRef,
EventEmitter,
NgModule,
OnDestroy,
OnInit,
Output,
TemplateRef,
ViewContainerRef,
Inject,
} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {BasePortalOutlet, ComponentPortal, Portal, TemplatePortal, DomPortal} from './portal';
/**
* Directive version of a `TemplatePortal`. Because the directive *is* a TemplatePortal,
* the directive instance itself can be attached to a host, enabling declarative use of portals.
*/
@Directive({
selector: '[cdkPortal]',
exportAs: 'cdkPortal',
})
export class CdkPortal extends TemplatePortal {
constructor(templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef) {
super(templateRef, viewContainerRef);
}
}
/**
* @deprecated Use `CdkPortal` instead.
* @breaking-change 9.0.0
*/
@Directive({
selector: '[cdk-portal], [portal]',
exportAs: 'cdkPortal',
providers: [{
provide: CdkPortal,
useExisting: TemplatePortalDirective
}]
})
export class TemplatePortalDirective extends CdkPortal {}
/**
* Possible attached references to the CdkPortalOutlet.
*/
export type CdkPortalOutletAttachedRef = ComponentRef<any> | EmbeddedViewRef<any> | null;
/**
* Directive version of a PortalOutlet. Because the directive *is* a PortalOutlet, portals can be
* directly attached to it, enabling declarative use.
*
* Usage:
* `<ng-template [cdkPortalOutlet]="greeting"></ng-template>`
*/
@Directive({
selector: '[cdkPortalOutlet]',
exportAs: 'cdkPortalOutlet',
inputs: ['portal: cdkPortalOutlet']
})
export class CdkPortalOutlet extends BasePortalOutlet implements OnInit, OnDestroy {
private _document: Document;
/** Whether the portal component is initialized. */
private _isInitialized = false;
/** Reference to the currently-attached component/view ref. */
private _attachedRef: CdkPortalOutletAttachedRef;
constructor(
private _componentFactoryResolver: ComponentFactoryResolver,
private _viewContainerRef: ViewContainerRef,
/**
* @deprecated `_document` parameter to be made required.
* @breaking-change 9.0.0
*/
@Inject(DOCUMENT) _document?: any) {
super();
this._document = _document;
}
/** Portal associated with the Portal outlet. */
get portal(): Portal<any> | null {
return this._attachedPortal;
}
set portal(portal: Portal<any> | null) {
// Ignore the cases where the `portal` is set to a falsy value before the lifecycle hooks have
// run. This handles the cases where the user might do something like `<div cdkPortalOutlet>`
// and attach a portal programmatically in the parent component. When Angular does the first CD
// round, it will fire the setter with empty string, causing the user's content to be cleared.
if (this.hasAttached() && !portal && !this._isInitialized) {
return;
}
if (this.hasAttached()) {
super.detach();
}
if (portal) {
super.attach(portal);
}
this._attachedPortal = portal;
}
/** Emits when a portal is attached to the outlet. */
@Output() attached: EventEmitter<CdkPortalOutletAttachedRef> =
new EventEmitter<CdkPortalOutletAttachedRef>();
/** Component or view reference that is attached to the portal. */
get attachedRef(): CdkPortalOutletAttachedRef |
ngOnInit() {
this._isInitialized = true;
}
ngOnDestroy() {
super.dispose();
this._attachedPortal = null;
this._attachedRef = null;
}
/**
* Attach the given ComponentPortal to this PortalOutlet using the ComponentFactoryResolver.
*
* @param portal Portal to be attached to the portal outlet.
* @returns Reference to the created component.
*/
attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
portal.setAttachedHost(this);
// If the portal specifies an origin, use that as the logical location of the component
// in the application tree. Otherwise use the location of this PortalOutlet.
const viewContainerRef = portal.viewContainerRef != null ?
portal.viewContainerRef :
this._viewContainerRef;
const resolver = portal.componentFactoryResolver || this._componentFactoryResolver;
const componentFactory = resolver.resolveComponentFactory(portal.component);
const ref = viewContainerRef.createComponent(
componentFactory, viewContainerRef.length,
portal.injector || viewContainerRef.injector);
// If we're using a view container that's different from the injected one (e.g. when the portal
// specifies its own) we need to move the component into the outlet, otherwise it'll be rendered
// inside of the alternate view container.
if (viewContainerRef !== this._viewContainerRef) {
this._getRootNode().appendChild((ref.hostView as EmbeddedViewRef<any>).rootNodes[0]);
}
super.setDisposeFn(() => ref.destroy());
this._attachedPortal = portal;
this._attachedRef = ref;
this.attached.emit(ref);
return ref;
}
/**
* Attach the given TemplatePortal to this PortalHost as an embedded View.
* @param portal Portal to be attached.
* @returns Reference to the created embedded view.
*/
attachTemplatePortal<C>(portal: TemplatePortal<C>): EmbeddedViewRef<C> {
portal.setAttachedHost(this);
const viewRef = this._viewContainerRef.createEmbeddedView(portal.templateRef, portal.context);
super.setDisposeFn(() => this._viewContainerRef.clear());
this._attachedPortal = portal;
this._attachedRef = viewRef;
this.attached.emit(viewRef);
return viewRef;
}
/**
* Attaches the given DomPortal to this PortalHost by moving all of the portal content into it.
* @param portal Portal to be attached.
* @deprecated To be turned into a method.
* @breaking-change 10.0.0
*/
attachDomPortal = (portal: DomPortal) => {
// @breaking-change 9.0.0 Remove check and error once the
// `_document` constructor parameter is required.
if (!this._document && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('Cannot attach DOM portal without _document constructor parameter');
}
const element = portal.element;
if (!element.parentNode && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('DOM portal content must be attached to a parent node.');
}
// Anchor used to save the element's previous position so
// that we can restore it when the portal is detached.
const anchorNode = this._document.createComment('dom-portal');
portal.setAttachedHost(this);
element.parentNode!.insertBefore(anchorNode, element);
this._getRootNode().appendChild(element);
super.setDisposeFn(() => {
if (anchorNode.parentNode) {
anchorNode.parentNode!.replaceChild(element, anchorNode);
}
});
}
/** Gets the root node of the portal outlet. */
private _getRootNode(): HTMLElement {
const nativeElement: Node = this._viewContainerRef.element.nativeElement;
// The directive could be set on a template which will result in a comment
// node being the root. Use the comment's parent node if that is the case.
return (nativeElement.nodeType === nativeElement.ELEMENT_NODE ?
nativeElement : nativeElement.parentNode!) as HTMLElement;
}
static ngAcceptInputType_portal: Portal<any> | null | undefined | '';
}
/**
* @deprecated Use `CdkPortalOutlet` instead.
* @breaking-change 9.0.0
*/
@Directive({
selector: '[cdkPortalHost], [portalHost]',
exportAs: 'cdkPortalHost',
inputs: ['portal: cdkPortalHost'],
providers: [{
provide: CdkPortalOutlet,
useExisting: PortalHostDirective
}]
})
export class PortalHostDirective extends CdkPortalOutlet {}
@NgModule({
exports: [CdkPortal, CdkPortalOutlet, TemplatePortalDirective, PortalHostDirective],
declarations: [CdkPortal, CdkPortalOutlet, TemplatePortalDirective, PortalHostDirective],
})
export class PortalModule {}
| {
return this._attachedRef;
} | identifier_body |
portal-directives.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
ComponentFactoryResolver,
ComponentRef,
Directive,
EmbeddedViewRef,
EventEmitter,
NgModule,
OnDestroy,
OnInit,
Output,
TemplateRef,
ViewContainerRef,
Inject,
} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {BasePortalOutlet, ComponentPortal, Portal, TemplatePortal, DomPortal} from './portal';
/**
* Directive version of a `TemplatePortal`. Because the directive *is* a TemplatePortal, | */
@Directive({
selector: '[cdkPortal]',
exportAs: 'cdkPortal',
})
export class CdkPortal extends TemplatePortal {
constructor(templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef) {
super(templateRef, viewContainerRef);
}
}
/**
* @deprecated Use `CdkPortal` instead.
* @breaking-change 9.0.0
*/
@Directive({
selector: '[cdk-portal], [portal]',
exportAs: 'cdkPortal',
providers: [{
provide: CdkPortal,
useExisting: TemplatePortalDirective
}]
})
export class TemplatePortalDirective extends CdkPortal {}
/**
* Possible attached references to the CdkPortalOutlet.
*/
export type CdkPortalOutletAttachedRef = ComponentRef<any> | EmbeddedViewRef<any> | null;
/**
* Directive version of a PortalOutlet. Because the directive *is* a PortalOutlet, portals can be
* directly attached to it, enabling declarative use.
*
* Usage:
* `<ng-template [cdkPortalOutlet]="greeting"></ng-template>`
*/
@Directive({
selector: '[cdkPortalOutlet]',
exportAs: 'cdkPortalOutlet',
inputs: ['portal: cdkPortalOutlet']
})
export class CdkPortalOutlet extends BasePortalOutlet implements OnInit, OnDestroy {
private _document: Document;
/** Whether the portal component is initialized. */
private _isInitialized = false;
/** Reference to the currently-attached component/view ref. */
private _attachedRef: CdkPortalOutletAttachedRef;
constructor(
private _componentFactoryResolver: ComponentFactoryResolver,
private _viewContainerRef: ViewContainerRef,
/**
* @deprecated `_document` parameter to be made required.
* @breaking-change 9.0.0
*/
@Inject(DOCUMENT) _document?: any) {
super();
this._document = _document;
}
/** Portal associated with the Portal outlet. */
get portal(): Portal<any> | null {
return this._attachedPortal;
}
set portal(portal: Portal<any> | null) {
// Ignore the cases where the `portal` is set to a falsy value before the lifecycle hooks have
// run. This handles the cases where the user might do something like `<div cdkPortalOutlet>`
// and attach a portal programmatically in the parent component. When Angular does the first CD
// round, it will fire the setter with empty string, causing the user's content to be cleared.
if (this.hasAttached() && !portal && !this._isInitialized) {
return;
}
if (this.hasAttached()) {
super.detach();
}
if (portal) {
super.attach(portal);
}
this._attachedPortal = portal;
}
/** Emits when a portal is attached to the outlet. */
@Output() attached: EventEmitter<CdkPortalOutletAttachedRef> =
new EventEmitter<CdkPortalOutletAttachedRef>();
/** Component or view reference that is attached to the portal. */
get attachedRef(): CdkPortalOutletAttachedRef {
return this._attachedRef;
}
ngOnInit() {
this._isInitialized = true;
}
ngOnDestroy() {
super.dispose();
this._attachedPortal = null;
this._attachedRef = null;
}
/**
* Attach the given ComponentPortal to this PortalOutlet using the ComponentFactoryResolver.
*
* @param portal Portal to be attached to the portal outlet.
* @returns Reference to the created component.
*/
attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
portal.setAttachedHost(this);
// If the portal specifies an origin, use that as the logical location of the component
// in the application tree. Otherwise use the location of this PortalOutlet.
const viewContainerRef = portal.viewContainerRef != null ?
portal.viewContainerRef :
this._viewContainerRef;
const resolver = portal.componentFactoryResolver || this._componentFactoryResolver;
const componentFactory = resolver.resolveComponentFactory(portal.component);
const ref = viewContainerRef.createComponent(
componentFactory, viewContainerRef.length,
portal.injector || viewContainerRef.injector);
// If we're using a view container that's different from the injected one (e.g. when the portal
// specifies its own) we need to move the component into the outlet, otherwise it'll be rendered
// inside of the alternate view container.
if (viewContainerRef !== this._viewContainerRef) {
this._getRootNode().appendChild((ref.hostView as EmbeddedViewRef<any>).rootNodes[0]);
}
super.setDisposeFn(() => ref.destroy());
this._attachedPortal = portal;
this._attachedRef = ref;
this.attached.emit(ref);
return ref;
}
/**
* Attach the given TemplatePortal to this PortalHost as an embedded View.
* @param portal Portal to be attached.
* @returns Reference to the created embedded view.
*/
attachTemplatePortal<C>(portal: TemplatePortal<C>): EmbeddedViewRef<C> {
portal.setAttachedHost(this);
const viewRef = this._viewContainerRef.createEmbeddedView(portal.templateRef, portal.context);
super.setDisposeFn(() => this._viewContainerRef.clear());
this._attachedPortal = portal;
this._attachedRef = viewRef;
this.attached.emit(viewRef);
return viewRef;
}
/**
* Attaches the given DomPortal to this PortalHost by moving all of the portal content into it.
* @param portal Portal to be attached.
* @deprecated To be turned into a method.
* @breaking-change 10.0.0
*/
attachDomPortal = (portal: DomPortal) => {
// @breaking-change 9.0.0 Remove check and error once the
// `_document` constructor parameter is required.
if (!this._document && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('Cannot attach DOM portal without _document constructor parameter');
}
const element = portal.element;
if (!element.parentNode && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('DOM portal content must be attached to a parent node.');
}
// Anchor used to save the element's previous position so
// that we can restore it when the portal is detached.
const anchorNode = this._document.createComment('dom-portal');
portal.setAttachedHost(this);
element.parentNode!.insertBefore(anchorNode, element);
this._getRootNode().appendChild(element);
super.setDisposeFn(() => {
if (anchorNode.parentNode) {
anchorNode.parentNode!.replaceChild(element, anchorNode);
}
});
}
/** Gets the root node of the portal outlet. */
private _getRootNode(): HTMLElement {
const nativeElement: Node = this._viewContainerRef.element.nativeElement;
// The directive could be set on a template which will result in a comment
// node being the root. Use the comment's parent node if that is the case.
return (nativeElement.nodeType === nativeElement.ELEMENT_NODE ?
nativeElement : nativeElement.parentNode!) as HTMLElement;
}
static ngAcceptInputType_portal: Portal<any> | null | undefined | '';
}
/**
* @deprecated Use `CdkPortalOutlet` instead.
* @breaking-change 9.0.0
*/
@Directive({
selector: '[cdkPortalHost], [portalHost]',
exportAs: 'cdkPortalHost',
inputs: ['portal: cdkPortalHost'],
providers: [{
provide: CdkPortalOutlet,
useExisting: PortalHostDirective
}]
})
export class PortalHostDirective extends CdkPortalOutlet {}
@NgModule({
exports: [CdkPortal, CdkPortalOutlet, TemplatePortalDirective, PortalHostDirective],
declarations: [CdkPortal, CdkPortalOutlet, TemplatePortalDirective, PortalHostDirective],
})
export class PortalModule {} | * the directive instance itself can be attached to a host, enabling declarative use of portals. | random_line_split |
portal-directives.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
ComponentFactoryResolver,
ComponentRef,
Directive,
EmbeddedViewRef,
EventEmitter,
NgModule,
OnDestroy,
OnInit,
Output,
TemplateRef,
ViewContainerRef,
Inject,
} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {BasePortalOutlet, ComponentPortal, Portal, TemplatePortal, DomPortal} from './portal';
/**
* Directive version of a `TemplatePortal`. Because the directive *is* a TemplatePortal,
* the directive instance itself can be attached to a host, enabling declarative use of portals.
*/
@Directive({
selector: '[cdkPortal]',
exportAs: 'cdkPortal',
})
export class CdkPortal extends TemplatePortal {
constructor(templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef) {
super(templateRef, viewContainerRef);
}
}
/**
* @deprecated Use `CdkPortal` instead.
* @breaking-change 9.0.0
*/
@Directive({
selector: '[cdk-portal], [portal]',
exportAs: 'cdkPortal',
providers: [{
provide: CdkPortal,
useExisting: TemplatePortalDirective
}]
})
export class TemplatePortalDirective extends CdkPortal {}
/**
* Possible attached references to the CdkPortalOutlet.
*/
export type CdkPortalOutletAttachedRef = ComponentRef<any> | EmbeddedViewRef<any> | null;
/**
* Directive version of a PortalOutlet. Because the directive *is* a PortalOutlet, portals can be
* directly attached to it, enabling declarative use.
*
* Usage:
* `<ng-template [cdkPortalOutlet]="greeting"></ng-template>`
*/
@Directive({
selector: '[cdkPortalOutlet]',
exportAs: 'cdkPortalOutlet',
inputs: ['portal: cdkPortalOutlet']
})
export class | extends BasePortalOutlet implements OnInit, OnDestroy {
private _document: Document;
/** Whether the portal component is initialized. */
private _isInitialized = false;
/** Reference to the currently-attached component/view ref. */
private _attachedRef: CdkPortalOutletAttachedRef;
constructor(
private _componentFactoryResolver: ComponentFactoryResolver,
private _viewContainerRef: ViewContainerRef,
/**
* @deprecated `_document` parameter to be made required.
* @breaking-change 9.0.0
*/
@Inject(DOCUMENT) _document?: any) {
super();
this._document = _document;
}
/** Portal associated with the Portal outlet. */
get portal(): Portal<any> | null {
return this._attachedPortal;
}
set portal(portal: Portal<any> | null) {
// Ignore the cases where the `portal` is set to a falsy value before the lifecycle hooks have
// run. This handles the cases where the user might do something like `<div cdkPortalOutlet>`
// and attach a portal programmatically in the parent component. When Angular does the first CD
// round, it will fire the setter with empty string, causing the user's content to be cleared.
if (this.hasAttached() && !portal && !this._isInitialized) {
return;
}
if (this.hasAttached()) {
super.detach();
}
if (portal) {
super.attach(portal);
}
this._attachedPortal = portal;
}
/** Emits when a portal is attached to the outlet. */
@Output() attached: EventEmitter<CdkPortalOutletAttachedRef> =
new EventEmitter<CdkPortalOutletAttachedRef>();
/** Component or view reference that is attached to the portal. */
get attachedRef(): CdkPortalOutletAttachedRef {
return this._attachedRef;
}
ngOnInit() {
this._isInitialized = true;
}
ngOnDestroy() {
super.dispose();
this._attachedPortal = null;
this._attachedRef = null;
}
/**
* Attach the given ComponentPortal to this PortalOutlet using the ComponentFactoryResolver.
*
* @param portal Portal to be attached to the portal outlet.
* @returns Reference to the created component.
*/
attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
portal.setAttachedHost(this);
// If the portal specifies an origin, use that as the logical location of the component
// in the application tree. Otherwise use the location of this PortalOutlet.
const viewContainerRef = portal.viewContainerRef != null ?
portal.viewContainerRef :
this._viewContainerRef;
const resolver = portal.componentFactoryResolver || this._componentFactoryResolver;
const componentFactory = resolver.resolveComponentFactory(portal.component);
const ref = viewContainerRef.createComponent(
componentFactory, viewContainerRef.length,
portal.injector || viewContainerRef.injector);
// If we're using a view container that's different from the injected one (e.g. when the portal
// specifies its own) we need to move the component into the outlet, otherwise it'll be rendered
// inside of the alternate view container.
if (viewContainerRef !== this._viewContainerRef) {
this._getRootNode().appendChild((ref.hostView as EmbeddedViewRef<any>).rootNodes[0]);
}
super.setDisposeFn(() => ref.destroy());
this._attachedPortal = portal;
this._attachedRef = ref;
this.attached.emit(ref);
return ref;
}
/**
* Attach the given TemplatePortal to this PortalHost as an embedded View.
* @param portal Portal to be attached.
* @returns Reference to the created embedded view.
*/
attachTemplatePortal<C>(portal: TemplatePortal<C>): EmbeddedViewRef<C> {
portal.setAttachedHost(this);
const viewRef = this._viewContainerRef.createEmbeddedView(portal.templateRef, portal.context);
super.setDisposeFn(() => this._viewContainerRef.clear());
this._attachedPortal = portal;
this._attachedRef = viewRef;
this.attached.emit(viewRef);
return viewRef;
}
/**
* Attaches the given DomPortal to this PortalHost by moving all of the portal content into it.
* @param portal Portal to be attached.
* @deprecated To be turned into a method.
* @breaking-change 10.0.0
*/
attachDomPortal = (portal: DomPortal) => {
// @breaking-change 9.0.0 Remove check and error once the
// `_document` constructor parameter is required.
if (!this._document && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('Cannot attach DOM portal without _document constructor parameter');
}
const element = portal.element;
if (!element.parentNode && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('DOM portal content must be attached to a parent node.');
}
// Anchor used to save the element's previous position so
// that we can restore it when the portal is detached.
const anchorNode = this._document.createComment('dom-portal');
portal.setAttachedHost(this);
element.parentNode!.insertBefore(anchorNode, element);
this._getRootNode().appendChild(element);
super.setDisposeFn(() => {
if (anchorNode.parentNode) {
anchorNode.parentNode!.replaceChild(element, anchorNode);
}
});
}
/** Gets the root node of the portal outlet. */
private _getRootNode(): HTMLElement {
const nativeElement: Node = this._viewContainerRef.element.nativeElement;
// The directive could be set on a template which will result in a comment
// node being the root. Use the comment's parent node if that is the case.
return (nativeElement.nodeType === nativeElement.ELEMENT_NODE ?
nativeElement : nativeElement.parentNode!) as HTMLElement;
}
static ngAcceptInputType_portal: Portal<any> | null | undefined | '';
}
/**
* @deprecated Use `CdkPortalOutlet` instead.
* @breaking-change 9.0.0
*/
@Directive({
selector: '[cdkPortalHost], [portalHost]',
exportAs: 'cdkPortalHost',
inputs: ['portal: cdkPortalHost'],
providers: [{
provide: CdkPortalOutlet,
useExisting: PortalHostDirective
}]
})
export class PortalHostDirective extends CdkPortalOutlet {}
@NgModule({
exports: [CdkPortal, CdkPortalOutlet, TemplatePortalDirective, PortalHostDirective],
declarations: [CdkPortal, CdkPortalOutlet, TemplatePortalDirective, PortalHostDirective],
})
export class PortalModule {}
| CdkPortalOutlet | identifier_name |
upload.js | (function(win) {
var dataType = {
form: getFormData,
json: getJsonData,
data: getData
};
function genUId() {
var date = new Date().getTime();
var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (date + Math.random() * 16) % 16 | 0;
date = Math.floor(date / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
}); | var options = {
domain: '',
method: 'POST',
file_data_name: 'file',
unique_key: 'key',
base64_size: 4 * 1024 * 1024,
chunk_size: 4 * 1024 * 1024,
headers: {},
multi_parmas: {},
query: {},
support_options: true,
data: dataType.form,
genUId: genUId
};
if (!opts || !opts.domain) {
throw new Error('domain is null');
}
for (var key in opts) {
options[key] = opts[key];
}
return options;
}
function mEach(m, callback) {
for (var key in m) {
callback(key, m[key]);
}
}
function getFormData(file, opts) {
var form = new FormData();
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
form.append(opts.unique_key, unique_value);
opts.unique_value = unique_value;
}
form.append(opts.file_data_name, file);
mEach(opts.multi_parmas, function(key, value) {
form.append(key, value);
});
return form;
}
function getJsonData(file, opts) {
var data = {};
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
data[opts.unique_key] = unique_value;
opts.unique_value = unique_value;
}
data[opts.file_data_name] = file;
mEach(opts.multi_parmas, function(key, value) {
data[key] = value;
});
return JSON.stringify(data);
}
function getData(file, opts) {
return file;
}
function Upload(options) {
this.options = mergeOption(options);
this.setOptions = function(opts) {
var me = this;
mEach(opts, function(key, value) {
me.options[key] = value;
});
};
this.upload = function(file, callback) {
if (!file) {
callback.onError('upload file is null.');
return;
}
var me = this;
uploadProcess(file, this.options, {
onProgress: function(loaded, total) {
callback.onProgress(loaded, total);
},
onCompleted: function(data) {
callback.onCompleted(data);
},
onError: function(errorCode) {
callback.onError(errorCode);
},
onOpen: function(xhr) {
me.xhr = xhr;
}
});
};
this.cancel = function() {
this.xhr && this.xhr.abort();
};
}
function init(options) {
return new Upload(options);
}
function getResizeRatio(imageInfo,config){
//hasOwnProperty?
var ratio = 1;
var oWidth = imageInfo.width;
var maxWidth = config.maxWidth || 0;
if(maxWidth > 0 && oWidth > maxWidth){
ratio = maxWidth/oWidth;
}
var oHeight = imageInfo.height;
var maxHeight = config.maxHeight || 0;
if(maxHeight > 0 && oHeight > maxHeight){
var ratioHeight = maxHeight/oHeight;
ratio = Math.min(ratio,ratioHeight);
}
var maxSize = config.maxSize || 0;
var oSize = Math.ceil(imageInfo.size/1000); //K,Math.ceil(0.3) = 1;
if(oSize > maxSize){
ratioSize = maxSize/oSize;
ratio = Math.min(ratio,ratioSize);
}
return ratio;
}
function resize(file,config,callback){
//file对象没有高宽
var type = file.type; //image format
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt){
var imageData = evt.target.result;
var img = new Image();
img.src = imageData;
var width = img.width;
var height = img.height;
var imageInfo = {
width : width,
height : height,
size : evt.total
}
var ratio = getResizeRatio(imageInfo,config);
var newImageData = imageData;
if(ratio < 1){
newImageData = compress(img, width*ratio, height*ratio);;
}
callback(newImageData);
}
function compress(img, width, height){
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, width, height);
/*
If the height or width of the canvas is 0, the string "data:," is returned.
If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
Chrome also supports the image/webp type.
*/
var supportTypes = {
"image/jpg" : true,
"image/png" : true,
"image/webp" : supportWebP()
};
// var exportType = "image/png";
// if(supportTypes[type]){
// exportType = type;
// }
// 多端一致,缩略图必须是 jpg
var exportType = "image/jpg";
var newImageData = canvas.toDataURL(exportType);
return newImageData;
}
function supportWebP(){
try{
return (canvas.toDataURL('image/webp').indexOf('data:image/webp') == 0);
}catch(err) {
return false;
}
}
}
win.UploadFile = {
init: init,
dataType: dataType,
resize : resize
};
})(window); | return uuid;
};
function mergeOption(opts) { | random_line_split |
upload.js | (function(win) {
var dataType = {
form: getFormData,
json: getJsonData,
data: getData
};
function genUId() {
var date = new Date().getTime();
var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (date + Math.random() * 16) % 16 | 0;
date = Math.floor(date / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
function mergeOption(opts) {
var options = {
domain: '',
method: 'POST',
file_data_name: 'file',
unique_key: 'key',
base64_size: 4 * 1024 * 1024,
chunk_size: 4 * 1024 * 1024,
headers: {},
multi_parmas: {},
query: {},
support_options: true,
data: dataType.form,
genUId: genUId
};
if (!opts || !opts.domain) {
throw new Error('domain is null');
}
for (var key in opts) {
options[key] = opts[key];
}
return options;
}
function | (m, callback) {
for (var key in m) {
callback(key, m[key]);
}
}
function getFormData(file, opts) {
var form = new FormData();
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
form.append(opts.unique_key, unique_value);
opts.unique_value = unique_value;
}
form.append(opts.file_data_name, file);
mEach(opts.multi_parmas, function(key, value) {
form.append(key, value);
});
return form;
}
function getJsonData(file, opts) {
var data = {};
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
data[opts.unique_key] = unique_value;
opts.unique_value = unique_value;
}
data[opts.file_data_name] = file;
mEach(opts.multi_parmas, function(key, value) {
data[key] = value;
});
return JSON.stringify(data);
}
function getData(file, opts) {
return file;
}
function Upload(options) {
this.options = mergeOption(options);
this.setOptions = function(opts) {
var me = this;
mEach(opts, function(key, value) {
me.options[key] = value;
});
};
this.upload = function(file, callback) {
if (!file) {
callback.onError('upload file is null.');
return;
}
var me = this;
uploadProcess(file, this.options, {
onProgress: function(loaded, total) {
callback.onProgress(loaded, total);
},
onCompleted: function(data) {
callback.onCompleted(data);
},
onError: function(errorCode) {
callback.onError(errorCode);
},
onOpen: function(xhr) {
me.xhr = xhr;
}
});
};
this.cancel = function() {
this.xhr && this.xhr.abort();
};
}
function init(options) {
return new Upload(options);
}
function getResizeRatio(imageInfo,config){
//hasOwnProperty?
var ratio = 1;
var oWidth = imageInfo.width;
var maxWidth = config.maxWidth || 0;
if(maxWidth > 0 && oWidth > maxWidth){
ratio = maxWidth/oWidth;
}
var oHeight = imageInfo.height;
var maxHeight = config.maxHeight || 0;
if(maxHeight > 0 && oHeight > maxHeight){
var ratioHeight = maxHeight/oHeight;
ratio = Math.min(ratio,ratioHeight);
}
var maxSize = config.maxSize || 0;
var oSize = Math.ceil(imageInfo.size/1000); //K,Math.ceil(0.3) = 1;
if(oSize > maxSize){
ratioSize = maxSize/oSize;
ratio = Math.min(ratio,ratioSize);
}
return ratio;
}
function resize(file,config,callback){
//file对象没有高宽
var type = file.type; //image format
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt){
var imageData = evt.target.result;
var img = new Image();
img.src = imageData;
var width = img.width;
var height = img.height;
var imageInfo = {
width : width,
height : height,
size : evt.total
}
var ratio = getResizeRatio(imageInfo,config);
var newImageData = imageData;
if(ratio < 1){
newImageData = compress(img, width*ratio, height*ratio);;
}
callback(newImageData);
}
function compress(img, width, height){
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, width, height);
/*
If the height or width of the canvas is 0, the string "data:," is returned.
If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
Chrome also supports the image/webp type.
*/
var supportTypes = {
"image/jpg" : true,
"image/png" : true,
"image/webp" : supportWebP()
};
// var exportType = "image/png";
// if(supportTypes[type]){
// exportType = type;
// }
// 多端一致,缩略图必须是 jpg
var exportType = "image/jpg";
var newImageData = canvas.toDataURL(exportType);
return newImageData;
}
function supportWebP(){
try{
return (canvas.toDataURL('image/webp').indexOf('data:image/webp') == 0);
}catch(err) {
return false;
}
}
}
win.UploadFile = {
init: init,
dataType: dataType,
resize : resize
};
})(window); | mEach | identifier_name |
upload.js | (function(win) {
var dataType = {
form: getFormData,
json: getJsonData,
data: getData
};
function genUId() {
var date = new Date().getTime();
var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (date + Math.random() * 16) % 16 | 0;
date = Math.floor(date / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
function mergeOption(opts) {
var options = {
domain: '',
method: 'POST',
file_data_name: 'file',
unique_key: 'key',
base64_size: 4 * 1024 * 1024,
chunk_size: 4 * 1024 * 1024,
headers: {},
multi_parmas: {},
query: {},
support_options: true,
data: dataType.form,
genUId: genUId
};
if (!opts || !opts.domain) {
throw new Error('domain is null');
}
for (var key in opts) {
options[key] = opts[key];
}
return options;
}
function mEach(m, callback) {
for (var key in m) {
callback(key, m[key]);
}
}
function getFormData(file, opts) {
var form = new FormData();
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
form.append(opts.unique_key, unique_value);
opts.unique_value = unique_value;
}
form.append(opts.file_data_name, file);
mEach(opts.multi_parmas, function(key, value) {
form.append(key, value);
});
return form;
}
function getJsonData(file, opts) {
var data = {};
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
data[opts.unique_key] = unique_value;
opts.unique_value = unique_value;
}
data[opts.file_data_name] = file;
mEach(opts.multi_parmas, function(key, value) {
data[key] = value;
});
return JSON.stringify(data);
}
function getData(file, opts) {
return file;
}
function Upload(options) {
this.options = mergeOption(options);
this.setOptions = function(opts) {
var me = this;
mEach(opts, function(key, value) {
me.options[key] = value;
});
};
this.upload = function(file, callback) {
if (!file) {
callback.onError('upload file is null.');
return;
}
var me = this;
uploadProcess(file, this.options, {
onProgress: function(loaded, total) {
callback.onProgress(loaded, total);
},
onCompleted: function(data) {
callback.onCompleted(data);
},
onError: function(errorCode) {
callback.onError(errorCode);
},
onOpen: function(xhr) {
me.xhr = xhr;
}
});
};
this.cancel = function() {
this.xhr && this.xhr.abort();
};
}
function init(options) {
return new Upload(options);
}
function getResizeRatio(imageInfo,config){
//hasOwnProperty?
var ratio = 1;
var oWidth = imageInfo.width;
var maxWidth = config.maxWidth || 0;
if(maxWidth > 0 && oWidth > maxWidth) |
var oHeight = imageInfo.height;
var maxHeight = config.maxHeight || 0;
if(maxHeight > 0 && oHeight > maxHeight){
var ratioHeight = maxHeight/oHeight;
ratio = Math.min(ratio,ratioHeight);
}
var maxSize = config.maxSize || 0;
var oSize = Math.ceil(imageInfo.size/1000); //K,Math.ceil(0.3) = 1;
if(oSize > maxSize){
ratioSize = maxSize/oSize;
ratio = Math.min(ratio,ratioSize);
}
return ratio;
}
function resize(file,config,callback){
//file对象没有高宽
var type = file.type; //image format
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt){
var imageData = evt.target.result;
var img = new Image();
img.src = imageData;
var width = img.width;
var height = img.height;
var imageInfo = {
width : width,
height : height,
size : evt.total
}
var ratio = getResizeRatio(imageInfo,config);
var newImageData = imageData;
if(ratio < 1){
newImageData = compress(img, width*ratio, height*ratio);;
}
callback(newImageData);
}
function compress(img, width, height){
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, width, height);
/*
If the height or width of the canvas is 0, the string "data:," is returned.
If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
Chrome also supports the image/webp type.
*/
var supportTypes = {
"image/jpg" : true,
"image/png" : true,
"image/webp" : supportWebP()
};
// var exportType = "image/png";
// if(supportTypes[type]){
// exportType = type;
// }
// 多端一致,缩略图必须是 jpg
var exportType = "image/jpg";
var newImageData = canvas.toDataURL(exportType);
return newImageData;
}
function supportWebP(){
try{
return (canvas.toDataURL('image/webp').indexOf('data:image/webp') == 0);
}catch(err) {
return false;
}
}
}
win.UploadFile = {
init: init,
dataType: dataType,
resize : resize
};
})(window); | {
ratio = maxWidth/oWidth;
} | conditional_block |
upload.js | (function(win) {
var dataType = {
form: getFormData,
json: getJsonData,
data: getData
};
function genUId() {
var date = new Date().getTime();
var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (date + Math.random() * 16) % 16 | 0;
date = Math.floor(date / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
function mergeOption(opts) {
var options = {
domain: '',
method: 'POST',
file_data_name: 'file',
unique_key: 'key',
base64_size: 4 * 1024 * 1024,
chunk_size: 4 * 1024 * 1024,
headers: {},
multi_parmas: {},
query: {},
support_options: true,
data: dataType.form,
genUId: genUId
};
if (!opts || !opts.domain) {
throw new Error('domain is null');
}
for (var key in opts) {
options[key] = opts[key];
}
return options;
}
function mEach(m, callback) {
for (var key in m) {
callback(key, m[key]);
}
}
function getFormData(file, opts) {
var form = new FormData();
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
form.append(opts.unique_key, unique_value);
opts.unique_value = unique_value;
}
form.append(opts.file_data_name, file);
mEach(opts.multi_parmas, function(key, value) {
form.append(key, value);
});
return form;
}
function getJsonData(file, opts) {
var data = {};
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
data[opts.unique_key] = unique_value;
opts.unique_value = unique_value;
}
data[opts.file_data_name] = file;
mEach(opts.multi_parmas, function(key, value) {
data[key] = value;
});
return JSON.stringify(data);
}
function getData(file, opts) {
return file;
}
function Upload(options) {
this.options = mergeOption(options);
this.setOptions = function(opts) {
var me = this;
mEach(opts, function(key, value) {
me.options[key] = value;
});
};
this.upload = function(file, callback) {
if (!file) {
callback.onError('upload file is null.');
return;
}
var me = this;
uploadProcess(file, this.options, {
onProgress: function(loaded, total) {
callback.onProgress(loaded, total);
},
onCompleted: function(data) {
callback.onCompleted(data);
},
onError: function(errorCode) {
callback.onError(errorCode);
},
onOpen: function(xhr) {
me.xhr = xhr;
}
});
};
this.cancel = function() {
this.xhr && this.xhr.abort();
};
}
function init(options) |
function getResizeRatio(imageInfo,config){
//hasOwnProperty?
var ratio = 1;
var oWidth = imageInfo.width;
var maxWidth = config.maxWidth || 0;
if(maxWidth > 0 && oWidth > maxWidth){
ratio = maxWidth/oWidth;
}
var oHeight = imageInfo.height;
var maxHeight = config.maxHeight || 0;
if(maxHeight > 0 && oHeight > maxHeight){
var ratioHeight = maxHeight/oHeight;
ratio = Math.min(ratio,ratioHeight);
}
var maxSize = config.maxSize || 0;
var oSize = Math.ceil(imageInfo.size/1000); //K,Math.ceil(0.3) = 1;
if(oSize > maxSize){
ratioSize = maxSize/oSize;
ratio = Math.min(ratio,ratioSize);
}
return ratio;
}
function resize(file,config,callback){
//file对象没有高宽
var type = file.type; //image format
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt){
var imageData = evt.target.result;
var img = new Image();
img.src = imageData;
var width = img.width;
var height = img.height;
var imageInfo = {
width : width,
height : height,
size : evt.total
}
var ratio = getResizeRatio(imageInfo,config);
var newImageData = imageData;
if(ratio < 1){
newImageData = compress(img, width*ratio, height*ratio);;
}
callback(newImageData);
}
function compress(img, width, height){
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, width, height);
/*
If the height or width of the canvas is 0, the string "data:," is returned.
If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
Chrome also supports the image/webp type.
*/
var supportTypes = {
"image/jpg" : true,
"image/png" : true,
"image/webp" : supportWebP()
};
// var exportType = "image/png";
// if(supportTypes[type]){
// exportType = type;
// }
// 多端一致,缩略图必须是 jpg
var exportType = "image/jpg";
var newImageData = canvas.toDataURL(exportType);
return newImageData;
}
function supportWebP(){
try{
return (canvas.toDataURL('image/webp').indexOf('data:image/webp') == 0);
}catch(err) {
return false;
}
}
}
win.UploadFile = {
init: init,
dataType: dataType,
resize : resize
};
})(window); | {
return new Upload(options);
} | identifier_body |
poke-catalog.component.ts | import { OnInit, Component, Input, EventEmitter } from "@angular/core";
import { Pokemon } from "./pokemon.model";
import { ExternalImageURLPipe } from "./../pipes/external-image-url.pipe";
import { PokeCatalogService } from "./poke-catalog.service";
@Component({
selector: "poke-catalog",
pipes: [ExternalImageURLPipe],
providers: [PokeCatalogService],
templateUrl: "app/poke-catalog/poke-catalog.component.html",
styleUrls: ["app/poke-catalog/poke-catalog.component.css"]
})
export class PokeCatalogComponent implements OnInit {
originalPokemonList: Array<Pokemon> = [];
pokemonList: Array<Pokemon> = [];
searchValue: string = "";
@Input() set searchValueInput(value: string) {
this.searchValue = value;
this.filterPokemon();
};
constructor(private _pokeCatalogService: PokeCatalogService) {
console.log(">> PokeCatalogComponent()");
}
| () {
this.pokemonList = this.originalPokemonList.filter((pokemon, index)=> {
// If the value to search is a substring of the pokemon name; then the pokemonList will have the current pokemon
return pokemon.name.includes(this.searchValue);
});
}
public ngOnInit() {
this._pokeCatalogService.getPokemonList().then((pokemonList: Pokemon[]) => {
this.pokemonList = pokemonList;
this.originalPokemonList = pokemonList;
});
}
}
| filterPokemon | identifier_name |
poke-catalog.component.ts | import { OnInit, Component, Input, EventEmitter } from "@angular/core";
import { Pokemon } from "./pokemon.model";
import { ExternalImageURLPipe } from "./../pipes/external-image-url.pipe";
import { PokeCatalogService } from "./poke-catalog.service";
@Component({
selector: "poke-catalog",
pipes: [ExternalImageURLPipe],
providers: [PokeCatalogService],
templateUrl: "app/poke-catalog/poke-catalog.component.html",
styleUrls: ["app/poke-catalog/poke-catalog.component.css"]
})
export class PokeCatalogComponent implements OnInit {
originalPokemonList: Array<Pokemon> = [];
pokemonList: Array<Pokemon> = [];
searchValue: string = "";
@Input() set searchValueInput(value: string) {
this.searchValue = value;
this.filterPokemon();
};
constructor(private _pokeCatalogService: PokeCatalogService) {
console.log(">> PokeCatalogComponent()");
}
filterPokemon() |
public ngOnInit() {
this._pokeCatalogService.getPokemonList().then((pokemonList: Pokemon[]) => {
this.pokemonList = pokemonList;
this.originalPokemonList = pokemonList;
});
}
}
| {
this.pokemonList = this.originalPokemonList.filter((pokemon, index)=> {
// If the value to search is a substring of the pokemon name; then the pokemonList will have the current pokemon
return pokemon.name.includes(this.searchValue);
});
} | identifier_body |
poke-catalog.component.ts | import { OnInit, Component, Input, EventEmitter } from "@angular/core";
import { Pokemon } from "./pokemon.model";
import { ExternalImageURLPipe } from "./../pipes/external-image-url.pipe";
import { PokeCatalogService } from "./poke-catalog.service";
@Component({
selector: "poke-catalog", | styleUrls: ["app/poke-catalog/poke-catalog.component.css"]
})
export class PokeCatalogComponent implements OnInit {
originalPokemonList: Array<Pokemon> = [];
pokemonList: Array<Pokemon> = [];
searchValue: string = "";
@Input() set searchValueInput(value: string) {
this.searchValue = value;
this.filterPokemon();
};
constructor(private _pokeCatalogService: PokeCatalogService) {
console.log(">> PokeCatalogComponent()");
}
filterPokemon() {
this.pokemonList = this.originalPokemonList.filter((pokemon, index)=> {
// If the value to search is a substring of the pokemon name; then the pokemonList will have the current pokemon
return pokemon.name.includes(this.searchValue);
});
}
public ngOnInit() {
this._pokeCatalogService.getPokemonList().then((pokemonList: Pokemon[]) => {
this.pokemonList = pokemonList;
this.originalPokemonList = pokemonList;
});
}
} | pipes: [ExternalImageURLPipe],
providers: [PokeCatalogService],
templateUrl: "app/poke-catalog/poke-catalog.component.html", | random_line_split |
log.rs | // This Source Code Form is subject to the terms of
// the Mozilla Public License, v. 2.0. If a copy of
// the MPL was not distributed with this file, You
// can obtain one at http://mozilla.org/MPL/2.0/.
use std::error::Error;
pub fn error(e: &Error) {
target::error(e)
} | // ANDROID //////////////////////////////////////////////////////////////////
#[cfg(target_os = "android")]
mod target {
use libc::*;
use std::error::Error;
use std::ffi::*;
const TAG: &'static [u8] = b"CryptoBox";
const LEVEL_ERROR: c_int = 6;
pub fn error(e: &Error) {
log(&format!("{}", e), LEVEL_ERROR)
}
fn log(msg: &str, lvl: c_int) {
let tag = CString::new(TAG).unwrap();
let msg = CString::new(msg.as_bytes()).unwrap_or(CString::new("<malformed log message>").unwrap());
unsafe {
__android_log_write(lvl, tag.as_ptr(), msg.as_ptr())
};
}
#[link(name = "log")]
extern {
fn __android_log_write(prio: c_int, tag: *const c_char, text: *const c_char) -> c_int;
}
}
// FALLBACK /////////////////////////////////////////////////////////////////
#[cfg(not(target_os = "android"))]
mod target {
use std::error::Error;
use std::io::{Write, stderr};
pub fn error(e: &Error) {
writeln!(&mut stderr(), "ERROR: {}", e).unwrap();
}
} | random_line_split | |
log.rs | // This Source Code Form is subject to the terms of
// the Mozilla Public License, v. 2.0. If a copy of
// the MPL was not distributed with this file, You
// can obtain one at http://mozilla.org/MPL/2.0/.
use std::error::Error;
pub fn error(e: &Error) {
target::error(e)
}
// ANDROID //////////////////////////////////////////////////////////////////
#[cfg(target_os = "android")]
mod target {
use libc::*;
use std::error::Error;
use std::ffi::*;
const TAG: &'static [u8] = b"CryptoBox";
const LEVEL_ERROR: c_int = 6;
pub fn | (e: &Error) {
log(&format!("{}", e), LEVEL_ERROR)
}
fn log(msg: &str, lvl: c_int) {
let tag = CString::new(TAG).unwrap();
let msg = CString::new(msg.as_bytes()).unwrap_or(CString::new("<malformed log message>").unwrap());
unsafe {
__android_log_write(lvl, tag.as_ptr(), msg.as_ptr())
};
}
#[link(name = "log")]
extern {
fn __android_log_write(prio: c_int, tag: *const c_char, text: *const c_char) -> c_int;
}
}
// FALLBACK /////////////////////////////////////////////////////////////////
#[cfg(not(target_os = "android"))]
mod target {
use std::error::Error;
use std::io::{Write, stderr};
pub fn error(e: &Error) {
writeln!(&mut stderr(), "ERROR: {}", e).unwrap();
}
}
| error | identifier_name |
log.rs | // This Source Code Form is subject to the terms of
// the Mozilla Public License, v. 2.0. If a copy of
// the MPL was not distributed with this file, You
// can obtain one at http://mozilla.org/MPL/2.0/.
use std::error::Error;
pub fn error(e: &Error) {
target::error(e)
}
// ANDROID //////////////////////////////////////////////////////////////////
#[cfg(target_os = "android")]
mod target {
use libc::*;
use std::error::Error;
use std::ffi::*;
const TAG: &'static [u8] = b"CryptoBox";
const LEVEL_ERROR: c_int = 6;
pub fn error(e: &Error) {
log(&format!("{}", e), LEVEL_ERROR)
}
fn log(msg: &str, lvl: c_int) {
let tag = CString::new(TAG).unwrap();
let msg = CString::new(msg.as_bytes()).unwrap_or(CString::new("<malformed log message>").unwrap());
unsafe {
__android_log_write(lvl, tag.as_ptr(), msg.as_ptr())
};
}
#[link(name = "log")]
extern {
fn __android_log_write(prio: c_int, tag: *const c_char, text: *const c_char) -> c_int;
}
}
// FALLBACK /////////////////////////////////////////////////////////////////
#[cfg(not(target_os = "android"))]
mod target {
use std::error::Error;
use std::io::{Write, stderr};
pub fn error(e: &Error) |
}
| {
writeln!(&mut stderr(), "ERROR: {}", e).unwrap();
} | identifier_body |
main.py | import json
import random
import requests
from plugin import create_plugin
from message import SteelyMessage
HELP_STR = """
Request your favourite bible quotes, right to the chat.
Usage:
/bible - Random quote
/bible Genesis 1:3 - Specific verse
/bible help - This help text
Verses are specified in the format {book} {chapter}:{verse}
TODO: Book acronyms, e.g. Gen -> Genesis
TODO: Verse ranges, e.g. Genesis 1:1-3
"""
BIBLE_FILE = "plugins/bible/en_kjv.json"
BIBLE_URL = 'https://raw.githubusercontent.com/thiagobodruk/bible/master/json/en_kjv.json'
plugin = create_plugin(name='bible', author='CianLR', help=HELP_STR)
bible = None
book_to_index = {}
def make_book_to_index(bible):
btoi = {}
for i, book in enumerate(bible):
btoi[book['name'].lower()] = i
return btoi
@plugin.setup()
def plugin_setup():
global bible, book_to_index
try:
bible = json.loads(open(BIBLE_FILE, encoding='utf-8-sig').read())
book_to_index = make_book_to_index(bible)
return
except BaseException as e:
pass
# We've tried nothing and we're all out of ideas, download a new bible.
try:
bible = json.loads(
requests.get(BIBLE_URL).content.decode('utf-8-sig'))
except BaseException as e:
return "Error loading bible: " + str(e)
book_to_index = make_book_to_index(bible)
with open(BIBLE_FILE, 'w') as f:
json.dump(bible, f)
@plugin.listen(command='bible help')
def | (bot, message: SteelyMessage, **kwargs):
bot.sendMessage(
HELP_STR,
thread_id=message.thread_id, thread_type=message.thread_type)
def is_valid_quote(book, chapter, verse):
return (0 <= book < len(bible) and
0 <= chapter < len(bible[book]['chapters']) and
0 <= verse < len(bible[book]['chapters'][chapter]))
def get_quote(book, chapter, verse):
return "{}\n - {} {}:{}".format(
bible[book]["chapters"][chapter][verse],
bible[book]["name"], chapter + 1, verse + 1)
def get_quote_from_ref(book_name, ref):
if book_name.lower() not in book_to_index:
return "Could not find book name: " + book_name
book_i = book_to_index[book_name.lower()]
if len(ref.split(':')) != 2:
return 'Reference not in form "Book Chapter:Passage"'
chapter, verse = ref.split(':')
if not chapter.isnumeric():
return "Chapter must be an int"
chapter_i = int(chapter) - 1
if not verse.isnumeric():
return "Passage must be an int"
verse_i = int(verse) - 1
if not is_valid_quote(book_i, chapter_i, verse_i):
return "Verse or chapter out of range"
return get_quote(book_i, chapter_i, verse_i)
@plugin.listen(command='bible [book] [passage]')
def passage_command(bot, message: SteelyMessage, **kwargs):
if 'passage' not in kwargs:
book = random.randrange(len(bible))
chapter = random.randrange(len(bible[book]["chapters"]))
verse = random.randrange(len(bible[book]["chapters"][chapter]))
bot.sendMessage(
get_quote(book, chapter, verse),
thread_id=message.thread_id, thread_type=message.thread_type)
else:
bot.sendMessage(
get_quote_from_ref(kwargs['book'], kwargs['passage']),
thread_id=message.thread_id, thread_type=message.thread_type)
| help_command | identifier_name |
main.py | import json
import random
import requests
from plugin import create_plugin
from message import SteelyMessage
HELP_STR = """
Request your favourite bible quotes, right to the chat.
Usage:
/bible - Random quote
/bible Genesis 1:3 - Specific verse
/bible help - This help text
Verses are specified in the format {book} {chapter}:{verse}
TODO: Book acronyms, e.g. Gen -> Genesis
TODO: Verse ranges, e.g. Genesis 1:1-3
"""
BIBLE_FILE = "plugins/bible/en_kjv.json"
BIBLE_URL = 'https://raw.githubusercontent.com/thiagobodruk/bible/master/json/en_kjv.json'
plugin = create_plugin(name='bible', author='CianLR', help=HELP_STR)
bible = None
book_to_index = {}
def make_book_to_index(bible):
btoi = {}
for i, book in enumerate(bible):
btoi[book['name'].lower()] = i
return btoi
@plugin.setup()
def plugin_setup():
global bible, book_to_index
try:
bible = json.loads(open(BIBLE_FILE, encoding='utf-8-sig').read())
book_to_index = make_book_to_index(bible)
return
except BaseException as e:
pass
# We've tried nothing and we're all out of ideas, download a new bible.
try:
bible = json.loads(
requests.get(BIBLE_URL).content.decode('utf-8-sig'))
except BaseException as e:
return "Error loading bible: " + str(e)
book_to_index = make_book_to_index(bible)
with open(BIBLE_FILE, 'w') as f:
json.dump(bible, f)
@plugin.listen(command='bible help')
def help_command(bot, message: SteelyMessage, **kwargs):
bot.sendMessage(
HELP_STR,
thread_id=message.thread_id, thread_type=message.thread_type)
def is_valid_quote(book, chapter, verse):
return (0 <= book < len(bible) and
0 <= chapter < len(bible[book]['chapters']) and
0 <= verse < len(bible[book]['chapters'][chapter]))
def get_quote(book, chapter, verse):
return "{}\n - {} {}:{}".format(
bible[book]["chapters"][chapter][verse],
bible[book]["name"], chapter + 1, verse + 1)
def get_quote_from_ref(book_name, ref):
if book_name.lower() not in book_to_index:
return "Could not find book name: " + book_name
book_i = book_to_index[book_name.lower()]
if len(ref.split(':')) != 2:
return 'Reference not in form "Book Chapter:Passage"'
chapter, verse = ref.split(':')
if not chapter.isnumeric():
return "Chapter must be an int"
chapter_i = int(chapter) - 1
if not verse.isnumeric():
|
verse_i = int(verse) - 1
if not is_valid_quote(book_i, chapter_i, verse_i):
return "Verse or chapter out of range"
return get_quote(book_i, chapter_i, verse_i)
@plugin.listen(command='bible [book] [passage]')
def passage_command(bot, message: SteelyMessage, **kwargs):
if 'passage' not in kwargs:
book = random.randrange(len(bible))
chapter = random.randrange(len(bible[book]["chapters"]))
verse = random.randrange(len(bible[book]["chapters"][chapter]))
bot.sendMessage(
get_quote(book, chapter, verse),
thread_id=message.thread_id, thread_type=message.thread_type)
else:
bot.sendMessage(
get_quote_from_ref(kwargs['book'], kwargs['passage']),
thread_id=message.thread_id, thread_type=message.thread_type)
| return "Passage must be an int" | conditional_block |
main.py | import json
import random
import requests
from plugin import create_plugin
from message import SteelyMessage
HELP_STR = """
Request your favourite bible quotes, right to the chat.
Usage:
/bible - Random quote
/bible Genesis 1:3 - Specific verse
/bible help - This help text
Verses are specified in the format {book} {chapter}:{verse}
TODO: Book acronyms, e.g. Gen -> Genesis
TODO: Verse ranges, e.g. Genesis 1:1-3
"""
BIBLE_FILE = "plugins/bible/en_kjv.json"
BIBLE_URL = 'https://raw.githubusercontent.com/thiagobodruk/bible/master/json/en_kjv.json'
plugin = create_plugin(name='bible', author='CianLR', help=HELP_STR)
bible = None
book_to_index = {}
def make_book_to_index(bible):
btoi = {}
for i, book in enumerate(bible):
btoi[book['name'].lower()] = i
return btoi
@plugin.setup()
def plugin_setup():
global bible, book_to_index
try:
bible = json.loads(open(BIBLE_FILE, encoding='utf-8-sig').read())
book_to_index = make_book_to_index(bible)
return
except BaseException as e:
pass
# We've tried nothing and we're all out of ideas, download a new bible.
try:
bible = json.loads(
requests.get(BIBLE_URL).content.decode('utf-8-sig'))
except BaseException as e:
return "Error loading bible: " + str(e)
book_to_index = make_book_to_index(bible)
with open(BIBLE_FILE, 'w') as f:
json.dump(bible, f)
@plugin.listen(command='bible help')
def help_command(bot, message: SteelyMessage, **kwargs):
bot.sendMessage(
HELP_STR,
thread_id=message.thread_id, thread_type=message.thread_type)
def is_valid_quote(book, chapter, verse):
return (0 <= book < len(bible) and
0 <= chapter < len(bible[book]['chapters']) and
0 <= verse < len(bible[book]['chapters'][chapter]))
def get_quote(book, chapter, verse): | return "{}\n - {} {}:{}".format(
bible[book]["chapters"][chapter][verse],
bible[book]["name"], chapter + 1, verse + 1)
def get_quote_from_ref(book_name, ref):
if book_name.lower() not in book_to_index:
return "Could not find book name: " + book_name
book_i = book_to_index[book_name.lower()]
if len(ref.split(':')) != 2:
return 'Reference not in form "Book Chapter:Passage"'
chapter, verse = ref.split(':')
if not chapter.isnumeric():
return "Chapter must be an int"
chapter_i = int(chapter) - 1
if not verse.isnumeric():
return "Passage must be an int"
verse_i = int(verse) - 1
if not is_valid_quote(book_i, chapter_i, verse_i):
return "Verse or chapter out of range"
return get_quote(book_i, chapter_i, verse_i)
@plugin.listen(command='bible [book] [passage]')
def passage_command(bot, message: SteelyMessage, **kwargs):
if 'passage' not in kwargs:
book = random.randrange(len(bible))
chapter = random.randrange(len(bible[book]["chapters"]))
verse = random.randrange(len(bible[book]["chapters"][chapter]))
bot.sendMessage(
get_quote(book, chapter, verse),
thread_id=message.thread_id, thread_type=message.thread_type)
else:
bot.sendMessage(
get_quote_from_ref(kwargs['book'], kwargs['passage']),
thread_id=message.thread_id, thread_type=message.thread_type) | random_line_split | |
main.py | import json
import random
import requests
from plugin import create_plugin
from message import SteelyMessage
HELP_STR = """
Request your favourite bible quotes, right to the chat.
Usage:
/bible - Random quote
/bible Genesis 1:3 - Specific verse
/bible help - This help text
Verses are specified in the format {book} {chapter}:{verse}
TODO: Book acronyms, e.g. Gen -> Genesis
TODO: Verse ranges, e.g. Genesis 1:1-3
"""
BIBLE_FILE = "plugins/bible/en_kjv.json"
BIBLE_URL = 'https://raw.githubusercontent.com/thiagobodruk/bible/master/json/en_kjv.json'
plugin = create_plugin(name='bible', author='CianLR', help=HELP_STR)
bible = None
book_to_index = {}
def make_book_to_index(bible):
btoi = {}
for i, book in enumerate(bible):
btoi[book['name'].lower()] = i
return btoi
@plugin.setup()
def plugin_setup():
global bible, book_to_index
try:
bible = json.loads(open(BIBLE_FILE, encoding='utf-8-sig').read())
book_to_index = make_book_to_index(bible)
return
except BaseException as e:
pass
# We've tried nothing and we're all out of ideas, download a new bible.
try:
bible = json.loads(
requests.get(BIBLE_URL).content.decode('utf-8-sig'))
except BaseException as e:
return "Error loading bible: " + str(e)
book_to_index = make_book_to_index(bible)
with open(BIBLE_FILE, 'w') as f:
json.dump(bible, f)
@plugin.listen(command='bible help')
def help_command(bot, message: SteelyMessage, **kwargs):
bot.sendMessage(
HELP_STR,
thread_id=message.thread_id, thread_type=message.thread_type)
def is_valid_quote(book, chapter, verse):
|
def get_quote(book, chapter, verse):
return "{}\n - {} {}:{}".format(
bible[book]["chapters"][chapter][verse],
bible[book]["name"], chapter + 1, verse + 1)
def get_quote_from_ref(book_name, ref):
if book_name.lower() not in book_to_index:
return "Could not find book name: " + book_name
book_i = book_to_index[book_name.lower()]
if len(ref.split(':')) != 2:
return 'Reference not in form "Book Chapter:Passage"'
chapter, verse = ref.split(':')
if not chapter.isnumeric():
return "Chapter must be an int"
chapter_i = int(chapter) - 1
if not verse.isnumeric():
return "Passage must be an int"
verse_i = int(verse) - 1
if not is_valid_quote(book_i, chapter_i, verse_i):
return "Verse or chapter out of range"
return get_quote(book_i, chapter_i, verse_i)
@plugin.listen(command='bible [book] [passage]')
def passage_command(bot, message: SteelyMessage, **kwargs):
if 'passage' not in kwargs:
book = random.randrange(len(bible))
chapter = random.randrange(len(bible[book]["chapters"]))
verse = random.randrange(len(bible[book]["chapters"][chapter]))
bot.sendMessage(
get_quote(book, chapter, verse),
thread_id=message.thread_id, thread_type=message.thread_type)
else:
bot.sendMessage(
get_quote_from_ref(kwargs['book'], kwargs['passage']),
thread_id=message.thread_id, thread_type=message.thread_type)
| return (0 <= book < len(bible) and
0 <= chapter < len(bible[book]['chapters']) and
0 <= verse < len(bible[book]['chapters'][chapter])) | identifier_body |
CompareVersionsDialog.tsx | /* eslint-disable i18next/no-literal-string */
import {css, cx} from "@emotion/css"
import {WindowContentProps} from "@touk/window-manager"
import _ from "lodash"
import React from "react"
import {connect} from "react-redux"
import {formatAbsolutely} from "../../common/DateUtils"
import * as JsonUtils from "../../common/JsonUtils"
import HttpService from "../../http/HttpService"
import {getProcessId, getProcessVersionId, getVersions} from "../../reducers/selectors/graph"
import {getTargetEnvironmentId} from "../../reducers/selectors/settings"
import "../../stylesheets/visualization.styl"
import {WindowContent} from "../../windowManager"
import EdgeDetailsContent from "../graph/node-modal/edge/EdgeDetailsContent"
import NodeDetailsContent from "../graph/node-modal/NodeDetailsContent"
import {ProcessVersionType} from "../Process/types"
import {SelectWithFocus} from "../withFocus"
interface State {
currentDiffId: string,
otherVersion: string,
remoteVersions: ProcessVersionType[],
difference: unknown,
}
//TODO: handle different textarea heights
class VersionsForm extends React.Component<Props, State> {
//TODO: better way of detecting remote version? also: how to sort versions??
remotePrefix = "remote-"
initState: State = {
otherVersion: null,
currentDiffId: null,
difference: null,
remoteVersions: [],
}
state = this.initState
isLayoutChangeOnly(diffId: string): boolean {
const {type, currentNode, otherNode} = this.state.difference[diffId]
if (type === "NodeDifferent") {
return this.differentPathsForObjects(currentNode, otherNode).every(path => path.startsWith("additionalFields.layoutData"))
}
}
componentDidMount() {
if (this.props.processId && this.props.otherEnvironment) {
HttpService.fetchRemoteVersions(this.props.processId).then(response => this.setState({remoteVersions: response.data || []}))
}
}
loadVersion(versionId: string) {
if (versionId) {
HttpService.compareProcesses(
this.props.processId,
this.props.version,
this.versionToPass(versionId),
this.isRemote(versionId),
).then(
(response) => this.setState({difference: response.data, otherVersion: versionId, currentDiffId: null}),
)
} else |
}
isRemote(versionId: string) {
return versionId.startsWith(this.remotePrefix)
}
versionToPass(versionId: string) {
return versionId.replace(this.remotePrefix, "")
}
versionDisplayString(versionId: string) {
return this.isRemote(versionId) ? `${this.versionToPass(versionId)} on ${this.props.otherEnvironment}` : versionId
}
createVersionElement(version: ProcessVersionType, versionPrefix = "") {
const versionId = versionPrefix + version.processVersionId
return (
<option key={versionId} value={versionId}>
{this.versionDisplayString(versionId)} - created by {version.user} {formatAbsolutely(version.createDate)}</option>
)
}
render() {
return (
<>
<div className="esp-form-row">
<p>Version to compare</p>
<SelectWithFocus
autoFocus={true}
id="otherVersion"
className="node-input"
value={this.state.otherVersion || ""}
onChange={(e) => this.loadVersion(e.target.value)}
>
<option key="" value=""/>
{this.props.versions.filter(version => this.props.version !== version.processVersionId)
.map(version => this.createVersionElement(version))}
{this.state.remoteVersions.map(version => this.createVersionElement(version, this.remotePrefix))}
</SelectWithFocus>
</div>
{
this.state.otherVersion ?
(
<div>
<div className="esp-form-row">
<p>Difference to pick</p>
<SelectWithFocus
id="otherVersion"
className="node-input"
value={this.state.currentDiffId || ""}
onChange={(e) => this.setState({currentDiffId: e.target.value})}
>
<option key="" value=""/>
{_.keys(this.state.difference).map((diffId) => {
const isLayoutOnly = this.isLayoutChangeOnly(diffId)
return (
<option key={diffId} value={diffId} disabled={isLayoutOnly}>{diffId} {isLayoutOnly && "(position only)"}</option>)
})}
</SelectWithFocus>
</div>
{this.state.currentDiffId ?
this.printDiff(this.state.currentDiffId) :
null}
</div>
) :
null
}
</>
)
}
printDiff(diffId) {
const diff = this.state.difference[diffId]
switch (diff.type) {
case "NodeNotPresentInOther":
case "NodeNotPresentInCurrent":
case "NodeDifferent":
return this.renderDiff(diff.currentNode, diff.otherNode, this.printNode)
case "EdgeNotPresentInCurrent":
case "EdgeNotPresentInOther":
case "EdgeDifferent":
return this.renderDiff(diff.currentEdge, diff.otherEdge, this.printEdge)
case "PropertiesDifferent":
return this.renderDiff(diff.currentProperties, diff.otherProperties, this.printProperties)
default:
console.error(`Difference type ${diff.type} is not supported`)
}
}
renderDiff(currentElement, otherElement, printElement) {
const differentPaths = this.differentPathsForObjects(currentElement, otherElement)
return (
<div className="compareContainer">
<div>
<div className="versionHeader">Current version</div>
{printElement(currentElement, differentPaths)}
</div>
<div>
<div className="versionHeader">Version {this.versionDisplayString(this.state.otherVersion)}</div>
{printElement(otherElement, [])}
</div>
</div>
)
}
differentPathsForObjects(currentNode, otherNode) {
const diffObject = JsonUtils.objectDiff(currentNode, otherNode)
const flattenObj = JsonUtils.flattenObj(diffObject)
return _.keys(flattenObj)
}
printNode(node, pathsToMark) {
return node ?
(
<NodeDetailsContent
isEditMode={false}
showValidation={false}
showSwitch={false}
node={node}
pathsToMark={pathsToMark}
onChange={() => {return}}
/>
) :
(<div className="notPresent">Node not present</div>)
}
printEdge(edge, pathsToMark) {
return edge ?
(
<EdgeDetailsContent
edge={edge}
readOnly={true}
showValidation={false}
showSwitch={false}
changeEdgeTypeValue={() => {return}}
changeEdgeTypeCondition={() => {return}}
pathsToMark={pathsToMark}
variableTypes={{}}
/>
) :
(<div className="notPresent">Edge not present</div>)
}
printProperties(property, pathsToMark) {
return property ?
(
<NodeDetailsContent
isEditMode={false}
showValidation={false}
showSwitch={false}
node={property}
pathsToMark={pathsToMark}
onChange={() => {return}}
/>
) :
(<div className="notPresent">Properties not present</div>)
}
}
function mapState(state) {
return {
processId: getProcessId(state),
version: getProcessVersionId(state),
otherEnvironment: getTargetEnvironmentId(state),
versions: getVersions(state),
}
}
type Props = ReturnType<typeof mapState>
//TODO: move to hooks
const CompareVersionsForm = connect(mapState)(VersionsForm)
export function CompareVersionsDialog(props: WindowContentProps): JSX.Element {
return (
<WindowContent {...props}>
<div className={cx("compareModal", "modalContentDark", css({minWidth: 980, padding: "1em"}))}>
<CompareVersionsForm/>
</div>
</WindowContent>
)
}
| {
this.setState(this.initState)
} | conditional_block |
CompareVersionsDialog.tsx | /* eslint-disable i18next/no-literal-string */
import {css, cx} from "@emotion/css"
import {WindowContentProps} from "@touk/window-manager"
import _ from "lodash"
import React from "react"
import {connect} from "react-redux"
import {formatAbsolutely} from "../../common/DateUtils"
import * as JsonUtils from "../../common/JsonUtils"
import HttpService from "../../http/HttpService"
import {getProcessId, getProcessVersionId, getVersions} from "../../reducers/selectors/graph"
import {getTargetEnvironmentId} from "../../reducers/selectors/settings"
import "../../stylesheets/visualization.styl"
import {WindowContent} from "../../windowManager"
import EdgeDetailsContent from "../graph/node-modal/edge/EdgeDetailsContent"
import NodeDetailsContent from "../graph/node-modal/NodeDetailsContent"
import {ProcessVersionType} from "../Process/types"
import {SelectWithFocus} from "../withFocus"
interface State {
currentDiffId: string,
otherVersion: string,
remoteVersions: ProcessVersionType[],
difference: unknown,
}
//TODO: handle different textarea heights
class VersionsForm extends React.Component<Props, State> {
//TODO: better way of detecting remote version? also: how to sort versions??
remotePrefix = "remote-"
initState: State = {
otherVersion: null,
currentDiffId: null,
difference: null,
remoteVersions: [],
}
state = this.initState
isLayoutChangeOnly(diffId: string): boolean {
const {type, currentNode, otherNode} = this.state.difference[diffId]
if (type === "NodeDifferent") {
return this.differentPathsForObjects(currentNode, otherNode).every(path => path.startsWith("additionalFields.layoutData"))
}
}
componentDidMount() {
if (this.props.processId && this.props.otherEnvironment) {
HttpService.fetchRemoteVersions(this.props.processId).then(response => this.setState({remoteVersions: response.data || []}))
}
}
loadVersion(versionId: string) {
if (versionId) {
HttpService.compareProcesses(
this.props.processId,
this.props.version,
this.versionToPass(versionId),
this.isRemote(versionId),
).then(
(response) => this.setState({difference: response.data, otherVersion: versionId, currentDiffId: null}),
)
} else {
this.setState(this.initState)
}
}
isRemote(versionId: string) {
return versionId.startsWith(this.remotePrefix)
}
versionToPass(versionId: string) {
return versionId.replace(this.remotePrefix, "")
}
versionDisplayString(versionId: string) {
return this.isRemote(versionId) ? `${this.versionToPass(versionId)} on ${this.props.otherEnvironment}` : versionId
}
createVersionElement(version: ProcessVersionType, versionPrefix = "") {
const versionId = versionPrefix + version.processVersionId
return (
<option key={versionId} value={versionId}>
{this.versionDisplayString(versionId)} - created by {version.user} {formatAbsolutely(version.createDate)}</option>
)
}
render() {
return (
<>
<div className="esp-form-row">
<p>Version to compare</p>
<SelectWithFocus
autoFocus={true}
id="otherVersion"
className="node-input"
value={this.state.otherVersion || ""}
onChange={(e) => this.loadVersion(e.target.value)}
>
<option key="" value=""/>
{this.props.versions.filter(version => this.props.version !== version.processVersionId)
.map(version => this.createVersionElement(version))}
{this.state.remoteVersions.map(version => this.createVersionElement(version, this.remotePrefix))}
</SelectWithFocus>
</div>
{
this.state.otherVersion ?
(
<div>
<div className="esp-form-row">
<p>Difference to pick</p>
<SelectWithFocus
id="otherVersion"
className="node-input"
value={this.state.currentDiffId || ""}
onChange={(e) => this.setState({currentDiffId: e.target.value})}
>
<option key="" value=""/>
{_.keys(this.state.difference).map((diffId) => {
const isLayoutOnly = this.isLayoutChangeOnly(diffId)
return (
<option key={diffId} value={diffId} disabled={isLayoutOnly}>{diffId} {isLayoutOnly && "(position only)"}</option>)
})}
</SelectWithFocus>
</div>
{this.state.currentDiffId ?
this.printDiff(this.state.currentDiffId) :
null}
</div>
) :
null
}
</>
)
}
printDiff(diffId) {
const diff = this.state.difference[diffId]
switch (diff.type) {
case "NodeNotPresentInOther":
case "NodeNotPresentInCurrent":
case "NodeDifferent":
return this.renderDiff(diff.currentNode, diff.otherNode, this.printNode)
case "EdgeNotPresentInCurrent":
case "EdgeNotPresentInOther":
case "EdgeDifferent":
return this.renderDiff(diff.currentEdge, diff.otherEdge, this.printEdge)
case "PropertiesDifferent":
return this.renderDiff(diff.currentProperties, diff.otherProperties, this.printProperties)
default:
console.error(`Difference type ${diff.type} is not supported`)
}
}
renderDiff(currentElement, otherElement, printElement) {
const differentPaths = this.differentPathsForObjects(currentElement, otherElement)
return (
<div className="compareContainer">
<div> | <div className="versionHeader">Version {this.versionDisplayString(this.state.otherVersion)}</div>
{printElement(otherElement, [])}
</div>
</div>
)
}
differentPathsForObjects(currentNode, otherNode) {
const diffObject = JsonUtils.objectDiff(currentNode, otherNode)
const flattenObj = JsonUtils.flattenObj(diffObject)
return _.keys(flattenObj)
}
printNode(node, pathsToMark) {
return node ?
(
<NodeDetailsContent
isEditMode={false}
showValidation={false}
showSwitch={false}
node={node}
pathsToMark={pathsToMark}
onChange={() => {return}}
/>
) :
(<div className="notPresent">Node not present</div>)
}
printEdge(edge, pathsToMark) {
return edge ?
(
<EdgeDetailsContent
edge={edge}
readOnly={true}
showValidation={false}
showSwitch={false}
changeEdgeTypeValue={() => {return}}
changeEdgeTypeCondition={() => {return}}
pathsToMark={pathsToMark}
variableTypes={{}}
/>
) :
(<div className="notPresent">Edge not present</div>)
}
printProperties(property, pathsToMark) {
return property ?
(
<NodeDetailsContent
isEditMode={false}
showValidation={false}
showSwitch={false}
node={property}
pathsToMark={pathsToMark}
onChange={() => {return}}
/>
) :
(<div className="notPresent">Properties not present</div>)
}
}
function mapState(state) {
return {
processId: getProcessId(state),
version: getProcessVersionId(state),
otherEnvironment: getTargetEnvironmentId(state),
versions: getVersions(state),
}
}
type Props = ReturnType<typeof mapState>
//TODO: move to hooks
const CompareVersionsForm = connect(mapState)(VersionsForm)
export function CompareVersionsDialog(props: WindowContentProps): JSX.Element {
return (
<WindowContent {...props}>
<div className={cx("compareModal", "modalContentDark", css({minWidth: 980, padding: "1em"}))}>
<CompareVersionsForm/>
</div>
</WindowContent>
)
} | <div className="versionHeader">Current version</div>
{printElement(currentElement, differentPaths)}
</div>
<div> | random_line_split |
CompareVersionsDialog.tsx | /* eslint-disable i18next/no-literal-string */
import {css, cx} from "@emotion/css"
import {WindowContentProps} from "@touk/window-manager"
import _ from "lodash"
import React from "react"
import {connect} from "react-redux"
import {formatAbsolutely} from "../../common/DateUtils"
import * as JsonUtils from "../../common/JsonUtils"
import HttpService from "../../http/HttpService"
import {getProcessId, getProcessVersionId, getVersions} from "../../reducers/selectors/graph"
import {getTargetEnvironmentId} from "../../reducers/selectors/settings"
import "../../stylesheets/visualization.styl"
import {WindowContent} from "../../windowManager"
import EdgeDetailsContent from "../graph/node-modal/edge/EdgeDetailsContent"
import NodeDetailsContent from "../graph/node-modal/NodeDetailsContent"
import {ProcessVersionType} from "../Process/types"
import {SelectWithFocus} from "../withFocus"
interface State {
currentDiffId: string,
otherVersion: string,
remoteVersions: ProcessVersionType[],
difference: unknown,
}
//TODO: handle different textarea heights
class VersionsForm extends React.Component<Props, State> {
//TODO: better way of detecting remote version? also: how to sort versions??
remotePrefix = "remote-"
initState: State = {
otherVersion: null,
currentDiffId: null,
difference: null,
remoteVersions: [],
}
state = this.initState
isLayoutChangeOnly(diffId: string): boolean {
const {type, currentNode, otherNode} = this.state.difference[diffId]
if (type === "NodeDifferent") {
return this.differentPathsForObjects(currentNode, otherNode).every(path => path.startsWith("additionalFields.layoutData"))
}
}
componentDidMount() {
if (this.props.processId && this.props.otherEnvironment) {
HttpService.fetchRemoteVersions(this.props.processId).then(response => this.setState({remoteVersions: response.data || []}))
}
}
loadVersion(versionId: string) {
if (versionId) {
HttpService.compareProcesses(
this.props.processId,
this.props.version,
this.versionToPass(versionId),
this.isRemote(versionId),
).then(
(response) => this.setState({difference: response.data, otherVersion: versionId, currentDiffId: null}),
)
} else {
this.setState(this.initState)
}
}
isRemote(versionId: string) {
return versionId.startsWith(this.remotePrefix)
}
versionToPass(versionId: string) {
return versionId.replace(this.remotePrefix, "")
}
versionDisplayString(versionId: string) {
return this.isRemote(versionId) ? `${this.versionToPass(versionId)} on ${this.props.otherEnvironment}` : versionId
}
createVersionElement(version: ProcessVersionType, versionPrefix = "") {
const versionId = versionPrefix + version.processVersionId
return (
<option key={versionId} value={versionId}>
{this.versionDisplayString(versionId)} - created by {version.user} {formatAbsolutely(version.createDate)}</option>
)
}
render() | >
<CompareVersionsForm/>
</div>
</WindowContent>
)
}
| {
return (
<>
<div className="esp-form-row">
<p>Version to compare</p>
<SelectWithFocus
autoFocus={true}
id="otherVersion"
className="node-input"
value={this.state.otherVersion || ""}
onChange={(e) => this.loadVersion(e.target.value)}
>
<option key="" value=""/>
{this.props.versions.filter(version => this.props.version !== version.processVersionId)
.map(version => this.createVersionElement(version))}
{this.state.remoteVersions.map(version => this.createVersionElement(version, this.remotePrefix))}
</SelectWithFocus>
</div>
{
this.state.otherVersion ?
(
<div>
<div className="esp-form-row">
<p>Difference to pick</p>
<SelectWithFocus
id="otherVersion"
className="node-input"
value={this.state.currentDiffId || ""}
onChange={(e) => this.setState({currentDiffId: e.target.value})}
>
<option key="" value=""/>
{_.keys(this.state.difference).map((diffId) => {
const isLayoutOnly = this.isLayoutChangeOnly(diffId)
return (
<option key={diffId} value={diffId} disabled={isLayoutOnly}>{diffId} {isLayoutOnly && "(position only)"}</option>)
})}
</SelectWithFocus>
</div>
{this.state.currentDiffId ?
this.printDiff(this.state.currentDiffId) :
null}
</div>
) :
null
}
</>
)
}
printDiff(diffId) {
const diff = this.state.difference[diffId]
switch (diff.type) {
case "NodeNotPresentInOther":
case "NodeNotPresentInCurrent":
case "NodeDifferent":
return this.renderDiff(diff.currentNode, diff.otherNode, this.printNode)
case "EdgeNotPresentInCurrent":
case "EdgeNotPresentInOther":
case "EdgeDifferent":
return this.renderDiff(diff.currentEdge, diff.otherEdge, this.printEdge)
case "PropertiesDifferent":
return this.renderDiff(diff.currentProperties, diff.otherProperties, this.printProperties)
default:
console.error(`Difference type ${diff.type} is not supported`)
}
}
renderDiff(currentElement, otherElement, printElement) {
const differentPaths = this.differentPathsForObjects(currentElement, otherElement)
return (
<div className="compareContainer">
<div>
<div className="versionHeader">Current version</div>
{printElement(currentElement, differentPaths)}
</div>
<div>
<div className="versionHeader">Version {this.versionDisplayString(this.state.otherVersion)}</div>
{printElement(otherElement, [])}
</div>
</div>
)
}
differentPathsForObjects(currentNode, otherNode) {
const diffObject = JsonUtils.objectDiff(currentNode, otherNode)
const flattenObj = JsonUtils.flattenObj(diffObject)
return _.keys(flattenObj)
}
printNode(node, pathsToMark) {
return node ?
(
<NodeDetailsContent
isEditMode={false}
showValidation={false}
showSwitch={false}
node={node}
pathsToMark={pathsToMark}
onChange={() => {return}}
/>
) :
(<div className="notPresent">Node not present</div>)
}
printEdge(edge, pathsToMark) {
return edge ?
(
<EdgeDetailsContent
edge={edge}
readOnly={true}
showValidation={false}
showSwitch={false}
changeEdgeTypeValue={() => {return}}
changeEdgeTypeCondition={() => {return}}
pathsToMark={pathsToMark}
variableTypes={{}}
/>
) :
(<div className="notPresent">Edge not present</div>)
}
printProperties(property, pathsToMark) {
return property ?
(
<NodeDetailsContent
isEditMode={false}
showValidation={false}
showSwitch={false}
node={property}
pathsToMark={pathsToMark}
onChange={() => {return}}
/>
) :
(<div className="notPresent">Properties not present</div>)
}
}
function mapState(state) {
return {
processId: getProcessId(state),
version: getProcessVersionId(state),
otherEnvironment: getTargetEnvironmentId(state),
versions: getVersions(state),
}
}
type Props = ReturnType<typeof mapState>
//TODO: move to hooks
const CompareVersionsForm = connect(mapState)(VersionsForm)
export function CompareVersionsDialog(props: WindowContentProps): JSX.Element {
return (
<WindowContent {...props}>
<div className={cx("compareModal", "modalContentDark", css({minWidth: 980, padding: "1em"}))} | identifier_body |
CompareVersionsDialog.tsx | /* eslint-disable i18next/no-literal-string */
import {css, cx} from "@emotion/css"
import {WindowContentProps} from "@touk/window-manager"
import _ from "lodash"
import React from "react"
import {connect} from "react-redux"
import {formatAbsolutely} from "../../common/DateUtils"
import * as JsonUtils from "../../common/JsonUtils"
import HttpService from "../../http/HttpService"
import {getProcessId, getProcessVersionId, getVersions} from "../../reducers/selectors/graph"
import {getTargetEnvironmentId} from "../../reducers/selectors/settings"
import "../../stylesheets/visualization.styl"
import {WindowContent} from "../../windowManager"
import EdgeDetailsContent from "../graph/node-modal/edge/EdgeDetailsContent"
import NodeDetailsContent from "../graph/node-modal/NodeDetailsContent"
import {ProcessVersionType} from "../Process/types"
import {SelectWithFocus} from "../withFocus"
interface State {
currentDiffId: string,
otherVersion: string,
remoteVersions: ProcessVersionType[],
difference: unknown,
}
//TODO: handle different textarea heights
class VersionsForm extends React.Component<Props, State> {
//TODO: better way of detecting remote version? also: how to sort versions??
remotePrefix = "remote-"
initState: State = {
otherVersion: null,
currentDiffId: null,
difference: null,
remoteVersions: [],
}
state = this.initState
isLayoutChangeOnly(diffId: string): boolean {
const {type, currentNode, otherNode} = this.state.difference[diffId]
if (type === "NodeDifferent") {
return this.differentPathsForObjects(currentNode, otherNode).every(path => path.startsWith("additionalFields.layoutData"))
}
}
componentDidMount() {
if (this.props.processId && this.props.otherEnvironment) {
HttpService.fetchRemoteVersions(this.props.processId).then(response => this.setState({remoteVersions: response.data || []}))
}
}
loadVersion(versionId: string) {
if (versionId) {
HttpService.compareProcesses(
this.props.processId,
this.props.version,
this.versionToPass(versionId),
this.isRemote(versionId),
).then(
(response) => this.setState({difference: response.data, otherVersion: versionId, currentDiffId: null}),
)
} else {
this.setState(this.initState)
}
}
isRemote(versionId: string) {
return versionId.startsWith(this.remotePrefix)
}
versionToPass(versionId: string) {
return versionId.replace(this.remotePrefix, "")
}
versionDisplayString(versionId: string) {
return this.isRemote(versionId) ? `${this.versionToPass(versionId)} on ${this.props.otherEnvironment}` : versionId
}
| (version: ProcessVersionType, versionPrefix = "") {
const versionId = versionPrefix + version.processVersionId
return (
<option key={versionId} value={versionId}>
{this.versionDisplayString(versionId)} - created by {version.user} {formatAbsolutely(version.createDate)}</option>
)
}
render() {
return (
<>
<div className="esp-form-row">
<p>Version to compare</p>
<SelectWithFocus
autoFocus={true}
id="otherVersion"
className="node-input"
value={this.state.otherVersion || ""}
onChange={(e) => this.loadVersion(e.target.value)}
>
<option key="" value=""/>
{this.props.versions.filter(version => this.props.version !== version.processVersionId)
.map(version => this.createVersionElement(version))}
{this.state.remoteVersions.map(version => this.createVersionElement(version, this.remotePrefix))}
</SelectWithFocus>
</div>
{
this.state.otherVersion ?
(
<div>
<div className="esp-form-row">
<p>Difference to pick</p>
<SelectWithFocus
id="otherVersion"
className="node-input"
value={this.state.currentDiffId || ""}
onChange={(e) => this.setState({currentDiffId: e.target.value})}
>
<option key="" value=""/>
{_.keys(this.state.difference).map((diffId) => {
const isLayoutOnly = this.isLayoutChangeOnly(diffId)
return (
<option key={diffId} value={diffId} disabled={isLayoutOnly}>{diffId} {isLayoutOnly && "(position only)"}</option>)
})}
</SelectWithFocus>
</div>
{this.state.currentDiffId ?
this.printDiff(this.state.currentDiffId) :
null}
</div>
) :
null
}
</>
)
}
printDiff(diffId) {
const diff = this.state.difference[diffId]
switch (diff.type) {
case "NodeNotPresentInOther":
case "NodeNotPresentInCurrent":
case "NodeDifferent":
return this.renderDiff(diff.currentNode, diff.otherNode, this.printNode)
case "EdgeNotPresentInCurrent":
case "EdgeNotPresentInOther":
case "EdgeDifferent":
return this.renderDiff(diff.currentEdge, diff.otherEdge, this.printEdge)
case "PropertiesDifferent":
return this.renderDiff(diff.currentProperties, diff.otherProperties, this.printProperties)
default:
console.error(`Difference type ${diff.type} is not supported`)
}
}
renderDiff(currentElement, otherElement, printElement) {
const differentPaths = this.differentPathsForObjects(currentElement, otherElement)
return (
<div className="compareContainer">
<div>
<div className="versionHeader">Current version</div>
{printElement(currentElement, differentPaths)}
</div>
<div>
<div className="versionHeader">Version {this.versionDisplayString(this.state.otherVersion)}</div>
{printElement(otherElement, [])}
</div>
</div>
)
}
differentPathsForObjects(currentNode, otherNode) {
const diffObject = JsonUtils.objectDiff(currentNode, otherNode)
const flattenObj = JsonUtils.flattenObj(diffObject)
return _.keys(flattenObj)
}
printNode(node, pathsToMark) {
return node ?
(
<NodeDetailsContent
isEditMode={false}
showValidation={false}
showSwitch={false}
node={node}
pathsToMark={pathsToMark}
onChange={() => {return}}
/>
) :
(<div className="notPresent">Node not present</div>)
}
printEdge(edge, pathsToMark) {
return edge ?
(
<EdgeDetailsContent
edge={edge}
readOnly={true}
showValidation={false}
showSwitch={false}
changeEdgeTypeValue={() => {return}}
changeEdgeTypeCondition={() => {return}}
pathsToMark={pathsToMark}
variableTypes={{}}
/>
) :
(<div className="notPresent">Edge not present</div>)
}
printProperties(property, pathsToMark) {
return property ?
(
<NodeDetailsContent
isEditMode={false}
showValidation={false}
showSwitch={false}
node={property}
pathsToMark={pathsToMark}
onChange={() => {return}}
/>
) :
(<div className="notPresent">Properties not present</div>)
}
}
function mapState(state) {
return {
processId: getProcessId(state),
version: getProcessVersionId(state),
otherEnvironment: getTargetEnvironmentId(state),
versions: getVersions(state),
}
}
type Props = ReturnType<typeof mapState>
//TODO: move to hooks
const CompareVersionsForm = connect(mapState)(VersionsForm)
export function CompareVersionsDialog(props: WindowContentProps): JSX.Element {
return (
<WindowContent {...props}>
<div className={cx("compareModal", "modalContentDark", css({minWidth: 980, padding: "1em"}))}>
<CompareVersionsForm/>
</div>
</WindowContent>
)
}
| createVersionElement | identifier_name |
p3starscreen.py | #!/usr/bin/env python
import os
import sys
import argparse
import pat3dem.star as p3s
def main():
|
if __name__ == '__main__':
main()
| progname = os.path.basename(sys.argv[0])
usage = progname + """ [options] <a star file>
Write two star files after screening by an item and a cutoff in the star file.
Write one star file after screening by a file containing blacklist/whitelist (either keyword or item).
"""
args_def = {'screen':'0', 'cutoff':'00', 'sfile':'0', 'white':0}
parser = argparse.ArgumentParser()
parser.add_argument("star", nargs='*', help="specify a star file to be screened")
parser.add_argument("-s", "--screen", type=str, help="specify the item, by which the star file will be screened, by default {} (no screening). e.g., 'OriginX'".format(args_def['screen']))
parser.add_argument("-c", "--cutoff", type=str, help="specify the cutoff, by default '{}' (-s and -sf will be combined)".format(args_def['cutoff']))
parser.add_argument("-sf", "--sfile", type=str, help="specify a file containing a keyword each line, by default '{}' (no screening). e.g., 'f.txt'".format(args_def['sfile']))
parser.add_argument("-w", "--white", type=int, help="specify as 1 if you provide a whitelist in -sf".format(args_def['white']))
args = parser.parse_args()
if len(sys.argv) == 1:
print "usage: " + usage
print "Please run '" + progname + " -h' for detailed options."
sys.exit(1)
# get default values
for i in args_def:
if args.__dict__[i] == None:
args.__dict__[i] = args_def[i]
# preprocess -sf
if args.sfile != '0':
lines_sf = open(args.sfile).readlines()
lines_sfile = []
for line in lines_sf:
line = line.strip()
if line != '':
lines_sfile += [line]
# get the star file
star = args.star[0]
basename = os.path.basename(os.path.splitext(star)[0])
star_dict = p3s.star_parse(star, 'data_')
header = star_dict['data_'] + star_dict['loop_']
header_len = len(header)
with open(star) as read_star:
lines = read_star.readlines()[header_len:-1]
if args.screen != '0':
# get the sc number
scn = star_dict['_rln'+args.screen]
if args.cutoff != '00':
# Name the output files
screened1 = '{}_screened_{}-gt-{}.star'.format(basename, args.screen, args.cutoff)
screened2 = '{}_screened_{}-le-{}.star'.format(basename, args.screen, args.cutoff)
write_screen1 = open(screened1, 'w')
write_screen1.write(''.join(header))
write_screen2 = open(screened2, 'w')
write_screen2.write(''.join(header))
for line in lines:
if float(line.split()[scn]) > float(args.cutoff):
write_screen1.write(line)
else:
write_screen2.write(line)
write_screen1.write(' \n')
write_screen1.close()
write_screen2.write(' \n')
write_screen2.close()
print 'The screened star files have been written in {} and {}!'.format(screened1, screened2)
elif args.sfile != '0':
with open('{}_screened.star'.format(basename), 'w') as write_screen:
write_screen.write(''.join(header))
if args.white == 0:
for line in lines:
key = line.split()[scn]
if key not in lines_sfile:
print 'Include {}.'.format(key)
write_screen.write(line)
else:
for line in lines:
key = line.split()[scn]
if key in lines_sfile:
print 'Include {}.'.format(key)
write_screen.write(line)
write_screen.write(' \n')
elif args.sfile != '0':
with open('{}_screened.star'.format(basename), 'w') as write_screen:
write_screen.write(''.join(header))
if args.white == 0:
for line in lines:
skip = 0
for key in lines_sfile:
if key in line:
skip = 1
print 'Skip {}.'.format(key)
break
if skip == 0:
write_screen.write(line)
else:
for line in lines:
for key in lines_sfile:
if key in line:
print 'Include {}.'.format(key)
write_screen.write(line)
break
write_screen.write(' \n') | identifier_body |
p3starscreen.py | #!/usr/bin/env python
import os
import sys
import argparse
import pat3dem.star as p3s
def | ():
progname = os.path.basename(sys.argv[0])
usage = progname + """ [options] <a star file>
Write two star files after screening by an item and a cutoff in the star file.
Write one star file after screening by a file containing blacklist/whitelist (either keyword or item).
"""
args_def = {'screen':'0', 'cutoff':'00', 'sfile':'0', 'white':0}
parser = argparse.ArgumentParser()
parser.add_argument("star", nargs='*', help="specify a star file to be screened")
parser.add_argument("-s", "--screen", type=str, help="specify the item, by which the star file will be screened, by default {} (no screening). e.g., 'OriginX'".format(args_def['screen']))
parser.add_argument("-c", "--cutoff", type=str, help="specify the cutoff, by default '{}' (-s and -sf will be combined)".format(args_def['cutoff']))
parser.add_argument("-sf", "--sfile", type=str, help="specify a file containing a keyword each line, by default '{}' (no screening). e.g., 'f.txt'".format(args_def['sfile']))
parser.add_argument("-w", "--white", type=int, help="specify as 1 if you provide a whitelist in -sf".format(args_def['white']))
args = parser.parse_args()
if len(sys.argv) == 1:
print "usage: " + usage
print "Please run '" + progname + " -h' for detailed options."
sys.exit(1)
# get default values
for i in args_def:
if args.__dict__[i] == None:
args.__dict__[i] = args_def[i]
# preprocess -sf
if args.sfile != '0':
lines_sf = open(args.sfile).readlines()
lines_sfile = []
for line in lines_sf:
line = line.strip()
if line != '':
lines_sfile += [line]
# get the star file
star = args.star[0]
basename = os.path.basename(os.path.splitext(star)[0])
star_dict = p3s.star_parse(star, 'data_')
header = star_dict['data_'] + star_dict['loop_']
header_len = len(header)
with open(star) as read_star:
lines = read_star.readlines()[header_len:-1]
if args.screen != '0':
# get the sc number
scn = star_dict['_rln'+args.screen]
if args.cutoff != '00':
# Name the output files
screened1 = '{}_screened_{}-gt-{}.star'.format(basename, args.screen, args.cutoff)
screened2 = '{}_screened_{}-le-{}.star'.format(basename, args.screen, args.cutoff)
write_screen1 = open(screened1, 'w')
write_screen1.write(''.join(header))
write_screen2 = open(screened2, 'w')
write_screen2.write(''.join(header))
for line in lines:
if float(line.split()[scn]) > float(args.cutoff):
write_screen1.write(line)
else:
write_screen2.write(line)
write_screen1.write(' \n')
write_screen1.close()
write_screen2.write(' \n')
write_screen2.close()
print 'The screened star files have been written in {} and {}!'.format(screened1, screened2)
elif args.sfile != '0':
with open('{}_screened.star'.format(basename), 'w') as write_screen:
write_screen.write(''.join(header))
if args.white == 0:
for line in lines:
key = line.split()[scn]
if key not in lines_sfile:
print 'Include {}.'.format(key)
write_screen.write(line)
else:
for line in lines:
key = line.split()[scn]
if key in lines_sfile:
print 'Include {}.'.format(key)
write_screen.write(line)
write_screen.write(' \n')
elif args.sfile != '0':
with open('{}_screened.star'.format(basename), 'w') as write_screen:
write_screen.write(''.join(header))
if args.white == 0:
for line in lines:
skip = 0
for key in lines_sfile:
if key in line:
skip = 1
print 'Skip {}.'.format(key)
break
if skip == 0:
write_screen.write(line)
else:
for line in lines:
for key in lines_sfile:
if key in line:
print 'Include {}.'.format(key)
write_screen.write(line)
break
write_screen.write(' \n')
if __name__ == '__main__':
main()
| main | identifier_name |
p3starscreen.py | #!/usr/bin/env python
import os
import sys
import argparse
import pat3dem.star as p3s
def main():
progname = os.path.basename(sys.argv[0])
usage = progname + """ [options] <a star file>
Write two star files after screening by an item and a cutoff in the star file.
Write one star file after screening by a file containing blacklist/whitelist (either keyword or item).
"""
args_def = {'screen':'0', 'cutoff':'00', 'sfile':'0', 'white':0}
parser = argparse.ArgumentParser()
parser.add_argument("star", nargs='*', help="specify a star file to be screened")
parser.add_argument("-s", "--screen", type=str, help="specify the item, by which the star file will be screened, by default {} (no screening). e.g., 'OriginX'".format(args_def['screen']))
parser.add_argument("-c", "--cutoff", type=str, help="specify the cutoff, by default '{}' (-s and -sf will be combined)".format(args_def['cutoff']))
parser.add_argument("-sf", "--sfile", type=str, help="specify a file containing a keyword each line, by default '{}' (no screening). e.g., 'f.txt'".format(args_def['sfile']))
parser.add_argument("-w", "--white", type=int, help="specify as 1 if you provide a whitelist in -sf".format(args_def['white']))
args = parser.parse_args()
if len(sys.argv) == 1:
print "usage: " + usage
print "Please run '" + progname + " -h' for detailed options."
sys.exit(1)
# get default values
for i in args_def:
if args.__dict__[i] == None:
args.__dict__[i] = args_def[i]
# preprocess -sf
if args.sfile != '0':
lines_sf = open(args.sfile).readlines()
lines_sfile = []
for line in lines_sf:
line = line.strip()
if line != '':
lines_sfile += [line]
# get the star file
star = args.star[0]
basename = os.path.basename(os.path.splitext(star)[0])
star_dict = p3s.star_parse(star, 'data_')
header = star_dict['data_'] + star_dict['loop_']
header_len = len(header)
with open(star) as read_star:
lines = read_star.readlines()[header_len:-1]
if args.screen != '0':
# get the sc number
scn = star_dict['_rln'+args.screen]
if args.cutoff != '00':
# Name the output files
screened1 = '{}_screened_{}-gt-{}.star'.format(basename, args.screen, args.cutoff)
screened2 = '{}_screened_{}-le-{}.star'.format(basename, args.screen, args.cutoff)
write_screen1 = open(screened1, 'w')
write_screen1.write(''.join(header))
write_screen2 = open(screened2, 'w')
write_screen2.write(''.join(header))
for line in lines:
if float(line.split()[scn]) > float(args.cutoff):
write_screen1.write(line)
else:
write_screen2.write(line)
write_screen1.write(' \n')
write_screen1.close()
write_screen2.write(' \n')
write_screen2.close()
print 'The screened star files have been written in {} and {}!'.format(screened1, screened2)
elif args.sfile != '0':
with open('{}_screened.star'.format(basename), 'w') as write_screen:
write_screen.write(''.join(header))
if args.white == 0:
for line in lines:
key = line.split()[scn]
if key not in lines_sfile:
print 'Include {}.'.format(key)
write_screen.write(line)
else:
for line in lines:
key = line.split()[scn]
if key in lines_sfile:
|
write_screen.write(' \n')
elif args.sfile != '0':
with open('{}_screened.star'.format(basename), 'w') as write_screen:
write_screen.write(''.join(header))
if args.white == 0:
for line in lines:
skip = 0
for key in lines_sfile:
if key in line:
skip = 1
print 'Skip {}.'.format(key)
break
if skip == 0:
write_screen.write(line)
else:
for line in lines:
for key in lines_sfile:
if key in line:
print 'Include {}.'.format(key)
write_screen.write(line)
break
write_screen.write(' \n')
if __name__ == '__main__':
main()
| print 'Include {}.'.format(key)
write_screen.write(line) | conditional_block |
p3starscreen.py | #!/usr/bin/env python
import os
import sys
import argparse
import pat3dem.star as p3s
def main():
progname = os.path.basename(sys.argv[0])
usage = progname + """ [options] <a star file>
Write two star files after screening by an item and a cutoff in the star file.
Write one star file after screening by a file containing blacklist/whitelist (either keyword or item).
"""
args_def = {'screen':'0', 'cutoff':'00', 'sfile':'0', 'white':0}
parser = argparse.ArgumentParser()
parser.add_argument("star", nargs='*', help="specify a star file to be screened")
parser.add_argument("-s", "--screen", type=str, help="specify the item, by which the star file will be screened, by default {} (no screening). e.g., 'OriginX'".format(args_def['screen']))
parser.add_argument("-c", "--cutoff", type=str, help="specify the cutoff, by default '{}' (-s and -sf will be combined)".format(args_def['cutoff']))
parser.add_argument("-sf", "--sfile", type=str, help="specify a file containing a keyword each line, by default '{}' (no screening). e.g., 'f.txt'".format(args_def['sfile']))
parser.add_argument("-w", "--white", type=int, help="specify as 1 if you provide a whitelist in -sf".format(args_def['white']))
args = parser.parse_args()
if len(sys.argv) == 1:
print "usage: " + usage
print "Please run '" + progname + " -h' for detailed options."
sys.exit(1)
# get default values
for i in args_def:
if args.__dict__[i] == None:
args.__dict__[i] = args_def[i]
# preprocess -sf
if args.sfile != '0':
lines_sf = open(args.sfile).readlines()
lines_sfile = []
for line in lines_sf:
line = line.strip()
if line != '':
lines_sfile += [line]
# get the star file
star = args.star[0]
basename = os.path.basename(os.path.splitext(star)[0])
star_dict = p3s.star_parse(star, 'data_')
header = star_dict['data_'] + star_dict['loop_']
header_len = len(header)
with open(star) as read_star:
lines = read_star.readlines()[header_len:-1]
if args.screen != '0':
# get the sc number
scn = star_dict['_rln'+args.screen]
if args.cutoff != '00':
# Name the output files
screened1 = '{}_screened_{}-gt-{}.star'.format(basename, args.screen, args.cutoff)
screened2 = '{}_screened_{}-le-{}.star'.format(basename, args.screen, args.cutoff)
write_screen1 = open(screened1, 'w')
write_screen1.write(''.join(header))
write_screen2 = open(screened2, 'w')
write_screen2.write(''.join(header))
for line in lines:
if float(line.split()[scn]) > float(args.cutoff):
write_screen1.write(line)
else:
write_screen2.write(line)
write_screen1.write(' \n')
write_screen1.close()
write_screen2.write(' \n')
write_screen2.close()
print 'The screened star files have been written in {} and {}!'.format(screened1, screened2)
elif args.sfile != '0':
with open('{}_screened.star'.format(basename), 'w') as write_screen:
write_screen.write(''.join(header))
if args.white == 0:
for line in lines:
key = line.split()[scn]
if key not in lines_sfile:
print 'Include {}.'.format(key)
write_screen.write(line)
else:
for line in lines:
key = line.split()[scn]
if key in lines_sfile:
print 'Include {}.'.format(key)
write_screen.write(line)
write_screen.write(' \n') | if args.white == 0:
for line in lines:
skip = 0
for key in lines_sfile:
if key in line:
skip = 1
print 'Skip {}.'.format(key)
break
if skip == 0:
write_screen.write(line)
else:
for line in lines:
for key in lines_sfile:
if key in line:
print 'Include {}.'.format(key)
write_screen.write(line)
break
write_screen.write(' \n')
if __name__ == '__main__':
main() | elif args.sfile != '0':
with open('{}_screened.star'.format(basename), 'w') as write_screen:
write_screen.write(''.join(header)) | random_line_split |
mod.rs | pub use self::mouse_joint::{MouseJointConfig, MouseJoint};
use std::rc::{Rc, Weak};
use std::cell::RefCell;
use std::mem;
use std::ptr;
use super::{Body, BodyHandleWeak};
use super::island::{Position, Velocity};
use ::dynamics::world::TimeStep;
mod mouse_joint;
pub type JointHandle<'a> = Rc<RefCell<Joint<'a>>>;
pub type JointHandleWeak<'a> = Weak<RefCell<Joint<'a>>>;
/// A joint edge is used to connect bodies and joints together in a joint graph where
/// each body is a node and each joint is an edge. Each joint has two joint nodes,
/// one for each attached body.
pub struct JointEdge<'a> {
pub body: BodyHandleWeak<'a>,
pub joint: JointHandleWeak<'a>,
}
pub enum JointType {
Mouse(MouseJointConfig),
}
/// `JointConfig`s are used to construct joints.
pub struct JointConfig<'a> {
pub joint_type: JointType,
/// The first attached body.
pub body_a: BodyHandleWeak<'a>,
/// The second attached body.
pub body_b: BodyHandleWeak<'a>,
/// Set this flag to true if the attached bodies should collide.
pub collide_connected: bool,
}
pub struct JointData<'a> {
body_a: BodyHandleWeak<'a>,
body_b: BodyHandleWeak<'a>,
is_island: bool,
is_collide_connected: bool,
}
pub enum Joint<'a> {
Mouse(MouseJoint<'a>),
}
impl<'a> Joint<'a> {
/*pub fn new(joint_config: &JointConfig<'a>) -> JointHandle<'a> {
let result: JointHandle<'a>;
unsafe {
result = Rc::new(RefCell::new(mem::uninitialized()));
let edge_to_a = JointEdge {
body: joint_config.body_a.clone(),
joint: Rc::downgrade(&result),
};
let edge_to_b = JointEdge {
body: joint_config.body_b.clone(),
joint: Rc::downgrade(&result),
};
let joint_data = JointData {
edge_to_a: edge_to_a,
edge_to_b: edge_to_b,
is_island: false,
is_collide_connected: joint_config.collide_connected,
};
match joint_config.joint_type {
JointType::Mouse(ref joint_config) => {
ptr::write(&mut *result.borrow_mut(), Joint::Mouse(MouseJoint::new(joint_config, joint_data)));
}
}
}
result
}*/
pub fn new(joint_config: &JointConfig<'a>) -> JointHandle<'a> {
let joint_data = JointData {
body_a: joint_config.body_a.clone(),
body_b: joint_config.body_b.clone(),
is_island: false,
is_collide_connected: joint_config.collide_connected,
};
let result;
result = match joint_config.joint_type {
JointType::Mouse(ref joint_config) => Rc::new(RefCell::new(Joint::Mouse(MouseJoint::new(joint_config, joint_data)))),
};
result
}
fn get_joint_data(&self) -> &JointData<'a> {
match self {
&Joint::Mouse(ref joint) => &joint.joint_data,
}
}
fn get_joint_data_mut(&mut self) -> &mut JointData<'a> {
match self {
&mut Joint::Mouse(ref mut joint) => &mut joint.joint_data,
}
}
pub fn get_other_body(&self, body: BodyHandleWeak<'a>) -> Option<BodyHandleWeak<'a>> {
let b = body.upgrade().unwrap();
let pb = &(*b) as *const RefCell<Body>;
let b_a = self.get_joint_data().body_a.upgrade().unwrap();
let pb_a = &(*b_a) as *const RefCell<Body>;
if pb == pb_a {
return Some(self.get_joint_data().body_b.clone());
}
let b_b = self.get_joint_data().body_b.upgrade().unwrap();
let pb_b = &(*b_b) as *const RefCell<Body>;
if pb == pb_b {
return Some(self.get_joint_data().body_a.clone());
}
None
} | self.get_joint_data_mut().is_island = is_island;
}
pub fn is_island(&self) -> bool {
self.get_joint_data().is_island
}
pub fn initialize_velocity_constraints(&mut self, step: TimeStep, positions: &Vec<Position>, velocities: &mut Vec<Velocity>) {
match self {
&mut Joint::Mouse(ref mut joint) => joint.initialize_velocity_constraints(step, positions, velocities),
}
}
pub fn solve_velocity_constraints(&mut self, step: TimeStep, velocities: &mut Vec<Velocity>) {
match self {
&mut Joint::Mouse(ref mut joint) => joint.solve_velocity_constraints(step, velocities),
}
}
/// This returns true if the position errors are within tolerance.
pub fn solve_position_constraints(&mut self, step: TimeStep, positions: &mut Vec<Position>) -> bool {
true
}
} |
pub fn set_island(&mut self, is_island: bool) { | random_line_split |
mod.rs | pub use self::mouse_joint::{MouseJointConfig, MouseJoint};
use std::rc::{Rc, Weak};
use std::cell::RefCell;
use std::mem;
use std::ptr;
use super::{Body, BodyHandleWeak};
use super::island::{Position, Velocity};
use ::dynamics::world::TimeStep;
mod mouse_joint;
pub type JointHandle<'a> = Rc<RefCell<Joint<'a>>>;
pub type JointHandleWeak<'a> = Weak<RefCell<Joint<'a>>>;
/// A joint edge is used to connect bodies and joints together in a joint graph where
/// each body is a node and each joint is an edge. Each joint has two joint nodes,
/// one for each attached body.
pub struct JointEdge<'a> {
pub body: BodyHandleWeak<'a>,
pub joint: JointHandleWeak<'a>,
}
pub enum JointType {
Mouse(MouseJointConfig),
}
/// `JointConfig`s are used to construct joints.
pub struct JointConfig<'a> {
pub joint_type: JointType,
/// The first attached body.
pub body_a: BodyHandleWeak<'a>,
/// The second attached body.
pub body_b: BodyHandleWeak<'a>,
/// Set this flag to true if the attached bodies should collide.
pub collide_connected: bool,
}
pub struct JointData<'a> {
body_a: BodyHandleWeak<'a>,
body_b: BodyHandleWeak<'a>,
is_island: bool,
is_collide_connected: bool,
}
pub enum Joint<'a> {
Mouse(MouseJoint<'a>),
}
impl<'a> Joint<'a> {
/*pub fn new(joint_config: &JointConfig<'a>) -> JointHandle<'a> {
let result: JointHandle<'a>;
unsafe {
result = Rc::new(RefCell::new(mem::uninitialized()));
let edge_to_a = JointEdge {
body: joint_config.body_a.clone(),
joint: Rc::downgrade(&result),
};
let edge_to_b = JointEdge {
body: joint_config.body_b.clone(),
joint: Rc::downgrade(&result),
};
let joint_data = JointData {
edge_to_a: edge_to_a,
edge_to_b: edge_to_b,
is_island: false,
is_collide_connected: joint_config.collide_connected,
};
match joint_config.joint_type {
JointType::Mouse(ref joint_config) => {
ptr::write(&mut *result.borrow_mut(), Joint::Mouse(MouseJoint::new(joint_config, joint_data)));
}
}
}
result
}*/
pub fn new(joint_config: &JointConfig<'a>) -> JointHandle<'a> {
let joint_data = JointData {
body_a: joint_config.body_a.clone(),
body_b: joint_config.body_b.clone(),
is_island: false,
is_collide_connected: joint_config.collide_connected,
};
let result;
result = match joint_config.joint_type {
JointType::Mouse(ref joint_config) => Rc::new(RefCell::new(Joint::Mouse(MouseJoint::new(joint_config, joint_data)))),
};
result
}
fn get_joint_data(&self) -> &JointData<'a> {
match self {
&Joint::Mouse(ref joint) => &joint.joint_data,
}
}
fn get_joint_data_mut(&mut self) -> &mut JointData<'a> {
match self {
&mut Joint::Mouse(ref mut joint) => &mut joint.joint_data,
}
}
pub fn get_other_body(&self, body: BodyHandleWeak<'a>) -> Option<BodyHandleWeak<'a>> {
let b = body.upgrade().unwrap();
let pb = &(*b) as *const RefCell<Body>;
let b_a = self.get_joint_data().body_a.upgrade().unwrap();
let pb_a = &(*b_a) as *const RefCell<Body>;
if pb == pb_a {
return Some(self.get_joint_data().body_b.clone());
}
let b_b = self.get_joint_data().body_b.upgrade().unwrap();
let pb_b = &(*b_b) as *const RefCell<Body>;
if pb == pb_b {
return Some(self.get_joint_data().body_a.clone());
}
None
}
pub fn set_island(&mut self, is_island: bool) {
self.get_joint_data_mut().is_island = is_island;
}
pub fn | (&self) -> bool {
self.get_joint_data().is_island
}
pub fn initialize_velocity_constraints(&mut self, step: TimeStep, positions: &Vec<Position>, velocities: &mut Vec<Velocity>) {
match self {
&mut Joint::Mouse(ref mut joint) => joint.initialize_velocity_constraints(step, positions, velocities),
}
}
pub fn solve_velocity_constraints(&mut self, step: TimeStep, velocities: &mut Vec<Velocity>) {
match self {
&mut Joint::Mouse(ref mut joint) => joint.solve_velocity_constraints(step, velocities),
}
}
/// This returns true if the position errors are within tolerance.
pub fn solve_position_constraints(&mut self, step: TimeStep, positions: &mut Vec<Position>) -> bool {
true
}
}
| is_island | identifier_name |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use channel::diem_channel::{self, Receiver};
use diem_config::{
config::{Peer, PeerRole},
network_id::NetworkContext,
};
use diem_crypto::x25519::PublicKey;
use diem_logger::prelude::*;
use diem_metrics::{
register_histogram, register_int_counter_vec, register_int_gauge_vec, DurationHistogram,
IntCounterVec, IntGaugeVec,
};
use diem_network_address_encryption::{Encryptor, Error as EncryptorError};
use diem_types::on_chain_config::{OnChainConfigPayload, ValidatorSet, ON_CHAIN_CONFIG_REGISTRY};
use futures::{sink::SinkExt, StreamExt};
use network::{
connectivity_manager::{ConnectivityRequest, DiscoverySource},
counters::inc_by_with_context,
logging::NetworkSchema,
};
use once_cell::sync::Lazy;
use short_hex_str::AsShortHexStr;
use std::{collections::HashSet, sync::Arc};
use subscription_service::ReconfigSubscription;
pub mod builder;
/// Histogram of idle time of spent in event processing loop
pub static EVENT_PROCESSING_LOOP_IDLE_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| {
DurationHistogram::new(
register_histogram!(
"simple_onchain_discovery_event_processing_loop_idle_duration_s",
"Histogram of idle time of spent in event processing loop"
)
.unwrap(),
)
});
/// Histogram of busy time of spent in event processing loop
pub static EVENT_PROCESSING_LOOP_BUSY_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| {
DurationHistogram::new(
register_histogram!(
"simple_onchain_discovery_event_processing_loop_busy_duration_s",
"Histogram of busy time of spent in event processing loop"
)
.unwrap(),
)
});
pub static DISCOVERY_COUNTS: Lazy<IntCounterVec> = Lazy::new(|| {
register_int_counter_vec!(
"diem_simple_onchain_discovery_counts",
"Histogram of busy time of spent in event processing loop",
&["role_type", "network_id", "peer_id", "metric"]
)
.unwrap()
});
pub static NETWORK_KEY_MISMATCH: Lazy<IntGaugeVec> = Lazy::new(|| {
register_int_gauge_vec!(
"diem_network_key_mismatch",
"Gauge of whether the network key mismatches onchain state",
&["role_type", "network_id", "peer_id"]
)
.unwrap()
});
/// Listener which converts published updates from the OnChainConfig to ConnectivityRequests
/// for the ConnectivityManager.
pub struct ConfigurationChangeListener {
network_context: Arc<NetworkContext>,
expected_pubkey: PublicKey,
encryptor: Encryptor,
conn_mgr_reqs_tx: channel::Sender<ConnectivityRequest>,
reconfig_events: diem_channel::Receiver<(), OnChainConfigPayload>,
}
pub fn gen_simple_discovery_reconfig_subscription(
) -> (ReconfigSubscription, Receiver<(), OnChainConfigPayload>) {
ReconfigSubscription::subscribe_all("network", ON_CHAIN_CONFIG_REGISTRY.to_vec(), vec![])
}
/// Extracts a set of ConnectivityRequests from a ValidatorSet which are appropriate for a network with type role.
fn extract_updates(
network_context: Arc<NetworkContext>,
encryptor: &Encryptor,
node_set: ValidatorSet,
) -> Vec<ConnectivityRequest> {
let is_validator = network_context.network_id().is_validator_network();
// Decode addresses while ignoring bad addresses
let discovered_peers = node_set
.into_iter()
.map(|info| {
let peer_id = *info.account_address();
let config = info.into_config();
let addrs = if is_validator {
let result = encryptor.decrypt(&config.validator_network_addresses, peer_id);
if let Err(EncryptorError::StorageError(_)) = result {
panic!(format!(
"Unable to initialize validator network addresses: {:?}",
result
));
}
result.map_err(anyhow::Error::from)
} else {
config
.fullnode_network_addresses()
.map_err(anyhow::Error::from)
}
.map_err(|err| {
inc_by_with_context(&DISCOVERY_COUNTS, &network_context, "read_failure", 1);
warn!(
NetworkSchema::new(&network_context),
"OnChainDiscovery: Failed to parse any network address: peer: {}, err: {}",
peer_id,
err
)
})
.unwrap_or_default();
let peer_role = if is_validator {
PeerRole::Validator
} else {
PeerRole::ValidatorFullNode
};
(peer_id, Peer::from_addrs(peer_role, addrs))
})
.collect();
vec![ConnectivityRequest::UpdateDiscoveredPeers(
DiscoverySource::OnChain,
discovered_peers,
)]
}
impl ConfigurationChangeListener {
/// Creates a new ConfigurationChangeListener
pub fn new(
network_context: Arc<NetworkContext>,
expected_pubkey: PublicKey,
encryptor: Encryptor,
conn_mgr_reqs_tx: channel::Sender<ConnectivityRequest>,
reconfig_events: diem_channel::Receiver<(), OnChainConfigPayload>,
) -> Self {
Self {
network_context,
expected_pubkey,
encryptor,
conn_mgr_reqs_tx,
reconfig_events,
}
}
async fn next_reconfig_event(&mut self) -> Option<OnChainConfigPayload> {
let _idle_timer = EVENT_PROCESSING_LOOP_IDLE_DURATION_S.start_timer();
self.reconfig_events.next().await
}
fn find_key_mismatches(&self, onchain_keys: Option<&HashSet<PublicKey>>) {
let mismatch = onchain_keys.map_or(0, |pubkeys| {
if !pubkeys.contains(&self.expected_pubkey) {
error!(
NetworkSchema::new(&self.network_context),
"Onchain pubkey {:?} differs from local pubkey {}",
pubkeys,
self.expected_pubkey
);
1
} else {
0
}
});
NETWORK_KEY_MISMATCH
.with_label_values(&[
self.network_context.role().as_str(),
self.network_context.network_id().as_str(),
self.network_context.peer_id().short_str().as_str(),
])
.set(mismatch);
}
/// Processes a received OnChainConfigPayload. Depending on role (Validator or FullNode), parses
/// the appropriate configuration changes and passes it to the ConnectionManager channel.
async fn process_payload(&mut self, payload: OnChainConfigPayload) {
let _process_timer = EVENT_PROCESSING_LOOP_BUSY_DURATION_S.start_timer();
let node_set: ValidatorSet = payload
.get()
.expect("failed to get ValidatorSet from payload");
let updates = extract_updates(self.network_context.clone(), &self.encryptor, node_set);
// Ensure that the public key matches what's onchain for this peer
for request in &updates {
if let ConnectivityRequest::UpdateDiscoveredPeers(_, peer_updates) = request {
self.find_key_mismatches(
peer_updates
.get(&self.network_context.peer_id())
.map(|peer| &peer.keys),
)
}
}
inc_by_with_context(
&DISCOVERY_COUNTS,
&self.network_context,
"new_nodes",
updates.len() as u64,
);
info!(
NetworkSchema::new(&self.network_context),
"Update {} Network about new Node IDs",
self.network_context.network_id()
);
for update in updates {
match self.conn_mgr_reqs_tx.send(update).await {
Ok(()) => (),
Err(e) => {
inc_by_with_context(
&DISCOVERY_COUNTS,
&self.network_context,
"send_failure",
1,
);
warn!(
NetworkSchema::new(&self.network_context),
"Failed to send update to ConnectivityManager {}", e
)
}
}
}
}
/// Starts the listener to wait on reconfiguration events.
pub async fn start(mut self) {
info!(
NetworkSchema::new(&self.network_context),
"{} Starting OnChain Discovery actor", self.network_context
); | self.process_payload(payload).await;
}
warn!(
NetworkSchema::new(&self.network_context),
"{} OnChain Discovery actor terminated", self.network_context,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use diem_config::config::HANDSHAKE_VERSION;
use diem_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey},
x25519::PrivateKey,
PrivateKey as PK, Uniform,
};
use diem_types::{
network_address::NetworkAddress, on_chain_config::OnChainConfig,
validator_config::ValidatorConfig, validator_info::ValidatorInfo, PeerId,
};
use futures::executor::block_on;
use rand::{rngs::StdRng, SeedableRng};
use std::{collections::HashMap, time::Instant};
use tokio::{
runtime::Runtime,
time::{timeout_at, Duration},
};
#[test]
fn metric_if_key_mismatch() {
diem_logger::DiemLogger::init_for_testing();
let runtime = Runtime::new().unwrap();
let consensus_private_key = Ed25519PrivateKey::generate_for_testing();
let consensus_pubkey = consensus_private_key.public_key();
let pubkey = test_pubkey([0u8; 32]);
let different_pubkey = test_pubkey([1u8; 32]);
let peer_id = diem_types::account_address::from_identity_public_key(pubkey);
// Build up the Reconfig Listener
let (conn_mgr_reqs_tx, _rx) = channel::new_test(1);
let (mut reconfig_tx, reconfig_rx) = gen_simple_discovery_reconfig_subscription();
let network_context = NetworkContext::mock_with_peer_id(peer_id);
let listener = ConfigurationChangeListener::new(
network_context.clone(),
pubkey,
Encryptor::for_testing(),
conn_mgr_reqs_tx,
reconfig_rx,
);
// Build up and send an update with a different pubkey
send_pubkey_update(
peer_id,
consensus_pubkey,
different_pubkey,
&mut reconfig_tx,
);
let listener_future = async move {
// Run the test, ensuring we actually stop after a couple seconds in case it fails to fail
timeout_at(
tokio::time::Instant::from(Instant::now() + Duration::from_secs(1)),
listener.start(),
)
.await
.expect_err("Expect timeout");
};
// Ensure the metric is updated
check_network_key_mismatch_metric(0, &network_context);
block_on(runtime.spawn(listener_future)).unwrap();
check_network_key_mismatch_metric(1, &network_context);
}
fn check_network_key_mismatch_metric(expected: i64, network_context: &NetworkContext) {
assert_eq!(
expected,
NETWORK_KEY_MISMATCH
.get_metric_with_label_values(&[
network_context.role().as_str(),
network_context.network_id().as_str(),
network_context.peer_id().short_str().as_str()
])
.unwrap()
.get()
)
}
fn send_pubkey_update(
peer_id: PeerId,
consensus_pubkey: Ed25519PublicKey,
pubkey: PublicKey,
reconfig_tx: &mut ReconfigSubscription,
) {
let validator_address =
NetworkAddress::mock().append_prod_protos(pubkey, HANDSHAKE_VERSION);
let addresses = vec![validator_address];
let encryptor = Encryptor::for_testing();
let encrypted_addresses = encryptor.encrypt(&addresses, peer_id, 0).unwrap();
let encoded_addresses = bcs::to_bytes(&addresses).unwrap();
let validator = ValidatorInfo::new(
peer_id,
0,
ValidatorConfig::new(consensus_pubkey, encrypted_addresses, encoded_addresses),
);
let validator_set = ValidatorSet::new(vec![validator]);
let mut configs = HashMap::new();
configs.insert(
ValidatorSet::CONFIG_ID,
bcs::to_bytes(&validator_set).unwrap(),
);
let payload = OnChainConfigPayload::new(1, Arc::new(configs));
reconfig_tx.publish(payload).unwrap();
}
fn test_pubkey(seed: [u8; 32]) -> PublicKey {
let mut rng: StdRng = SeedableRng::from_seed(seed);
let private_key = PrivateKey::generate(&mut rng);
private_key.public_key()
}
} |
while let Some(payload) = self.next_reconfig_event().await { | random_line_split |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use channel::diem_channel::{self, Receiver};
use diem_config::{
config::{Peer, PeerRole},
network_id::NetworkContext,
};
use diem_crypto::x25519::PublicKey;
use diem_logger::prelude::*;
use diem_metrics::{
register_histogram, register_int_counter_vec, register_int_gauge_vec, DurationHistogram,
IntCounterVec, IntGaugeVec,
};
use diem_network_address_encryption::{Encryptor, Error as EncryptorError};
use diem_types::on_chain_config::{OnChainConfigPayload, ValidatorSet, ON_CHAIN_CONFIG_REGISTRY};
use futures::{sink::SinkExt, StreamExt};
use network::{
connectivity_manager::{ConnectivityRequest, DiscoverySource},
counters::inc_by_with_context,
logging::NetworkSchema,
};
use once_cell::sync::Lazy;
use short_hex_str::AsShortHexStr;
use std::{collections::HashSet, sync::Arc};
use subscription_service::ReconfigSubscription;
pub mod builder;
/// Histogram of idle time of spent in event processing loop
pub static EVENT_PROCESSING_LOOP_IDLE_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| {
DurationHistogram::new(
register_histogram!(
"simple_onchain_discovery_event_processing_loop_idle_duration_s",
"Histogram of idle time of spent in event processing loop"
)
.unwrap(),
)
});
/// Histogram of busy time of spent in event processing loop
pub static EVENT_PROCESSING_LOOP_BUSY_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| {
DurationHistogram::new(
register_histogram!(
"simple_onchain_discovery_event_processing_loop_busy_duration_s",
"Histogram of busy time of spent in event processing loop"
)
.unwrap(),
)
});
pub static DISCOVERY_COUNTS: Lazy<IntCounterVec> = Lazy::new(|| {
register_int_counter_vec!(
"diem_simple_onchain_discovery_counts",
"Histogram of busy time of spent in event processing loop",
&["role_type", "network_id", "peer_id", "metric"]
)
.unwrap()
});
pub static NETWORK_KEY_MISMATCH: Lazy<IntGaugeVec> = Lazy::new(|| {
register_int_gauge_vec!(
"diem_network_key_mismatch",
"Gauge of whether the network key mismatches onchain state",
&["role_type", "network_id", "peer_id"]
)
.unwrap()
});
/// Listener which converts published updates from the OnChainConfig to ConnectivityRequests
/// for the ConnectivityManager.
pub struct ConfigurationChangeListener {
network_context: Arc<NetworkContext>,
expected_pubkey: PublicKey,
encryptor: Encryptor,
conn_mgr_reqs_tx: channel::Sender<ConnectivityRequest>,
reconfig_events: diem_channel::Receiver<(), OnChainConfigPayload>,
}
pub fn gen_simple_discovery_reconfig_subscription(
) -> (ReconfigSubscription, Receiver<(), OnChainConfigPayload>) {
ReconfigSubscription::subscribe_all("network", ON_CHAIN_CONFIG_REGISTRY.to_vec(), vec![])
}
/// Extracts a set of ConnectivityRequests from a ValidatorSet which are appropriate for a network with type role.
fn extract_updates(
network_context: Arc<NetworkContext>,
encryptor: &Encryptor,
node_set: ValidatorSet,
) -> Vec<ConnectivityRequest> {
let is_validator = network_context.network_id().is_validator_network();
// Decode addresses while ignoring bad addresses
let discovered_peers = node_set
.into_iter()
.map(|info| {
let peer_id = *info.account_address();
let config = info.into_config();
let addrs = if is_validator {
let result = encryptor.decrypt(&config.validator_network_addresses, peer_id);
if let Err(EncryptorError::StorageError(_)) = result {
panic!(format!(
"Unable to initialize validator network addresses: {:?}",
result
));
}
result.map_err(anyhow::Error::from)
} else {
config
.fullnode_network_addresses()
.map_err(anyhow::Error::from)
}
.map_err(|err| {
inc_by_with_context(&DISCOVERY_COUNTS, &network_context, "read_failure", 1);
warn!(
NetworkSchema::new(&network_context),
"OnChainDiscovery: Failed to parse any network address: peer: {}, err: {}",
peer_id,
err
)
})
.unwrap_or_default();
let peer_role = if is_validator {
PeerRole::Validator
} else {
PeerRole::ValidatorFullNode
};
(peer_id, Peer::from_addrs(peer_role, addrs))
})
.collect();
vec![ConnectivityRequest::UpdateDiscoveredPeers(
DiscoverySource::OnChain,
discovered_peers,
)]
}
impl ConfigurationChangeListener {
/// Creates a new ConfigurationChangeListener
pub fn new(
network_context: Arc<NetworkContext>,
expected_pubkey: PublicKey,
encryptor: Encryptor,
conn_mgr_reqs_tx: channel::Sender<ConnectivityRequest>,
reconfig_events: diem_channel::Receiver<(), OnChainConfigPayload>,
) -> Self {
Self {
network_context,
expected_pubkey,
encryptor,
conn_mgr_reqs_tx,
reconfig_events,
}
}
async fn next_reconfig_event(&mut self) -> Option<OnChainConfigPayload> {
let _idle_timer = EVENT_PROCESSING_LOOP_IDLE_DURATION_S.start_timer();
self.reconfig_events.next().await
}
fn find_key_mismatches(&self, onchain_keys: Option<&HashSet<PublicKey>>) {
let mismatch = onchain_keys.map_or(0, |pubkeys| {
if !pubkeys.contains(&self.expected_pubkey) {
error!(
NetworkSchema::new(&self.network_context),
"Onchain pubkey {:?} differs from local pubkey {}",
pubkeys,
self.expected_pubkey
);
1
} else {
0
}
});
NETWORK_KEY_MISMATCH
.with_label_values(&[
self.network_context.role().as_str(),
self.network_context.network_id().as_str(),
self.network_context.peer_id().short_str().as_str(),
])
.set(mismatch);
}
/// Processes a received OnChainConfigPayload. Depending on role (Validator or FullNode), parses
/// the appropriate configuration changes and passes it to the ConnectionManager channel.
async fn process_payload(&mut self, payload: OnChainConfigPayload) {
let _process_timer = EVENT_PROCESSING_LOOP_BUSY_DURATION_S.start_timer();
let node_set: ValidatorSet = payload
.get()
.expect("failed to get ValidatorSet from payload");
let updates = extract_updates(self.network_context.clone(), &self.encryptor, node_set);
// Ensure that the public key matches what's onchain for this peer
for request in &updates {
if let ConnectivityRequest::UpdateDiscoveredPeers(_, peer_updates) = request {
self.find_key_mismatches(
peer_updates
.get(&self.network_context.peer_id())
.map(|peer| &peer.keys),
)
}
}
inc_by_with_context(
&DISCOVERY_COUNTS,
&self.network_context,
"new_nodes",
updates.len() as u64,
);
info!(
NetworkSchema::new(&self.network_context),
"Update {} Network about new Node IDs",
self.network_context.network_id()
);
for update in updates {
match self.conn_mgr_reqs_tx.send(update).await {
Ok(()) => (),
Err(e) => {
inc_by_with_context(
&DISCOVERY_COUNTS,
&self.network_context,
"send_failure",
1,
);
warn!(
NetworkSchema::new(&self.network_context),
"Failed to send update to ConnectivityManager {}", e
)
}
}
}
}
/// Starts the listener to wait on reconfiguration events.
pub async fn start(mut self) {
info!(
NetworkSchema::new(&self.network_context),
"{} Starting OnChain Discovery actor", self.network_context
);
while let Some(payload) = self.next_reconfig_event().await {
self.process_payload(payload).await;
}
warn!(
NetworkSchema::new(&self.network_context),
"{} OnChain Discovery actor terminated", self.network_context,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use diem_config::config::HANDSHAKE_VERSION;
use diem_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey},
x25519::PrivateKey,
PrivateKey as PK, Uniform,
};
use diem_types::{
network_address::NetworkAddress, on_chain_config::OnChainConfig,
validator_config::ValidatorConfig, validator_info::ValidatorInfo, PeerId,
};
use futures::executor::block_on;
use rand::{rngs::StdRng, SeedableRng};
use std::{collections::HashMap, time::Instant};
use tokio::{
runtime::Runtime,
time::{timeout_at, Duration},
};
#[test]
fn metric_if_key_mismatch() {
diem_logger::DiemLogger::init_for_testing();
let runtime = Runtime::new().unwrap();
let consensus_private_key = Ed25519PrivateKey::generate_for_testing();
let consensus_pubkey = consensus_private_key.public_key();
let pubkey = test_pubkey([0u8; 32]);
let different_pubkey = test_pubkey([1u8; 32]);
let peer_id = diem_types::account_address::from_identity_public_key(pubkey);
// Build up the Reconfig Listener
let (conn_mgr_reqs_tx, _rx) = channel::new_test(1);
let (mut reconfig_tx, reconfig_rx) = gen_simple_discovery_reconfig_subscription();
let network_context = NetworkContext::mock_with_peer_id(peer_id);
let listener = ConfigurationChangeListener::new(
network_context.clone(),
pubkey,
Encryptor::for_testing(),
conn_mgr_reqs_tx,
reconfig_rx,
);
// Build up and send an update with a different pubkey
send_pubkey_update(
peer_id,
consensus_pubkey,
different_pubkey,
&mut reconfig_tx,
);
let listener_future = async move {
// Run the test, ensuring we actually stop after a couple seconds in case it fails to fail
timeout_at(
tokio::time::Instant::from(Instant::now() + Duration::from_secs(1)),
listener.start(),
)
.await
.expect_err("Expect timeout");
};
// Ensure the metric is updated
check_network_key_mismatch_metric(0, &network_context);
block_on(runtime.spawn(listener_future)).unwrap();
check_network_key_mismatch_metric(1, &network_context);
}
fn check_network_key_mismatch_metric(expected: i64, network_context: &NetworkContext) {
assert_eq!(
expected,
NETWORK_KEY_MISMATCH
.get_metric_with_label_values(&[
network_context.role().as_str(),
network_context.network_id().as_str(),
network_context.peer_id().short_str().as_str()
])
.unwrap()
.get()
)
}
fn send_pubkey_update(
peer_id: PeerId,
consensus_pubkey: Ed25519PublicKey,
pubkey: PublicKey,
reconfig_tx: &mut ReconfigSubscription,
) {
let validator_address =
NetworkAddress::mock().append_prod_protos(pubkey, HANDSHAKE_VERSION);
let addresses = vec![validator_address];
let encryptor = Encryptor::for_testing();
let encrypted_addresses = encryptor.encrypt(&addresses, peer_id, 0).unwrap();
let encoded_addresses = bcs::to_bytes(&addresses).unwrap();
let validator = ValidatorInfo::new(
peer_id,
0,
ValidatorConfig::new(consensus_pubkey, encrypted_addresses, encoded_addresses),
);
let validator_set = ValidatorSet::new(vec![validator]);
let mut configs = HashMap::new();
configs.insert(
ValidatorSet::CONFIG_ID,
bcs::to_bytes(&validator_set).unwrap(),
);
let payload = OnChainConfigPayload::new(1, Arc::new(configs));
reconfig_tx.publish(payload).unwrap();
}
fn | (seed: [u8; 32]) -> PublicKey {
let mut rng: StdRng = SeedableRng::from_seed(seed);
let private_key = PrivateKey::generate(&mut rng);
private_key.public_key()
}
}
| test_pubkey | identifier_name |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use channel::diem_channel::{self, Receiver};
use diem_config::{
config::{Peer, PeerRole},
network_id::NetworkContext,
};
use diem_crypto::x25519::PublicKey;
use diem_logger::prelude::*;
use diem_metrics::{
register_histogram, register_int_counter_vec, register_int_gauge_vec, DurationHistogram,
IntCounterVec, IntGaugeVec,
};
use diem_network_address_encryption::{Encryptor, Error as EncryptorError};
use diem_types::on_chain_config::{OnChainConfigPayload, ValidatorSet, ON_CHAIN_CONFIG_REGISTRY};
use futures::{sink::SinkExt, StreamExt};
use network::{
connectivity_manager::{ConnectivityRequest, DiscoverySource},
counters::inc_by_with_context,
logging::NetworkSchema,
};
use once_cell::sync::Lazy;
use short_hex_str::AsShortHexStr;
use std::{collections::HashSet, sync::Arc};
use subscription_service::ReconfigSubscription;
pub mod builder;
/// Histogram of idle time of spent in event processing loop
pub static EVENT_PROCESSING_LOOP_IDLE_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| {
DurationHistogram::new(
register_histogram!(
"simple_onchain_discovery_event_processing_loop_idle_duration_s",
"Histogram of idle time of spent in event processing loop"
)
.unwrap(),
)
});
/// Histogram of busy time of spent in event processing loop
pub static EVENT_PROCESSING_LOOP_BUSY_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| {
DurationHistogram::new(
register_histogram!(
"simple_onchain_discovery_event_processing_loop_busy_duration_s",
"Histogram of busy time of spent in event processing loop"
)
.unwrap(),
)
});
pub static DISCOVERY_COUNTS: Lazy<IntCounterVec> = Lazy::new(|| {
register_int_counter_vec!(
"diem_simple_onchain_discovery_counts",
"Histogram of busy time of spent in event processing loop",
&["role_type", "network_id", "peer_id", "metric"]
)
.unwrap()
});
pub static NETWORK_KEY_MISMATCH: Lazy<IntGaugeVec> = Lazy::new(|| {
register_int_gauge_vec!(
"diem_network_key_mismatch",
"Gauge of whether the network key mismatches onchain state",
&["role_type", "network_id", "peer_id"]
)
.unwrap()
});
/// Listener which converts published updates from the OnChainConfig to ConnectivityRequests
/// for the ConnectivityManager.
pub struct ConfigurationChangeListener {
network_context: Arc<NetworkContext>,
expected_pubkey: PublicKey,
encryptor: Encryptor,
conn_mgr_reqs_tx: channel::Sender<ConnectivityRequest>,
reconfig_events: diem_channel::Receiver<(), OnChainConfigPayload>,
}
pub fn gen_simple_discovery_reconfig_subscription(
) -> (ReconfigSubscription, Receiver<(), OnChainConfigPayload>) {
ReconfigSubscription::subscribe_all("network", ON_CHAIN_CONFIG_REGISTRY.to_vec(), vec![])
}
/// Extracts a set of ConnectivityRequests from a ValidatorSet which are appropriate for a network with type role.
fn extract_updates(
network_context: Arc<NetworkContext>,
encryptor: &Encryptor,
node_set: ValidatorSet,
) -> Vec<ConnectivityRequest> {
let is_validator = network_context.network_id().is_validator_network();
// Decode addresses while ignoring bad addresses
let discovered_peers = node_set
.into_iter()
.map(|info| {
let peer_id = *info.account_address();
let config = info.into_config();
let addrs = if is_validator {
let result = encryptor.decrypt(&config.validator_network_addresses, peer_id);
if let Err(EncryptorError::StorageError(_)) = result {
panic!(format!(
"Unable to initialize validator network addresses: {:?}",
result
));
}
result.map_err(anyhow::Error::from)
} else {
config
.fullnode_network_addresses()
.map_err(anyhow::Error::from)
}
.map_err(|err| {
inc_by_with_context(&DISCOVERY_COUNTS, &network_context, "read_failure", 1);
warn!(
NetworkSchema::new(&network_context),
"OnChainDiscovery: Failed to parse any network address: peer: {}, err: {}",
peer_id,
err
)
})
.unwrap_or_default();
let peer_role = if is_validator {
PeerRole::Validator
} else {
PeerRole::ValidatorFullNode
};
(peer_id, Peer::from_addrs(peer_role, addrs))
})
.collect();
vec![ConnectivityRequest::UpdateDiscoveredPeers(
DiscoverySource::OnChain,
discovered_peers,
)]
}
impl ConfigurationChangeListener {
/// Creates a new ConfigurationChangeListener
pub fn new(
network_context: Arc<NetworkContext>,
expected_pubkey: PublicKey,
encryptor: Encryptor,
conn_mgr_reqs_tx: channel::Sender<ConnectivityRequest>,
reconfig_events: diem_channel::Receiver<(), OnChainConfigPayload>,
) -> Self {
Self {
network_context,
expected_pubkey,
encryptor,
conn_mgr_reqs_tx,
reconfig_events,
}
}
async fn next_reconfig_event(&mut self) -> Option<OnChainConfigPayload> {
let _idle_timer = EVENT_PROCESSING_LOOP_IDLE_DURATION_S.start_timer();
self.reconfig_events.next().await
}
fn find_key_mismatches(&self, onchain_keys: Option<&HashSet<PublicKey>>) |
/// Processes a received OnChainConfigPayload. Depending on role (Validator or FullNode), parses
/// the appropriate configuration changes and passes it to the ConnectionManager channel.
async fn process_payload(&mut self, payload: OnChainConfigPayload) {
let _process_timer = EVENT_PROCESSING_LOOP_BUSY_DURATION_S.start_timer();
let node_set: ValidatorSet = payload
.get()
.expect("failed to get ValidatorSet from payload");
let updates = extract_updates(self.network_context.clone(), &self.encryptor, node_set);
// Ensure that the public key matches what's onchain for this peer
for request in &updates {
if let ConnectivityRequest::UpdateDiscoveredPeers(_, peer_updates) = request {
self.find_key_mismatches(
peer_updates
.get(&self.network_context.peer_id())
.map(|peer| &peer.keys),
)
}
}
inc_by_with_context(
&DISCOVERY_COUNTS,
&self.network_context,
"new_nodes",
updates.len() as u64,
);
info!(
NetworkSchema::new(&self.network_context),
"Update {} Network about new Node IDs",
self.network_context.network_id()
);
for update in updates {
match self.conn_mgr_reqs_tx.send(update).await {
Ok(()) => (),
Err(e) => {
inc_by_with_context(
&DISCOVERY_COUNTS,
&self.network_context,
"send_failure",
1,
);
warn!(
NetworkSchema::new(&self.network_context),
"Failed to send update to ConnectivityManager {}", e
)
}
}
}
}
/// Starts the listener to wait on reconfiguration events.
pub async fn start(mut self) {
info!(
NetworkSchema::new(&self.network_context),
"{} Starting OnChain Discovery actor", self.network_context
);
while let Some(payload) = self.next_reconfig_event().await {
self.process_payload(payload).await;
}
warn!(
NetworkSchema::new(&self.network_context),
"{} OnChain Discovery actor terminated", self.network_context,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use diem_config::config::HANDSHAKE_VERSION;
use diem_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey},
x25519::PrivateKey,
PrivateKey as PK, Uniform,
};
use diem_types::{
network_address::NetworkAddress, on_chain_config::OnChainConfig,
validator_config::ValidatorConfig, validator_info::ValidatorInfo, PeerId,
};
use futures::executor::block_on;
use rand::{rngs::StdRng, SeedableRng};
use std::{collections::HashMap, time::Instant};
use tokio::{
runtime::Runtime,
time::{timeout_at, Duration},
};
#[test]
fn metric_if_key_mismatch() {
diem_logger::DiemLogger::init_for_testing();
let runtime = Runtime::new().unwrap();
let consensus_private_key = Ed25519PrivateKey::generate_for_testing();
let consensus_pubkey = consensus_private_key.public_key();
let pubkey = test_pubkey([0u8; 32]);
let different_pubkey = test_pubkey([1u8; 32]);
let peer_id = diem_types::account_address::from_identity_public_key(pubkey);
// Build up the Reconfig Listener
let (conn_mgr_reqs_tx, _rx) = channel::new_test(1);
let (mut reconfig_tx, reconfig_rx) = gen_simple_discovery_reconfig_subscription();
let network_context = NetworkContext::mock_with_peer_id(peer_id);
let listener = ConfigurationChangeListener::new(
network_context.clone(),
pubkey,
Encryptor::for_testing(),
conn_mgr_reqs_tx,
reconfig_rx,
);
// Build up and send an update with a different pubkey
send_pubkey_update(
peer_id,
consensus_pubkey,
different_pubkey,
&mut reconfig_tx,
);
let listener_future = async move {
// Run the test, ensuring we actually stop after a couple seconds in case it fails to fail
timeout_at(
tokio::time::Instant::from(Instant::now() + Duration::from_secs(1)),
listener.start(),
)
.await
.expect_err("Expect timeout");
};
// Ensure the metric is updated
check_network_key_mismatch_metric(0, &network_context);
block_on(runtime.spawn(listener_future)).unwrap();
check_network_key_mismatch_metric(1, &network_context);
}
fn check_network_key_mismatch_metric(expected: i64, network_context: &NetworkContext) {
assert_eq!(
expected,
NETWORK_KEY_MISMATCH
.get_metric_with_label_values(&[
network_context.role().as_str(),
network_context.network_id().as_str(),
network_context.peer_id().short_str().as_str()
])
.unwrap()
.get()
)
}
fn send_pubkey_update(
peer_id: PeerId,
consensus_pubkey: Ed25519PublicKey,
pubkey: PublicKey,
reconfig_tx: &mut ReconfigSubscription,
) {
let validator_address =
NetworkAddress::mock().append_prod_protos(pubkey, HANDSHAKE_VERSION);
let addresses = vec![validator_address];
let encryptor = Encryptor::for_testing();
let encrypted_addresses = encryptor.encrypt(&addresses, peer_id, 0).unwrap();
let encoded_addresses = bcs::to_bytes(&addresses).unwrap();
let validator = ValidatorInfo::new(
peer_id,
0,
ValidatorConfig::new(consensus_pubkey, encrypted_addresses, encoded_addresses),
);
let validator_set = ValidatorSet::new(vec![validator]);
let mut configs = HashMap::new();
configs.insert(
ValidatorSet::CONFIG_ID,
bcs::to_bytes(&validator_set).unwrap(),
);
let payload = OnChainConfigPayload::new(1, Arc::new(configs));
reconfig_tx.publish(payload).unwrap();
}
fn test_pubkey(seed: [u8; 32]) -> PublicKey {
let mut rng: StdRng = SeedableRng::from_seed(seed);
let private_key = PrivateKey::generate(&mut rng);
private_key.public_key()
}
}
| {
let mismatch = onchain_keys.map_or(0, |pubkeys| {
if !pubkeys.contains(&self.expected_pubkey) {
error!(
NetworkSchema::new(&self.network_context),
"Onchain pubkey {:?} differs from local pubkey {}",
pubkeys,
self.expected_pubkey
);
1
} else {
0
}
});
NETWORK_KEY_MISMATCH
.with_label_values(&[
self.network_context.role().as_str(),
self.network_context.network_id().as_str(),
self.network_context.peer_id().short_str().as_str(),
])
.set(mismatch);
} | identifier_body |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use channel::diem_channel::{self, Receiver};
use diem_config::{
config::{Peer, PeerRole},
network_id::NetworkContext,
};
use diem_crypto::x25519::PublicKey;
use diem_logger::prelude::*;
use diem_metrics::{
register_histogram, register_int_counter_vec, register_int_gauge_vec, DurationHistogram,
IntCounterVec, IntGaugeVec,
};
use diem_network_address_encryption::{Encryptor, Error as EncryptorError};
use diem_types::on_chain_config::{OnChainConfigPayload, ValidatorSet, ON_CHAIN_CONFIG_REGISTRY};
use futures::{sink::SinkExt, StreamExt};
use network::{
connectivity_manager::{ConnectivityRequest, DiscoverySource},
counters::inc_by_with_context,
logging::NetworkSchema,
};
use once_cell::sync::Lazy;
use short_hex_str::AsShortHexStr;
use std::{collections::HashSet, sync::Arc};
use subscription_service::ReconfigSubscription;
pub mod builder;
/// Histogram of idle time of spent in event processing loop
pub static EVENT_PROCESSING_LOOP_IDLE_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| {
DurationHistogram::new(
register_histogram!(
"simple_onchain_discovery_event_processing_loop_idle_duration_s",
"Histogram of idle time of spent in event processing loop"
)
.unwrap(),
)
});
/// Histogram of busy time of spent in event processing loop
pub static EVENT_PROCESSING_LOOP_BUSY_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| {
DurationHistogram::new(
register_histogram!(
"simple_onchain_discovery_event_processing_loop_busy_duration_s",
"Histogram of busy time of spent in event processing loop"
)
.unwrap(),
)
});
pub static DISCOVERY_COUNTS: Lazy<IntCounterVec> = Lazy::new(|| {
register_int_counter_vec!(
"diem_simple_onchain_discovery_counts",
"Histogram of busy time of spent in event processing loop",
&["role_type", "network_id", "peer_id", "metric"]
)
.unwrap()
});
pub static NETWORK_KEY_MISMATCH: Lazy<IntGaugeVec> = Lazy::new(|| {
register_int_gauge_vec!(
"diem_network_key_mismatch",
"Gauge of whether the network key mismatches onchain state",
&["role_type", "network_id", "peer_id"]
)
.unwrap()
});
/// Listener which converts published updates from the OnChainConfig to ConnectivityRequests
/// for the ConnectivityManager.
pub struct ConfigurationChangeListener {
network_context: Arc<NetworkContext>,
expected_pubkey: PublicKey,
encryptor: Encryptor,
conn_mgr_reqs_tx: channel::Sender<ConnectivityRequest>,
reconfig_events: diem_channel::Receiver<(), OnChainConfigPayload>,
}
pub fn gen_simple_discovery_reconfig_subscription(
) -> (ReconfigSubscription, Receiver<(), OnChainConfigPayload>) {
ReconfigSubscription::subscribe_all("network", ON_CHAIN_CONFIG_REGISTRY.to_vec(), vec![])
}
/// Extracts a set of ConnectivityRequests from a ValidatorSet which are appropriate for a network with type role.
fn extract_updates(
network_context: Arc<NetworkContext>,
encryptor: &Encryptor,
node_set: ValidatorSet,
) -> Vec<ConnectivityRequest> {
let is_validator = network_context.network_id().is_validator_network();
// Decode addresses while ignoring bad addresses
let discovered_peers = node_set
.into_iter()
.map(|info| {
let peer_id = *info.account_address();
let config = info.into_config();
let addrs = if is_validator {
let result = encryptor.decrypt(&config.validator_network_addresses, peer_id);
if let Err(EncryptorError::StorageError(_)) = result {
panic!(format!(
"Unable to initialize validator network addresses: {:?}",
result
));
}
result.map_err(anyhow::Error::from)
} else {
config
.fullnode_network_addresses()
.map_err(anyhow::Error::from)
}
.map_err(|err| {
inc_by_with_context(&DISCOVERY_COUNTS, &network_context, "read_failure", 1);
warn!(
NetworkSchema::new(&network_context),
"OnChainDiscovery: Failed to parse any network address: peer: {}, err: {}",
peer_id,
err
)
})
.unwrap_or_default();
let peer_role = if is_validator | else {
PeerRole::ValidatorFullNode
};
(peer_id, Peer::from_addrs(peer_role, addrs))
})
.collect();
vec![ConnectivityRequest::UpdateDiscoveredPeers(
DiscoverySource::OnChain,
discovered_peers,
)]
}
impl ConfigurationChangeListener {
/// Creates a new ConfigurationChangeListener
pub fn new(
network_context: Arc<NetworkContext>,
expected_pubkey: PublicKey,
encryptor: Encryptor,
conn_mgr_reqs_tx: channel::Sender<ConnectivityRequest>,
reconfig_events: diem_channel::Receiver<(), OnChainConfigPayload>,
) -> Self {
Self {
network_context,
expected_pubkey,
encryptor,
conn_mgr_reqs_tx,
reconfig_events,
}
}
async fn next_reconfig_event(&mut self) -> Option<OnChainConfigPayload> {
let _idle_timer = EVENT_PROCESSING_LOOP_IDLE_DURATION_S.start_timer();
self.reconfig_events.next().await
}
fn find_key_mismatches(&self, onchain_keys: Option<&HashSet<PublicKey>>) {
let mismatch = onchain_keys.map_or(0, |pubkeys| {
if !pubkeys.contains(&self.expected_pubkey) {
error!(
NetworkSchema::new(&self.network_context),
"Onchain pubkey {:?} differs from local pubkey {}",
pubkeys,
self.expected_pubkey
);
1
} else {
0
}
});
NETWORK_KEY_MISMATCH
.with_label_values(&[
self.network_context.role().as_str(),
self.network_context.network_id().as_str(),
self.network_context.peer_id().short_str().as_str(),
])
.set(mismatch);
}
/// Processes a received OnChainConfigPayload. Depending on role (Validator or FullNode), parses
/// the appropriate configuration changes and passes it to the ConnectionManager channel.
async fn process_payload(&mut self, payload: OnChainConfigPayload) {
let _process_timer = EVENT_PROCESSING_LOOP_BUSY_DURATION_S.start_timer();
let node_set: ValidatorSet = payload
.get()
.expect("failed to get ValidatorSet from payload");
let updates = extract_updates(self.network_context.clone(), &self.encryptor, node_set);
// Ensure that the public key matches what's onchain for this peer
for request in &updates {
if let ConnectivityRequest::UpdateDiscoveredPeers(_, peer_updates) = request {
self.find_key_mismatches(
peer_updates
.get(&self.network_context.peer_id())
.map(|peer| &peer.keys),
)
}
}
inc_by_with_context(
&DISCOVERY_COUNTS,
&self.network_context,
"new_nodes",
updates.len() as u64,
);
info!(
NetworkSchema::new(&self.network_context),
"Update {} Network about new Node IDs",
self.network_context.network_id()
);
for update in updates {
match self.conn_mgr_reqs_tx.send(update).await {
Ok(()) => (),
Err(e) => {
inc_by_with_context(
&DISCOVERY_COUNTS,
&self.network_context,
"send_failure",
1,
);
warn!(
NetworkSchema::new(&self.network_context),
"Failed to send update to ConnectivityManager {}", e
)
}
}
}
}
/// Starts the listener to wait on reconfiguration events.
pub async fn start(mut self) {
info!(
NetworkSchema::new(&self.network_context),
"{} Starting OnChain Discovery actor", self.network_context
);
while let Some(payload) = self.next_reconfig_event().await {
self.process_payload(payload).await;
}
warn!(
NetworkSchema::new(&self.network_context),
"{} OnChain Discovery actor terminated", self.network_context,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use diem_config::config::HANDSHAKE_VERSION;
use diem_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey},
x25519::PrivateKey,
PrivateKey as PK, Uniform,
};
use diem_types::{
network_address::NetworkAddress, on_chain_config::OnChainConfig,
validator_config::ValidatorConfig, validator_info::ValidatorInfo, PeerId,
};
use futures::executor::block_on;
use rand::{rngs::StdRng, SeedableRng};
use std::{collections::HashMap, time::Instant};
use tokio::{
runtime::Runtime,
time::{timeout_at, Duration},
};
#[test]
fn metric_if_key_mismatch() {
diem_logger::DiemLogger::init_for_testing();
let runtime = Runtime::new().unwrap();
let consensus_private_key = Ed25519PrivateKey::generate_for_testing();
let consensus_pubkey = consensus_private_key.public_key();
let pubkey = test_pubkey([0u8; 32]);
let different_pubkey = test_pubkey([1u8; 32]);
let peer_id = diem_types::account_address::from_identity_public_key(pubkey);
// Build up the Reconfig Listener
let (conn_mgr_reqs_tx, _rx) = channel::new_test(1);
let (mut reconfig_tx, reconfig_rx) = gen_simple_discovery_reconfig_subscription();
let network_context = NetworkContext::mock_with_peer_id(peer_id);
let listener = ConfigurationChangeListener::new(
network_context.clone(),
pubkey,
Encryptor::for_testing(),
conn_mgr_reqs_tx,
reconfig_rx,
);
// Build up and send an update with a different pubkey
send_pubkey_update(
peer_id,
consensus_pubkey,
different_pubkey,
&mut reconfig_tx,
);
let listener_future = async move {
// Run the test, ensuring we actually stop after a couple seconds in case it fails to fail
timeout_at(
tokio::time::Instant::from(Instant::now() + Duration::from_secs(1)),
listener.start(),
)
.await
.expect_err("Expect timeout");
};
// Ensure the metric is updated
check_network_key_mismatch_metric(0, &network_context);
block_on(runtime.spawn(listener_future)).unwrap();
check_network_key_mismatch_metric(1, &network_context);
}
fn check_network_key_mismatch_metric(expected: i64, network_context: &NetworkContext) {
assert_eq!(
expected,
NETWORK_KEY_MISMATCH
.get_metric_with_label_values(&[
network_context.role().as_str(),
network_context.network_id().as_str(),
network_context.peer_id().short_str().as_str()
])
.unwrap()
.get()
)
}
fn send_pubkey_update(
peer_id: PeerId,
consensus_pubkey: Ed25519PublicKey,
pubkey: PublicKey,
reconfig_tx: &mut ReconfigSubscription,
) {
let validator_address =
NetworkAddress::mock().append_prod_protos(pubkey, HANDSHAKE_VERSION);
let addresses = vec![validator_address];
let encryptor = Encryptor::for_testing();
let encrypted_addresses = encryptor.encrypt(&addresses, peer_id, 0).unwrap();
let encoded_addresses = bcs::to_bytes(&addresses).unwrap();
let validator = ValidatorInfo::new(
peer_id,
0,
ValidatorConfig::new(consensus_pubkey, encrypted_addresses, encoded_addresses),
);
let validator_set = ValidatorSet::new(vec![validator]);
let mut configs = HashMap::new();
configs.insert(
ValidatorSet::CONFIG_ID,
bcs::to_bytes(&validator_set).unwrap(),
);
let payload = OnChainConfigPayload::new(1, Arc::new(configs));
reconfig_tx.publish(payload).unwrap();
}
fn test_pubkey(seed: [u8; 32]) -> PublicKey {
let mut rng: StdRng = SeedableRng::from_seed(seed);
let private_key = PrivateKey::generate(&mut rng);
private_key.public_key()
}
}
| {
PeerRole::Validator
} | conditional_block |
gcal.js | /*!
* FullCalendar v1.6.1 Google Calendar Plugin
* Docs & License: http://arshaw.com/fullcalendar/
* (c) 2013 Adam Shaw
*/
(function($) {
var fc = $.fullCalendar;
var formatDate = fc.formatDate;
var parseISO8601 = fc.parseISO8601;
var addDays = fc.addDays;
var applyAll = fc.applyAll;
fc.sourceNormalizers.push(function(sourceOptions) {
if (sourceOptions.dataType == 'gcal' ||
sourceOptions.dataType === undefined &&
(sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) {
sourceOptions.dataType = 'gcal';
if (sourceOptions.editable === undefined) {
sourceOptions.editable = false;
}
}
});
fc.sourceFetchers.push(function(sourceOptions, start, end) {
if (sourceOptions.dataType == 'gcal') {
return transformOptions(sourceOptions, start, end);
}
});
function | (sourceOptions, start, end) {
var success = sourceOptions.success;
var data = $.extend({}, sourceOptions.data || {}, {
'start-min': formatDate(start, 'u'),
'start-max': formatDate(end, 'u'),
'singleevents': true,
'max-results': 9999
});
var ctz = sourceOptions.currentTimezone;
if (ctz) {
data.ctz = ctz = ctz.replace(' ', '_');
}
return $.extend({}, sourceOptions, {
url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?',
dataType: 'jsonp',
data: data,
startParam: false,
endParam: false,
success: function(data) {
var events = [];
if (data.feed.entry) {
$.each(data.feed.entry, function(i, entry) {
var startStr = entry['gd$when'][0]['startTime'];
var start = parseISO8601(startStr, true);
var end = parseISO8601(entry['gd$when'][0]['endTime'], true);
var allDay = startStr.indexOf('T') == -1;
var url;
$.each(entry.link, function(i, link) {
if (link.type == 'text/html') {
url = link.href;
if (ctz) {
url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz;
}
}
});
if (allDay) {
addDays(end, -1); // make inclusive
}
events.push({
id: entry['gCal$uid']['value'],
title: entry['title']['$t'],
url: url,
start: start,
end: end,
allDay: allDay,
location: entry['gd$where'][0]['valueString'],
description: entry['content']['$t']
});
});
}
var args = [events].concat(Array.prototype.slice.call(arguments, 1));
var res = applyAll(success, this, args);
if ($.isArray(res)) {
return res;
}
return events;
}
});
}
// legacy
fc.gcalFeed = function(url, sourceOptions) {
return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' });
};
})(jQuery);
| transformOptions | identifier_name |
gcal.js | /*!
* FullCalendar v1.6.1 Google Calendar Plugin
* Docs & License: http://arshaw.com/fullcalendar/
* (c) 2013 Adam Shaw
*/
(function($) {
var fc = $.fullCalendar;
var formatDate = fc.formatDate;
var parseISO8601 = fc.parseISO8601;
var addDays = fc.addDays;
var applyAll = fc.applyAll;
fc.sourceNormalizers.push(function(sourceOptions) {
if (sourceOptions.dataType == 'gcal' ||
sourceOptions.dataType === undefined &&
(sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) {
| sourceOptions.editable = false;
}
}
});
fc.sourceFetchers.push(function(sourceOptions, start, end) {
if (sourceOptions.dataType == 'gcal') {
return transformOptions(sourceOptions, start, end);
}
});
function transformOptions(sourceOptions, start, end) {
var success = sourceOptions.success;
var data = $.extend({}, sourceOptions.data || {}, {
'start-min': formatDate(start, 'u'),
'start-max': formatDate(end, 'u'),
'singleevents': true,
'max-results': 9999
});
var ctz = sourceOptions.currentTimezone;
if (ctz) {
data.ctz = ctz = ctz.replace(' ', '_');
}
return $.extend({}, sourceOptions, {
url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?',
dataType: 'jsonp',
data: data,
startParam: false,
endParam: false,
success: function(data) {
var events = [];
if (data.feed.entry) {
$.each(data.feed.entry, function(i, entry) {
var startStr = entry['gd$when'][0]['startTime'];
var start = parseISO8601(startStr, true);
var end = parseISO8601(entry['gd$when'][0]['endTime'], true);
var allDay = startStr.indexOf('T') == -1;
var url;
$.each(entry.link, function(i, link) {
if (link.type == 'text/html') {
url = link.href;
if (ctz) {
url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz;
}
}
});
if (allDay) {
addDays(end, -1); // make inclusive
}
events.push({
id: entry['gCal$uid']['value'],
title: entry['title']['$t'],
url: url,
start: start,
end: end,
allDay: allDay,
location: entry['gd$where'][0]['valueString'],
description: entry['content']['$t']
});
});
}
var args = [events].concat(Array.prototype.slice.call(arguments, 1));
var res = applyAll(success, this, args);
if ($.isArray(res)) {
return res;
}
return events;
}
});
}
// legacy
fc.gcalFeed = function(url, sourceOptions) {
return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' });
};
})(jQuery); | sourceOptions.dataType = 'gcal';
if (sourceOptions.editable === undefined) {
| random_line_split |
gcal.js | /*!
* FullCalendar v1.6.1 Google Calendar Plugin
* Docs & License: http://arshaw.com/fullcalendar/
* (c) 2013 Adam Shaw
*/
(function($) {
var fc = $.fullCalendar;
var formatDate = fc.formatDate;
var parseISO8601 = fc.parseISO8601;
var addDays = fc.addDays;
var applyAll = fc.applyAll;
fc.sourceNormalizers.push(function(sourceOptions) {
if (sourceOptions.dataType == 'gcal' ||
sourceOptions.dataType === undefined &&
(sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) {
sourceOptions.dataType = 'gcal';
if (sourceOptions.editable === undefined) {
sourceOptions.editable = false;
}
}
});
fc.sourceFetchers.push(function(sourceOptions, start, end) {
if (sourceOptions.dataType == 'gcal') {
return transformOptions(sourceOptions, start, end);
}
});
function transformOptions(sourceOptions, start, end) |
// legacy
fc.gcalFeed = function(url, sourceOptions) {
return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' });
};
})(jQuery);
| {
var success = sourceOptions.success;
var data = $.extend({}, sourceOptions.data || {}, {
'start-min': formatDate(start, 'u'),
'start-max': formatDate(end, 'u'),
'singleevents': true,
'max-results': 9999
});
var ctz = sourceOptions.currentTimezone;
if (ctz) {
data.ctz = ctz = ctz.replace(' ', '_');
}
return $.extend({}, sourceOptions, {
url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?',
dataType: 'jsonp',
data: data,
startParam: false,
endParam: false,
success: function(data) {
var events = [];
if (data.feed.entry) {
$.each(data.feed.entry, function(i, entry) {
var startStr = entry['gd$when'][0]['startTime'];
var start = parseISO8601(startStr, true);
var end = parseISO8601(entry['gd$when'][0]['endTime'], true);
var allDay = startStr.indexOf('T') == -1;
var url;
$.each(entry.link, function(i, link) {
if (link.type == 'text/html') {
url = link.href;
if (ctz) {
url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz;
}
}
});
if (allDay) {
addDays(end, -1); // make inclusive
}
events.push({
id: entry['gCal$uid']['value'],
title: entry['title']['$t'],
url: url,
start: start,
end: end,
allDay: allDay,
location: entry['gd$where'][0]['valueString'],
description: entry['content']['$t']
});
});
}
var args = [events].concat(Array.prototype.slice.call(arguments, 1));
var res = applyAll(success, this, args);
if ($.isArray(res)) {
return res;
}
return events;
}
});
} | identifier_body |
gcal.js | /*!
* FullCalendar v1.6.1 Google Calendar Plugin
* Docs & License: http://arshaw.com/fullcalendar/
* (c) 2013 Adam Shaw
*/
(function($) {
var fc = $.fullCalendar;
var formatDate = fc.formatDate;
var parseISO8601 = fc.parseISO8601;
var addDays = fc.addDays;
var applyAll = fc.applyAll;
fc.sourceNormalizers.push(function(sourceOptions) {
if (sourceOptions.dataType == 'gcal' ||
sourceOptions.dataType === undefined &&
(sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) {
sourceOptions.dataType = 'gcal';
if (sourceOptions.editable === undefined) {
sourceOptions.editable = false;
}
}
});
fc.sourceFetchers.push(function(sourceOptions, start, end) {
if (sourceOptions.dataType == 'gcal') {
return transformOptions(sourceOptions, start, end);
}
});
function transformOptions(sourceOptions, start, end) {
var success = sourceOptions.success;
var data = $.extend({}, sourceOptions.data || {}, {
'start-min': formatDate(start, 'u'),
'start-max': formatDate(end, 'u'),
'singleevents': true,
'max-results': 9999
});
var ctz = sourceOptions.currentTimezone;
if (ctz) {
data.ctz = ctz = ctz.replace(' ', '_');
}
return $.extend({}, sourceOptions, {
url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?',
dataType: 'jsonp',
data: data,
startParam: false,
endParam: false,
success: function(data) {
var events = [];
if (data.feed.entry) {
$.each(data.feed.entry, function(i, entry) {
var startStr = entry['gd$when'][0]['startTime'];
var start = parseISO8601(startStr, true);
var end = parseISO8601(entry['gd$when'][0]['endTime'], true);
var allDay = startStr.indexOf('T') == -1;
var url;
$.each(entry.link, function(i, link) {
if (link.type == 'text/html') {
url = link.href;
if (ctz) {
url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz;
}
}
});
if (allDay) {
addDays(end, -1); // make inclusive
}
events.push({
id: entry['gCal$uid']['value'],
title: entry['title']['$t'],
url: url,
start: start,
end: end,
allDay: allDay,
location: entry['gd$where'][0]['valueString'],
description: entry['content']['$t']
});
});
}
var args = [events].concat(Array.prototype.slice.call(arguments, 1));
var res = applyAll(success, this, args);
if ($.isArray(res)) |
return events;
}
});
}
// legacy
fc.gcalFeed = function(url, sourceOptions) {
return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' });
};
})(jQuery);
| {
return res;
} | conditional_block |
ext.py | import json
import logging
from foxglove import glove
from httpx import Response
from .settings import Settings
logger = logging.getLogger('ext')
def lenient_json(v):
if isinstance(v, (str, bytes)):
try:
return json.loads(v)
except (ValueError, TypeError):
pass
return v
class ApiError(RuntimeError):
def __init__(self, method, url, status, response_text):
self.method = method
self.url = url
self.status = status
self.body = response_text
def __str__(self):
return f'{self.method} {self.url}, unexpected response {self.status}'
class ApiSession:
def __init__(self, root_url, settings: Settings):
self.settings = settings
self.root = root_url.rstrip('/') + '/'
async def get(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('GET', uri, allowed_statuses=allowed_statuses, **data)
async def delete(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('DELETE', uri, allowed_statuses=allowed_statuses, **data)
async def post(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('POST', uri, allowed_statuses=allowed_statuses, **data)
async def put(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('PUT', uri, allowed_statuses=allowed_statuses, **data)
async def _request(self, method, uri, allowed_statuses=(200, 201), **data) -> Response:
method, url, data = self._modify_request(method, self.root + str(uri).lstrip('/'), data)
kwargs = {}
headers = data.pop('headers_', None)
if headers is not None:
kwargs['headers'] = headers
if timeout := data.pop('timeout_', None):
|
r = await glove.http.request(method, url, json=data or None, **kwargs)
if isinstance(allowed_statuses, int):
allowed_statuses = (allowed_statuses,)
if allowed_statuses != '*' and r.status_code not in allowed_statuses:
data = {
'request_real_url': str(r.request.url),
'request_headers': dict(r.request.headers),
'request_data': data,
'response_headers': dict(r.headers),
'response_content': lenient_json(r.text),
}
logger.warning(
'%s unexpected response %s /%s -> %s',
self.__class__.__name__,
method,
uri,
r.status_code,
extra={'data': data} if self.settings.verbose_http_errors else {},
)
raise ApiError(method, url, r.status_code, r.text)
else:
logger.debug('%s /%s -> %s', method, uri, r.status_code)
return r
def _modify_request(self, method, url, data):
return method, url, data
class Mandrill(ApiSession):
def __init__(self, settings):
super().__init__(settings.mandrill_url, settings)
def _modify_request(self, method, url, data):
data['key'] = self.settings.mandrill_key
return method, url, data
class MessageBird(ApiSession):
def __init__(self, settings):
super().__init__(settings.messagebird_url, settings)
def _modify_request(self, method, url, data):
data['headers_'] = {'Authorization': f'AccessKey {self.settings.messagebird_key}'}
return method, url, data
| kwargs['timeout'] = timeout | conditional_block |
ext.py | import json
import logging
from foxglove import glove
from httpx import Response
from .settings import Settings
| logger = logging.getLogger('ext')
def lenient_json(v):
if isinstance(v, (str, bytes)):
try:
return json.loads(v)
except (ValueError, TypeError):
pass
return v
class ApiError(RuntimeError):
def __init__(self, method, url, status, response_text):
self.method = method
self.url = url
self.status = status
self.body = response_text
def __str__(self):
return f'{self.method} {self.url}, unexpected response {self.status}'
class ApiSession:
def __init__(self, root_url, settings: Settings):
self.settings = settings
self.root = root_url.rstrip('/') + '/'
async def get(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('GET', uri, allowed_statuses=allowed_statuses, **data)
async def delete(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('DELETE', uri, allowed_statuses=allowed_statuses, **data)
async def post(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('POST', uri, allowed_statuses=allowed_statuses, **data)
async def put(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('PUT', uri, allowed_statuses=allowed_statuses, **data)
async def _request(self, method, uri, allowed_statuses=(200, 201), **data) -> Response:
method, url, data = self._modify_request(method, self.root + str(uri).lstrip('/'), data)
kwargs = {}
headers = data.pop('headers_', None)
if headers is not None:
kwargs['headers'] = headers
if timeout := data.pop('timeout_', None):
kwargs['timeout'] = timeout
r = await glove.http.request(method, url, json=data or None, **kwargs)
if isinstance(allowed_statuses, int):
allowed_statuses = (allowed_statuses,)
if allowed_statuses != '*' and r.status_code not in allowed_statuses:
data = {
'request_real_url': str(r.request.url),
'request_headers': dict(r.request.headers),
'request_data': data,
'response_headers': dict(r.headers),
'response_content': lenient_json(r.text),
}
logger.warning(
'%s unexpected response %s /%s -> %s',
self.__class__.__name__,
method,
uri,
r.status_code,
extra={'data': data} if self.settings.verbose_http_errors else {},
)
raise ApiError(method, url, r.status_code, r.text)
else:
logger.debug('%s /%s -> %s', method, uri, r.status_code)
return r
def _modify_request(self, method, url, data):
return method, url, data
class Mandrill(ApiSession):
def __init__(self, settings):
super().__init__(settings.mandrill_url, settings)
def _modify_request(self, method, url, data):
data['key'] = self.settings.mandrill_key
return method, url, data
class MessageBird(ApiSession):
def __init__(self, settings):
super().__init__(settings.messagebird_url, settings)
def _modify_request(self, method, url, data):
data['headers_'] = {'Authorization': f'AccessKey {self.settings.messagebird_key}'}
return method, url, data | random_line_split | |
ext.py | import json
import logging
from foxglove import glove
from httpx import Response
from .settings import Settings
logger = logging.getLogger('ext')
def lenient_json(v):
if isinstance(v, (str, bytes)):
try:
return json.loads(v)
except (ValueError, TypeError):
pass
return v
class ApiError(RuntimeError):
def __init__(self, method, url, status, response_text):
self.method = method
self.url = url
self.status = status
self.body = response_text
def __str__(self):
return f'{self.method} {self.url}, unexpected response {self.status}'
class | :
def __init__(self, root_url, settings: Settings):
self.settings = settings
self.root = root_url.rstrip('/') + '/'
async def get(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('GET', uri, allowed_statuses=allowed_statuses, **data)
async def delete(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('DELETE', uri, allowed_statuses=allowed_statuses, **data)
async def post(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('POST', uri, allowed_statuses=allowed_statuses, **data)
async def put(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('PUT', uri, allowed_statuses=allowed_statuses, **data)
async def _request(self, method, uri, allowed_statuses=(200, 201), **data) -> Response:
method, url, data = self._modify_request(method, self.root + str(uri).lstrip('/'), data)
kwargs = {}
headers = data.pop('headers_', None)
if headers is not None:
kwargs['headers'] = headers
if timeout := data.pop('timeout_', None):
kwargs['timeout'] = timeout
r = await glove.http.request(method, url, json=data or None, **kwargs)
if isinstance(allowed_statuses, int):
allowed_statuses = (allowed_statuses,)
if allowed_statuses != '*' and r.status_code not in allowed_statuses:
data = {
'request_real_url': str(r.request.url),
'request_headers': dict(r.request.headers),
'request_data': data,
'response_headers': dict(r.headers),
'response_content': lenient_json(r.text),
}
logger.warning(
'%s unexpected response %s /%s -> %s',
self.__class__.__name__,
method,
uri,
r.status_code,
extra={'data': data} if self.settings.verbose_http_errors else {},
)
raise ApiError(method, url, r.status_code, r.text)
else:
logger.debug('%s /%s -> %s', method, uri, r.status_code)
return r
def _modify_request(self, method, url, data):
return method, url, data
class Mandrill(ApiSession):
def __init__(self, settings):
super().__init__(settings.mandrill_url, settings)
def _modify_request(self, method, url, data):
data['key'] = self.settings.mandrill_key
return method, url, data
class MessageBird(ApiSession):
def __init__(self, settings):
super().__init__(settings.messagebird_url, settings)
def _modify_request(self, method, url, data):
data['headers_'] = {'Authorization': f'AccessKey {self.settings.messagebird_key}'}
return method, url, data
| ApiSession | identifier_name |
ext.py | import json
import logging
from foxglove import glove
from httpx import Response
from .settings import Settings
logger = logging.getLogger('ext')
def lenient_json(v):
if isinstance(v, (str, bytes)):
try:
return json.loads(v)
except (ValueError, TypeError):
pass
return v
class ApiError(RuntimeError):
def __init__(self, method, url, status, response_text):
self.method = method
self.url = url
self.status = status
self.body = response_text
def __str__(self):
return f'{self.method} {self.url}, unexpected response {self.status}'
class ApiSession:
def __init__(self, root_url, settings: Settings):
self.settings = settings
self.root = root_url.rstrip('/') + '/'
async def get(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('GET', uri, allowed_statuses=allowed_statuses, **data)
async def delete(self, uri, *, allowed_statuses=(200,), **data) -> Response:
|
async def post(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('POST', uri, allowed_statuses=allowed_statuses, **data)
async def put(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('PUT', uri, allowed_statuses=allowed_statuses, **data)
async def _request(self, method, uri, allowed_statuses=(200, 201), **data) -> Response:
method, url, data = self._modify_request(method, self.root + str(uri).lstrip('/'), data)
kwargs = {}
headers = data.pop('headers_', None)
if headers is not None:
kwargs['headers'] = headers
if timeout := data.pop('timeout_', None):
kwargs['timeout'] = timeout
r = await glove.http.request(method, url, json=data or None, **kwargs)
if isinstance(allowed_statuses, int):
allowed_statuses = (allowed_statuses,)
if allowed_statuses != '*' and r.status_code not in allowed_statuses:
data = {
'request_real_url': str(r.request.url),
'request_headers': dict(r.request.headers),
'request_data': data,
'response_headers': dict(r.headers),
'response_content': lenient_json(r.text),
}
logger.warning(
'%s unexpected response %s /%s -> %s',
self.__class__.__name__,
method,
uri,
r.status_code,
extra={'data': data} if self.settings.verbose_http_errors else {},
)
raise ApiError(method, url, r.status_code, r.text)
else:
logger.debug('%s /%s -> %s', method, uri, r.status_code)
return r
def _modify_request(self, method, url, data):
return method, url, data
class Mandrill(ApiSession):
def __init__(self, settings):
super().__init__(settings.mandrill_url, settings)
def _modify_request(self, method, url, data):
data['key'] = self.settings.mandrill_key
return method, url, data
class MessageBird(ApiSession):
def __init__(self, settings):
super().__init__(settings.messagebird_url, settings)
def _modify_request(self, method, url, data):
data['headers_'] = {'Authorization': f'AccessKey {self.settings.messagebird_key}'}
return method, url, data
| return await self._request('DELETE', uri, allowed_statuses=allowed_statuses, **data) | identifier_body |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::HashSet;
use std::cmp::Reverse;
fn has_distinct_pair(set:&HashSet<i64>, sum: i64) -> bool {
for k in set.iter() {
let v = sum - k;
if *k != v && set.contains(&v) {
return true;
}
}
false
}
fn print_medians(file_name: &str) -> io::Result<u64> {
let f = File::open(file_name)?;
let reader = BufReader::new(f);
let mut set:HashSet<i64> = HashSet::new();
for line in reader.lines() {
let line = line.unwrap();
let value = i64::from_str(&line).expect("error parsing value");
set.insert(value);
}
let mut result = 0;
for s in -10000..10001 {
if has_distinct_pair(&set, s) {
result = result + 1;
}
}
Ok(result)
}
fn main() | {
for arg in std::env::args().skip(1) {
let value = print_medians(&arg).expect("failed to read");
println!("answer = {}", value);
}
} | identifier_body | |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::HashSet;
use std::cmp::Reverse;
fn has_distinct_pair(set:&HashSet<i64>, sum: i64) -> bool {
for k in set.iter() {
let v = sum - k;
if *k != v && set.contains(&v) {
return true;
}
}
false
}
fn print_medians(file_name: &str) -> io::Result<u64> {
let f = File::open(file_name)?;
let reader = BufReader::new(f);
let mut set:HashSet<i64> = HashSet::new();
for line in reader.lines() {
let line = line.unwrap();
let value = i64::from_str(&line).expect("error parsing value");
set.insert(value);
}
let mut result = 0;
for s in -10000..10001 {
if has_distinct_pair(&set, s) |
}
Ok(result)
}
fn main() {
for arg in std::env::args().skip(1) {
let value = print_medians(&arg).expect("failed to read");
println!("answer = {}", value);
}
}
| {
result = result + 1;
} | conditional_block |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::HashSet;
use std::cmp::Reverse;
fn has_distinct_pair(set:&HashSet<i64>, sum: i64) -> bool {
for k in set.iter() {
let v = sum - k;
if *k != v && set.contains(&v) {
return true;
}
}
false
}
fn print_medians(file_name: &str) -> io::Result<u64> {
let f = File::open(file_name)?;
let reader = BufReader::new(f);
let mut set:HashSet<i64> = HashSet::new();
for line in reader.lines() {
let line = line.unwrap();
let value = i64::from_str(&line).expect("error parsing value");
set.insert(value);
}
| let mut result = 0;
for s in -10000..10001 {
if has_distinct_pair(&set, s) {
result = result + 1;
}
}
Ok(result)
}
fn main() {
for arg in std::env::args().skip(1) {
let value = print_medians(&arg).expect("failed to read");
println!("answer = {}", value);
}
} | random_line_split | |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::HashSet;
use std::cmp::Reverse;
fn | (set:&HashSet<i64>, sum: i64) -> bool {
for k in set.iter() {
let v = sum - k;
if *k != v && set.contains(&v) {
return true;
}
}
false
}
fn print_medians(file_name: &str) -> io::Result<u64> {
let f = File::open(file_name)?;
let reader = BufReader::new(f);
let mut set:HashSet<i64> = HashSet::new();
for line in reader.lines() {
let line = line.unwrap();
let value = i64::from_str(&line).expect("error parsing value");
set.insert(value);
}
let mut result = 0;
for s in -10000..10001 {
if has_distinct_pair(&set, s) {
result = result + 1;
}
}
Ok(result)
}
fn main() {
for arg in std::env::args().skip(1) {
let value = print_medians(&arg).expect("failed to read");
println!("answer = {}", value);
}
}
| has_distinct_pair | identifier_name |
index.js | 'use strict';
const basicAuth = require('basic-auth');
function unauthorized(res, realm) {
const _realm = realm || 'Authorization Required';
res.set('WWW-Authenticate', `Basic realm=${_realm}`);
return res.sendStatus(401);
};
function isPromiseLike(obj) |
function isValidUser(user, username, password) {
return !(!user || user.name !== username || user.pass !== password);
}
function createMiddleware(username, password, realm) {
const _realm = typeof username === 'function'
? password
: realm;
return function basicAuthMiddleware(req, res, next) {
const user = basicAuth(req);
if (!user) {
return unauthorized(res, realm);
}
let authorized = null;
if (typeof username === 'function') {
const checkFn = username;
try {
authorized = checkFn(user.name, user.pass, function checkFnCallback(err, authentified) {
if (err) {
return next(err);
}
if (authentified) {
return next();
}
return unauthorized(res, _realm);
});
} catch(err) {
next(err);
}
} else if (Array.isArray(username)) {
authorized = username.some(([username, password]) => isValidUser(user, username, password));
} else {
authorized = isValidUser(user, username, password);
}
if (isPromiseLike(authorized)) {
return authorized
.then(function(authorized) {
if (authorized === true) {
return next();
}
return unauthorized(res, _realm);
})
.catch(next);
}
if (authorized === false) {
return unauthorized(res, _realm);
}
if (authorized === true) {
return next();
}
};
};
module.exports = createMiddleware;
| {
return obj && typeof obj.then === 'function';
} | identifier_body |
index.js | 'use strict';
const basicAuth = require('basic-auth');
function unauthorized(res, realm) {
const _realm = realm || 'Authorization Required';
res.set('WWW-Authenticate', `Basic realm=${_realm}`);
return res.sendStatus(401);
};
function isPromiseLike(obj) {
return obj && typeof obj.then === 'function';
}
function isValidUser(user, username, password) {
return !(!user || user.name !== username || user.pass !== password);
}
function createMiddleware(username, password, realm) {
const _realm = typeof username === 'function'
? password
: realm;
| }
let authorized = null;
if (typeof username === 'function') {
const checkFn = username;
try {
authorized = checkFn(user.name, user.pass, function checkFnCallback(err, authentified) {
if (err) {
return next(err);
}
if (authentified) {
return next();
}
return unauthorized(res, _realm);
});
} catch(err) {
next(err);
}
} else if (Array.isArray(username)) {
authorized = username.some(([username, password]) => isValidUser(user, username, password));
} else {
authorized = isValidUser(user, username, password);
}
if (isPromiseLike(authorized)) {
return authorized
.then(function(authorized) {
if (authorized === true) {
return next();
}
return unauthorized(res, _realm);
})
.catch(next);
}
if (authorized === false) {
return unauthorized(res, _realm);
}
if (authorized === true) {
return next();
}
};
};
module.exports = createMiddleware; | return function basicAuthMiddleware(req, res, next) {
const user = basicAuth(req);
if (!user) {
return unauthorized(res, realm); | random_line_split |
index.js | 'use strict';
const basicAuth = require('basic-auth');
function unauthorized(res, realm) {
const _realm = realm || 'Authorization Required';
res.set('WWW-Authenticate', `Basic realm=${_realm}`);
return res.sendStatus(401);
};
function | (obj) {
return obj && typeof obj.then === 'function';
}
function isValidUser(user, username, password) {
return !(!user || user.name !== username || user.pass !== password);
}
function createMiddleware(username, password, realm) {
const _realm = typeof username === 'function'
? password
: realm;
return function basicAuthMiddleware(req, res, next) {
const user = basicAuth(req);
if (!user) {
return unauthorized(res, realm);
}
let authorized = null;
if (typeof username === 'function') {
const checkFn = username;
try {
authorized = checkFn(user.name, user.pass, function checkFnCallback(err, authentified) {
if (err) {
return next(err);
}
if (authentified) {
return next();
}
return unauthorized(res, _realm);
});
} catch(err) {
next(err);
}
} else if (Array.isArray(username)) {
authorized = username.some(([username, password]) => isValidUser(user, username, password));
} else {
authorized = isValidUser(user, username, password);
}
if (isPromiseLike(authorized)) {
return authorized
.then(function(authorized) {
if (authorized === true) {
return next();
}
return unauthorized(res, _realm);
})
.catch(next);
}
if (authorized === false) {
return unauthorized(res, _realm);
}
if (authorized === true) {
return next();
}
};
};
module.exports = createMiddleware;
| isPromiseLike | identifier_name |
index.js | 'use strict';
const basicAuth = require('basic-auth');
function unauthorized(res, realm) {
const _realm = realm || 'Authorization Required';
res.set('WWW-Authenticate', `Basic realm=${_realm}`);
return res.sendStatus(401);
};
function isPromiseLike(obj) {
return obj && typeof obj.then === 'function';
}
function isValidUser(user, username, password) {
return !(!user || user.name !== username || user.pass !== password);
}
function createMiddleware(username, password, realm) {
const _realm = typeof username === 'function'
? password
: realm;
return function basicAuthMiddleware(req, res, next) {
const user = basicAuth(req);
if (!user) {
return unauthorized(res, realm);
}
let authorized = null;
if (typeof username === 'function') {
const checkFn = username;
try {
authorized = checkFn(user.name, user.pass, function checkFnCallback(err, authentified) {
if (err) {
return next(err);
}
if (authentified) {
return next();
}
return unauthorized(res, _realm);
});
} catch(err) {
next(err);
}
} else if (Array.isArray(username)) | else {
authorized = isValidUser(user, username, password);
}
if (isPromiseLike(authorized)) {
return authorized
.then(function(authorized) {
if (authorized === true) {
return next();
}
return unauthorized(res, _realm);
})
.catch(next);
}
if (authorized === false) {
return unauthorized(res, _realm);
}
if (authorized === true) {
return next();
}
};
};
module.exports = createMiddleware;
| {
authorized = username.some(([username, password]) => isValidUser(user, username, password));
} | conditional_block |
gtkshortcutgen.py | #!/usr/bin/python3
# vim:fileencoding=utf-8:sw=4:et
"""
GtkShortcutsWindow helper for generating GtkBuilder XML file.
```
shortcuts1 = [
shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"),
]
shortcuts2 = [
shortcut_entry("Import channels from file", "<ctrl>o"),
shortcut_entry("Export channels to file", "<ctrl>e"),
]
groups = [
group_entry("Application", shortcuts1),
group_entry("Import/Export Channels", shortcuts2),
]
sections = [
section_entry("shortcut", groups)
]
entry = shortcut_window_entry("shortcut-window", sections, modal=1)
shortcuts_xml_string = shortcut_xml_gen(entry)
builder = Gtk.Builder()
builder.add_from_string(shortcuts_xml_string)
```
"""
from __future__ import print_function, unicode_literals, absolute_import, division
import sys
import os
import io
import logging as log
NATIVE=sys.getfilesystemencoding()
from lxml import etree
def shortcut_xml_gen(shortcut_entries):
root = etree.Element("interface")
root.append(create_object_tree(shortcut_entries))
content = etree.tostring(root, xml_declaration=True, encoding="UTF-8",
pretty_print=True)
content = content.decode("UTF-8")
return content
def create_object_tree(base_entry):
def objnode(adict):
prefix = "GtkShortcuts"
if not adict["klass"].startswith(prefix):
adict["klass"] = prefix + adict["klass"]
if "attrib" not in adict:
adict["attrib"]= {}
aobj = etree.Element ("object", attrib=adict["attrib"])
aobj.attrib["class"] = adict["klass"]
return aobj
def propnode(name, value):
aobj = etree.Element ("property", attrib={"name": name})
if name == "title":
aobj.attrib["translatable"] = "yes"
aobj.text = str(value)
return aobj
def append_props(parent, item):
if "properties" in item:
props = [propnode(x, y) for x, y in item["properties"].items()]
[parent.append(x) for x in props]
def do_object_tree(entry):
eroot = objnode(entry)
append_props(eroot, entry)
if "childs" in entry:
for kid in entry["childs"]:
ke = etree.Element("child")
eroot.append(ke)
subroot = do_object_tree(kid)
ke.append(subroot)
return eroot
return do_object_tree(base_entry)
def shortcut_entry(title, accel=None, gesture=None, **kwargs):
props = { "title": title, "visible": 1, }
if accel:
props["accelerator"] = accel
if gesture:
props["shortcut-type"] = gesture
props.update(kwargs)
entry = {
"klass": "Shortcut",
"properties": props,
}
return entry
def group_entry(title, shortcuts, **kwargs):
entry = {
"klass":"Group",
"properties": {
"visible": 1,
"title": title,
},
"childs": shortcuts,
}
entry["properties"].update(kwargs)
return entry
def section_entry(name, groups, **kwargs):
entry = {
"klass": "Section",
"properties": {
"visible": 1,
"section-name": name,
},
"childs": groups,
}
entry["properties"].update(kwargs)
return entry
def shortcut_window_entry(id_, sections, **kwargs):
entry = {
"klass": "Window",
"attrib": {"id": id_},
"properties": {"modal": "1"},
"childs": sections,
}
entry["properties"].update(kwargs)
return entry
def main():
def set_stdio_encoding(enc=NATIVE):
|
set_stdio_encoding()
log_level = log.INFO
log.basicConfig(format="%(levelname)s>> %(message)s", level=log_level)
shortcuts1 = [
shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"),
]
shortcuts2 = [
shortcut_entry("Import channels from file", "<ctrl>o"),
shortcut_entry("Export channels to file", "<ctrl>e"),
]
groups = [
group_entry("Application", shortcuts1),
group_entry("Import/Export Channels", shortcuts2),
]
sections = [
section_entry("shortcut", groups)
]
entry = shortcut_window_entry("shortcut-window", sections, modal=1)
content = shortcut_xml_gen(entry)
print(content)
def test_gui(shortcut_xml):
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
builder = Gtk.Builder()
builder.add_from_string(shortcut_xml)
win = builder.get_object("shortcut-window")
win.connect("delete-event", lambda *w: Gtk.main_quit())
win.show_all()
Gtk.main()
test_gui(content)
if __name__ == '__main__':
import signal; signal.signal(signal.SIGINT, signal.SIG_DFL)
main()
| import codecs; stdio = ["stdin", "stdout", "stderr"]
for x in stdio:
obj = getattr(sys, x)
if not obj.encoding: setattr(sys, x, codecs.getwriter(enc)(obj)) | identifier_body |
gtkshortcutgen.py | #!/usr/bin/python3
# vim:fileencoding=utf-8:sw=4:et
"""
GtkShortcutsWindow helper for generating GtkBuilder XML file.
```
shortcuts1 = [
shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"),
]
shortcuts2 = [
shortcut_entry("Import channels from file", "<ctrl>o"),
shortcut_entry("Export channels to file", "<ctrl>e"),
]
groups = [
group_entry("Application", shortcuts1),
group_entry("Import/Export Channels", shortcuts2),
]
sections = [
section_entry("shortcut", groups)
]
entry = shortcut_window_entry("shortcut-window", sections, modal=1)
shortcuts_xml_string = shortcut_xml_gen(entry)
builder = Gtk.Builder()
builder.add_from_string(shortcuts_xml_string)
```
"""
from __future__ import print_function, unicode_literals, absolute_import, division
import sys
import os
import io
import logging as log
NATIVE=sys.getfilesystemencoding()
from lxml import etree
def shortcut_xml_gen(shortcut_entries):
root = etree.Element("interface")
root.append(create_object_tree(shortcut_entries))
content = etree.tostring(root, xml_declaration=True, encoding="UTF-8",
pretty_print=True)
content = content.decode("UTF-8")
return content
def | (base_entry):
def objnode(adict):
prefix = "GtkShortcuts"
if not adict["klass"].startswith(prefix):
adict["klass"] = prefix + adict["klass"]
if "attrib" not in adict:
adict["attrib"]= {}
aobj = etree.Element ("object", attrib=adict["attrib"])
aobj.attrib["class"] = adict["klass"]
return aobj
def propnode(name, value):
aobj = etree.Element ("property", attrib={"name": name})
if name == "title":
aobj.attrib["translatable"] = "yes"
aobj.text = str(value)
return aobj
def append_props(parent, item):
if "properties" in item:
props = [propnode(x, y) for x, y in item["properties"].items()]
[parent.append(x) for x in props]
def do_object_tree(entry):
eroot = objnode(entry)
append_props(eroot, entry)
if "childs" in entry:
for kid in entry["childs"]:
ke = etree.Element("child")
eroot.append(ke)
subroot = do_object_tree(kid)
ke.append(subroot)
return eroot
return do_object_tree(base_entry)
def shortcut_entry(title, accel=None, gesture=None, **kwargs):
props = { "title": title, "visible": 1, }
if accel:
props["accelerator"] = accel
if gesture:
props["shortcut-type"] = gesture
props.update(kwargs)
entry = {
"klass": "Shortcut",
"properties": props,
}
return entry
def group_entry(title, shortcuts, **kwargs):
entry = {
"klass":"Group",
"properties": {
"visible": 1,
"title": title,
},
"childs": shortcuts,
}
entry["properties"].update(kwargs)
return entry
def section_entry(name, groups, **kwargs):
entry = {
"klass": "Section",
"properties": {
"visible": 1,
"section-name": name,
},
"childs": groups,
}
entry["properties"].update(kwargs)
return entry
def shortcut_window_entry(id_, sections, **kwargs):
entry = {
"klass": "Window",
"attrib": {"id": id_},
"properties": {"modal": "1"},
"childs": sections,
}
entry["properties"].update(kwargs)
return entry
def main():
def set_stdio_encoding(enc=NATIVE):
import codecs; stdio = ["stdin", "stdout", "stderr"]
for x in stdio:
obj = getattr(sys, x)
if not obj.encoding: setattr(sys, x, codecs.getwriter(enc)(obj))
set_stdio_encoding()
log_level = log.INFO
log.basicConfig(format="%(levelname)s>> %(message)s", level=log_level)
shortcuts1 = [
shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"),
]
shortcuts2 = [
shortcut_entry("Import channels from file", "<ctrl>o"),
shortcut_entry("Export channels to file", "<ctrl>e"),
]
groups = [
group_entry("Application", shortcuts1),
group_entry("Import/Export Channels", shortcuts2),
]
sections = [
section_entry("shortcut", groups)
]
entry = shortcut_window_entry("shortcut-window", sections, modal=1)
content = shortcut_xml_gen(entry)
print(content)
def test_gui(shortcut_xml):
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
builder = Gtk.Builder()
builder.add_from_string(shortcut_xml)
win = builder.get_object("shortcut-window")
win.connect("delete-event", lambda *w: Gtk.main_quit())
win.show_all()
Gtk.main()
test_gui(content)
if __name__ == '__main__':
import signal; signal.signal(signal.SIGINT, signal.SIG_DFL)
main()
| create_object_tree | identifier_name |
gtkshortcutgen.py | #!/usr/bin/python3
# vim:fileencoding=utf-8:sw=4:et
"""
GtkShortcutsWindow helper for generating GtkBuilder XML file.
```
shortcuts1 = [
shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"),
]
shortcuts2 = [
shortcut_entry("Import channels from file", "<ctrl>o"),
shortcut_entry("Export channels to file", "<ctrl>e"),
]
groups = [
group_entry("Application", shortcuts1),
group_entry("Import/Export Channels", shortcuts2),
]
sections = [
section_entry("shortcut", groups)
]
entry = shortcut_window_entry("shortcut-window", sections, modal=1)
shortcuts_xml_string = shortcut_xml_gen(entry)
builder = Gtk.Builder()
builder.add_from_string(shortcuts_xml_string)
```
"""
from __future__ import print_function, unicode_literals, absolute_import, division
import sys
import os
import io
import logging as log
NATIVE=sys.getfilesystemencoding()
from lxml import etree
def shortcut_xml_gen(shortcut_entries):
root = etree.Element("interface")
root.append(create_object_tree(shortcut_entries))
content = etree.tostring(root, xml_declaration=True, encoding="UTF-8",
pretty_print=True)
content = content.decode("UTF-8")
return content
def create_object_tree(base_entry):
def objnode(adict):
prefix = "GtkShortcuts"
if not adict["klass"].startswith(prefix):
adict["klass"] = prefix + adict["klass"]
if "attrib" not in adict:
adict["attrib"]= {}
aobj = etree.Element ("object", attrib=adict["attrib"])
aobj.attrib["class"] = adict["klass"]
return aobj
def propnode(name, value):
aobj = etree.Element ("property", attrib={"name": name})
if name == "title":
aobj.attrib["translatable"] = "yes"
aobj.text = str(value)
return aobj
def append_props(parent, item):
if "properties" in item:
props = [propnode(x, y) for x, y in item["properties"].items()]
[parent.append(x) for x in props]
def do_object_tree(entry):
eroot = objnode(entry)
append_props(eroot, entry)
if "childs" in entry:
for kid in entry["childs"]:
ke = etree.Element("child")
eroot.append(ke)
subroot = do_object_tree(kid)
ke.append(subroot)
return eroot
return do_object_tree(base_entry)
def shortcut_entry(title, accel=None, gesture=None, **kwargs):
props = { "title": title, "visible": 1, }
if accel:
props["accelerator"] = accel
if gesture:
props["shortcut-type"] = gesture
props.update(kwargs)
entry = {
"klass": "Shortcut",
"properties": props,
}
return entry
def group_entry(title, shortcuts, **kwargs):
entry = {
"klass":"Group",
"properties": {
"visible": 1,
"title": title,
},
"childs": shortcuts,
}
entry["properties"].update(kwargs) | entry = {
"klass": "Section",
"properties": {
"visible": 1,
"section-name": name,
},
"childs": groups,
}
entry["properties"].update(kwargs)
return entry
def shortcut_window_entry(id_, sections, **kwargs):
entry = {
"klass": "Window",
"attrib": {"id": id_},
"properties": {"modal": "1"},
"childs": sections,
}
entry["properties"].update(kwargs)
return entry
def main():
def set_stdio_encoding(enc=NATIVE):
import codecs; stdio = ["stdin", "stdout", "stderr"]
for x in stdio:
obj = getattr(sys, x)
if not obj.encoding: setattr(sys, x, codecs.getwriter(enc)(obj))
set_stdio_encoding()
log_level = log.INFO
log.basicConfig(format="%(levelname)s>> %(message)s", level=log_level)
shortcuts1 = [
shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"),
]
shortcuts2 = [
shortcut_entry("Import channels from file", "<ctrl>o"),
shortcut_entry("Export channels to file", "<ctrl>e"),
]
groups = [
group_entry("Application", shortcuts1),
group_entry("Import/Export Channels", shortcuts2),
]
sections = [
section_entry("shortcut", groups)
]
entry = shortcut_window_entry("shortcut-window", sections, modal=1)
content = shortcut_xml_gen(entry)
print(content)
def test_gui(shortcut_xml):
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
builder = Gtk.Builder()
builder.add_from_string(shortcut_xml)
win = builder.get_object("shortcut-window")
win.connect("delete-event", lambda *w: Gtk.main_quit())
win.show_all()
Gtk.main()
test_gui(content)
if __name__ == '__main__':
import signal; signal.signal(signal.SIGINT, signal.SIG_DFL)
main() | return entry
def section_entry(name, groups, **kwargs): | random_line_split |
gtkshortcutgen.py | #!/usr/bin/python3
# vim:fileencoding=utf-8:sw=4:et
"""
GtkShortcutsWindow helper for generating GtkBuilder XML file.
```
shortcuts1 = [
shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"),
]
shortcuts2 = [
shortcut_entry("Import channels from file", "<ctrl>o"),
shortcut_entry("Export channels to file", "<ctrl>e"),
]
groups = [
group_entry("Application", shortcuts1),
group_entry("Import/Export Channels", shortcuts2),
]
sections = [
section_entry("shortcut", groups)
]
entry = shortcut_window_entry("shortcut-window", sections, modal=1)
shortcuts_xml_string = shortcut_xml_gen(entry)
builder = Gtk.Builder()
builder.add_from_string(shortcuts_xml_string)
```
"""
from __future__ import print_function, unicode_literals, absolute_import, division
import sys
import os
import io
import logging as log
NATIVE=sys.getfilesystemencoding()
from lxml import etree
def shortcut_xml_gen(shortcut_entries):
root = etree.Element("interface")
root.append(create_object_tree(shortcut_entries))
content = etree.tostring(root, xml_declaration=True, encoding="UTF-8",
pretty_print=True)
content = content.decode("UTF-8")
return content
def create_object_tree(base_entry):
def objnode(adict):
prefix = "GtkShortcuts"
if not adict["klass"].startswith(prefix):
|
if "attrib" not in adict:
adict["attrib"]= {}
aobj = etree.Element ("object", attrib=adict["attrib"])
aobj.attrib["class"] = adict["klass"]
return aobj
def propnode(name, value):
aobj = etree.Element ("property", attrib={"name": name})
if name == "title":
aobj.attrib["translatable"] = "yes"
aobj.text = str(value)
return aobj
def append_props(parent, item):
if "properties" in item:
props = [propnode(x, y) for x, y in item["properties"].items()]
[parent.append(x) for x in props]
def do_object_tree(entry):
eroot = objnode(entry)
append_props(eroot, entry)
if "childs" in entry:
for kid in entry["childs"]:
ke = etree.Element("child")
eroot.append(ke)
subroot = do_object_tree(kid)
ke.append(subroot)
return eroot
return do_object_tree(base_entry)
def shortcut_entry(title, accel=None, gesture=None, **kwargs):
props = { "title": title, "visible": 1, }
if accel:
props["accelerator"] = accel
if gesture:
props["shortcut-type"] = gesture
props.update(kwargs)
entry = {
"klass": "Shortcut",
"properties": props,
}
return entry
def group_entry(title, shortcuts, **kwargs):
entry = {
"klass":"Group",
"properties": {
"visible": 1,
"title": title,
},
"childs": shortcuts,
}
entry["properties"].update(kwargs)
return entry
def section_entry(name, groups, **kwargs):
entry = {
"klass": "Section",
"properties": {
"visible": 1,
"section-name": name,
},
"childs": groups,
}
entry["properties"].update(kwargs)
return entry
def shortcut_window_entry(id_, sections, **kwargs):
entry = {
"klass": "Window",
"attrib": {"id": id_},
"properties": {"modal": "1"},
"childs": sections,
}
entry["properties"].update(kwargs)
return entry
def main():
def set_stdio_encoding(enc=NATIVE):
import codecs; stdio = ["stdin", "stdout", "stderr"]
for x in stdio:
obj = getattr(sys, x)
if not obj.encoding: setattr(sys, x, codecs.getwriter(enc)(obj))
set_stdio_encoding()
log_level = log.INFO
log.basicConfig(format="%(levelname)s>> %(message)s", level=log_level)
shortcuts1 = [
shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"),
]
shortcuts2 = [
shortcut_entry("Import channels from file", "<ctrl>o"),
shortcut_entry("Export channels to file", "<ctrl>e"),
]
groups = [
group_entry("Application", shortcuts1),
group_entry("Import/Export Channels", shortcuts2),
]
sections = [
section_entry("shortcut", groups)
]
entry = shortcut_window_entry("shortcut-window", sections, modal=1)
content = shortcut_xml_gen(entry)
print(content)
def test_gui(shortcut_xml):
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
builder = Gtk.Builder()
builder.add_from_string(shortcut_xml)
win = builder.get_object("shortcut-window")
win.connect("delete-event", lambda *w: Gtk.main_quit())
win.show_all()
Gtk.main()
test_gui(content)
if __name__ == '__main__':
import signal; signal.signal(signal.SIGINT, signal.SIG_DFL)
main()
| adict["klass"] = prefix + adict["klass"] | conditional_block |
form_builder_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {FormBuilder, FormControl} from '@angular/forms';
import {PromiseWrapper} from '../src/facade/promise';
export function main() | {
function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; }
function asyncValidator(_: any /** TODO #9100 */) { return PromiseWrapper.resolve(null); }
describe('Form Builder', () => {
var b: any /** TODO #9100 */;
beforeEach(() => { b = new FormBuilder(); });
it('should create controls from a value', () => {
var g = b.group({'login': 'some value'});
expect(g.controls['login'].value).toEqual('some value');
});
it('should create controls from an array', () => {
var g = b.group(
{'login': ['some value'], 'password': ['some value', syncValidator, asyncValidator]});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['password'].value).toEqual('some value');
expect(g.controls['password'].validator).toEqual(syncValidator);
expect(g.controls['password'].asyncValidator).toEqual(asyncValidator);
});
it('should use controls', () => {
var g = b.group({'login': b.control('some value', syncValidator, asyncValidator)});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it('should create groups with optional controls', () => {
var g = b.group({'login': 'some value'}, {'optionals': {'login': false}});
expect(g.contains('login')).toEqual(false);
});
it('should create groups with a custom validator', () => {
var g = b.group(
{'login': 'some value'}, {'validator': syncValidator, 'asyncValidator': asyncValidator});
expect(g.validator).toBe(syncValidator);
expect(g.asyncValidator).toBe(asyncValidator);
});
it('should create control arrays', () => {
var c = b.control('three');
var a = b.array(
['one', ['two', syncValidator], c, b.array(['four'])], syncValidator, asyncValidator);
expect(a.value).toEqual(['one', 'two', 'three', ['four']]);
expect(a.validator).toBe(syncValidator);
expect(a.asyncValidator).toBe(asyncValidator);
});
});
} | identifier_body | |
form_builder_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {FormBuilder, FormControl} from '@angular/forms';
import {PromiseWrapper} from '../src/facade/promise';
export function main() {
function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; }
function | (_: any /** TODO #9100 */) { return PromiseWrapper.resolve(null); }
describe('Form Builder', () => {
var b: any /** TODO #9100 */;
beforeEach(() => { b = new FormBuilder(); });
it('should create controls from a value', () => {
var g = b.group({'login': 'some value'});
expect(g.controls['login'].value).toEqual('some value');
});
it('should create controls from an array', () => {
var g = b.group(
{'login': ['some value'], 'password': ['some value', syncValidator, asyncValidator]});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['password'].value).toEqual('some value');
expect(g.controls['password'].validator).toEqual(syncValidator);
expect(g.controls['password'].asyncValidator).toEqual(asyncValidator);
});
it('should use controls', () => {
var g = b.group({'login': b.control('some value', syncValidator, asyncValidator)});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it('should create groups with optional controls', () => {
var g = b.group({'login': 'some value'}, {'optionals': {'login': false}});
expect(g.contains('login')).toEqual(false);
});
it('should create groups with a custom validator', () => {
var g = b.group(
{'login': 'some value'}, {'validator': syncValidator, 'asyncValidator': asyncValidator});
expect(g.validator).toBe(syncValidator);
expect(g.asyncValidator).toBe(asyncValidator);
});
it('should create control arrays', () => {
var c = b.control('three');
var a = b.array(
['one', ['two', syncValidator], c, b.array(['four'])], syncValidator, asyncValidator);
expect(a.value).toEqual(['one', 'two', 'three', ['four']]);
expect(a.validator).toBe(syncValidator);
expect(a.asyncValidator).toBe(asyncValidator);
});
});
}
| asyncValidator | identifier_name |
form_builder_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {FormBuilder, FormControl} from '@angular/forms';
import {PromiseWrapper} from '../src/facade/promise';
export function main() { | var b: any /** TODO #9100 */;
beforeEach(() => { b = new FormBuilder(); });
it('should create controls from a value', () => {
var g = b.group({'login': 'some value'});
expect(g.controls['login'].value).toEqual('some value');
});
it('should create controls from an array', () => {
var g = b.group(
{'login': ['some value'], 'password': ['some value', syncValidator, asyncValidator]});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['password'].value).toEqual('some value');
expect(g.controls['password'].validator).toEqual(syncValidator);
expect(g.controls['password'].asyncValidator).toEqual(asyncValidator);
});
it('should use controls', () => {
var g = b.group({'login': b.control('some value', syncValidator, asyncValidator)});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it('should create groups with optional controls', () => {
var g = b.group({'login': 'some value'}, {'optionals': {'login': false}});
expect(g.contains('login')).toEqual(false);
});
it('should create groups with a custom validator', () => {
var g = b.group(
{'login': 'some value'}, {'validator': syncValidator, 'asyncValidator': asyncValidator});
expect(g.validator).toBe(syncValidator);
expect(g.asyncValidator).toBe(asyncValidator);
});
it('should create control arrays', () => {
var c = b.control('three');
var a = b.array(
['one', ['two', syncValidator], c, b.array(['four'])], syncValidator, asyncValidator);
expect(a.value).toEqual(['one', 'two', 'three', ['four']]);
expect(a.validator).toBe(syncValidator);
expect(a.asyncValidator).toBe(asyncValidator);
});
});
} | function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; }
function asyncValidator(_: any /** TODO #9100 */) { return PromiseWrapper.resolve(null); }
describe('Form Builder', () => { | random_line_split |
test_dolfin_linear_solver.py | # Copyright (C) 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
import pytest
from numpy import isclose
from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction,
UnitSquareMesh)
from rbnics.backends import LinearSolver as FactoryLinearSolver
from rbnics.backends.dolfin import LinearSolver as DolfinLinearSolver
from test_dolfin_utils import RandomDolfinFunction
LinearSolver = None
AllLinearSolver = {"dolfin": DolfinLinearSolver, "factory": FactoryLinearSolver}
class Data(object):
def __init__(self, Th, callback_type):
# Create mesh and define function space
mesh = UnitSquareMesh(Th, Th)
self.V = FunctionSpace(mesh, "Lagrange", 1)
# Define variational problem
u = TrialFunction(self.V)
v = TestFunction(self.V)
self.a = inner(grad(u), grad(v)) * dx + inner(u, v) * dx
self.f = lambda g: g * v * dx
# Define callback function depending on callback type
assert callback_type in ("form callbacks", "tensor callbacks")
if callback_type == "form callbacks":
def callback(arg):
return arg
elif callback_type == "tensor callbacks":
def callback(arg):
return assemble(arg)
self.callback_type = callback_type
self.callback = callback
def generate_random(self):
# Generate random rhs
g = RandomDolfinFunction(self.V)
# Return
return (self.a, self.f(g))
def evaluate_builtin(self, a, f):
a = self.callback(a)
f = self.callback(f)
result_builtin = Function(self.V)
if self.callback_type == "form callbacks":
solve(a == f, result_builtin, solver_parameters={"linear_solver": "mumps"})
elif self.callback_type == "tensor callbacks":
solve(a, result_builtin.vector(), f, "mumps")
return result_builtin
def evaluate_backend(self, a, f):
a = self.callback(a)
f = self.callback(f)
result_backend = Function(self.V)
solver = LinearSolver(a, result_backend, f)
solver.set_parameters({
"linear_solver": "mumps"
})
solver.solve()
return result_backend
def assert_backend(self, a, f, result_backend):
result_builtin = self.evaluate_builtin(a, f)
error = Function(self.V)
error.vector().add_local(+ result_backend.vector().get_local())
error.vector().add_local(- result_builtin.vector().get_local())
error.vector().apply("add")
relative_error = error.vector().norm("l2") / result_builtin.vector().norm("l2")
assert isclose(relative_error, 0., atol=1e-12)
@pytest.mark.parametrize("Th", [2**i for i in range(3, 9)])
@pytest.mark.parametrize("callback_type", ["form callbacks", "tensor callbacks"])
@pytest.mark.parametrize("test_type", ["builtin"] + list(AllLinearSolver.keys()))
def test_dolfin_linear_solver(Th, callback_type, test_type, benchmark):
data = Data(Th, callback_type)
print("Th = " + str(Th) + ", Nh = " + str(data.V.dim()))
if test_type == "builtin":
print("Testing " + test_type + ", callback_type = " + callback_type)
benchmark(data.evaluate_builtin, setup=data.generate_random)
else:
| print("Testing " + test_type + " backend" + ", callback_type = " + callback_type)
global LinearSolver
LinearSolver = AllLinearSolver[test_type]
benchmark(data.evaluate_backend, setup=data.generate_random, teardown=data.assert_backend) | conditional_block | |
test_dolfin_linear_solver.py | # Copyright (C) 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
import pytest
from numpy import isclose
from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction,
UnitSquareMesh)
from rbnics.backends import LinearSolver as FactoryLinearSolver
from rbnics.backends.dolfin import LinearSolver as DolfinLinearSolver
from test_dolfin_utils import RandomDolfinFunction
LinearSolver = None
AllLinearSolver = {"dolfin": DolfinLinearSolver, "factory": FactoryLinearSolver}
class Data(object):
def __init__(self, Th, callback_type):
# Create mesh and define function space
mesh = UnitSquareMesh(Th, Th)
self.V = FunctionSpace(mesh, "Lagrange", 1)
# Define variational problem
u = TrialFunction(self.V)
v = TestFunction(self.V)
self.a = inner(grad(u), grad(v)) * dx + inner(u, v) * dx
self.f = lambda g: g * v * dx
# Define callback function depending on callback type
assert callback_type in ("form callbacks", "tensor callbacks")
if callback_type == "form callbacks":
def | (arg):
return arg
elif callback_type == "tensor callbacks":
def callback(arg):
return assemble(arg)
self.callback_type = callback_type
self.callback = callback
def generate_random(self):
# Generate random rhs
g = RandomDolfinFunction(self.V)
# Return
return (self.a, self.f(g))
def evaluate_builtin(self, a, f):
a = self.callback(a)
f = self.callback(f)
result_builtin = Function(self.V)
if self.callback_type == "form callbacks":
solve(a == f, result_builtin, solver_parameters={"linear_solver": "mumps"})
elif self.callback_type == "tensor callbacks":
solve(a, result_builtin.vector(), f, "mumps")
return result_builtin
def evaluate_backend(self, a, f):
a = self.callback(a)
f = self.callback(f)
result_backend = Function(self.V)
solver = LinearSolver(a, result_backend, f)
solver.set_parameters({
"linear_solver": "mumps"
})
solver.solve()
return result_backend
def assert_backend(self, a, f, result_backend):
result_builtin = self.evaluate_builtin(a, f)
error = Function(self.V)
error.vector().add_local(+ result_backend.vector().get_local())
error.vector().add_local(- result_builtin.vector().get_local())
error.vector().apply("add")
relative_error = error.vector().norm("l2") / result_builtin.vector().norm("l2")
assert isclose(relative_error, 0., atol=1e-12)
@pytest.mark.parametrize("Th", [2**i for i in range(3, 9)])
@pytest.mark.parametrize("callback_type", ["form callbacks", "tensor callbacks"])
@pytest.mark.parametrize("test_type", ["builtin"] + list(AllLinearSolver.keys()))
def test_dolfin_linear_solver(Th, callback_type, test_type, benchmark):
data = Data(Th, callback_type)
print("Th = " + str(Th) + ", Nh = " + str(data.V.dim()))
if test_type == "builtin":
print("Testing " + test_type + ", callback_type = " + callback_type)
benchmark(data.evaluate_builtin, setup=data.generate_random)
else:
print("Testing " + test_type + " backend" + ", callback_type = " + callback_type)
global LinearSolver
LinearSolver = AllLinearSolver[test_type]
benchmark(data.evaluate_backend, setup=data.generate_random, teardown=data.assert_backend)
| callback | identifier_name |
test_dolfin_linear_solver.py | # Copyright (C) 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
import pytest
from numpy import isclose
from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction,
UnitSquareMesh)
from rbnics.backends import LinearSolver as FactoryLinearSolver
from rbnics.backends.dolfin import LinearSolver as DolfinLinearSolver
from test_dolfin_utils import RandomDolfinFunction
LinearSolver = None
AllLinearSolver = {"dolfin": DolfinLinearSolver, "factory": FactoryLinearSolver}
class Data(object):
def __init__(self, Th, callback_type):
# Create mesh and define function space
mesh = UnitSquareMesh(Th, Th)
self.V = FunctionSpace(mesh, "Lagrange", 1)
# Define variational problem
u = TrialFunction(self.V)
v = TestFunction(self.V)
self.a = inner(grad(u), grad(v)) * dx + inner(u, v) * dx
self.f = lambda g: g * v * dx
# Define callback function depending on callback type
assert callback_type in ("form callbacks", "tensor callbacks")
if callback_type == "form callbacks":
def callback(arg):
return arg
elif callback_type == "tensor callbacks":
def callback(arg):
return assemble(arg)
self.callback_type = callback_type
self.callback = callback
def generate_random(self):
# Generate random rhs
g = RandomDolfinFunction(self.V)
# Return
return (self.a, self.f(g))
def evaluate_builtin(self, a, f):
a = self.callback(a)
f = self.callback(f)
result_builtin = Function(self.V)
if self.callback_type == "form callbacks":
solve(a == f, result_builtin, solver_parameters={"linear_solver": "mumps"})
elif self.callback_type == "tensor callbacks":
solve(a, result_builtin.vector(), f, "mumps")
return result_builtin
def evaluate_backend(self, a, f):
|
def assert_backend(self, a, f, result_backend):
result_builtin = self.evaluate_builtin(a, f)
error = Function(self.V)
error.vector().add_local(+ result_backend.vector().get_local())
error.vector().add_local(- result_builtin.vector().get_local())
error.vector().apply("add")
relative_error = error.vector().norm("l2") / result_builtin.vector().norm("l2")
assert isclose(relative_error, 0., atol=1e-12)
@pytest.mark.parametrize("Th", [2**i for i in range(3, 9)])
@pytest.mark.parametrize("callback_type", ["form callbacks", "tensor callbacks"])
@pytest.mark.parametrize("test_type", ["builtin"] + list(AllLinearSolver.keys()))
def test_dolfin_linear_solver(Th, callback_type, test_type, benchmark):
data = Data(Th, callback_type)
print("Th = " + str(Th) + ", Nh = " + str(data.V.dim()))
if test_type == "builtin":
print("Testing " + test_type + ", callback_type = " + callback_type)
benchmark(data.evaluate_builtin, setup=data.generate_random)
else:
print("Testing " + test_type + " backend" + ", callback_type = " + callback_type)
global LinearSolver
LinearSolver = AllLinearSolver[test_type]
benchmark(data.evaluate_backend, setup=data.generate_random, teardown=data.assert_backend)
| a = self.callback(a)
f = self.callback(f)
result_backend = Function(self.V)
solver = LinearSolver(a, result_backend, f)
solver.set_parameters({
"linear_solver": "mumps"
})
solver.solve()
return result_backend | identifier_body |
test_dolfin_linear_solver.py | # Copyright (C) 2015-2022 by the RBniCS authors | # SPDX-License-Identifier: LGPL-3.0-or-later
import pytest
from numpy import isclose
from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction,
UnitSquareMesh)
from rbnics.backends import LinearSolver as FactoryLinearSolver
from rbnics.backends.dolfin import LinearSolver as DolfinLinearSolver
from test_dolfin_utils import RandomDolfinFunction
LinearSolver = None
AllLinearSolver = {"dolfin": DolfinLinearSolver, "factory": FactoryLinearSolver}
class Data(object):
def __init__(self, Th, callback_type):
# Create mesh and define function space
mesh = UnitSquareMesh(Th, Th)
self.V = FunctionSpace(mesh, "Lagrange", 1)
# Define variational problem
u = TrialFunction(self.V)
v = TestFunction(self.V)
self.a = inner(grad(u), grad(v)) * dx + inner(u, v) * dx
self.f = lambda g: g * v * dx
# Define callback function depending on callback type
assert callback_type in ("form callbacks", "tensor callbacks")
if callback_type == "form callbacks":
def callback(arg):
return arg
elif callback_type == "tensor callbacks":
def callback(arg):
return assemble(arg)
self.callback_type = callback_type
self.callback = callback
def generate_random(self):
# Generate random rhs
g = RandomDolfinFunction(self.V)
# Return
return (self.a, self.f(g))
def evaluate_builtin(self, a, f):
a = self.callback(a)
f = self.callback(f)
result_builtin = Function(self.V)
if self.callback_type == "form callbacks":
solve(a == f, result_builtin, solver_parameters={"linear_solver": "mumps"})
elif self.callback_type == "tensor callbacks":
solve(a, result_builtin.vector(), f, "mumps")
return result_builtin
def evaluate_backend(self, a, f):
a = self.callback(a)
f = self.callback(f)
result_backend = Function(self.V)
solver = LinearSolver(a, result_backend, f)
solver.set_parameters({
"linear_solver": "mumps"
})
solver.solve()
return result_backend
def assert_backend(self, a, f, result_backend):
result_builtin = self.evaluate_builtin(a, f)
error = Function(self.V)
error.vector().add_local(+ result_backend.vector().get_local())
error.vector().add_local(- result_builtin.vector().get_local())
error.vector().apply("add")
relative_error = error.vector().norm("l2") / result_builtin.vector().norm("l2")
assert isclose(relative_error, 0., atol=1e-12)
@pytest.mark.parametrize("Th", [2**i for i in range(3, 9)])
@pytest.mark.parametrize("callback_type", ["form callbacks", "tensor callbacks"])
@pytest.mark.parametrize("test_type", ["builtin"] + list(AllLinearSolver.keys()))
def test_dolfin_linear_solver(Th, callback_type, test_type, benchmark):
data = Data(Th, callback_type)
print("Th = " + str(Th) + ", Nh = " + str(data.V.dim()))
if test_type == "builtin":
print("Testing " + test_type + ", callback_type = " + callback_type)
benchmark(data.evaluate_builtin, setup=data.generate_random)
else:
print("Testing " + test_type + " backend" + ", callback_type = " + callback_type)
global LinearSolver
LinearSolver = AllLinearSolver[test_type]
benchmark(data.evaluate_backend, setup=data.generate_random, teardown=data.assert_backend) | #
# This file is part of RBniCS.
# | random_line_split |
ToolRegistry.ts | /**
* Copyright © 2021 Rémi Pace.
* This file is part of Abc-Map.
*
* Abc-Map is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Abc-Map is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General
* Public License along with Abc-Map. If not, see <https://www.gnu.org/licenses/>.
*/
import { AbstractTool } from './AbstractTool';
import { NoneTool } from './none/NoneTool';
import { PointTool } from './point/PointTool';
import { MapTool } from '@abc-map/shared';
import { mainStore } from '../store/store';
import { LineStringTool } from './line-string/LineStringTool';
import { PolygonTool } from './polygon/PolygonTool';
import { SelectionTool } from './selection/SelectionTool';
import { TextTool } from './text/TextTool';
import { getServices } from '../Services';
import { EditPropertiesTool } from './edit-properties/EditPropertiesTool';
export class ToolRegistry {
public static ge | : AbstractTool[] {
const history = getServices().history;
const modals = getServices().modals;
return [
new NoneTool(mainStore, history),
new PointTool(mainStore, history),
new LineStringTool(mainStore, history),
new PolygonTool(mainStore, history),
new TextTool(mainStore, history),
new SelectionTool(mainStore, history),
new EditPropertiesTool(mainStore, history, modals),
];
}
public static getById(id: MapTool): AbstractTool {
const result = this.getAll().find((tl) => tl.getId() === id);
if (!result) {
throw new Error(`Tool not found: ${id}`);
}
return result;
}
}
| tAll() | identifier_name |
ToolRegistry.ts | /**
* Copyright © 2021 Rémi Pace.
* This file is part of Abc-Map.
*
* Abc-Map is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Abc-Map is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General
* Public License along with Abc-Map. If not, see <https://www.gnu.org/licenses/>.
*/
import { AbstractTool } from './AbstractTool';
import { NoneTool } from './none/NoneTool';
import { PointTool } from './point/PointTool';
import { MapTool } from '@abc-map/shared';
import { mainStore } from '../store/store';
import { LineStringTool } from './line-string/LineStringTool';
import { PolygonTool } from './polygon/PolygonTool';
import { SelectionTool } from './selection/SelectionTool';
import { TextTool } from './text/TextTool';
import { getServices } from '../Services';
import { EditPropertiesTool } from './edit-properties/EditPropertiesTool';
export class ToolRegistry {
public static getAll(): AbstractTool[] {
const history = getServices().history;
const modals = getServices().modals;
return [
new NoneTool(mainStore, history),
new PointTool(mainStore, history),
new LineStringTool(mainStore, history),
new PolygonTool(mainStore, history),
new TextTool(mainStore, history),
new SelectionTool(mainStore, history),
new EditPropertiesTool(mainStore, history, modals),
];
}
public static getById(id: MapTool): AbstractTool {
const result = this.getAll().find((tl) => tl.getId() === id);
if (!result) {
| return result;
}
}
| throw new Error(`Tool not found: ${id}`);
}
| conditional_block |
ToolRegistry.ts | /**
* Copyright © 2021 Rémi Pace.
* This file is part of Abc-Map.
*
* Abc-Map is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as | * the License, or (at your option) any later version.
*
* Abc-Map is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General
* Public License along with Abc-Map. If not, see <https://www.gnu.org/licenses/>.
*/
import { AbstractTool } from './AbstractTool';
import { NoneTool } from './none/NoneTool';
import { PointTool } from './point/PointTool';
import { MapTool } from '@abc-map/shared';
import { mainStore } from '../store/store';
import { LineStringTool } from './line-string/LineStringTool';
import { PolygonTool } from './polygon/PolygonTool';
import { SelectionTool } from './selection/SelectionTool';
import { TextTool } from './text/TextTool';
import { getServices } from '../Services';
import { EditPropertiesTool } from './edit-properties/EditPropertiesTool';
export class ToolRegistry {
public static getAll(): AbstractTool[] {
const history = getServices().history;
const modals = getServices().modals;
return [
new NoneTool(mainStore, history),
new PointTool(mainStore, history),
new LineStringTool(mainStore, history),
new PolygonTool(mainStore, history),
new TextTool(mainStore, history),
new SelectionTool(mainStore, history),
new EditPropertiesTool(mainStore, history, modals),
];
}
public static getById(id: MapTool): AbstractTool {
const result = this.getAll().find((tl) => tl.getId() === id);
if (!result) {
throw new Error(`Tool not found: ${id}`);
}
return result;
}
} | * published by the Free Software Foundation, either version 3 of | random_line_split |
20160112212733-create-workout.js | /* jshint node: true */
/* jshint esversion: 6 */
'use strict';
module.exports = { | allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
workout_date: {
type: Sequelize.DATEONLY
},
UserId: {
allowNull: false,
references: {
model: 'Users',
key: 'id'
},
type: Sequelize.BIGINT
},
LocationId: {
allowNull: false,
references: {
model: 'Locations',
key: 'id'
},
type: Sequelize.BIGINT
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Workouts');
}
}; | up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Workouts', {
id: { | random_line_split |
get_event_authorization.rs | //! `GET /_matrix/federation/*/event_auth/{roomId}/{eventId}`
//!
//! Endpoint to retrieve the complete auth chain for a given event.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1event_authroomideventid
use ruma_common::{api::ruma_api, EventId, RoomId};
use serde_json::value::RawValue as RawJsonValue;
ruma_api! {
metadata: {
description: "Retrieves the complete auth chain for a given event.",
name: "get_event_authorization",
method: GET,
stable_path: "/_matrix/federation/v1/event_auth/:room_id/:event_id",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// The room ID to get the auth chain for.
#[ruma_api(path)]
pub room_id: &'a RoomId,
/// The event ID to get the auth chain for.
#[ruma_api(path)]
pub event_id: &'a EventId,
}
response: {
/// The full set of authorization events that make up the state of the room,
/// and their authorization events, recursively.
pub auth_chain: Vec<Box<RawJsonValue>>,
}
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given room id and event id.
pub fn new(room_id: &'a RoomId, event_id: &'a EventId) -> Self {
Self { room_id, event_id }
}
}
impl Response {
/// Creates a new `Response` with the given auth chain.
pub fn new(auth_chain: Vec<Box<RawJsonValue>>) -> Self |
}
}
| {
Self { auth_chain }
} | identifier_body |
get_event_authorization.rs | //! `GET /_matrix/federation/*/event_auth/{roomId}/{eventId}`
//!
//! Endpoint to retrieve the complete auth chain for a given event.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1event_authroomideventid
use ruma_common::{api::ruma_api, EventId, RoomId};
use serde_json::value::RawValue as RawJsonValue;
ruma_api! {
metadata: {
description: "Retrieves the complete auth chain for a given event.",
name: "get_event_authorization",
method: GET,
stable_path: "/_matrix/federation/v1/event_auth/:room_id/:event_id",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// The room ID to get the auth chain for.
#[ruma_api(path)]
pub room_id: &'a RoomId,
/// The event ID to get the auth chain for.
#[ruma_api(path)]
pub event_id: &'a EventId,
}
response: {
/// The full set of authorization events that make up the state of the room,
/// and their authorization events, recursively.
pub auth_chain: Vec<Box<RawJsonValue>>,
}
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given room id and event id.
pub fn new(room_id: &'a RoomId, event_id: &'a EventId) -> Self {
Self { room_id, event_id }
}
}
impl Response {
/// Creates a new `Response` with the given auth chain.
pub fn | (auth_chain: Vec<Box<RawJsonValue>>) -> Self {
Self { auth_chain }
}
}
}
| new | identifier_name |
mod.rs | // Copyright 2017 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
mod callback;
mod executor;
mod lock;
mod promise;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use futures::task::{self, Task};
use futures::{Async, Future, Poll};
use self::callback::{Abort, Request as RequestCallback, UnaryRequest as UnaryRequestCallback};
use self::executor::SpawnNotify;
use self::promise::{Batch as BatchPromise, Shutdown as ShutdownPromise};
use crate::call::server::RequestContext;
use crate::call::{BatchContext, Call, MessageReader};
use crate::cq::CompletionQueue;
use crate::error::{Error, Result};
use crate::server::RequestCallContext;
pub(crate) use self::executor::{Executor, Kicker};
pub use self::lock::SpinLock;
pub use self::promise::BatchType;
/// A handle that is used to notify future that the task finishes.
pub struct NotifyHandle<T> {
result: Option<Result<T>>,
task: Option<Task>,
stale: bool,
}
impl<T> NotifyHandle<T> {
fn new() -> NotifyHandle<T> {
NotifyHandle {
result: None,
task: None,
stale: false,
}
}
/// Set the result and notify future if necessary.
fn set_result(&mut self, res: Result<T>) -> Option<Task> {
self.result = Some(res);
self.task.take()
}
}
type Inner<T> = SpinLock<NotifyHandle<T>>;
fn new_inner<T>() -> Arc<Inner<T>> {
Arc::new(SpinLock::new(NotifyHandle::new()))
}
/// Get the future status without the need to poll.
///
/// If the future is polled successfully, this function will return None.
/// Not implemented as method as it's only for internal usage.
pub fn check_alive<T>(f: &CqFuture<T>) -> Result<()> {
let guard = f.inner.lock();
match guard.result {
None => Ok(()),
Some(Err(Error::RpcFailure(ref status))) => {
Err(Error::RpcFinished(Some(status.to_owned())))
}
Some(Ok(_)) | Some(Err(_)) => Err(Error::RpcFinished(None)),
}
}
/// A future object for task that is scheduled to `CompletionQueue`.
pub struct CqFuture<T> {
inner: Arc<Inner<T>>,
}
impl<T> CqFuture<T> {
fn new(inner: Arc<Inner<T>>) -> CqFuture<T> {
CqFuture { inner }
}
}
impl<T> Future for CqFuture<T> {
type Item = T;
type Error = Error;
fn poll(&mut self) -> Poll<T, Error> {
let mut guard = self.inner.lock();
if guard.stale {
panic!("Resolved future is not supposed to be polled again.");
}
if let Some(res) = guard.result.take() {
guard.stale = true;
return Ok(Async::Ready(res?));
}
// So the task has not been finished yet, add notification hook.
if guard.task.is_none() || !guard.task.as_ref().unwrap().will_notify_current() {
guard.task = Some(task::current());
}
Ok(Async::NotReady)
}
}
/// Future object for batch jobs.
pub type BatchFuture = CqFuture<Option<MessageReader>>;
/// A result holder for asynchronous execution.
// This enum is going to be passed to FFI, so don't use trait or generic here.
pub enum CallTag {
Batch(BatchPromise),
Request(RequestCallback),
UnaryRequest(UnaryRequestCallback),
Abort(Abort),
Shutdown(ShutdownPromise),
Spawn(SpawnNotify),
}
impl CallTag {
/// Generate a Future/CallTag pair for batch jobs.
pub fn batch_pair(ty: BatchType) -> (BatchFuture, CallTag) {
let inner = new_inner();
let batch = BatchPromise::new(ty, inner.clone());
(CqFuture::new(inner), CallTag::Batch(batch))
}
/// Generate a CallTag for request job. We don't have an eventloop
/// to pull the future, so just the tag is enough.
pub fn request(ctx: RequestCallContext) -> CallTag {
CallTag::Request(RequestCallback::new(ctx))
}
/// Generate a Future/CallTag pair for shutdown call.
pub fn shutdown_pair() -> (CqFuture<()>, CallTag) {
let inner = new_inner();
let shutdown = ShutdownPromise::new(inner.clone());
(CqFuture::new(inner), CallTag::Shutdown(shutdown))
}
/// Generate a CallTag for abort call before handler is called.
pub fn abort(call: Call) -> CallTag {
CallTag::Abort(Abort::new(call))
}
/// Generate a CallTag for unary request job.
pub fn unary_request(ctx: RequestContext, rc: RequestCallContext) -> CallTag {
let cb = UnaryRequestCallback::new(ctx, rc);
CallTag::UnaryRequest(cb)
}
/// Get the batch context from result holder.
pub fn batch_ctx(&self) -> Option<&BatchContext> {
match *self {
CallTag::Batch(ref prom) => Some(prom.context()),
CallTag::UnaryRequest(ref cb) => Some(cb.batch_ctx()),
CallTag::Abort(ref cb) => Some(cb.batch_ctx()),
_ => None,
}
}
/// Get the request context from the result holder.
pub fn request_ctx(&self) -> Option<&RequestContext> {
match *self {
CallTag::Request(ref prom) => Some(prom.context()),
CallTag::UnaryRequest(ref cb) => Some(cb.request_ctx()),
_ => None,
} | CallTag::Batch(prom) => prom.resolve(success),
CallTag::Request(cb) => cb.resolve(cq, success),
CallTag::UnaryRequest(cb) => cb.resolve(cq, success),
CallTag::Abort(_) => {}
CallTag::Shutdown(prom) => prom.resolve(success),
CallTag::Spawn(notify) => notify.resolve(success),
}
}
}
impl Debug for CallTag {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match *self {
CallTag::Batch(ref ctx) => write!(f, "CallTag::Batch({:?})", ctx),
CallTag::Request(_) => write!(f, "CallTag::Request(..)"),
CallTag::UnaryRequest(_) => write!(f, "CallTag::UnaryRequest(..)"),
CallTag::Abort(_) => write!(f, "CallTag::Abort(..)"),
CallTag::Shutdown(_) => write!(f, "CallTag::Shutdown"),
CallTag::Spawn(_) => write!(f, "CallTag::Spawn"),
}
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc::*;
use std::sync::*;
use std::thread;
use super::*;
use crate::env::Environment;
#[test]
fn test_resolve() {
let env = Environment::new(1);
let (cq_f1, tag1) = CallTag::shutdown_pair();
let (cq_f2, tag2) = CallTag::shutdown_pair();
let (tx, rx) = mpsc::channel();
let handler = thread::spawn(move || {
tx.send(cq_f1.wait()).unwrap();
tx.send(cq_f2.wait()).unwrap();
});
assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Empty);
tag1.resolve(&env.pick_cq(), true);
assert!(rx.recv().unwrap().is_ok());
assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Empty);
tag2.resolve(&env.pick_cq(), false);
match rx.recv() {
Ok(Err(Error::ShutdownFailed)) => {}
res => panic!("expect shutdown failed, but got {:?}", res),
}
handler.join().unwrap();
}
} | }
/// Resolve the CallTag with given status.
pub fn resolve(self, cq: &CompletionQueue, success: bool) {
match self { | random_line_split |
mod.rs | // Copyright 2017 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
mod callback;
mod executor;
mod lock;
mod promise;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use futures::task::{self, Task};
use futures::{Async, Future, Poll};
use self::callback::{Abort, Request as RequestCallback, UnaryRequest as UnaryRequestCallback};
use self::executor::SpawnNotify;
use self::promise::{Batch as BatchPromise, Shutdown as ShutdownPromise};
use crate::call::server::RequestContext;
use crate::call::{BatchContext, Call, MessageReader};
use crate::cq::CompletionQueue;
use crate::error::{Error, Result};
use crate::server::RequestCallContext;
pub(crate) use self::executor::{Executor, Kicker};
pub use self::lock::SpinLock;
pub use self::promise::BatchType;
/// A handle that is used to notify future that the task finishes.
pub struct NotifyHandle<T> {
result: Option<Result<T>>,
task: Option<Task>,
stale: bool,
}
impl<T> NotifyHandle<T> {
fn new() -> NotifyHandle<T> {
NotifyHandle {
result: None,
task: None,
stale: false,
}
}
/// Set the result and notify future if necessary.
fn set_result(&mut self, res: Result<T>) -> Option<Task> {
self.result = Some(res);
self.task.take()
}
}
type Inner<T> = SpinLock<NotifyHandle<T>>;
fn new_inner<T>() -> Arc<Inner<T>> {
Arc::new(SpinLock::new(NotifyHandle::new()))
}
/// Get the future status without the need to poll.
///
/// If the future is polled successfully, this function will return None.
/// Not implemented as method as it's only for internal usage.
pub fn check_alive<T>(f: &CqFuture<T>) -> Result<()> {
let guard = f.inner.lock();
match guard.result {
None => Ok(()),
Some(Err(Error::RpcFailure(ref status))) => {
Err(Error::RpcFinished(Some(status.to_owned())))
}
Some(Ok(_)) | Some(Err(_)) => Err(Error::RpcFinished(None)),
}
}
/// A future object for task that is scheduled to `CompletionQueue`.
pub struct CqFuture<T> {
inner: Arc<Inner<T>>,
}
impl<T> CqFuture<T> {
fn new(inner: Arc<Inner<T>>) -> CqFuture<T> {
CqFuture { inner }
}
}
impl<T> Future for CqFuture<T> {
type Item = T;
type Error = Error;
fn | (&mut self) -> Poll<T, Error> {
let mut guard = self.inner.lock();
if guard.stale {
panic!("Resolved future is not supposed to be polled again.");
}
if let Some(res) = guard.result.take() {
guard.stale = true;
return Ok(Async::Ready(res?));
}
// So the task has not been finished yet, add notification hook.
if guard.task.is_none() || !guard.task.as_ref().unwrap().will_notify_current() {
guard.task = Some(task::current());
}
Ok(Async::NotReady)
}
}
/// Future object for batch jobs.
pub type BatchFuture = CqFuture<Option<MessageReader>>;
/// A result holder for asynchronous execution.
// This enum is going to be passed to FFI, so don't use trait or generic here.
pub enum CallTag {
Batch(BatchPromise),
Request(RequestCallback),
UnaryRequest(UnaryRequestCallback),
Abort(Abort),
Shutdown(ShutdownPromise),
Spawn(SpawnNotify),
}
impl CallTag {
/// Generate a Future/CallTag pair for batch jobs.
pub fn batch_pair(ty: BatchType) -> (BatchFuture, CallTag) {
let inner = new_inner();
let batch = BatchPromise::new(ty, inner.clone());
(CqFuture::new(inner), CallTag::Batch(batch))
}
/// Generate a CallTag for request job. We don't have an eventloop
/// to pull the future, so just the tag is enough.
pub fn request(ctx: RequestCallContext) -> CallTag {
CallTag::Request(RequestCallback::new(ctx))
}
/// Generate a Future/CallTag pair for shutdown call.
pub fn shutdown_pair() -> (CqFuture<()>, CallTag) {
let inner = new_inner();
let shutdown = ShutdownPromise::new(inner.clone());
(CqFuture::new(inner), CallTag::Shutdown(shutdown))
}
/// Generate a CallTag for abort call before handler is called.
pub fn abort(call: Call) -> CallTag {
CallTag::Abort(Abort::new(call))
}
/// Generate a CallTag for unary request job.
pub fn unary_request(ctx: RequestContext, rc: RequestCallContext) -> CallTag {
let cb = UnaryRequestCallback::new(ctx, rc);
CallTag::UnaryRequest(cb)
}
/// Get the batch context from result holder.
pub fn batch_ctx(&self) -> Option<&BatchContext> {
match *self {
CallTag::Batch(ref prom) => Some(prom.context()),
CallTag::UnaryRequest(ref cb) => Some(cb.batch_ctx()),
CallTag::Abort(ref cb) => Some(cb.batch_ctx()),
_ => None,
}
}
/// Get the request context from the result holder.
pub fn request_ctx(&self) -> Option<&RequestContext> {
match *self {
CallTag::Request(ref prom) => Some(prom.context()),
CallTag::UnaryRequest(ref cb) => Some(cb.request_ctx()),
_ => None,
}
}
/// Resolve the CallTag with given status.
pub fn resolve(self, cq: &CompletionQueue, success: bool) {
match self {
CallTag::Batch(prom) => prom.resolve(success),
CallTag::Request(cb) => cb.resolve(cq, success),
CallTag::UnaryRequest(cb) => cb.resolve(cq, success),
CallTag::Abort(_) => {}
CallTag::Shutdown(prom) => prom.resolve(success),
CallTag::Spawn(notify) => notify.resolve(success),
}
}
}
impl Debug for CallTag {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match *self {
CallTag::Batch(ref ctx) => write!(f, "CallTag::Batch({:?})", ctx),
CallTag::Request(_) => write!(f, "CallTag::Request(..)"),
CallTag::UnaryRequest(_) => write!(f, "CallTag::UnaryRequest(..)"),
CallTag::Abort(_) => write!(f, "CallTag::Abort(..)"),
CallTag::Shutdown(_) => write!(f, "CallTag::Shutdown"),
CallTag::Spawn(_) => write!(f, "CallTag::Spawn"),
}
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc::*;
use std::sync::*;
use std::thread;
use super::*;
use crate::env::Environment;
#[test]
fn test_resolve() {
let env = Environment::new(1);
let (cq_f1, tag1) = CallTag::shutdown_pair();
let (cq_f2, tag2) = CallTag::shutdown_pair();
let (tx, rx) = mpsc::channel();
let handler = thread::spawn(move || {
tx.send(cq_f1.wait()).unwrap();
tx.send(cq_f2.wait()).unwrap();
});
assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Empty);
tag1.resolve(&env.pick_cq(), true);
assert!(rx.recv().unwrap().is_ok());
assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Empty);
tag2.resolve(&env.pick_cq(), false);
match rx.recv() {
Ok(Err(Error::ShutdownFailed)) => {}
res => panic!("expect shutdown failed, but got {:?}", res),
}
handler.join().unwrap();
}
}
| poll | identifier_name |
mod.rs | // Copyright 2017 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
mod callback;
mod executor;
mod lock;
mod promise;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use futures::task::{self, Task};
use futures::{Async, Future, Poll};
use self::callback::{Abort, Request as RequestCallback, UnaryRequest as UnaryRequestCallback};
use self::executor::SpawnNotify;
use self::promise::{Batch as BatchPromise, Shutdown as ShutdownPromise};
use crate::call::server::RequestContext;
use crate::call::{BatchContext, Call, MessageReader};
use crate::cq::CompletionQueue;
use crate::error::{Error, Result};
use crate::server::RequestCallContext;
pub(crate) use self::executor::{Executor, Kicker};
pub use self::lock::SpinLock;
pub use self::promise::BatchType;
/// A handle that is used to notify future that the task finishes.
pub struct NotifyHandle<T> {
result: Option<Result<T>>,
task: Option<Task>,
stale: bool,
}
impl<T> NotifyHandle<T> {
fn new() -> NotifyHandle<T> {
NotifyHandle {
result: None,
task: None,
stale: false,
}
}
/// Set the result and notify future if necessary.
fn set_result(&mut self, res: Result<T>) -> Option<Task> {
self.result = Some(res);
self.task.take()
}
}
type Inner<T> = SpinLock<NotifyHandle<T>>;
fn new_inner<T>() -> Arc<Inner<T>> {
Arc::new(SpinLock::new(NotifyHandle::new()))
}
/// Get the future status without the need to poll.
///
/// If the future is polled successfully, this function will return None.
/// Not implemented as method as it's only for internal usage.
pub fn check_alive<T>(f: &CqFuture<T>) -> Result<()> {
let guard = f.inner.lock();
match guard.result {
None => Ok(()),
Some(Err(Error::RpcFailure(ref status))) => {
Err(Error::RpcFinished(Some(status.to_owned())))
}
Some(Ok(_)) | Some(Err(_)) => Err(Error::RpcFinished(None)),
}
}
/// A future object for task that is scheduled to `CompletionQueue`.
pub struct CqFuture<T> {
inner: Arc<Inner<T>>,
}
impl<T> CqFuture<T> {
fn new(inner: Arc<Inner<T>>) -> CqFuture<T> {
CqFuture { inner }
}
}
impl<T> Future for CqFuture<T> {
type Item = T;
type Error = Error;
fn poll(&mut self) -> Poll<T, Error> {
let mut guard = self.inner.lock();
if guard.stale {
panic!("Resolved future is not supposed to be polled again.");
}
if let Some(res) = guard.result.take() {
guard.stale = true;
return Ok(Async::Ready(res?));
}
// So the task has not been finished yet, add notification hook.
if guard.task.is_none() || !guard.task.as_ref().unwrap().will_notify_current() {
guard.task = Some(task::current());
}
Ok(Async::NotReady)
}
}
/// Future object for batch jobs.
pub type BatchFuture = CqFuture<Option<MessageReader>>;
/// A result holder for asynchronous execution.
// This enum is going to be passed to FFI, so don't use trait or generic here.
pub enum CallTag {
Batch(BatchPromise),
Request(RequestCallback),
UnaryRequest(UnaryRequestCallback),
Abort(Abort),
Shutdown(ShutdownPromise),
Spawn(SpawnNotify),
}
impl CallTag {
/// Generate a Future/CallTag pair for batch jobs.
pub fn batch_pair(ty: BatchType) -> (BatchFuture, CallTag) {
let inner = new_inner();
let batch = BatchPromise::new(ty, inner.clone());
(CqFuture::new(inner), CallTag::Batch(batch))
}
/// Generate a CallTag for request job. We don't have an eventloop
/// to pull the future, so just the tag is enough.
pub fn request(ctx: RequestCallContext) -> CallTag {
CallTag::Request(RequestCallback::new(ctx))
}
/// Generate a Future/CallTag pair for shutdown call.
pub fn shutdown_pair() -> (CqFuture<()>, CallTag) {
let inner = new_inner();
let shutdown = ShutdownPromise::new(inner.clone());
(CqFuture::new(inner), CallTag::Shutdown(shutdown))
}
/// Generate a CallTag for abort call before handler is called.
pub fn abort(call: Call) -> CallTag {
CallTag::Abort(Abort::new(call))
}
/// Generate a CallTag for unary request job.
pub fn unary_request(ctx: RequestContext, rc: RequestCallContext) -> CallTag {
let cb = UnaryRequestCallback::new(ctx, rc);
CallTag::UnaryRequest(cb)
}
/// Get the batch context from result holder.
pub fn batch_ctx(&self) -> Option<&BatchContext> {
match *self {
CallTag::Batch(ref prom) => Some(prom.context()),
CallTag::UnaryRequest(ref cb) => Some(cb.batch_ctx()),
CallTag::Abort(ref cb) => Some(cb.batch_ctx()),
_ => None,
}
}
/// Get the request context from the result holder.
pub fn request_ctx(&self) -> Option<&RequestContext> {
match *self {
CallTag::Request(ref prom) => Some(prom.context()),
CallTag::UnaryRequest(ref cb) => Some(cb.request_ctx()),
_ => None,
}
}
/// Resolve the CallTag with given status.
pub fn resolve(self, cq: &CompletionQueue, success: bool) {
match self {
CallTag::Batch(prom) => prom.resolve(success),
CallTag::Request(cb) => cb.resolve(cq, success),
CallTag::UnaryRequest(cb) => cb.resolve(cq, success),
CallTag::Abort(_) => {}
CallTag::Shutdown(prom) => prom.resolve(success),
CallTag::Spawn(notify) => notify.resolve(success),
}
}
}
impl Debug for CallTag {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result |
}
#[cfg(test)]
mod tests {
use std::sync::mpsc::*;
use std::sync::*;
use std::thread;
use super::*;
use crate::env::Environment;
#[test]
fn test_resolve() {
let env = Environment::new(1);
let (cq_f1, tag1) = CallTag::shutdown_pair();
let (cq_f2, tag2) = CallTag::shutdown_pair();
let (tx, rx) = mpsc::channel();
let handler = thread::spawn(move || {
tx.send(cq_f1.wait()).unwrap();
tx.send(cq_f2.wait()).unwrap();
});
assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Empty);
tag1.resolve(&env.pick_cq(), true);
assert!(rx.recv().unwrap().is_ok());
assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Empty);
tag2.resolve(&env.pick_cq(), false);
match rx.recv() {
Ok(Err(Error::ShutdownFailed)) => {}
res => panic!("expect shutdown failed, but got {:?}", res),
}
handler.join().unwrap();
}
}
| {
match *self {
CallTag::Batch(ref ctx) => write!(f, "CallTag::Batch({:?})", ctx),
CallTag::Request(_) => write!(f, "CallTag::Request(..)"),
CallTag::UnaryRequest(_) => write!(f, "CallTag::UnaryRequest(..)"),
CallTag::Abort(_) => write!(f, "CallTag::Abort(..)"),
CallTag::Shutdown(_) => write!(f, "CallTag::Shutdown"),
CallTag::Spawn(_) => write!(f, "CallTag::Spawn"),
}
} | identifier_body |
utm.py | # -*- coding: utf-8 -*-
"""Working with UTM and Lat/Long coordinates
Based on http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html
"""
from math import sin, cos, sqrt, tan, pi, floor
__author__ = "P. Tute, C. Taylor"
__maintainer__ = "B. Henne"
__contact__ = "henne@dcsec.uni-hannover.de"
__copyright__ = "(c) 1997-2003 C. Taylor, 2010-2011, DCSec, Leibniz Universitaet Hannover, Germany"
__license__ = """
The Python code is based on Javascript code of Charles L. Taylor from
http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html
The author allowed us to reuse his code.
Original license:
The documents, images, and other materials on the Chuck Taylor
Web site are copyright (c) 1997-2003 by C. Taylor, unless otherwise noted.
Visitors are permitted to download the materials located on the Chuck Taylor
Web site to their own systems, on a temporary basis, for the purpose of viewing
them or, in the case of software applications, using them in accordance with
their intended purpose.
Republishing or redistribution of any of the materials located on the Chuck Taylor
Web site requires permission from C. Taylor. MoSP has been granted to use the code."""
# Ellipsoid model constants (actual values here are for WGS84)
UTMScaleFactor = 0.9996 #: Ellipsoid model constant
sm_a = 6378137.0 #: Ellipsoid model constant: Semi-major axis a
sm_b = 6356752.314 #: Ellipsoid model constant: Semi-major axis b
sm_EccSquared = 6.69437999013e-03 #: Ellipsoid model constant
def long_to_zone(lon):
"""Calculates the current UTM-zone for a given longitude."""
return floor((lon + 180.0) / 6) + 1
def rad_to_deg(rad):
"""Converts radians to degrees."""
return (rad / pi * 180.0)
def deg_to_rad(deg):
"""Converts degrees to radians."""
return (deg / 180.0 * pi)
def UTMCentralMeridian(zone):
"""Calculates the central meridian for the given UTM-zone."""
return deg_to_rad(-183.0 + (zone * 6.0))
def ArcLengthOfMeridian(phi):
|
def MapLatLonToXY(phi, lambd, lambd0, xy):
"""Converts a latitude/longitude pair to x and y coordinates in the
Transverse Mercator projection. Note that Transverse Mercator is not
the same as UTM a scale factor is required to convert between them.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate ep2
ep2 = (sm_a**2.0 - sm_b**2.0) / sm_b**2.0
# Precalculate nu2
nu2 = ep2 * cos(phi)**2.0
# Precalculate N
N = sm_a**2.0 / (sm_b * sqrt(1 + nu2))
# Precalculate t
t = tan(phi)
t2 = t**2.0
# Precalculate l
l = lambd - lambd0
# Precalculate coefficients for l**n in the equations below
# so a normal human being can read the expressions for easting
# and northing
# -- l**1 and l**2 have coefficients of 1.0
l3coef = 1.0 - t2 + nu2
l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2**2.0)
l5coef = 5.0 - 18.0 * t2 + (t2**2.0) + 14.0 * nu2 - 58.0 * t2 * nu2
l6coef = 61.0 - 58.0 * t2 + (t2**2.0) + 270.0 * nu2 - 330.0 * t2 * nu2
l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2**2.0) - (t2**3.0)
l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2**2.0) - (t2**3.0)
# Calculate easting (x)
xy[0] = (N * cos(phi) * l + (N / 6.0 * cos(phi)**3.0 * l3coef * l**3.0)
+ (N / 120.0 * cos(phi)**5.0 * l5coef * l**5.0)
+ (N / 5040.0 * cos(phi)**7.0 * l7coef * l**7.0))
# Calculate northing (y)
xy[1] = (ArcLengthOfMeridian(phi)
+ (t / 2.0 * N * cos(phi)**2.0 * l**2.0)
+ (t / 24.0 * N * cos(phi)**4.0 * l4coef * l**4.0)
+ (t / 720.0 * N * cos(phi)**6.0 * l6coef * l**6.0)
+ (t / 40320.0 * N * cos(phi)**8.0 * l8coef * l**8.0))
return
def latlong_to_utm(lon, lat, zone = None):
"""Converts a latitude/longitude pair to x and y coordinates in the
Universal Transverse Mercator projection."""
if zone is None:
zone = long_to_zone(lon)
xy = [0, 0]
MapLatLonToXY(deg_to_rad(lat), deg_to_rad(lon), UTMCentralMeridian(zone), xy)
xy[0] = xy[0] * UTMScaleFactor + 500000.0
xy[1] = xy[1] * UTMScaleFactor
if xy[1] < 0.0:
xy[1] = xy[1] + 10000000.0
return [round(coord, 2) for coord in xy]
def FootpointLatitude(y):
"""Computes the footpoint latitude for use in converting transverse
Mercator coordinates to ellipsoidal coordinates.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate n (Eq. 10.18)
n = (sm_a - sm_b) / (sm_a + sm_b)
# Precalculate alpha_ (Eq. 10.22)
# (Same as alpha in Eq. 10.17)
alpha_ = (((sm_a + sm_b) / 2.0)
* (1 + (n**2.0 / 4) + (n**4.0 / 64)))
# Precalculate y_ (Eq. 10.23)
y_ = y / alpha_
# Precalculate beta_ (Eq. 10.22)
beta_ = ((3.0 * n / 2.0) + (-27.0 * n**3.0 / 32.0)
+ (269.0 * n**5.0 / 512.0))
# Precalculate gamma_ (Eq. 10.22)
gamma_ = ((21.0 * n**2.0 / 16.0)
+ (-55.0 * n**4.0 / 32.0))
# Precalculate delta_ (Eq. 10.22)
delta_ = ((151.0 * n**3.0 / 96.0)
+ (-417.0 * n**5.0 / 128.0))
# Precalculate epsilon_ (Eq. 10.22)
epsilon_ = ((1097.0 * n**4.0 / 512.0))
# Now calculate the sum of the series (Eq. 10.21)
result = (y_ + (beta_ * sin(2.0 * y_))
+ (gamma_ * sin(4.0 * y_))
+ (delta_ * sin(6.0 * y_))
+ (epsilon_ * sin(8.0 * y_)))
return result
def MapXYToLatLon(x, y, lambda0):
"""Converts x and y coordinates in the Transverse Mercator projection to
a latitude/longitude pair. Note that Transverse Mercator is not
the same as UTM a scale factor is required to convert between them.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994.
Remarks:
The local variables Nf, nuf2, tf, and tf2 serve the same purpose as
N, nu2, t, and t2 in MapLatLonToXY, but they are computed with respect
sto the footpoint latitude phif.
x1frac, x2frac, x2poly, x3poly, etc. are to enhance readability and
to optimize computations."""
philambda = []
# Get the value of phif, the footpoint latitude.
phif = FootpointLatitude(y)
# Precalculate ep2
ep2 = ((sm_a**2.0 - sm_b**2.0)
/ sm_b**2.0)
# Precalculate cos (phif)
cf = cos(phif)
# Precalculate nuf2
nuf2 = ep2 * cf**2.0
# Precalculate Nf and initialize Nfpow
Nf = sm_a**2.0 / (sm_b * sqrt(1 + nuf2))
Nfpow = Nf
# Precalculate tf
tf = tan(phif)
tf2 = tf**2
tf4 = tf2**2
# Precalculate fractional coefficients for x**n in the equations
# below to simplify the expressions for latitude and longitude.
x1frac = 1.0 / (Nfpow * cf)
Nfpow *= Nf # now equals Nf**2)
x2frac = tf / (2.0 * Nfpow)
Nfpow *= Nf # now equals Nf**3)
x3frac = 1.0 / (6.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**4)
x4frac = tf / (24.0 * Nfpow)
Nfpow *= Nf # now equals Nf**5)
x5frac = 1.0 / (120.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**6)
x6frac = tf / (720.0 * Nfpow)
Nfpow *= Nf # now equals Nf**7)
x7frac = 1.0 / (5040.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**8)
x8frac = tf / (40320.0 * Nfpow)
# Precalculate polynomial coefficients for x**n.
# -- x**1 does not have a polynomial coefficient.
x2poly = -1.0 - nuf2
x3poly = -1.0 - 2 * tf2 - nuf2
x4poly = (5.0 + 3.0 * tf2 + 6.0 * nuf2 - 6.0 * tf2 * nuf2
- 3.0 * (nuf2 *nuf2) - 9.0 * tf2 * (nuf2 * nuf2))
x5poly = 5.0 + 28.0 * tf2 + 24.0 * tf4 + 6.0 * nuf2 + 8.0 * tf2 * nuf2
x6poly = (-61.0 - 90.0 * tf2 - 45.0 * tf4 - 107.0 * nuf2
+ 162.0 * tf2 * nuf2)
x7poly = -61.0 - 662.0 * tf2 - 1320.0 * tf4 - 720.0 * (tf4 * tf2)
x8poly = 1385.0 + 3633.0 * tf2 + 4095.0 * tf4 + 1575 * (tf4 * tf2)
# Calculate latitude
philambda.append(phif + x2frac * x2poly * x**2
+ x4frac * x4poly * x**4.0
+ x6frac * x6poly * x**6.0
+ x8frac * x8poly * x**8.0)
# Calculate longitude
philambda.append(lambda0 + x1frac * x
+ x3frac * x3poly * x**3.0
+ x5frac * x5poly * x**5.0
+ x7frac * x7poly * x**7.0)
return philambda
def utm_to_latlong(x, y, zone, southhemi=False):
"""Converts x and y coordinates in the Universal Transverse Mercator
projection to a latitude/longitude pair."""
x -= 500000.0
x /= UTMScaleFactor
# If in southern hemisphere, adjust y accordingly.
if southhemi:
y -= 10000000.0
y /= UTMScaleFactor
cmeridian = UTMCentralMeridian(zone)
lat_lon = MapXYToLatLon(x, y, cmeridian)
return list(reversed([rad_to_deg(i) for i in lat_lon]))
| """Computes the ellipsoidal distance from the equator to a point at a
given latitude.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate n
n = (sm_a - sm_b) / (sm_a + sm_b)
# Precalculate alpha
alpha = (((sm_a + sm_b) / 2.0)
* (1.0 + (n**2.0 / 4.0) + (n**4.0 / 64.0)))
# Precalculate beta
beta = ((-3.0 * n / 2.0) + (9.0 * n**3.0 / 16.0)
+ (-3.0 * n**5.0 / 32.0))
# Precalculate gamma
gamma = ((15.0 * n**2.0 / 16.0)
+ (-15.0 * n**4.0 / 32.0))
# Precalculate delta
delta = ((-35.0 * n**3.0 / 48.0)
+ (105.0 * n**5.0 / 256.0))
# Precalculate epsilon
epsilon = (315.0 * n**4.0 / 512.0)
# Now calculate the sum of the series and return
result = (alpha
* (phi + (beta * sin(2.0 * phi))
+ (gamma * sin(4.0 * phi))
+ (delta * sin(6.0 * phi))
+ (epsilon * sin(8.0 * phi))))
return result | identifier_body |
utm.py | # -*- coding: utf-8 -*-
"""Working with UTM and Lat/Long coordinates
Based on http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html
"""
from math import sin, cos, sqrt, tan, pi, floor
__author__ = "P. Tute, C. Taylor"
__maintainer__ = "B. Henne"
__contact__ = "henne@dcsec.uni-hannover.de"
__copyright__ = "(c) 1997-2003 C. Taylor, 2010-2011, DCSec, Leibniz Universitaet Hannover, Germany"
__license__ = """
The Python code is based on Javascript code of Charles L. Taylor from
http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html
The author allowed us to reuse his code.
Original license:
The documents, images, and other materials on the Chuck Taylor
Web site are copyright (c) 1997-2003 by C. Taylor, unless otherwise noted.
Visitors are permitted to download the materials located on the Chuck Taylor
Web site to their own systems, on a temporary basis, for the purpose of viewing
them or, in the case of software applications, using them in accordance with
their intended purpose.
Republishing or redistribution of any of the materials located on the Chuck Taylor
Web site requires permission from C. Taylor. MoSP has been granted to use the code."""
# Ellipsoid model constants (actual values here are for WGS84)
UTMScaleFactor = 0.9996 #: Ellipsoid model constant
sm_a = 6378137.0 #: Ellipsoid model constant: Semi-major axis a
sm_b = 6356752.314 #: Ellipsoid model constant: Semi-major axis b
sm_EccSquared = 6.69437999013e-03 #: Ellipsoid model constant
def long_to_zone(lon):
"""Calculates the current UTM-zone for a given longitude."""
return floor((lon + 180.0) / 6) + 1
def rad_to_deg(rad):
"""Converts radians to degrees."""
return (rad / pi * 180.0)
def | (deg):
"""Converts degrees to radians."""
return (deg / 180.0 * pi)
def UTMCentralMeridian(zone):
"""Calculates the central meridian for the given UTM-zone."""
return deg_to_rad(-183.0 + (zone * 6.0))
def ArcLengthOfMeridian(phi):
"""Computes the ellipsoidal distance from the equator to a point at a
given latitude.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate n
n = (sm_a - sm_b) / (sm_a + sm_b)
# Precalculate alpha
alpha = (((sm_a + sm_b) / 2.0)
* (1.0 + (n**2.0 / 4.0) + (n**4.0 / 64.0)))
# Precalculate beta
beta = ((-3.0 * n / 2.0) + (9.0 * n**3.0 / 16.0)
+ (-3.0 * n**5.0 / 32.0))
# Precalculate gamma
gamma = ((15.0 * n**2.0 / 16.0)
+ (-15.0 * n**4.0 / 32.0))
# Precalculate delta
delta = ((-35.0 * n**3.0 / 48.0)
+ (105.0 * n**5.0 / 256.0))
# Precalculate epsilon
epsilon = (315.0 * n**4.0 / 512.0)
# Now calculate the sum of the series and return
result = (alpha
* (phi + (beta * sin(2.0 * phi))
+ (gamma * sin(4.0 * phi))
+ (delta * sin(6.0 * phi))
+ (epsilon * sin(8.0 * phi))))
return result
def MapLatLonToXY(phi, lambd, lambd0, xy):
"""Converts a latitude/longitude pair to x and y coordinates in the
Transverse Mercator projection. Note that Transverse Mercator is not
the same as UTM a scale factor is required to convert between them.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate ep2
ep2 = (sm_a**2.0 - sm_b**2.0) / sm_b**2.0
# Precalculate nu2
nu2 = ep2 * cos(phi)**2.0
# Precalculate N
N = sm_a**2.0 / (sm_b * sqrt(1 + nu2))
# Precalculate t
t = tan(phi)
t2 = t**2.0
# Precalculate l
l = lambd - lambd0
# Precalculate coefficients for l**n in the equations below
# so a normal human being can read the expressions for easting
# and northing
# -- l**1 and l**2 have coefficients of 1.0
l3coef = 1.0 - t2 + nu2
l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2**2.0)
l5coef = 5.0 - 18.0 * t2 + (t2**2.0) + 14.0 * nu2 - 58.0 * t2 * nu2
l6coef = 61.0 - 58.0 * t2 + (t2**2.0) + 270.0 * nu2 - 330.0 * t2 * nu2
l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2**2.0) - (t2**3.0)
l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2**2.0) - (t2**3.0)
# Calculate easting (x)
xy[0] = (N * cos(phi) * l + (N / 6.0 * cos(phi)**3.0 * l3coef * l**3.0)
+ (N / 120.0 * cos(phi)**5.0 * l5coef * l**5.0)
+ (N / 5040.0 * cos(phi)**7.0 * l7coef * l**7.0))
# Calculate northing (y)
xy[1] = (ArcLengthOfMeridian(phi)
+ (t / 2.0 * N * cos(phi)**2.0 * l**2.0)
+ (t / 24.0 * N * cos(phi)**4.0 * l4coef * l**4.0)
+ (t / 720.0 * N * cos(phi)**6.0 * l6coef * l**6.0)
+ (t / 40320.0 * N * cos(phi)**8.0 * l8coef * l**8.0))
return
def latlong_to_utm(lon, lat, zone = None):
"""Converts a latitude/longitude pair to x and y coordinates in the
Universal Transverse Mercator projection."""
if zone is None:
zone = long_to_zone(lon)
xy = [0, 0]
MapLatLonToXY(deg_to_rad(lat), deg_to_rad(lon), UTMCentralMeridian(zone), xy)
xy[0] = xy[0] * UTMScaleFactor + 500000.0
xy[1] = xy[1] * UTMScaleFactor
if xy[1] < 0.0:
xy[1] = xy[1] + 10000000.0
return [round(coord, 2) for coord in xy]
def FootpointLatitude(y):
"""Computes the footpoint latitude for use in converting transverse
Mercator coordinates to ellipsoidal coordinates.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate n (Eq. 10.18)
n = (sm_a - sm_b) / (sm_a + sm_b)
# Precalculate alpha_ (Eq. 10.22)
# (Same as alpha in Eq. 10.17)
alpha_ = (((sm_a + sm_b) / 2.0)
* (1 + (n**2.0 / 4) + (n**4.0 / 64)))
# Precalculate y_ (Eq. 10.23)
y_ = y / alpha_
# Precalculate beta_ (Eq. 10.22)
beta_ = ((3.0 * n / 2.0) + (-27.0 * n**3.0 / 32.0)
+ (269.0 * n**5.0 / 512.0))
# Precalculate gamma_ (Eq. 10.22)
gamma_ = ((21.0 * n**2.0 / 16.0)
+ (-55.0 * n**4.0 / 32.0))
# Precalculate delta_ (Eq. 10.22)
delta_ = ((151.0 * n**3.0 / 96.0)
+ (-417.0 * n**5.0 / 128.0))
# Precalculate epsilon_ (Eq. 10.22)
epsilon_ = ((1097.0 * n**4.0 / 512.0))
# Now calculate the sum of the series (Eq. 10.21)
result = (y_ + (beta_ * sin(2.0 * y_))
+ (gamma_ * sin(4.0 * y_))
+ (delta_ * sin(6.0 * y_))
+ (epsilon_ * sin(8.0 * y_)))
return result
def MapXYToLatLon(x, y, lambda0):
"""Converts x and y coordinates in the Transverse Mercator projection to
a latitude/longitude pair. Note that Transverse Mercator is not
the same as UTM a scale factor is required to convert between them.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994.
Remarks:
The local variables Nf, nuf2, tf, and tf2 serve the same purpose as
N, nu2, t, and t2 in MapLatLonToXY, but they are computed with respect
sto the footpoint latitude phif.
x1frac, x2frac, x2poly, x3poly, etc. are to enhance readability and
to optimize computations."""
philambda = []
# Get the value of phif, the footpoint latitude.
phif = FootpointLatitude(y)
# Precalculate ep2
ep2 = ((sm_a**2.0 - sm_b**2.0)
/ sm_b**2.0)
# Precalculate cos (phif)
cf = cos(phif)
# Precalculate nuf2
nuf2 = ep2 * cf**2.0
# Precalculate Nf and initialize Nfpow
Nf = sm_a**2.0 / (sm_b * sqrt(1 + nuf2))
Nfpow = Nf
# Precalculate tf
tf = tan(phif)
tf2 = tf**2
tf4 = tf2**2
# Precalculate fractional coefficients for x**n in the equations
# below to simplify the expressions for latitude and longitude.
x1frac = 1.0 / (Nfpow * cf)
Nfpow *= Nf # now equals Nf**2)
x2frac = tf / (2.0 * Nfpow)
Nfpow *= Nf # now equals Nf**3)
x3frac = 1.0 / (6.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**4)
x4frac = tf / (24.0 * Nfpow)
Nfpow *= Nf # now equals Nf**5)
x5frac = 1.0 / (120.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**6)
x6frac = tf / (720.0 * Nfpow)
Nfpow *= Nf # now equals Nf**7)
x7frac = 1.0 / (5040.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**8)
x8frac = tf / (40320.0 * Nfpow)
# Precalculate polynomial coefficients for x**n.
# -- x**1 does not have a polynomial coefficient.
x2poly = -1.0 - nuf2
x3poly = -1.0 - 2 * tf2 - nuf2
x4poly = (5.0 + 3.0 * tf2 + 6.0 * nuf2 - 6.0 * tf2 * nuf2
- 3.0 * (nuf2 *nuf2) - 9.0 * tf2 * (nuf2 * nuf2))
x5poly = 5.0 + 28.0 * tf2 + 24.0 * tf4 + 6.0 * nuf2 + 8.0 * tf2 * nuf2
x6poly = (-61.0 - 90.0 * tf2 - 45.0 * tf4 - 107.0 * nuf2
+ 162.0 * tf2 * nuf2)
x7poly = -61.0 - 662.0 * tf2 - 1320.0 * tf4 - 720.0 * (tf4 * tf2)
x8poly = 1385.0 + 3633.0 * tf2 + 4095.0 * tf4 + 1575 * (tf4 * tf2)
# Calculate latitude
philambda.append(phif + x2frac * x2poly * x**2
+ x4frac * x4poly * x**4.0
+ x6frac * x6poly * x**6.0
+ x8frac * x8poly * x**8.0)
# Calculate longitude
philambda.append(lambda0 + x1frac * x
+ x3frac * x3poly * x**3.0
+ x5frac * x5poly * x**5.0
+ x7frac * x7poly * x**7.0)
return philambda
def utm_to_latlong(x, y, zone, southhemi=False):
"""Converts x and y coordinates in the Universal Transverse Mercator
projection to a latitude/longitude pair."""
x -= 500000.0
x /= UTMScaleFactor
# If in southern hemisphere, adjust y accordingly.
if southhemi:
y -= 10000000.0
y /= UTMScaleFactor
cmeridian = UTMCentralMeridian(zone)
lat_lon = MapXYToLatLon(x, y, cmeridian)
return list(reversed([rad_to_deg(i) for i in lat_lon]))
| deg_to_rad | identifier_name |
utm.py | # -*- coding: utf-8 -*-
"""Working with UTM and Lat/Long coordinates
Based on http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html
"""
from math import sin, cos, sqrt, tan, pi, floor
__author__ = "P. Tute, C. Taylor"
__maintainer__ = "B. Henne"
__contact__ = "henne@dcsec.uni-hannover.de"
__copyright__ = "(c) 1997-2003 C. Taylor, 2010-2011, DCSec, Leibniz Universitaet Hannover, Germany"
__license__ = """
The Python code is based on Javascript code of Charles L. Taylor from
http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html
The author allowed us to reuse his code.
Original license:
The documents, images, and other materials on the Chuck Taylor
Web site are copyright (c) 1997-2003 by C. Taylor, unless otherwise noted.
Visitors are permitted to download the materials located on the Chuck Taylor
Web site to their own systems, on a temporary basis, for the purpose of viewing
them or, in the case of software applications, using them in accordance with
their intended purpose.
Republishing or redistribution of any of the materials located on the Chuck Taylor
Web site requires permission from C. Taylor. MoSP has been granted to use the code."""
# Ellipsoid model constants (actual values here are for WGS84)
UTMScaleFactor = 0.9996 #: Ellipsoid model constant
sm_a = 6378137.0 #: Ellipsoid model constant: Semi-major axis a
sm_b = 6356752.314 #: Ellipsoid model constant: Semi-major axis b
sm_EccSquared = 6.69437999013e-03 #: Ellipsoid model constant
def long_to_zone(lon):
"""Calculates the current UTM-zone for a given longitude."""
return floor((lon + 180.0) / 6) + 1
def rad_to_deg(rad):
"""Converts radians to degrees."""
return (rad / pi * 180.0)
def deg_to_rad(deg):
"""Converts degrees to radians."""
return (deg / 180.0 * pi)
def UTMCentralMeridian(zone):
"""Calculates the central meridian for the given UTM-zone."""
return deg_to_rad(-183.0 + (zone * 6.0))
def ArcLengthOfMeridian(phi):
"""Computes the ellipsoidal distance from the equator to a point at a
given latitude.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate n
n = (sm_a - sm_b) / (sm_a + sm_b)
# Precalculate alpha
alpha = (((sm_a + sm_b) / 2.0)
* (1.0 + (n**2.0 / 4.0) + (n**4.0 / 64.0)))
# Precalculate beta
beta = ((-3.0 * n / 2.0) + (9.0 * n**3.0 / 16.0)
+ (-3.0 * n**5.0 / 32.0))
# Precalculate gamma
gamma = ((15.0 * n**2.0 / 16.0)
+ (-15.0 * n**4.0 / 32.0))
# Precalculate delta
delta = ((-35.0 * n**3.0 / 48.0)
+ (105.0 * n**5.0 / 256.0))
# Precalculate epsilon
epsilon = (315.0 * n**4.0 / 512.0)
# Now calculate the sum of the series and return
result = (alpha
* (phi + (beta * sin(2.0 * phi))
+ (gamma * sin(4.0 * phi))
+ (delta * sin(6.0 * phi))
+ (epsilon * sin(8.0 * phi))))
return result
def MapLatLonToXY(phi, lambd, lambd0, xy):
"""Converts a latitude/longitude pair to x and y coordinates in the
Transverse Mercator projection. Note that Transverse Mercator is not
the same as UTM a scale factor is required to convert between them.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate ep2
ep2 = (sm_a**2.0 - sm_b**2.0) / sm_b**2.0
# Precalculate nu2
nu2 = ep2 * cos(phi)**2.0
# Precalculate N
N = sm_a**2.0 / (sm_b * sqrt(1 + nu2))
# Precalculate t
t = tan(phi)
t2 = t**2.0
# Precalculate l
l = lambd - lambd0
# Precalculate coefficients for l**n in the equations below
# so a normal human being can read the expressions for easting
# and northing
# -- l**1 and l**2 have coefficients of 1.0
l3coef = 1.0 - t2 + nu2
l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2**2.0)
l5coef = 5.0 - 18.0 * t2 + (t2**2.0) + 14.0 * nu2 - 58.0 * t2 * nu2
l6coef = 61.0 - 58.0 * t2 + (t2**2.0) + 270.0 * nu2 - 330.0 * t2 * nu2
l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2**2.0) - (t2**3.0)
l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2**2.0) - (t2**3.0)
# Calculate easting (x)
xy[0] = (N * cos(phi) * l + (N / 6.0 * cos(phi)**3.0 * l3coef * l**3.0)
+ (N / 120.0 * cos(phi)**5.0 * l5coef * l**5.0)
+ (N / 5040.0 * cos(phi)**7.0 * l7coef * l**7.0))
# Calculate northing (y)
xy[1] = (ArcLengthOfMeridian(phi)
+ (t / 2.0 * N * cos(phi)**2.0 * l**2.0)
+ (t / 24.0 * N * cos(phi)**4.0 * l4coef * l**4.0)
+ (t / 720.0 * N * cos(phi)**6.0 * l6coef * l**6.0)
+ (t / 40320.0 * N * cos(phi)**8.0 * l8coef * l**8.0))
return
def latlong_to_utm(lon, lat, zone = None):
"""Converts a latitude/longitude pair to x and y coordinates in the
Universal Transverse Mercator projection."""
if zone is None:
|
xy = [0, 0]
MapLatLonToXY(deg_to_rad(lat), deg_to_rad(lon), UTMCentralMeridian(zone), xy)
xy[0] = xy[0] * UTMScaleFactor + 500000.0
xy[1] = xy[1] * UTMScaleFactor
if xy[1] < 0.0:
xy[1] = xy[1] + 10000000.0
return [round(coord, 2) for coord in xy]
def FootpointLatitude(y):
"""Computes the footpoint latitude for use in converting transverse
Mercator coordinates to ellipsoidal coordinates.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate n (Eq. 10.18)
n = (sm_a - sm_b) / (sm_a + sm_b)
# Precalculate alpha_ (Eq. 10.22)
# (Same as alpha in Eq. 10.17)
alpha_ = (((sm_a + sm_b) / 2.0)
* (1 + (n**2.0 / 4) + (n**4.0 / 64)))
# Precalculate y_ (Eq. 10.23)
y_ = y / alpha_
# Precalculate beta_ (Eq. 10.22)
beta_ = ((3.0 * n / 2.0) + (-27.0 * n**3.0 / 32.0)
+ (269.0 * n**5.0 / 512.0))
# Precalculate gamma_ (Eq. 10.22)
gamma_ = ((21.0 * n**2.0 / 16.0)
+ (-55.0 * n**4.0 / 32.0))
# Precalculate delta_ (Eq. 10.22)
delta_ = ((151.0 * n**3.0 / 96.0)
+ (-417.0 * n**5.0 / 128.0))
# Precalculate epsilon_ (Eq. 10.22)
epsilon_ = ((1097.0 * n**4.0 / 512.0))
# Now calculate the sum of the series (Eq. 10.21)
result = (y_ + (beta_ * sin(2.0 * y_))
+ (gamma_ * sin(4.0 * y_))
+ (delta_ * sin(6.0 * y_))
+ (epsilon_ * sin(8.0 * y_)))
return result
def MapXYToLatLon(x, y, lambda0):
"""Converts x and y coordinates in the Transverse Mercator projection to
a latitude/longitude pair. Note that Transverse Mercator is not
the same as UTM a scale factor is required to convert between them.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994.
Remarks:
The local variables Nf, nuf2, tf, and tf2 serve the same purpose as
N, nu2, t, and t2 in MapLatLonToXY, but they are computed with respect
sto the footpoint latitude phif.
x1frac, x2frac, x2poly, x3poly, etc. are to enhance readability and
to optimize computations."""
philambda = []
# Get the value of phif, the footpoint latitude.
phif = FootpointLatitude(y)
# Precalculate ep2
ep2 = ((sm_a**2.0 - sm_b**2.0)
/ sm_b**2.0)
# Precalculate cos (phif)
cf = cos(phif)
# Precalculate nuf2
nuf2 = ep2 * cf**2.0
# Precalculate Nf and initialize Nfpow
Nf = sm_a**2.0 / (sm_b * sqrt(1 + nuf2))
Nfpow = Nf
# Precalculate tf
tf = tan(phif)
tf2 = tf**2
tf4 = tf2**2
# Precalculate fractional coefficients for x**n in the equations
# below to simplify the expressions for latitude and longitude.
x1frac = 1.0 / (Nfpow * cf)
Nfpow *= Nf # now equals Nf**2)
x2frac = tf / (2.0 * Nfpow)
Nfpow *= Nf # now equals Nf**3)
x3frac = 1.0 / (6.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**4)
x4frac = tf / (24.0 * Nfpow)
Nfpow *= Nf # now equals Nf**5)
x5frac = 1.0 / (120.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**6)
x6frac = tf / (720.0 * Nfpow)
Nfpow *= Nf # now equals Nf**7)
x7frac = 1.0 / (5040.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**8)
x8frac = tf / (40320.0 * Nfpow)
# Precalculate polynomial coefficients for x**n.
# -- x**1 does not have a polynomial coefficient.
x2poly = -1.0 - nuf2
x3poly = -1.0 - 2 * tf2 - nuf2
x4poly = (5.0 + 3.0 * tf2 + 6.0 * nuf2 - 6.0 * tf2 * nuf2
- 3.0 * (nuf2 *nuf2) - 9.0 * tf2 * (nuf2 * nuf2))
x5poly = 5.0 + 28.0 * tf2 + 24.0 * tf4 + 6.0 * nuf2 + 8.0 * tf2 * nuf2
x6poly = (-61.0 - 90.0 * tf2 - 45.0 * tf4 - 107.0 * nuf2
+ 162.0 * tf2 * nuf2)
x7poly = -61.0 - 662.0 * tf2 - 1320.0 * tf4 - 720.0 * (tf4 * tf2)
x8poly = 1385.0 + 3633.0 * tf2 + 4095.0 * tf4 + 1575 * (tf4 * tf2)
# Calculate latitude
philambda.append(phif + x2frac * x2poly * x**2
+ x4frac * x4poly * x**4.0
+ x6frac * x6poly * x**6.0
+ x8frac * x8poly * x**8.0)
# Calculate longitude
philambda.append(lambda0 + x1frac * x
+ x3frac * x3poly * x**3.0
+ x5frac * x5poly * x**5.0
+ x7frac * x7poly * x**7.0)
return philambda
def utm_to_latlong(x, y, zone, southhemi=False):
"""Converts x and y coordinates in the Universal Transverse Mercator
projection to a latitude/longitude pair."""
x -= 500000.0
x /= UTMScaleFactor
# If in southern hemisphere, adjust y accordingly.
if southhemi:
y -= 10000000.0
y /= UTMScaleFactor
cmeridian = UTMCentralMeridian(zone)
lat_lon = MapXYToLatLon(x, y, cmeridian)
return list(reversed([rad_to_deg(i) for i in lat_lon]))
| zone = long_to_zone(lon) | conditional_block |
utm.py | # -*- coding: utf-8 -*-
"""Working with UTM and Lat/Long coordinates
Based on http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html
"""
from math import sin, cos, sqrt, tan, pi, floor
__author__ = "P. Tute, C. Taylor"
__maintainer__ = "B. Henne"
__contact__ = "henne@dcsec.uni-hannover.de"
__copyright__ = "(c) 1997-2003 C. Taylor, 2010-2011, DCSec, Leibniz Universitaet Hannover, Germany"
__license__ = """
The Python code is based on Javascript code of Charles L. Taylor from
http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html
The author allowed us to reuse his code.
Original license:
The documents, images, and other materials on the Chuck Taylor
Web site are copyright (c) 1997-2003 by C. Taylor, unless otherwise noted.
Visitors are permitted to download the materials located on the Chuck Taylor
Web site to their own systems, on a temporary basis, for the purpose of viewing
them or, in the case of software applications, using them in accordance with
their intended purpose.
Republishing or redistribution of any of the materials located on the Chuck Taylor
Web site requires permission from C. Taylor. MoSP has been granted to use the code."""
# Ellipsoid model constants (actual values here are for WGS84)
UTMScaleFactor = 0.9996 #: Ellipsoid model constant
sm_a = 6378137.0 #: Ellipsoid model constant: Semi-major axis a
sm_b = 6356752.314 #: Ellipsoid model constant: Semi-major axis b
sm_EccSquared = 6.69437999013e-03 #: Ellipsoid model constant
def long_to_zone(lon):
"""Calculates the current UTM-zone for a given longitude."""
return floor((lon + 180.0) / 6) + 1
def rad_to_deg(rad):
"""Converts radians to degrees."""
return (rad / pi * 180.0)
def deg_to_rad(deg):
"""Converts degrees to radians."""
return (deg / 180.0 * pi)
def UTMCentralMeridian(zone):
"""Calculates the central meridian for the given UTM-zone."""
return deg_to_rad(-183.0 + (zone * 6.0))
def ArcLengthOfMeridian(phi):
"""Computes the ellipsoidal distance from the equator to a point at a
given latitude.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate n
n = (sm_a - sm_b) / (sm_a + sm_b)
# Precalculate alpha
alpha = (((sm_a + sm_b) / 2.0)
* (1.0 + (n**2.0 / 4.0) + (n**4.0 / 64.0)))
# Precalculate beta
beta = ((-3.0 * n / 2.0) + (9.0 * n**3.0 / 16.0)
+ (-3.0 * n**5.0 / 32.0))
# Precalculate gamma
gamma = ((15.0 * n**2.0 / 16.0)
+ (-15.0 * n**4.0 / 32.0))
# Precalculate delta
delta = ((-35.0 * n**3.0 / 48.0)
+ (105.0 * n**5.0 / 256.0))
# Precalculate epsilon
epsilon = (315.0 * n**4.0 / 512.0)
# Now calculate the sum of the series and return
result = (alpha
* (phi + (beta * sin(2.0 * phi))
+ (gamma * sin(4.0 * phi))
+ (delta * sin(6.0 * phi))
+ (epsilon * sin(8.0 * phi))))
return result
def MapLatLonToXY(phi, lambd, lambd0, xy):
"""Converts a latitude/longitude pair to x and y coordinates in the
Transverse Mercator projection. Note that Transverse Mercator is not
the same as UTM a scale factor is required to convert between them.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate ep2
ep2 = (sm_a**2.0 - sm_b**2.0) / sm_b**2.0
# Precalculate nu2
nu2 = ep2 * cos(phi)**2.0
# Precalculate N
N = sm_a**2.0 / (sm_b * sqrt(1 + nu2))
# Precalculate t
t = tan(phi)
t2 = t**2.0
# Precalculate l
l = lambd - lambd0
# Precalculate coefficients for l**n in the equations below
# so a normal human being can read the expressions for easting
# and northing
# -- l**1 and l**2 have coefficients of 1.0
l3coef = 1.0 - t2 + nu2
l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2**2.0)
l5coef = 5.0 - 18.0 * t2 + (t2**2.0) + 14.0 * nu2 - 58.0 * t2 * nu2
l6coef = 61.0 - 58.0 * t2 + (t2**2.0) + 270.0 * nu2 - 330.0 * t2 * nu2
l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2**2.0) - (t2**3.0)
l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2**2.0) - (t2**3.0)
# Calculate easting (x)
xy[0] = (N * cos(phi) * l + (N / 6.0 * cos(phi)**3.0 * l3coef * l**3.0)
+ (N / 120.0 * cos(phi)**5.0 * l5coef * l**5.0)
+ (N / 5040.0 * cos(phi)**7.0 * l7coef * l**7.0))
# Calculate northing (y)
xy[1] = (ArcLengthOfMeridian(phi)
+ (t / 2.0 * N * cos(phi)**2.0 * l**2.0)
+ (t / 24.0 * N * cos(phi)**4.0 * l4coef * l**4.0)
+ (t / 720.0 * N * cos(phi)**6.0 * l6coef * l**6.0)
+ (t / 40320.0 * N * cos(phi)**8.0 * l8coef * l**8.0))
return |
if zone is None:
zone = long_to_zone(lon)
xy = [0, 0]
MapLatLonToXY(deg_to_rad(lat), deg_to_rad(lon), UTMCentralMeridian(zone), xy)
xy[0] = xy[0] * UTMScaleFactor + 500000.0
xy[1] = xy[1] * UTMScaleFactor
if xy[1] < 0.0:
xy[1] = xy[1] + 10000000.0
return [round(coord, 2) for coord in xy]
def FootpointLatitude(y):
"""Computes the footpoint latitude for use in converting transverse
Mercator coordinates to ellipsoidal coordinates.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994."""
# Precalculate n (Eq. 10.18)
n = (sm_a - sm_b) / (sm_a + sm_b)
# Precalculate alpha_ (Eq. 10.22)
# (Same as alpha in Eq. 10.17)
alpha_ = (((sm_a + sm_b) / 2.0)
* (1 + (n**2.0 / 4) + (n**4.0 / 64)))
# Precalculate y_ (Eq. 10.23)
y_ = y / alpha_
# Precalculate beta_ (Eq. 10.22)
beta_ = ((3.0 * n / 2.0) + (-27.0 * n**3.0 / 32.0)
+ (269.0 * n**5.0 / 512.0))
# Precalculate gamma_ (Eq. 10.22)
gamma_ = ((21.0 * n**2.0 / 16.0)
+ (-55.0 * n**4.0 / 32.0))
# Precalculate delta_ (Eq. 10.22)
delta_ = ((151.0 * n**3.0 / 96.0)
+ (-417.0 * n**5.0 / 128.0))
# Precalculate epsilon_ (Eq. 10.22)
epsilon_ = ((1097.0 * n**4.0 / 512.0))
# Now calculate the sum of the series (Eq. 10.21)
result = (y_ + (beta_ * sin(2.0 * y_))
+ (gamma_ * sin(4.0 * y_))
+ (delta_ * sin(6.0 * y_))
+ (epsilon_ * sin(8.0 * y_)))
return result
def MapXYToLatLon(x, y, lambda0):
"""Converts x and y coordinates in the Transverse Mercator projection to
a latitude/longitude pair. Note that Transverse Mercator is not
the same as UTM a scale factor is required to convert between them.
Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994.
Remarks:
The local variables Nf, nuf2, tf, and tf2 serve the same purpose as
N, nu2, t, and t2 in MapLatLonToXY, but they are computed with respect
sto the footpoint latitude phif.
x1frac, x2frac, x2poly, x3poly, etc. are to enhance readability and
to optimize computations."""
philambda = []
# Get the value of phif, the footpoint latitude.
phif = FootpointLatitude(y)
# Precalculate ep2
ep2 = ((sm_a**2.0 - sm_b**2.0)
/ sm_b**2.0)
# Precalculate cos (phif)
cf = cos(phif)
# Precalculate nuf2
nuf2 = ep2 * cf**2.0
# Precalculate Nf and initialize Nfpow
Nf = sm_a**2.0 / (sm_b * sqrt(1 + nuf2))
Nfpow = Nf
# Precalculate tf
tf = tan(phif)
tf2 = tf**2
tf4 = tf2**2
# Precalculate fractional coefficients for x**n in the equations
# below to simplify the expressions for latitude and longitude.
x1frac = 1.0 / (Nfpow * cf)
Nfpow *= Nf # now equals Nf**2)
x2frac = tf / (2.0 * Nfpow)
Nfpow *= Nf # now equals Nf**3)
x3frac = 1.0 / (6.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**4)
x4frac = tf / (24.0 * Nfpow)
Nfpow *= Nf # now equals Nf**5)
x5frac = 1.0 / (120.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**6)
x6frac = tf / (720.0 * Nfpow)
Nfpow *= Nf # now equals Nf**7)
x7frac = 1.0 / (5040.0 * Nfpow * cf)
Nfpow *= Nf # now equals Nf**8)
x8frac = tf / (40320.0 * Nfpow)
# Precalculate polynomial coefficients for x**n.
# -- x**1 does not have a polynomial coefficient.
x2poly = -1.0 - nuf2
x3poly = -1.0 - 2 * tf2 - nuf2
x4poly = (5.0 + 3.0 * tf2 + 6.0 * nuf2 - 6.0 * tf2 * nuf2
- 3.0 * (nuf2 *nuf2) - 9.0 * tf2 * (nuf2 * nuf2))
x5poly = 5.0 + 28.0 * tf2 + 24.0 * tf4 + 6.0 * nuf2 + 8.0 * tf2 * nuf2
x6poly = (-61.0 - 90.0 * tf2 - 45.0 * tf4 - 107.0 * nuf2
+ 162.0 * tf2 * nuf2)
x7poly = -61.0 - 662.0 * tf2 - 1320.0 * tf4 - 720.0 * (tf4 * tf2)
x8poly = 1385.0 + 3633.0 * tf2 + 4095.0 * tf4 + 1575 * (tf4 * tf2)
# Calculate latitude
philambda.append(phif + x2frac * x2poly * x**2
+ x4frac * x4poly * x**4.0
+ x6frac * x6poly * x**6.0
+ x8frac * x8poly * x**8.0)
# Calculate longitude
philambda.append(lambda0 + x1frac * x
+ x3frac * x3poly * x**3.0
+ x5frac * x5poly * x**5.0
+ x7frac * x7poly * x**7.0)
return philambda
def utm_to_latlong(x, y, zone, southhemi=False):
"""Converts x and y coordinates in the Universal Transverse Mercator
projection to a latitude/longitude pair."""
x -= 500000.0
x /= UTMScaleFactor
# If in southern hemisphere, adjust y accordingly.
if southhemi:
y -= 10000000.0
y /= UTMScaleFactor
cmeridian = UTMCentralMeridian(zone)
lat_lon = MapXYToLatLon(x, y, cmeridian)
return list(reversed([rad_to_deg(i) for i in lat_lon])) |
def latlong_to_utm(lon, lat, zone = None):
"""Converts a latitude/longitude pair to x and y coordinates in the
Universal Transverse Mercator projection.""" | random_line_split |
wechatService.py | # -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def | (req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
| auto_reply | identifier_name |
wechatService.py | # -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION: | eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
""" | respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT: | random_line_split |
wechatService.py | # -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
| """process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
| identifier_body | |
wechatService.py | # -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import urllib2
from wechatUtil import MessageUtil
from wechatReply import TextReply
class RobotService(object):
"""Auto reply robot service"""
KEY = 'd92d20bc1d8bb3cff585bf746603b2a9'
url = 'http://www.tuling123.com/openapi/api'
@staticmethod
def auto_reply(req_info):
query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')}
headers = {'Content-type': 'text/html', 'charset': 'utf-8'}
data = urllib.urlencode(query)
req = urllib2.Request(RobotService.url, data)
f = urllib2.urlopen(req).read()
return json.loads(f).get('text').replace('<br>', '\n')
#return json.loads(f).get('text')
class WechatService(object):
"""process request"""
@staticmethod
def processRequest(request):
"""process different message types.
:param request: post request message
:return: None
"""
requestMap = MessageUtil.parseXml(request)
fromUserName = requestMap.get(u'FromUserName')
toUserName = requestMap.get(u'ToUserName')
createTime = requestMap.get(u'CreateTime')
msgType = requestMap.get(u'MsgType')
msgId = requestMap.get(u'MsgId')
textReply = TextReply()
textReply.setToUserName(fromUserName)
textReply.setFromUserName(toUserName)
textReply.setCreateTime(time.time())
textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT)
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT:
content = requestMap.get('Content').decode('utf-8') # note: decode first
#respContent = u'您发送的是文本消息:' + content
respContent = RobotService.auto_reply(content)
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
respContent = u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE:
respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \
u'可以联系我,就当打发时间了.'
elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
pass
elif eventType == MessageUtil.EVENT_TYPE_SCAN:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_LOCATION:
# TODO
pass
elif eventType == MessageUtil.EVENT_TYPE_CLICK:
# TODO
pass
textReply.setContent(respContent)
respXml = MessageUtil.class2xml(textReply)
| return respXml
"""
if msgType == 'text':
content = requestMap.get('Content')
# TODO
elif msgType == 'image':
picUrl = requestMap.get('PicUrl')
# TODO
elif msgType == 'voice':
mediaId = requestMap.get('MediaId')
format = requestMap.get('Format')
# TODO
elif msgType == 'video':
mediaId = requestMap.get('MediaId')
thumbMediaId = requestMap.get('ThumbMediaId')
# TODO
elif msgType == 'location':
lat = requestMap.get('Location_X')
lng = requestMap.get('Location_Y')
label = requestMap.get('Label')
scale = requestMap.get('Scale')
# TODO
elif msgType == 'link':
title = requestMap.get('Title')
description = requestMap.get('Description')
url = requestMap.get('Url')
"""
| conditional_block | |
generate_playlist.py | """
Playlist Generation
"""
from os import path
from random import choice
import string
import pafy
from .. import content, g, playlists, screen, util, listview
from ..playlist import Playlist
from . import command, search, album_search
@command(r'mkp\s*(.{1,100})')
def generate_playlist(sourcefile):
"""Generate a playlist from video titles in sourcefile"""
# Hooks into this, check if the argument --description is present
if "--description" in sourcefile or "-d" in sourcefile:
description_generator(sourcefile)
return
expanded_sourcefile = path.expanduser(sourcefile)
if not check_sourcefile(expanded_sourcefile):
g.message = util.F('mkp empty') % expanded_sourcefile
else:
queries = read_sourcefile(expanded_sourcefile)
g.message = util.F('mkp parsed') % (len(queries), sourcefile)
if queries:
create_playlist(queries)
g.message = util.F('pl help')
g.content = content.playlists_display()
def read_sourcefile(filename):
"""Read each line as a query from filename"""
with open(filename) as srcfl:
queries = list()
for item in srcfl.readlines():
clean_item = str(item).strip()
if not clean_item:
continue
queries.append(clean_item)
return queries
def check_sourcefile(filename):
"""Check if filename exists and has a non-zero size"""
return path.isfile(filename) and path.getsize(filename) > 0
def create_playlist(queries, title=None):
"""Add a new playlist
Create playlist with a random name, get the first
match for each title in queries and append it to the playlist
"""
plname = None
if (title is not None):
plname=title.replace(" ", "-")
else:
plname=random_plname()
if not g.userpl.get(plname):
g.userpl[plname] = Playlist(plname)
for query in queries:
g.message = util.F('mkp finding') % query
screen.update()
qresult = find_best_match(query)
if qresult:
g.userpl[plname].songs.append(qresult)
if g.userpl[plname]:
playlists.save()
def find_best_match(query):
"""Find the best(first)"""
# This assumes that the first match is the best one
qs = search.generate_search_qs(query)
wdata = pafy.call_gdata('search', qs)
results = search.get_tracks_from_json(wdata)
if results:
res, score = album_search._best_song_match(
results, query, 0.1, 1.0, 0.0)
return res
def random_plname():
|
def description_generator(text):
""" Fetches a videos description and parses it for
<artist> - <track> combinations
"""
if not isinstance(g.model, Playlist):
g.message = util.F("mkp desc unknown")
return
# Use only the first result, for now
num = text.replace("--description", "")
num = num.replace("-d", "")
num = util.number_string_to_list(num)[0]
query = {}
query['id'] = g.model[num].ytid
query['part'] = 'snippet'
query['maxResults'] = '1'
data = pafy.call_gdata('videos', query)['items'][0]['snippet']
title = "mkp %s" % data['title']
data = util.fetch_songs(data['description'], data['title'])
columns = [
{"name": "idx", "size": 3, "heading": "Num"},
{"name": "artist", "size": 30, "heading": "Artist"},
{"name": "title", "size": "remaining", "heading": "Title"},
]
def run_m(idx):
""" Create playlist based on the
results selected
"""
create_playlist(idx, title)
if data:
data = [listview.ListSongtitle(x) for x in data]
g.content = listview.ListView(columns, data, run_m)
g.message = util.F("mkp desc which data")
else:
g.message = util.F("mkp no valid")
return
| """Generates a random alphanumeric string of 6 characters"""
n_chars = 6
return ''.join(choice(string.ascii_lowercase + string.digits)
for _ in range(n_chars)) | identifier_body |
generate_playlist.py | """
Playlist Generation
"""
from os import path
from random import choice
import string
import pafy
from .. import content, g, playlists, screen, util, listview
from ..playlist import Playlist
from . import command, search, album_search
@command(r'mkp\s*(.{1,100})')
def generate_playlist(sourcefile):
"""Generate a playlist from video titles in sourcefile"""
# Hooks into this, check if the argument --description is present
if "--description" in sourcefile or "-d" in sourcefile:
description_generator(sourcefile)
return
expanded_sourcefile = path.expanduser(sourcefile)
if not check_sourcefile(expanded_sourcefile):
g.message = util.F('mkp empty') % expanded_sourcefile
else:
queries = read_sourcefile(expanded_sourcefile)
g.message = util.F('mkp parsed') % (len(queries), sourcefile)
if queries:
create_playlist(queries)
g.message = util.F('pl help')
g.content = content.playlists_display()
def read_sourcefile(filename):
"""Read each line as a query from filename"""
with open(filename) as srcfl:
queries = list()
for item in srcfl.readlines():
clean_item = str(item).strip()
if not clean_item:
continue
queries.append(clean_item)
return queries
def | (filename):
"""Check if filename exists and has a non-zero size"""
return path.isfile(filename) and path.getsize(filename) > 0
def create_playlist(queries, title=None):
"""Add a new playlist
Create playlist with a random name, get the first
match for each title in queries and append it to the playlist
"""
plname = None
if (title is not None):
plname=title.replace(" ", "-")
else:
plname=random_plname()
if not g.userpl.get(plname):
g.userpl[plname] = Playlist(plname)
for query in queries:
g.message = util.F('mkp finding') % query
screen.update()
qresult = find_best_match(query)
if qresult:
g.userpl[plname].songs.append(qresult)
if g.userpl[plname]:
playlists.save()
def find_best_match(query):
"""Find the best(first)"""
# This assumes that the first match is the best one
qs = search.generate_search_qs(query)
wdata = pafy.call_gdata('search', qs)
results = search.get_tracks_from_json(wdata)
if results:
res, score = album_search._best_song_match(
results, query, 0.1, 1.0, 0.0)
return res
def random_plname():
"""Generates a random alphanumeric string of 6 characters"""
n_chars = 6
return ''.join(choice(string.ascii_lowercase + string.digits)
for _ in range(n_chars))
def description_generator(text):
""" Fetches a videos description and parses it for
<artist> - <track> combinations
"""
if not isinstance(g.model, Playlist):
g.message = util.F("mkp desc unknown")
return
# Use only the first result, for now
num = text.replace("--description", "")
num = num.replace("-d", "")
num = util.number_string_to_list(num)[0]
query = {}
query['id'] = g.model[num].ytid
query['part'] = 'snippet'
query['maxResults'] = '1'
data = pafy.call_gdata('videos', query)['items'][0]['snippet']
title = "mkp %s" % data['title']
data = util.fetch_songs(data['description'], data['title'])
columns = [
{"name": "idx", "size": 3, "heading": "Num"},
{"name": "artist", "size": 30, "heading": "Artist"},
{"name": "title", "size": "remaining", "heading": "Title"},
]
def run_m(idx):
""" Create playlist based on the
results selected
"""
create_playlist(idx, title)
if data:
data = [listview.ListSongtitle(x) for x in data]
g.content = listview.ListView(columns, data, run_m)
g.message = util.F("mkp desc which data")
else:
g.message = util.F("mkp no valid")
return
| check_sourcefile | identifier_name |
generate_playlist.py | """
Playlist Generation
"""
from os import path
from random import choice
import string
import pafy
from .. import content, g, playlists, screen, util, listview
from ..playlist import Playlist
from . import command, search, album_search
@command(r'mkp\s*(.{1,100})')
def generate_playlist(sourcefile):
"""Generate a playlist from video titles in sourcefile"""
# Hooks into this, check if the argument --description is present
if "--description" in sourcefile or "-d" in sourcefile:
description_generator(sourcefile)
return
expanded_sourcefile = path.expanduser(sourcefile)
if not check_sourcefile(expanded_sourcefile):
g.message = util.F('mkp empty') % expanded_sourcefile
else:
queries = read_sourcefile(expanded_sourcefile)
g.message = util.F('mkp parsed') % (len(queries), sourcefile)
if queries:
create_playlist(queries)
g.message = util.F('pl help')
g.content = content.playlists_display()
def read_sourcefile(filename):
"""Read each line as a query from filename"""
with open(filename) as srcfl:
queries = list()
for item in srcfl.readlines():
clean_item = str(item).strip()
if not clean_item:
continue
queries.append(clean_item)
return queries
def check_sourcefile(filename):
"""Check if filename exists and has a non-zero size"""
return path.isfile(filename) and path.getsize(filename) > 0
def create_playlist(queries, title=None):
"""Add a new playlist
Create playlist with a random name, get the first
match for each title in queries and append it to the playlist
"""
plname = None
if (title is not None):
|
else:
plname=random_plname()
if not g.userpl.get(plname):
g.userpl[plname] = Playlist(plname)
for query in queries:
g.message = util.F('mkp finding') % query
screen.update()
qresult = find_best_match(query)
if qresult:
g.userpl[plname].songs.append(qresult)
if g.userpl[plname]:
playlists.save()
def find_best_match(query):
"""Find the best(first)"""
# This assumes that the first match is the best one
qs = search.generate_search_qs(query)
wdata = pafy.call_gdata('search', qs)
results = search.get_tracks_from_json(wdata)
if results:
res, score = album_search._best_song_match(
results, query, 0.1, 1.0, 0.0)
return res
def random_plname():
"""Generates a random alphanumeric string of 6 characters"""
n_chars = 6
return ''.join(choice(string.ascii_lowercase + string.digits)
for _ in range(n_chars))
def description_generator(text):
""" Fetches a videos description and parses it for
<artist> - <track> combinations
"""
if not isinstance(g.model, Playlist):
g.message = util.F("mkp desc unknown")
return
# Use only the first result, for now
num = text.replace("--description", "")
num = num.replace("-d", "")
num = util.number_string_to_list(num)[0]
query = {}
query['id'] = g.model[num].ytid
query['part'] = 'snippet'
query['maxResults'] = '1'
data = pafy.call_gdata('videos', query)['items'][0]['snippet']
title = "mkp %s" % data['title']
data = util.fetch_songs(data['description'], data['title'])
columns = [
{"name": "idx", "size": 3, "heading": "Num"},
{"name": "artist", "size": 30, "heading": "Artist"},
{"name": "title", "size": "remaining", "heading": "Title"},
]
def run_m(idx):
""" Create playlist based on the
results selected
"""
create_playlist(idx, title)
if data:
data = [listview.ListSongtitle(x) for x in data]
g.content = listview.ListView(columns, data, run_m)
g.message = util.F("mkp desc which data")
else:
g.message = util.F("mkp no valid")
return
| plname=title.replace(" ", "-") | conditional_block |
generate_playlist.py | """
Playlist Generation
"""
from os import path
from random import choice
import string
import pafy
from .. import content, g, playlists, screen, util, listview
from ..playlist import Playlist
from . import command, search, album_search
@command(r'mkp\s*(.{1,100})')
def generate_playlist(sourcefile):
"""Generate a playlist from video titles in sourcefile"""
# Hooks into this, check if the argument --description is present
if "--description" in sourcefile or "-d" in sourcefile:
description_generator(sourcefile)
return
expanded_sourcefile = path.expanduser(sourcefile)
if not check_sourcefile(expanded_sourcefile):
g.message = util.F('mkp empty') % expanded_sourcefile
else:
queries = read_sourcefile(expanded_sourcefile)
g.message = util.F('mkp parsed') % (len(queries), sourcefile)
if queries:
create_playlist(queries)
g.message = util.F('pl help')
g.content = content.playlists_display()
def read_sourcefile(filename):
"""Read each line as a query from filename"""
with open(filename) as srcfl:
queries = list()
for item in srcfl.readlines():
clean_item = str(item).strip()
if not clean_item:
continue
queries.append(clean_item)
return queries
def check_sourcefile(filename):
"""Check if filename exists and has a non-zero size"""
return path.isfile(filename) and path.getsize(filename) > 0
def create_playlist(queries, title=None):
"""Add a new playlist
Create playlist with a random name, get the first
match for each title in queries and append it to the playlist
"""
plname = None
if (title is not None):
plname=title.replace(" ", "-")
else:
plname=random_plname()
if not g.userpl.get(plname):
g.userpl[plname] = Playlist(plname)
for query in queries:
g.message = util.F('mkp finding') % query
screen.update()
qresult = find_best_match(query)
if qresult:
g.userpl[plname].songs.append(qresult)
if g.userpl[plname]:
playlists.save()
def find_best_match(query):
"""Find the best(first)"""
# This assumes that the first match is the best one
qs = search.generate_search_qs(query)
wdata = pafy.call_gdata('search', qs)
results = search.get_tracks_from_json(wdata)
if results:
res, score = album_search._best_song_match(
results, query, 0.1, 1.0, 0.0)
return res
def random_plname():
"""Generates a random alphanumeric string of 6 characters"""
n_chars = 6
return ''.join(choice(string.ascii_lowercase + string.digits)
for _ in range(n_chars))
def description_generator(text):
""" Fetches a videos description and parses it for | if not isinstance(g.model, Playlist):
g.message = util.F("mkp desc unknown")
return
# Use only the first result, for now
num = text.replace("--description", "")
num = num.replace("-d", "")
num = util.number_string_to_list(num)[0]
query = {}
query['id'] = g.model[num].ytid
query['part'] = 'snippet'
query['maxResults'] = '1'
data = pafy.call_gdata('videos', query)['items'][0]['snippet']
title = "mkp %s" % data['title']
data = util.fetch_songs(data['description'], data['title'])
columns = [
{"name": "idx", "size": 3, "heading": "Num"},
{"name": "artist", "size": 30, "heading": "Artist"},
{"name": "title", "size": "remaining", "heading": "Title"},
]
def run_m(idx):
""" Create playlist based on the
results selected
"""
create_playlist(idx, title)
if data:
data = [listview.ListSongtitle(x) for x in data]
g.content = listview.ListView(columns, data, run_m)
g.message = util.F("mkp desc which data")
else:
g.message = util.F("mkp no valid")
return | <artist> - <track> combinations
""" | random_line_split |
history.py | import collections
import functools
import re
import wrappers
class History(object):
"""
Tracking of operations provenance.
>>> h = History("some_op")
>>> print str(h)
some_op()
>>> h.add_args(["w1", "w2"])
>>> print str(h)
some_op(
w1,
w2,
)
>>> h.add_kws({"a_keyword": "a_value"})
>>> print str(h)
some_op(
w1,
w2,
a_keyword=a_value,
)
>>> h
some_op(w1,w2,a_keyword=a_value,)
>>> h2 = History("another_op")
>>> h2.add_args(['foo'])
>>> h.add_args([h2])
>>> print str(h)
some_op(
another_op(
foo,
),
a_keyword=a_value,
)
>>> # new history test
>>> h = History("other_op")
>>> h.add_args([[History("w1"), History("w2")], 'bar'])
>>> print str(h)
other_op(
[
w1(),
w2(),
],
bar,
)
"""
def __init__(self, operation): | string = ""
if self.args:
def arg_str(arg):
if (
isinstance(arg, list)
and arg
and isinstance(arg[0], History)
):
return '[\n ' + ",\n ".join(
str(a).replace('\n', '\n ') for a in arg
) + ',\n ]'
elif isinstance(arg, History):
return str(arg).replace('\n', '\n ')
else:
return str(arg)
string += "\n".join(" %s," % arg_str(a) for a in self.args)
if self.kws:
string += "\n"
string += "\n".join(
" %s=%s," % (k, str(v)) for k, v in self.kws.iteritems())
if string:
return self.op + "(\n" + string + "\n)"
else:
return self.op + "()"
def __repr__(self):
pat = re.compile(r'\s+')
return pat.sub('', str(self))
def add_args(self, args):
self.args = args
def add_kws(self, kws):
self.kws = kws
def _gen_catch_history(wrps, list_of_histories):
for wrp in wrps:
if hasattr(wrp, "history"):
list_of_histories.append(wrp.history)
yield wrp
def track_history(func):
"""
Python decorator for Wrapper operations.
>>> @track_history
... def noop(wrps, arg, kw):
... wrps = list(wrps)
... return wrps[0]
>>>
>>> w1 = wrappers.Wrapper(history=History('w1'))
>>> w2 = wrappers.Wrapper(history=History('w2'))
>>> w3 = noop([w1,w2], 'an_arg', kw='a_kw')
>>> print w3.history
noop(
[
w1(),
w2(),
],
an_arg,
kw=a_kw,
)
"""
@functools.wraps(func)
def decorator(*args, **kws):
history = History(func.__name__)
if len(args):
func_args = list(args)
hist_args = list(args)
for i, arg in enumerate(args):
if isinstance(arg, wrappers.Wrapper):
hist_args[i] = arg.history
elif isinstance(arg, collections.Iterable) and not i:
list_of_histories = []
func_args[i] = _gen_catch_history(arg, list_of_histories)
hist_args[i] = list_of_histories
history.add_args(hist_args)
args = func_args
if len(kws):
history.add_kws(kws)
ret = func(*args, **kws)
ret.history = history
return ret
return decorator
if __name__ == "__main__":
import doctest
doctest.testmod() | self.op = str(operation)
self.args = None
self.kws = None
def __str__(self): | random_line_split |
history.py | import collections
import functools
import re
import wrappers
class History(object):
"""
Tracking of operations provenance.
>>> h = History("some_op")
>>> print str(h)
some_op()
>>> h.add_args(["w1", "w2"])
>>> print str(h)
some_op(
w1,
w2,
)
>>> h.add_kws({"a_keyword": "a_value"})
>>> print str(h)
some_op(
w1,
w2,
a_keyword=a_value,
)
>>> h
some_op(w1,w2,a_keyword=a_value,)
>>> h2 = History("another_op")
>>> h2.add_args(['foo'])
>>> h.add_args([h2])
>>> print str(h)
some_op(
another_op(
foo,
),
a_keyword=a_value,
)
>>> # new history test
>>> h = History("other_op")
>>> h.add_args([[History("w1"), History("w2")], 'bar'])
>>> print str(h)
other_op(
[
w1(),
w2(),
],
bar,
)
"""
def __init__(self, operation):
self.op = str(operation)
self.args = None
self.kws = None
def __str__(self):
string = ""
if self.args:
def arg_str(arg):
if (
isinstance(arg, list)
and arg
and isinstance(arg[0], History)
):
return '[\n ' + ",\n ".join(
str(a).replace('\n', '\n ') for a in arg
) + ',\n ]'
elif isinstance(arg, History):
return str(arg).replace('\n', '\n ')
else:
return str(arg)
string += "\n".join(" %s," % arg_str(a) for a in self.args)
if self.kws:
string += "\n"
string += "\n".join(
" %s=%s," % (k, str(v)) for k, v in self.kws.iteritems())
if string:
return self.op + "(\n" + string + "\n)"
else:
|
def __repr__(self):
pat = re.compile(r'\s+')
return pat.sub('', str(self))
def add_args(self, args):
self.args = args
def add_kws(self, kws):
self.kws = kws
def _gen_catch_history(wrps, list_of_histories):
for wrp in wrps:
if hasattr(wrp, "history"):
list_of_histories.append(wrp.history)
yield wrp
def track_history(func):
"""
Python decorator for Wrapper operations.
>>> @track_history
... def noop(wrps, arg, kw):
... wrps = list(wrps)
... return wrps[0]
>>>
>>> w1 = wrappers.Wrapper(history=History('w1'))
>>> w2 = wrappers.Wrapper(history=History('w2'))
>>> w3 = noop([w1,w2], 'an_arg', kw='a_kw')
>>> print w3.history
noop(
[
w1(),
w2(),
],
an_arg,
kw=a_kw,
)
"""
@functools.wraps(func)
def decorator(*args, **kws):
history = History(func.__name__)
if len(args):
func_args = list(args)
hist_args = list(args)
for i, arg in enumerate(args):
if isinstance(arg, wrappers.Wrapper):
hist_args[i] = arg.history
elif isinstance(arg, collections.Iterable) and not i:
list_of_histories = []
func_args[i] = _gen_catch_history(arg, list_of_histories)
hist_args[i] = list_of_histories
history.add_args(hist_args)
args = func_args
if len(kws):
history.add_kws(kws)
ret = func(*args, **kws)
ret.history = history
return ret
return decorator
if __name__ == "__main__":
import doctest
doctest.testmod()
| return self.op + "()" | conditional_block |
history.py | import collections
import functools
import re
import wrappers
class History(object):
"""
Tracking of operations provenance.
>>> h = History("some_op")
>>> print str(h)
some_op()
>>> h.add_args(["w1", "w2"])
>>> print str(h)
some_op(
w1,
w2,
)
>>> h.add_kws({"a_keyword": "a_value"})
>>> print str(h)
some_op(
w1,
w2,
a_keyword=a_value,
)
>>> h
some_op(w1,w2,a_keyword=a_value,)
>>> h2 = History("another_op")
>>> h2.add_args(['foo'])
>>> h.add_args([h2])
>>> print str(h)
some_op(
another_op(
foo,
),
a_keyword=a_value,
)
>>> # new history test
>>> h = History("other_op")
>>> h.add_args([[History("w1"), History("w2")], 'bar'])
>>> print str(h)
other_op(
[
w1(),
w2(),
],
bar,
)
"""
def __init__(self, operation):
|
def __str__(self):
string = ""
if self.args:
def arg_str(arg):
if (
isinstance(arg, list)
and arg
and isinstance(arg[0], History)
):
return '[\n ' + ",\n ".join(
str(a).replace('\n', '\n ') for a in arg
) + ',\n ]'
elif isinstance(arg, History):
return str(arg).replace('\n', '\n ')
else:
return str(arg)
string += "\n".join(" %s," % arg_str(a) for a in self.args)
if self.kws:
string += "\n"
string += "\n".join(
" %s=%s," % (k, str(v)) for k, v in self.kws.iteritems())
if string:
return self.op + "(\n" + string + "\n)"
else:
return self.op + "()"
def __repr__(self):
pat = re.compile(r'\s+')
return pat.sub('', str(self))
def add_args(self, args):
self.args = args
def add_kws(self, kws):
self.kws = kws
def _gen_catch_history(wrps, list_of_histories):
for wrp in wrps:
if hasattr(wrp, "history"):
list_of_histories.append(wrp.history)
yield wrp
def track_history(func):
"""
Python decorator for Wrapper operations.
>>> @track_history
... def noop(wrps, arg, kw):
... wrps = list(wrps)
... return wrps[0]
>>>
>>> w1 = wrappers.Wrapper(history=History('w1'))
>>> w2 = wrappers.Wrapper(history=History('w2'))
>>> w3 = noop([w1,w2], 'an_arg', kw='a_kw')
>>> print w3.history
noop(
[
w1(),
w2(),
],
an_arg,
kw=a_kw,
)
"""
@functools.wraps(func)
def decorator(*args, **kws):
history = History(func.__name__)
if len(args):
func_args = list(args)
hist_args = list(args)
for i, arg in enumerate(args):
if isinstance(arg, wrappers.Wrapper):
hist_args[i] = arg.history
elif isinstance(arg, collections.Iterable) and not i:
list_of_histories = []
func_args[i] = _gen_catch_history(arg, list_of_histories)
hist_args[i] = list_of_histories
history.add_args(hist_args)
args = func_args
if len(kws):
history.add_kws(kws)
ret = func(*args, **kws)
ret.history = history
return ret
return decorator
if __name__ == "__main__":
import doctest
doctest.testmod()
| self.op = str(operation)
self.args = None
self.kws = None | identifier_body |
history.py | import collections
import functools
import re
import wrappers
class History(object):
"""
Tracking of operations provenance.
>>> h = History("some_op")
>>> print str(h)
some_op()
>>> h.add_args(["w1", "w2"])
>>> print str(h)
some_op(
w1,
w2,
)
>>> h.add_kws({"a_keyword": "a_value"})
>>> print str(h)
some_op(
w1,
w2,
a_keyword=a_value,
)
>>> h
some_op(w1,w2,a_keyword=a_value,)
>>> h2 = History("another_op")
>>> h2.add_args(['foo'])
>>> h.add_args([h2])
>>> print str(h)
some_op(
another_op(
foo,
),
a_keyword=a_value,
)
>>> # new history test
>>> h = History("other_op")
>>> h.add_args([[History("w1"), History("w2")], 'bar'])
>>> print str(h)
other_op(
[
w1(),
w2(),
],
bar,
)
"""
def __init__(self, operation):
self.op = str(operation)
self.args = None
self.kws = None
def __str__(self):
string = ""
if self.args:
def arg_str(arg):
if (
isinstance(arg, list)
and arg
and isinstance(arg[0], History)
):
return '[\n ' + ",\n ".join(
str(a).replace('\n', '\n ') for a in arg
) + ',\n ]'
elif isinstance(arg, History):
return str(arg).replace('\n', '\n ')
else:
return str(arg)
string += "\n".join(" %s," % arg_str(a) for a in self.args)
if self.kws:
string += "\n"
string += "\n".join(
" %s=%s," % (k, str(v)) for k, v in self.kws.iteritems())
if string:
return self.op + "(\n" + string + "\n)"
else:
return self.op + "()"
def __repr__(self):
pat = re.compile(r'\s+')
return pat.sub('', str(self))
def add_args(self, args):
self.args = args
def | (self, kws):
self.kws = kws
def _gen_catch_history(wrps, list_of_histories):
for wrp in wrps:
if hasattr(wrp, "history"):
list_of_histories.append(wrp.history)
yield wrp
def track_history(func):
"""
Python decorator for Wrapper operations.
>>> @track_history
... def noop(wrps, arg, kw):
... wrps = list(wrps)
... return wrps[0]
>>>
>>> w1 = wrappers.Wrapper(history=History('w1'))
>>> w2 = wrappers.Wrapper(history=History('w2'))
>>> w3 = noop([w1,w2], 'an_arg', kw='a_kw')
>>> print w3.history
noop(
[
w1(),
w2(),
],
an_arg,
kw=a_kw,
)
"""
@functools.wraps(func)
def decorator(*args, **kws):
history = History(func.__name__)
if len(args):
func_args = list(args)
hist_args = list(args)
for i, arg in enumerate(args):
if isinstance(arg, wrappers.Wrapper):
hist_args[i] = arg.history
elif isinstance(arg, collections.Iterable) and not i:
list_of_histories = []
func_args[i] = _gen_catch_history(arg, list_of_histories)
hist_args[i] = list_of_histories
history.add_args(hist_args)
args = func_args
if len(kws):
history.add_kws(kws)
ret = func(*args, **kws)
ret.history = history
return ret
return decorator
if __name__ == "__main__":
import doctest
doctest.testmod()
| add_kws | identifier_name |
wall.rs | use glium;
use types;
use camera;
use shaders;
use texture;
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 3],
normal: [f32; 3],
tex_coords: [f32; 2]
}
implement_vertex!(Vertex, position, normal, tex_coords);
pub struct Wall {
matrix: types::Mat,
buffer: glium::VertexBuffer<Vertex>,
diffuse_texture: glium::texture::SrgbTexture2d,
normal_map: glium::texture::texture2d::Texture2d
}
impl Wall {
pub fn new(window: &types::Display) -> Self {
let material = "wall".to_string();
let diffuse_texture = texture::load(window, &material);
let normal_map = texture::load_normal(window, &material); | normal: [0.0, 0.0, -1.0],
tex_coords: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [0.0, 0.0] },
Vertex { position: [ 1.0, -1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [1.0, 0.0] },
]).unwrap();
Wall {
buffer: buffer,
diffuse_texture: diffuse_texture,
normal_map: normal_map,
matrix: [
[10.01, 0.0, 0.0, 0.0],
[0.0, 10.01, 0.0, 0.0],
[0.0, 0.0, 10.01, 0.0],
[0.0 , 10.0, 10.0, 1.0f32]
]
}
}
pub fn render(self: &Self, frame_buffer: &mut glium::Frame,
camera: &camera::Camera, library: &shaders::ShaderLibrary) {
use glium::Surface;
use glium::DrawParameters;
let strip = glium::index::PrimitiveType::TriangleStrip;
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
.. Default::default()
},
.. Default::default()
};
let light = [-1.0, 0.4, 0.9f32];
let uniforms = uniform! {
model: self.matrix,
projection: camera.projection,
view: camera.get_view(),
u_light: light,
diffuse_tex: &self.diffuse_texture,
normal_tex: &self.normal_map
};
frame_buffer.draw(&self.buffer, &glium::index::NoIndices(strip),
&library.lit_texture,
&uniforms, ¶ms).unwrap();
}
} | let buffer = glium::vertex::VertexBuffer::new(window, &[
Vertex { position: [-1.0, 1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [0.0, 1.0] },
Vertex { position: [ 1.0, 1.0, 0.0], | random_line_split |
wall.rs | use glium;
use types;
use camera;
use shaders;
use texture;
#[derive(Copy, Clone)]
struct | {
position: [f32; 3],
normal: [f32; 3],
tex_coords: [f32; 2]
}
implement_vertex!(Vertex, position, normal, tex_coords);
pub struct Wall {
matrix: types::Mat,
buffer: glium::VertexBuffer<Vertex>,
diffuse_texture: glium::texture::SrgbTexture2d,
normal_map: glium::texture::texture2d::Texture2d
}
impl Wall {
pub fn new(window: &types::Display) -> Self {
let material = "wall".to_string();
let diffuse_texture = texture::load(window, &material);
let normal_map = texture::load_normal(window, &material);
let buffer = glium::vertex::VertexBuffer::new(window, &[
Vertex { position: [-1.0, 1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [0.0, 1.0] },
Vertex { position: [ 1.0, 1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [0.0, 0.0] },
Vertex { position: [ 1.0, -1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [1.0, 0.0] },
]).unwrap();
Wall {
buffer: buffer,
diffuse_texture: diffuse_texture,
normal_map: normal_map,
matrix: [
[10.01, 0.0, 0.0, 0.0],
[0.0, 10.01, 0.0, 0.0],
[0.0, 0.0, 10.01, 0.0],
[0.0 , 10.0, 10.0, 1.0f32]
]
}
}
pub fn render(self: &Self, frame_buffer: &mut glium::Frame,
camera: &camera::Camera, library: &shaders::ShaderLibrary) {
use glium::Surface;
use glium::DrawParameters;
let strip = glium::index::PrimitiveType::TriangleStrip;
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
.. Default::default()
},
.. Default::default()
};
let light = [-1.0, 0.4, 0.9f32];
let uniforms = uniform! {
model: self.matrix,
projection: camera.projection,
view: camera.get_view(),
u_light: light,
diffuse_tex: &self.diffuse_texture,
normal_tex: &self.normal_map
};
frame_buffer.draw(&self.buffer, &glium::index::NoIndices(strip),
&library.lit_texture,
&uniforms, ¶ms).unwrap();
}
}
| Vertex | identifier_name |
wall.rs | use glium;
use types;
use camera;
use shaders;
use texture;
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 3],
normal: [f32; 3],
tex_coords: [f32; 2]
}
implement_vertex!(Vertex, position, normal, tex_coords);
pub struct Wall {
matrix: types::Mat,
buffer: glium::VertexBuffer<Vertex>,
diffuse_texture: glium::texture::SrgbTexture2d,
normal_map: glium::texture::texture2d::Texture2d
}
impl Wall {
pub fn new(window: &types::Display) -> Self {
let material = "wall".to_string();
let diffuse_texture = texture::load(window, &material);
let normal_map = texture::load_normal(window, &material);
let buffer = glium::vertex::VertexBuffer::new(window, &[
Vertex { position: [-1.0, 1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [0.0, 1.0] },
Vertex { position: [ 1.0, 1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [0.0, 0.0] },
Vertex { position: [ 1.0, -1.0, 0.0],
normal: [0.0, 0.0, -1.0],
tex_coords: [1.0, 0.0] },
]).unwrap();
Wall {
buffer: buffer,
diffuse_texture: diffuse_texture,
normal_map: normal_map,
matrix: [
[10.01, 0.0, 0.0, 0.0],
[0.0, 10.01, 0.0, 0.0],
[0.0, 0.0, 10.01, 0.0],
[0.0 , 10.0, 10.0, 1.0f32]
]
}
}
pub fn render(self: &Self, frame_buffer: &mut glium::Frame,
camera: &camera::Camera, library: &shaders::ShaderLibrary) |
}
| {
use glium::Surface;
use glium::DrawParameters;
let strip = glium::index::PrimitiveType::TriangleStrip;
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
.. Default::default()
},
.. Default::default()
};
let light = [-1.0, 0.4, 0.9f32];
let uniforms = uniform! {
model: self.matrix,
projection: camera.projection,
view: camera.get_view(),
u_light: light,
diffuse_tex: &self.diffuse_texture,
normal_tex: &self.normal_map
};
frame_buffer.draw(&self.buffer, &glium::index::NoIndices(strip),
&library.lit_texture,
&uniforms, ¶ms).unwrap();
} | identifier_body |
json_pipe_spec.ts | import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {Json, StringWrapper} from '../../src/facade/lang';
import {Component} from '@angular/core';
import {JsonPipe} from '@angular/common';
export function main() {
describe('JsonPipe', () => {
var regNewLine = '\n';
var inceptionObj: any;
var inceptionObjString: string;
var pipe: JsonPipe;
function normalize(obj: string): string |
beforeEach(() => {
inceptionObj = {dream: {dream: {dream: 'Limbo'}}};
inceptionObjString = '{\n' +
' "dream": {\n' +
' "dream": {\n' +
' "dream": "Limbo"\n' +
' }\n' +
' }\n' +
'}';
pipe = new JsonPipe();
});
describe('transform', () => {
it('should return JSON-formatted string',
() => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); });
it('should return JSON-formatted string even when normalized', () => {
var dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(inceptionObjString);
expect(dream1).toEqual(dream2);
});
it('should return JSON-formatted string similar to Json.stringify', () => {
var dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(Json.stringify(inceptionObj));
expect(dream1).toEqual(dream2);
});
});
describe('integration', () => {
it('should work with mutable objects',
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(TestComp).then((fixture) => {
let mutable: number[] = [1];
fixture.debugElement.componentInstance.data = mutable;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('[\n 1\n]');
mutable.push(2);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('[\n 1,\n 2\n]');
async.done();
});
}));
});
});
}
@Component({selector: 'test-comp', template: '{{data | json}}', pipes: [JsonPipe]})
class TestComp {
data: any;
}
| { return StringWrapper.replace(obj, regNewLine, ''); } | identifier_body |
json_pipe_spec.ts | import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {Json, StringWrapper} from '../../src/facade/lang';
import {Component} from '@angular/core';
import {JsonPipe} from '@angular/common';
export function main() {
describe('JsonPipe', () => {
var regNewLine = '\n';
var inceptionObj: any;
var inceptionObjString: string;
var pipe: JsonPipe;
function normalize(obj: string): string { return StringWrapper.replace(obj, regNewLine, ''); }
beforeEach(() => {
inceptionObj = {dream: {dream: {dream: 'Limbo'}}};
inceptionObjString = '{\n' +
' "dream": {\n' +
' "dream": {\n' +
' "dream": "Limbo"\n' +
' }\n' +
' }\n' +
'}';
pipe = new JsonPipe();
});
describe('transform', () => {
it('should return JSON-formatted string',
() => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); });
it('should return JSON-formatted string even when normalized', () => {
var dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(inceptionObjString);
expect(dream1).toEqual(dream2);
});
it('should return JSON-formatted string similar to Json.stringify', () => {
var dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(Json.stringify(inceptionObj));
expect(dream1).toEqual(dream2);
});
});
describe('integration', () => {
it('should work with mutable objects',
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(TestComp).then((fixture) => {
let mutable: number[] = [1];
fixture.debugElement.componentInstance.data = mutable;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('[\n 1\n]');
mutable.push(2);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('[\n 1,\n 2\n]');
async.done();
});
}));
});
});
}
@Component({selector: 'test-comp', template: '{{data | json}}', pipes: [JsonPipe]})
class | {
data: any;
}
| TestComp | identifier_name |
json_pipe_spec.ts | import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {Json, StringWrapper} from '../../src/facade/lang';
import {Component} from '@angular/core';
import {JsonPipe} from '@angular/common';
export function main() {
describe('JsonPipe', () => {
var regNewLine = '\n';
var inceptionObj: any;
var inceptionObjString: string;
var pipe: JsonPipe;
function normalize(obj: string): string { return StringWrapper.replace(obj, regNewLine, ''); }
beforeEach(() => {
inceptionObj = {dream: {dream: {dream: 'Limbo'}}};
inceptionObjString = '{\n' +
' "dream": {\n' +
' "dream": {\n' +
' "dream": "Limbo"\n' +
' }\n' +
' }\n' +
'}'; |
describe('transform', () => {
it('should return JSON-formatted string',
() => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); });
it('should return JSON-formatted string even when normalized', () => {
var dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(inceptionObjString);
expect(dream1).toEqual(dream2);
});
it('should return JSON-formatted string similar to Json.stringify', () => {
var dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(Json.stringify(inceptionObj));
expect(dream1).toEqual(dream2);
});
});
describe('integration', () => {
it('should work with mutable objects',
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.createAsync(TestComp).then((fixture) => {
let mutable: number[] = [1];
fixture.debugElement.componentInstance.data = mutable;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('[\n 1\n]');
mutable.push(2);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('[\n 1,\n 2\n]');
async.done();
});
}));
});
});
}
@Component({selector: 'test-comp', template: '{{data | json}}', pipes: [JsonPipe]})
class TestComp {
data: any;
} |
pipe = new JsonPipe();
}); | random_line_split |
test_worker_bigrams.py | # coding: utf-8
#
# Copyright 2012 NAMD-EMAP-FGV
#
# This file is part of PyPLN. You can get more information at: http://pypln.org/.
#
# PyPLN is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyPLN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyPLN. If not, see <http://www.gnu.org/licenses/>.
import nltk
from pypln.backend.workers.bigrams import Bigrams
from utils import TaskTest
bigram_measures = nltk.collocations.BigramAssocMeasures()
class TestBigramWorker(TaskTest):
def test_bigrams_should_return_correct_score(self):
# We need this list comprehension because we need to save the word list
# in mongo (thus, it needs to be json serializable). Also, a list is
# what will be available to the worker in real situations.
tokens = [w for w in
nltk.corpus.genesis.words('english-web.txt')]
doc_id = self.collection.insert({'tokens': tokens}, w=1)
Bigrams().delay(doc_id)
refreshed_document = self.collection.find_one({'_id': doc_id})
bigram_rank = refreshed_document['bigram_rank']
result = bigram_rank[0][1][0]
# This is the value of the chi_sq measure for this bigram in this
# colocation
expected_chi_sq = 95.59393417173634
self.assertEqual(result, expected_chi_sq)
def test_bigrams_could_contain_dollar_signs_and_dots(self):
tokens = ['$', '.']
doc_id = self.collection.insert({'tokens': tokens}, w=1)
Bigrams().delay(doc_id)
refreshed_document = self.collection.find_one({'_id': doc_id})
bigram_rank = refreshed_document['bigram_rank']
result = bigram_rank[0][1][0]
# 2.0 is the value of the chi_sq measure for this bigram in this
# colocation | expected_chi_sq = 2.0
self.assertEqual(result, expected_chi_sq) | random_line_split | |
test_worker_bigrams.py | # coding: utf-8
#
# Copyright 2012 NAMD-EMAP-FGV
#
# This file is part of PyPLN. You can get more information at: http://pypln.org/.
#
# PyPLN is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyPLN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyPLN. If not, see <http://www.gnu.org/licenses/>.
import nltk
from pypln.backend.workers.bigrams import Bigrams
from utils import TaskTest
bigram_measures = nltk.collocations.BigramAssocMeasures()
class TestBigramWorker(TaskTest):
| def test_bigrams_should_return_correct_score(self):
# We need this list comprehension because we need to save the word list
# in mongo (thus, it needs to be json serializable). Also, a list is
# what will be available to the worker in real situations.
tokens = [w for w in
nltk.corpus.genesis.words('english-web.txt')]
doc_id = self.collection.insert({'tokens': tokens}, w=1)
Bigrams().delay(doc_id)
refreshed_document = self.collection.find_one({'_id': doc_id})
bigram_rank = refreshed_document['bigram_rank']
result = bigram_rank[0][1][0]
# This is the value of the chi_sq measure for this bigram in this
# colocation
expected_chi_sq = 95.59393417173634
self.assertEqual(result, expected_chi_sq)
def test_bigrams_could_contain_dollar_signs_and_dots(self):
tokens = ['$', '.']
doc_id = self.collection.insert({'tokens': tokens}, w=1)
Bigrams().delay(doc_id)
refreshed_document = self.collection.find_one({'_id': doc_id})
bigram_rank = refreshed_document['bigram_rank']
result = bigram_rank[0][1][0]
# 2.0 is the value of the chi_sq measure for this bigram in this
# colocation
expected_chi_sq = 2.0
self.assertEqual(result, expected_chi_sq) | identifier_body | |
test_worker_bigrams.py | # coding: utf-8
#
# Copyright 2012 NAMD-EMAP-FGV
#
# This file is part of PyPLN. You can get more information at: http://pypln.org/.
#
# PyPLN is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyPLN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyPLN. If not, see <http://www.gnu.org/licenses/>.
import nltk
from pypln.backend.workers.bigrams import Bigrams
from utils import TaskTest
bigram_measures = nltk.collocations.BigramAssocMeasures()
class TestBigramWorker(TaskTest):
def | (self):
# We need this list comprehension because we need to save the word list
# in mongo (thus, it needs to be json serializable). Also, a list is
# what will be available to the worker in real situations.
tokens = [w for w in
nltk.corpus.genesis.words('english-web.txt')]
doc_id = self.collection.insert({'tokens': tokens}, w=1)
Bigrams().delay(doc_id)
refreshed_document = self.collection.find_one({'_id': doc_id})
bigram_rank = refreshed_document['bigram_rank']
result = bigram_rank[0][1][0]
# This is the value of the chi_sq measure for this bigram in this
# colocation
expected_chi_sq = 95.59393417173634
self.assertEqual(result, expected_chi_sq)
def test_bigrams_could_contain_dollar_signs_and_dots(self):
tokens = ['$', '.']
doc_id = self.collection.insert({'tokens': tokens}, w=1)
Bigrams().delay(doc_id)
refreshed_document = self.collection.find_one({'_id': doc_id})
bigram_rank = refreshed_document['bigram_rank']
result = bigram_rank[0][1][0]
# 2.0 is the value of the chi_sq measure for this bigram in this
# colocation
expected_chi_sq = 2.0
self.assertEqual(result, expected_chi_sq)
| test_bigrams_should_return_correct_score | identifier_name |
ActionMap.py | from enigma import eActionMap
class ActionMap:
def __init__(self, contexts = [ ], actions = { }, prio=0):
self.actions = actions
self.contexts = contexts
self.prio = prio
self.p = eActionMap.getInstance()
self.bound = False
self.exec_active = False
self.enabled = True
def setEnabled(self, enabled):
self.enabled = enabled
self.checkBind()
def doBind(self):
if not self.bound:
for ctx in self.contexts:
self.p.bindAction(ctx, self.prio, self.action)
self.bound = True
def doUnbind(self):
if self.bound:
for ctx in self.contexts:
self.p.unbindAction(ctx, self.action)
self.bound = False
def checkBind(self):
if self.exec_active and self.enabled:
self.doBind()
else:
self.doUnbind()
def execBegin(self):
self.exec_active = True
self.checkBind()
def execEnd(self):
self.exec_active = False
self.checkBind()
def action(self, context, action):
print " ".join(("action -> ", context, action))
if action in self.actions:
res = self.actions[action]()
if res is not None:
|
return 1
else:
print "unknown action %s/%s! typo in keymap?" % (context, action)
return 0
def destroy(self):
pass
class NumberActionMap(ActionMap):
def action(self, contexts, action):
numbers = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
if (action in numbers and self.actions.has_key(action)):
res = self.actions[action](int(action))
if res is not None:
return res
return 1
else:
return ActionMap.action(self, contexts, action)
class HelpableActionMap(ActionMap):
"""An Actionmap which automatically puts the actions into the helpList.
Note that you can only use ONE context here!"""
# sorry for this complicated code.
# it's not more than converting a "documented" actionmap
# (where the values are possibly (function, help)-tuples)
# into a "classic" actionmap, where values are just functions.
# the classic actionmap is then passed to the ActionMap constructor,
# the collected helpstrings (with correct context, action) is
# added to the screen's "helpList", which will be picked up by
# the "HelpableScreen".
def __init__(self, parent, context, actions = { }, prio=0):
alist = [ ]
adict = { }
for (action, funchelp) in actions.iteritems():
# check if this is a tuple
if isinstance(funchelp, tuple):
alist.append((action, funchelp[1]))
adict[action] = funchelp[0]
else:
adict[action] = funchelp
ActionMap.__init__(self, [context], adict, prio)
parent.helpList.append((self, context, alist))
| return res | conditional_block |
ActionMap.py | from enigma import eActionMap
class ActionMap:
def __init__(self, contexts = [ ], actions = { }, prio=0):
self.actions = actions
self.contexts = contexts
self.prio = prio
self.p = eActionMap.getInstance()
self.bound = False
self.exec_active = False
self.enabled = True
def setEnabled(self, enabled):
self.enabled = enabled
self.checkBind()
def doBind(self):
if not self.bound:
for ctx in self.contexts:
self.p.bindAction(ctx, self.prio, self.action)
self.bound = True
def doUnbind(self):
if self.bound:
for ctx in self.contexts:
self.p.unbindAction(ctx, self.action)
self.bound = False
def checkBind(self):
if self.exec_active and self.enabled:
self.doBind()
else:
self.doUnbind()
def execBegin(self):
self.exec_active = True
self.checkBind()
def execEnd(self):
self.exec_active = False
self.checkBind()
def action(self, context, action):
print " ".join(("action -> ", context, action))
if action in self.actions:
res = self.actions[action]()
if res is not None:
return res
return 1
else:
print "unknown action %s/%s! typo in keymap?" % (context, action)
return 0
def | (self):
pass
class NumberActionMap(ActionMap):
def action(self, contexts, action):
numbers = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
if (action in numbers and self.actions.has_key(action)):
res = self.actions[action](int(action))
if res is not None:
return res
return 1
else:
return ActionMap.action(self, contexts, action)
class HelpableActionMap(ActionMap):
"""An Actionmap which automatically puts the actions into the helpList.
Note that you can only use ONE context here!"""
# sorry for this complicated code.
# it's not more than converting a "documented" actionmap
# (where the values are possibly (function, help)-tuples)
# into a "classic" actionmap, where values are just functions.
# the classic actionmap is then passed to the ActionMap constructor,
# the collected helpstrings (with correct context, action) is
# added to the screen's "helpList", which will be picked up by
# the "HelpableScreen".
def __init__(self, parent, context, actions = { }, prio=0):
alist = [ ]
adict = { }
for (action, funchelp) in actions.iteritems():
# check if this is a tuple
if isinstance(funchelp, tuple):
alist.append((action, funchelp[1]))
adict[action] = funchelp[0]
else:
adict[action] = funchelp
ActionMap.__init__(self, [context], adict, prio)
parent.helpList.append((self, context, alist))
| destroy | identifier_name |
ActionMap.py | from enigma import eActionMap
class ActionMap:
def __init__(self, contexts = [ ], actions = { }, prio=0):
self.actions = actions
self.contexts = contexts
self.prio = prio
self.p = eActionMap.getInstance()
self.bound = False
self.exec_active = False
self.enabled = True
def setEnabled(self, enabled):
self.enabled = enabled
self.checkBind()
def doBind(self):
if not self.bound:
for ctx in self.contexts:
self.p.bindAction(ctx, self.prio, self.action)
self.bound = True
def doUnbind(self):
if self.bound:
for ctx in self.contexts:
self.p.unbindAction(ctx, self.action)
self.bound = False
def checkBind(self):
if self.exec_active and self.enabled:
self.doBind()
else:
self.doUnbind()
def execBegin(self):
self.exec_active = True
self.checkBind()
def execEnd(self):
self.exec_active = False
self.checkBind()
def action(self, context, action):
print " ".join(("action -> ", context, action))
if action in self.actions:
res = self.actions[action]()
if res is not None:
return res
return 1
else:
print "unknown action %s/%s! typo in keymap?" % (context, action)
return 0
def destroy(self):
pass
class NumberActionMap(ActionMap):
def action(self, contexts, action):
numbers = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
if (action in numbers and self.actions.has_key(action)):
res = self.actions[action](int(action))
if res is not None:
return res
return 1
else:
return ActionMap.action(self, contexts, action)
|
# sorry for this complicated code.
# it's not more than converting a "documented" actionmap
# (where the values are possibly (function, help)-tuples)
# into a "classic" actionmap, where values are just functions.
# the classic actionmap is then passed to the ActionMap constructor,
# the collected helpstrings (with correct context, action) is
# added to the screen's "helpList", which will be picked up by
# the "HelpableScreen".
def __init__(self, parent, context, actions = { }, prio=0):
alist = [ ]
adict = { }
for (action, funchelp) in actions.iteritems():
# check if this is a tuple
if isinstance(funchelp, tuple):
alist.append((action, funchelp[1]))
adict[action] = funchelp[0]
else:
adict[action] = funchelp
ActionMap.__init__(self, [context], adict, prio)
parent.helpList.append((self, context, alist)) | class HelpableActionMap(ActionMap):
"""An Actionmap which automatically puts the actions into the helpList.
Note that you can only use ONE context here!""" | random_line_split |
ActionMap.py | from enigma import eActionMap
class ActionMap:
def __init__(self, contexts = [ ], actions = { }, prio=0):
self.actions = actions
self.contexts = contexts
self.prio = prio
self.p = eActionMap.getInstance()
self.bound = False
self.exec_active = False
self.enabled = True
def setEnabled(self, enabled):
self.enabled = enabled
self.checkBind()
def doBind(self):
if not self.bound:
for ctx in self.contexts:
self.p.bindAction(ctx, self.prio, self.action)
self.bound = True
def doUnbind(self):
if self.bound:
for ctx in self.contexts:
self.p.unbindAction(ctx, self.action)
self.bound = False
def checkBind(self):
if self.exec_active and self.enabled:
self.doBind()
else:
self.doUnbind()
def execBegin(self):
self.exec_active = True
self.checkBind()
def execEnd(self):
self.exec_active = False
self.checkBind()
def action(self, context, action):
|
def destroy(self):
pass
class NumberActionMap(ActionMap):
def action(self, contexts, action):
numbers = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
if (action in numbers and self.actions.has_key(action)):
res = self.actions[action](int(action))
if res is not None:
return res
return 1
else:
return ActionMap.action(self, contexts, action)
class HelpableActionMap(ActionMap):
"""An Actionmap which automatically puts the actions into the helpList.
Note that you can only use ONE context here!"""
# sorry for this complicated code.
# it's not more than converting a "documented" actionmap
# (where the values are possibly (function, help)-tuples)
# into a "classic" actionmap, where values are just functions.
# the classic actionmap is then passed to the ActionMap constructor,
# the collected helpstrings (with correct context, action) is
# added to the screen's "helpList", which will be picked up by
# the "HelpableScreen".
def __init__(self, parent, context, actions = { }, prio=0):
alist = [ ]
adict = { }
for (action, funchelp) in actions.iteritems():
# check if this is a tuple
if isinstance(funchelp, tuple):
alist.append((action, funchelp[1]))
adict[action] = funchelp[0]
else:
adict[action] = funchelp
ActionMap.__init__(self, [context], adict, prio)
parent.helpList.append((self, context, alist))
| print " ".join(("action -> ", context, action))
if action in self.actions:
res = self.actions[action]()
if res is not None:
return res
return 1
else:
print "unknown action %s/%s! typo in keymap?" % (context, action)
return 0 | identifier_body |
htmlsourceelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLSourceElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLSourceElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLSourceElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct HTMLSourceElement {
pub htmlelement: HTMLElement
}
impl HTMLSourceElementDerived for EventTarget {
fn is_htmlsourceelement(&self) -> bool |
}
impl HTMLSourceElement {
pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLSourceElement {
HTMLSourceElement {
htmlelement: HTMLElement::new_inherited(HTMLSourceElementTypeId, localName, document)
}
}
pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLSourceElement> {
let element = HTMLSourceElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLSourceElementBinding::Wrap)
}
}
pub trait HTMLSourceElementMethods {
}
impl Reflectable for HTMLSourceElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
| {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLSourceElementTypeId))
} | identifier_body |
htmlsourceelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLSourceElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLSourceElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLSourceElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct HTMLSourceElement {
pub htmlelement: HTMLElement
}
impl HTMLSourceElementDerived for EventTarget {
fn is_htmlsourceelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLSourceElementTypeId))
}
}
impl HTMLSourceElement {
pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLSourceElement {
HTMLSourceElement {
htmlelement: HTMLElement::new_inherited(HTMLSourceElementTypeId, localName, document)
}
}
pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLSourceElement> {
let element = HTMLSourceElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLSourceElementBinding::Wrap)
}
}
pub trait HTMLSourceElementMethods {
}
impl Reflectable for HTMLSourceElement {
fn | <'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
| reflector | identifier_name |
htmlsourceelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLSourceElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLSourceElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::HTMLSourceElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId}; | }
impl HTMLSourceElementDerived for EventTarget {
fn is_htmlsourceelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLSourceElementTypeId))
}
}
impl HTMLSourceElement {
pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLSourceElement {
HTMLSourceElement {
htmlelement: HTMLElement::new_inherited(HTMLSourceElementTypeId, localName, document)
}
}
pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLSourceElement> {
let element = HTMLSourceElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLSourceElementBinding::Wrap)
}
}
pub trait HTMLSourceElementMethods {
}
impl Reflectable for HTMLSourceElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
} | use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct HTMLSourceElement {
pub htmlelement: HTMLElement | random_line_split |
cat.js | var shell = require('..');
var assert = require('assert'),
path = require('path'),
fs = require('fs');
// Node shims for < v0.7
fs.existsSync = fs.existsSync || path.existsSync;
shell.silent();
function numLines(str) {
return typeof str === 'string' ? str.match(/\n/g).length : 0;
}
// save current dir
var cur = shell.pwd();
shell.rm('-rf', 'tmp');
shell.mkdir('tmp')
//
// Invalids
//
shell.cat();
assert.ok(shell.error());
assert.equal(fs.existsSync('/asdfasdf'), false); // sanity check | // Valids
//
// simple
var result = shell.cat('resources/file1');
assert.equal(shell.error(), null);
assert.equal(result, 'test1');
// multiple files
var result = shell.cat('resources/file2', 'resources/file1');
assert.equal(shell.error(), null);
assert.equal(result, 'test2\ntest1');
// multiple files, array syntax
var result = shell.cat(['resources/file2', 'resources/file1']);
assert.equal(shell.error(), null);
assert.equal(result, 'test2\ntest1');
var result = shell.cat('resources/file*.txt');
assert.equal(shell.error(), null);
assert.ok(result.search('test1') > -1); // file order might be random
assert.ok(result.search('test2') > -1);
shell.exit(123); | shell.cat('/adsfasdf'); // file does not exist
assert.ok(shell.error());
// | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.