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 |
---|---|---|---|---|
ng_module.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 {ApplicationRef} from '../application_ref';
import {InjectorType, ɵɵdefineInjector} from '../di/interface/defs';
import {Provider} from '../di/interface/provider';
import {convertInjectableProviderToFactory} from '../di/util';
import {Type} from '../interface/type';
import {SchemaMetadata} from '../metadata/schema';
import {NgModuleType} from '../render3';
import {compileNgModule as render3CompileNgModule} from '../render3/jit/module';
import {TypeDecorator, makeDecorator} from '../util/decorators';
/**
* Represents the expansion of an `NgModule` into its scopes.
*
* A scope is a set of directives and pipes that are visible in a particular context. Each
* `NgModule` has two scopes. The `compilation` scope is the set of directives and pipes that will
* be recognized in the templates of components declared by the module. The `exported` scope is the
* set of directives and pipes exported by a module (that is, module B's exported scope gets added
* to module A's compilation scope when module A imports B).
*/
export interface NgModuleTransitiveScopes {
compilation: {directives: Set<any>; pipes: Set<any>;};
exported: {directives: Set<any>; pipes: Set<any>;};
schemas: SchemaMetadata[]|null;
}
/**
* @publicApi
*/
export type ɵɵNgModuleDefWithMeta<T, Declarations, Imports, Exports> = NgModuleDef<T>;
/**
* Runtime link information for NgModules.
*
* This is the internal data structure used by the runtime to assemble components, directives,
* pipes, and injectors.
*
* NOTE: Always use `ɵɵdefineNgModule` function to create this object,
* never create the object directly since the shape of this object
* can change between versions.
*/
export interface NgModuleDef<T> {
/** Token representing the module. Used by DI. */
type: T;
/** List of components to bootstrap. */
bootstrap: Type<any>[]|(() => Type<any>[]);
/** List of components, directives, and pipes declared by this module. */
declarations: Type<any>[]|(() => Type<any>[]);
/** List of modules or `ModuleWithProviders` imported by this module. */
imports: Type<any>[]|(() => Type<any>[]);
/**
* List of modules, `ModuleWithProviders`, components, directives, or pipes exported by this
* module.
*/
exports: Type<any>[]|(() => Type<any>[]);
/**
* Cached value of computed `transitiveCompileScopes` for this module.
*
* This should never be read directly, but accessed via `transitiveScopesFor`.
*/
transitiveCompileScopes: NgModuleTransitiveScopes|null;
/** The set of schemas that declare elements to be allowed in the NgModule. */
schemas: SchemaMetadata[]|null;
/** Unique ID for the module with which it should be registered. */
id: string|null;
}
/**
* A wrapper around an NgModule that associates it with the providers.
*
* @param T the module type. In Ivy applications, this must be explicitly
* provided.
*
* @publicApi
*/
export interface ModuleWithProviders<
T = any /** TODO(alxhub): remove default when callers pass explicit type param */> {
ngModule: Type<T>;
providers?: Provider[];
}
/**
* Type of the NgModule decorator / constructor function.
*
* @publicApi
*/
export interface NgModuleDecorator {
/**
* Decorator that marks a class as an NgModule and supplies configuration metadata.
*/
(obj?: NgModule): TypeDecorator;
new (obj?: NgModule): NgModule;
}
/**
* Type of the NgModule metadata.
*
* @publicApi
*/
export interface NgModule {
/**
* The set of injectable objects that are available in the injector
* of this module.
*
* @see [Dependency Injection guide](guide/dependency-injection)
* @see [NgModule guide](guide/providers)
*
* @usageNotes
*
* Dependencies whose providers are listed here become available for injection
* into any component, directive, pipe or service that is a child of this injector.
* The NgModule used for bootstrapping uses the root injector, and can provide dependencies
* to any part of the app.
*
* A lazy-loaded module has its own injector, typically a child of the app root injector.
* Lazy-loaded services are scoped to the lazy-loaded module's injector.
* If a lazy-loaded module also provides the `UserService`, any component created
* within that module's context (such as by router navigation) gets the local instance
* of the service, not the instance in the root injector.
* Components in external modules continue to receive the instance provided by their injectors.
*
* ### Example
*
* The following example defines a class that is injected in
* the HelloWorld NgModule:
*
* ```
* class Greeter {
* greet(name:string) {
* return 'Hello ' + name + '!';
* }
* }
*
* @NgModule({
* providers: [
* Greeter
* ]
* })
* class HelloWorld {
* greeter:Greeter;
*
* constructor(greeter:Greeter) {
* this.greeter = greeter;
* }
* }
* ```
*/
providers?: Provider[];
/**
* The set of components, directives, and pipes ([declarables](guide/glossary#declarable))
* that belong to this module.
*
* @usageNotes
*
* The set of selectors that are available to a template include those declared here, and
* those that are exported from imported NgModules.
*
* Declarables must belong to exactly one module.
* The compiler emits an error if you try to declare the same class in more than one module.
* Be careful not to declare a class that is imported from another module.
*
* ### Example
*
* The following example allows the CommonModule to use the `NgFor`
* directive.
*
* ```javascript
* @NgModule({
* declarations: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
declarations?: Array<Type<any>|any[]>;
/**
* The set of NgModules whose exported [declarables](guide/glossary#declarable)
* are available to templates in this module.
*
* @usageNotes
*
* A template can use exported declarables from any
* imported module, including those from modules that are imported indirectly
* and re-exported.
* For example, `ModuleA` imports `ModuleB`, and also exports
* it, which makes the declarables from `ModuleB` available
* wherever `ModuleA` is imported.
|
*
* ### Example
*
* The following example allows MainModule to use anything exported by
* `CommonModule`:
*
* ```javascript
* @NgModule({
* imports: [CommonModule]
* })
* class MainModule {
* }
* ```
*
*/
imports?: Array<Type<any>|ModuleWithProviders<{}>|any[]>;
/**
* The set of components, directives, and pipes declared in this
* NgModule that can be used in the template of any component that is part of an
* NgModule that imports this NgModule. Exported declarations are the module's public API.
*
* A declarable belongs to one and only one NgModule.
* A module can list another module among its exports, in which case all of that module's
* public declaration are exported.
*
* @usageNotes
*
* Declarations are private by default.
* If this ModuleA does not export UserComponent, then only the components within this
* ModuleA can use UserComponent.
*
* ModuleA can import ModuleB and also export it, making exports from ModuleB
* available to an NgModule that imports ModuleA.
*
* ### Example
*
* The following example exports the `NgFor` directive from CommonModule.
*
* ```javascript
* @NgModule({
* exports: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
exports?: Array<Type<any>|any[]>;
/**
* The set of components to compile when this NgModule is defined,
* so that they can be dynamically loaded into the view.
*
* For each component listed here, Angular creates a `ComponentFactory`
* and stores it in the `ComponentFactoryResolver`.
*
* Angular automatically adds components in the module's bootstrap
* and route definitions into the `entryComponents` list. Use this
* option to add components that are bootstrapped
* using one of the imperative techniques, such as `ViewContainerRef.createComponent()`.
*
* @see [Entry Components](guide/entry-components)
* @deprecated Since 9.0.0. With Ivy, this property is no longer necessary.
*/
entryComponents?: Array<Type<any>|any[]>;
/**
* The set of components that are bootstrapped when
* this module is bootstrapped. The components listed here
* are automatically added to `entryComponents`.
*/
bootstrap?: Array<Type<any>|any[]>;
/**
* The set of schemas that declare elements to be allowed in the NgModule.
* Elements and properties that are neither Angular components nor directives
* must be declared in a schema.
*
* Allowed value are `NO_ERRORS_SCHEMA` and `CUSTOM_ELEMENTS_SCHEMA`.
*
* @security When using one of `NO_ERRORS_SCHEMA` or `CUSTOM_ELEMENTS_SCHEMA`
* you must ensure that allowed elements and properties securely escape inputs.
*/
schemas?: Array<SchemaMetadata|any[]>;
/**
* A name or path that uniquely identifies this NgModule in `getModuleFactory`.
* If left `undefined`, the NgModule is not registered with
* `getModuleFactory`.
*/
id?: string;
/**
* If true, this module will be skipped by the AOT compiler and so will always be compiled
* using JIT.
*
* This exists to support future Ivy work and has no effect currently.
*/
jit?: true;
}
/**
* @Annotation
* @publicApi
*/
export const NgModule: NgModuleDecorator = makeDecorator(
'NgModule', (ngModule: NgModule) => ngModule, undefined, undefined,
/**
* Decorator that marks the following class as an NgModule, and supplies
* configuration metadata for it.
*
* * The `declarations` and `entryComponents` options configure the compiler
* with information about what belongs to the NgModule.
* * The `providers` options configures the NgModule's injector to provide
* dependencies the NgModule members.
* * The `imports` and `exports` options bring in members from other modules, and make
* this module's members available to others.
*/
(type: Type<any>, meta: NgModule) => SWITCH_COMPILE_NGMODULE(type, meta));
/**
* @description
* Hook for manual bootstrapping of the application instead of using bootstrap array in @NgModule
* annotation.
*
* Reference to the current application is provided as a parameter.
*
* See ["Bootstrapping"](guide/bootstrapping) and ["Entry components"](guide/entry-components).
*
* @usageNotes
* ```typescript
* class AppModule implements DoBootstrap {
* ngDoBootstrap(appRef: ApplicationRef) {
* appRef.bootstrap(AppComponent); // Or some other component
* }
* }
* ```
*
* @publicApi
*/
export interface DoBootstrap { ngDoBootstrap(appRef: ApplicationRef): void; }
function preR3NgModuleCompile(moduleType: Type<any>, metadata?: NgModule): void {
let imports = (metadata && metadata.imports) || [];
if (metadata && metadata.exports) {
imports = [...imports, metadata.exports];
}
(moduleType as InjectorType<any>).ɵinj = ɵɵdefineInjector({
factory: convertInjectableProviderToFactory(moduleType, {useClass: moduleType}),
providers: metadata && metadata.providers,
imports: imports,
});
}
export const SWITCH_COMPILE_NGMODULE__POST_R3__ = render3CompileNgModule;
const SWITCH_COMPILE_NGMODULE__PRE_R3__ = preR3NgModuleCompile;
const SWITCH_COMPILE_NGMODULE: typeof render3CompileNgModule = SWITCH_COMPILE_NGMODULE__PRE_R3__;
|
random_line_split
|
|
ng_module.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 {ApplicationRef} from '../application_ref';
import {InjectorType, ɵɵdefineInjector} from '../di/interface/defs';
import {Provider} from '../di/interface/provider';
import {convertInjectableProviderToFactory} from '../di/util';
import {Type} from '../interface/type';
import {SchemaMetadata} from '../metadata/schema';
import {NgModuleType} from '../render3';
import {compileNgModule as render3CompileNgModule} from '../render3/jit/module';
import {TypeDecorator, makeDecorator} from '../util/decorators';
/**
* Represents the expansion of an `NgModule` into its scopes.
*
* A scope is a set of directives and pipes that are visible in a particular context. Each
* `NgModule` has two scopes. The `compilation` scope is the set of directives and pipes that will
* be recognized in the templates of components declared by the module. The `exported` scope is the
* set of directives and pipes exported by a module (that is, module B's exported scope gets added
* to module A's compilation scope when module A imports B).
*/
export interface NgModuleTransitiveScopes {
compilation: {directives: Set<any>; pipes: Set<any>;};
exported: {directives: Set<any>; pipes: Set<any>;};
schemas: SchemaMetadata[]|null;
}
/**
* @publicApi
*/
export type ɵɵNgModuleDefWithMeta<T, Declarations, Imports, Exports> = NgModuleDef<T>;
/**
* Runtime link information for NgModules.
*
* This is the internal data structure used by the runtime to assemble components, directives,
* pipes, and injectors.
*
* NOTE: Always use `ɵɵdefineNgModule` function to create this object,
* never create the object directly since the shape of this object
* can change between versions.
*/
export interface NgModuleDef<T> {
/** Token representing the module. Used by DI. */
type: T;
/** List of components to bootstrap. */
bootstrap: Type<any>[]|(() => Type<any>[]);
/** List of components, directives, and pipes declared by this module. */
declarations: Type<any>[]|(() => Type<any>[]);
/** List of modules or `ModuleWithProviders` imported by this module. */
imports: Type<any>[]|(() => Type<any>[]);
/**
* List of modules, `ModuleWithProviders`, components, directives, or pipes exported by this
* module.
*/
exports: Type<any>[]|(() => Type<any>[]);
/**
* Cached value of computed `transitiveCompileScopes` for this module.
*
* This should never be read directly, but accessed via `transitiveScopesFor`.
*/
transitiveCompileScopes: NgModuleTransitiveScopes|null;
/** The set of schemas that declare elements to be allowed in the NgModule. */
schemas: SchemaMetadata[]|null;
/** Unique ID for the module with which it should be registered. */
id: string|null;
}
/**
* A wrapper around an NgModule that associates it with the providers.
*
* @param T the module type. In Ivy applications, this must be explicitly
* provided.
*
* @publicApi
*/
export interface ModuleWithProviders<
T = any /** TODO(alxhub): remove default when callers pass explicit type param */> {
ngModule: Type<T>;
providers?: Provider[];
}
/**
* Type of the NgModule decorator / constructor function.
*
* @publicApi
*/
export interface NgModuleDecorator {
/**
* Decorator that marks a class as an NgModule and supplies configuration metadata.
*/
(obj?: NgModule): TypeDecorator;
new (obj?: NgModule): NgModule;
}
/**
* Type of the NgModule metadata.
*
* @publicApi
*/
export interface NgModule {
/**
* The set of injectable objects that are available in the injector
* of this module.
*
* @see [Dependency Injection guide](guide/dependency-injection)
* @see [NgModule guide](guide/providers)
*
* @usageNotes
*
* Dependencies whose providers are listed here become available for injection
* into any component, directive, pipe or service that is a child of this injector.
* The NgModule used for bootstrapping uses the root injector, and can provide dependencies
* to any part of the app.
*
* A lazy-loaded module has its own injector, typically a child of the app root injector.
* Lazy-loaded services are scoped to the lazy-loaded module's injector.
* If a lazy-loaded module also provides the `UserService`, any component created
* within that module's context (such as by router navigation) gets the local instance
* of the service, not the instance in the root injector.
* Components in external modules continue to receive the instance provided by their injectors.
*
* ### Example
*
* The following example defines a class that is injected in
* the HelloWorld NgModule:
*
* ```
* class Greeter {
* greet(name:string) {
* return 'Hello ' + name + '!';
* }
* }
*
* @NgModule({
* providers: [
* Greeter
* ]
* })
* class HelloWorld {
* greeter:Greeter;
*
* constructor(greeter:Greeter) {
* this.greeter = greeter;
* }
* }
* ```
*/
providers?: Provider[];
/**
* The set of components, directives, and pipes ([declarables](guide/glossary#declarable))
* that belong to this module.
*
* @usageNotes
*
* The set of selectors that are available to a template include those declared here, and
* those that are exported from imported NgModules.
*
* Declarables must belong to exactly one module.
* The compiler emits an error if you try to declare the same class in more than one module.
* Be careful not to declare a class that is imported from another module.
*
* ### Example
*
* The following example allows the CommonModule to use the `NgFor`
* directive.
*
* ```javascript
* @NgModule({
* declarations: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
declarations?: Array<Type<any>|any[]>;
/**
* The set of NgModules whose exported [declarables](guide/glossary#declarable)
* are available to templates in this module.
*
* @usageNotes
*
* A template can use exported declarables from any
* imported module, including those from modules that are imported indirectly
* and re-exported.
* For example, `ModuleA` imports `ModuleB`, and also exports
* it, which makes the declarables from `ModuleB` available
* wherever `ModuleA` is imported.
*
* ### Example
*
* The following example allows MainModule to use anything exported by
* `CommonModule`:
*
* ```javascript
* @NgModule({
* imports: [CommonModule]
* })
* class MainModule {
* }
* ```
*
*/
imports?: Array<Type<any>|ModuleWithProviders<{}>|any[]>;
/**
* The set of components, directives, and pipes declared in this
* NgModule that can be used in the template of any component that is part of an
* NgModule that imports this NgModule. Exported declarations are the module's public API.
*
* A declarable belongs to one and only one NgModule.
* A module can list another module among its exports, in which case all of that module's
* public declaration are exported.
*
* @usageNotes
*
* Declarations are private by default.
* If this ModuleA does not export UserComponent, then only the components within this
* ModuleA can use UserComponent.
*
* ModuleA can import ModuleB and also export it, making exports from ModuleB
* available to an NgModule that imports ModuleA.
*
* ### Example
*
* The following example exports the `NgFor` directive from CommonModule.
*
* ```javascript
* @NgModule({
* exports: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
exports?: Array<Type<any>|any[]>;
/**
* The set of components to compile when this NgModule is defined,
* so that they can be dynamically loaded into the view.
*
* For each component listed here, Angular creates a `ComponentFactory`
* and stores it in the `ComponentFactoryResolver`.
*
* Angular automatically adds components in the module's bootstrap
* and route definitions into the `entryComponents` list. Use this
* option to add components that are bootstrapped
* using one of the imperative techniques, such as `ViewContainerRef.createComponent()`.
*
* @see [Entry Components](guide/entry-components)
* @deprecated Since 9.0.0. With Ivy, this property is no longer necessary.
*/
entryComponents?: Array<Type<any>|any[]>;
/**
* The set of components that are bootstrapped when
* this module is bootstrapped. The components listed here
* are automatically added to `entryComponents`.
*/
bootstrap?: Array<Type<any>|any[]>;
/**
* The set of schemas that declare elements to be allowed in the NgModule.
* Elements and properties that are neither Angular components nor directives
* must be declared in a schema.
*
* Allowed value are `NO_ERRORS_SCHEMA` and `CUSTOM_ELEMENTS_SCHEMA`.
*
* @security When using one of `NO_ERRORS_SCHEMA` or `CUSTOM_ELEMENTS_SCHEMA`
* you must ensure that allowed elements and properties securely escape inputs.
*/
schemas?: Array<SchemaMetadata|any[]>;
/**
* A name or path that uniquely identifies this NgModule in `getModuleFactory`.
* If left `undefined`, the NgModule is not registered with
* `getModuleFactory`.
*/
id?: string;
/**
* If true, this module will be skipped by the AOT compiler and so will always be compiled
* using JIT.
*
* This exists to support future Ivy work and has no effect currently.
*/
jit?: true;
}
/**
* @Annotation
* @publicApi
*/
export const NgModule: NgModuleDecorator = makeDecorator(
'NgModule', (ngModule: NgModule) => ngModule, undefined, undefined,
/**
* Decorator that marks the following class as an NgModule, and supplies
* configuration metadata for it.
*
* * The `declarations` and `entryComponents` options configure the compiler
* with information about what belongs to the NgModule.
* * The `providers` options configures the NgModule's injector to provide
* dependencies the NgModule members.
* * The `imports` and `exports` options bring in members from other modules, and make
* this module's members available to others.
*/
(type: Type<any>, meta: NgModule) => SWITCH_COMPILE_NGMODULE(type, meta));
/**
* @description
* Hook for manual bootstrapping of the application instead of using bootstrap array in @NgModule
* annotation.
*
* Reference to the current application is provided as a parameter.
*
* See ["Bootstrapping"](guide/bootstrapping) and ["Entry components"](guide/entry-components).
*
* @usageNotes
* ```typescript
* class AppModule implements DoBootstrap {
* ngDoBootstrap(appRef: ApplicationRef) {
* appRef.bootstrap(AppComponent); // Or some other component
* }
* }
* ```
*
* @publicApi
*/
export interface DoBootstrap { ngDoBootstrap(appRef: ApplicationRef): void; }
function preR3N
|
eType: Type<any>, metadata?: NgModule): void {
let imports = (metadata && metadata.imports) || [];
if (metadata && metadata.exports) {
imports = [...imports, metadata.exports];
}
(moduleType as InjectorType<any>).ɵinj = ɵɵdefineInjector({
factory: convertInjectableProviderToFactory(moduleType, {useClass: moduleType}),
providers: metadata && metadata.providers,
imports: imports,
});
}
export const SWITCH_COMPILE_NGMODULE__POST_R3__ = render3CompileNgModule;
const SWITCH_COMPILE_NGMODULE__PRE_R3__ = preR3NgModuleCompile;
const SWITCH_COMPILE_NGMODULE: typeof render3CompileNgModule = SWITCH_COMPILE_NGMODULE__PRE_R3__;
|
gModuleCompile(modul
|
identifier_name
|
ng_module.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 {ApplicationRef} from '../application_ref';
import {InjectorType, ɵɵdefineInjector} from '../di/interface/defs';
import {Provider} from '../di/interface/provider';
import {convertInjectableProviderToFactory} from '../di/util';
import {Type} from '../interface/type';
import {SchemaMetadata} from '../metadata/schema';
import {NgModuleType} from '../render3';
import {compileNgModule as render3CompileNgModule} from '../render3/jit/module';
import {TypeDecorator, makeDecorator} from '../util/decorators';
/**
* Represents the expansion of an `NgModule` into its scopes.
*
* A scope is a set of directives and pipes that are visible in a particular context. Each
* `NgModule` has two scopes. The `compilation` scope is the set of directives and pipes that will
* be recognized in the templates of components declared by the module. The `exported` scope is the
* set of directives and pipes exported by a module (that is, module B's exported scope gets added
* to module A's compilation scope when module A imports B).
*/
export interface NgModuleTransitiveScopes {
compilation: {directives: Set<any>; pipes: Set<any>;};
exported: {directives: Set<any>; pipes: Set<any>;};
schemas: SchemaMetadata[]|null;
}
/**
* @publicApi
*/
export type ɵɵNgModuleDefWithMeta<T, Declarations, Imports, Exports> = NgModuleDef<T>;
/**
* Runtime link information for NgModules.
*
* This is the internal data structure used by the runtime to assemble components, directives,
* pipes, and injectors.
*
* NOTE: Always use `ɵɵdefineNgModule` function to create this object,
* never create the object directly since the shape of this object
* can change between versions.
*/
export interface NgModuleDef<T> {
/** Token representing the module. Used by DI. */
type: T;
/** List of components to bootstrap. */
bootstrap: Type<any>[]|(() => Type<any>[]);
/** List of components, directives, and pipes declared by this module. */
declarations: Type<any>[]|(() => Type<any>[]);
/** List of modules or `ModuleWithProviders` imported by this module. */
imports: Type<any>[]|(() => Type<any>[]);
/**
* List of modules, `ModuleWithProviders`, components, directives, or pipes exported by this
* module.
*/
exports: Type<any>[]|(() => Type<any>[]);
/**
* Cached value of computed `transitiveCompileScopes` for this module.
*
* This should never be read directly, but accessed via `transitiveScopesFor`.
*/
transitiveCompileScopes: NgModuleTransitiveScopes|null;
/** The set of schemas that declare elements to be allowed in the NgModule. */
schemas: SchemaMetadata[]|null;
/** Unique ID for the module with which it should be registered. */
id: string|null;
}
/**
* A wrapper around an NgModule that associates it with the providers.
*
* @param T the module type. In Ivy applications, this must be explicitly
* provided.
*
* @publicApi
*/
export interface ModuleWithProviders<
T = any /** TODO(alxhub): remove default when callers pass explicit type param */> {
ngModule: Type<T>;
providers?: Provider[];
}
/**
* Type of the NgModule decorator / constructor function.
*
* @publicApi
*/
export interface NgModuleDecorator {
/**
* Decorator that marks a class as an NgModule and supplies configuration metadata.
*/
(obj?: NgModule): TypeDecorator;
new (obj?: NgModule): NgModule;
}
/**
* Type of the NgModule metadata.
*
* @publicApi
*/
export interface NgModule {
/**
* The set of injectable objects that are available in the injector
* of this module.
*
* @see [Dependency Injection guide](guide/dependency-injection)
* @see [NgModule guide](guide/providers)
*
* @usageNotes
*
* Dependencies whose providers are listed here become available for injection
* into any component, directive, pipe or service that is a child of this injector.
* The NgModule used for bootstrapping uses the root injector, and can provide dependencies
* to any part of the app.
*
* A lazy-loaded module has its own injector, typically a child of the app root injector.
* Lazy-loaded services are scoped to the lazy-loaded module's injector.
* If a lazy-loaded module also provides the `UserService`, any component created
* within that module's context (such as by router navigation) gets the local instance
* of the service, not the instance in the root injector.
* Components in external modules continue to receive the instance provided by their injectors.
*
* ### Example
*
* The following example defines a class that is injected in
* the HelloWorld NgModule:
*
* ```
* class Greeter {
* greet(name:string) {
* return 'Hello ' + name + '!';
* }
* }
*
* @NgModule({
* providers: [
* Greeter
* ]
* })
* class HelloWorld {
* greeter:Greeter;
*
* constructor(greeter:Greeter) {
* this.greeter = greeter;
* }
* }
* ```
*/
providers?: Provider[];
/**
* The set of components, directives, and pipes ([declarables](guide/glossary#declarable))
* that belong to this module.
*
* @usageNotes
*
* The set of selectors that are available to a template include those declared here, and
* those that are exported from imported NgModules.
*
* Declarables must belong to exactly one module.
* The compiler emits an error if you try to declare the same class in more than one module.
* Be careful not to declare a class that is imported from another module.
*
* ### Example
*
* The following example allows the CommonModule to use the `NgFor`
* directive.
*
* ```javascript
* @NgModule({
* declarations: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
declarations?: Array<Type<any>|any[]>;
/**
* The set of NgModules whose exported [declarables](guide/glossary#declarable)
* are available to templates in this module.
*
* @usageNotes
*
* A template can use exported declarables from any
* imported module, including those from modules that are imported indirectly
* and re-exported.
* For example, `ModuleA` imports `ModuleB`, and also exports
* it, which makes the declarables from `ModuleB` available
* wherever `ModuleA` is imported.
*
* ### Example
*
* The following example allows MainModule to use anything exported by
* `CommonModule`:
*
* ```javascript
* @NgModule({
* imports: [CommonModule]
* })
* class MainModule {
* }
* ```
*
*/
imports?: Array<Type<any>|ModuleWithProviders<{}>|any[]>;
/**
* The set of components, directives, and pipes declared in this
* NgModule that can be used in the template of any component that is part of an
* NgModule that imports this NgModule. Exported declarations are the module's public API.
*
* A declarable belongs to one and only one NgModule.
* A module can list another module among its exports, in which case all of that module's
* public declaration are exported.
*
* @usageNotes
*
* Declarations are private by default.
* If this ModuleA does not export UserComponent, then only the components within this
* ModuleA can use UserComponent.
*
* ModuleA can import ModuleB and also export it, making exports from ModuleB
* available to an NgModule that imports ModuleA.
*
* ### Example
*
* The following example exports the `NgFor` directive from CommonModule.
*
* ```javascript
* @NgModule({
* exports: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
exports?: Array<Type<any>|any[]>;
/**
* The set of components to compile when this NgModule is defined,
* so that they can be dynamically loaded into the view.
*
* For each component listed here, Angular creates a `ComponentFactory`
* and stores it in the `ComponentFactoryResolver`.
*
* Angular automatically adds components in the module's bootstrap
* and route definitions into the `entryComponents` list. Use this
* option to add components that are bootstrapped
* using one of the imperative techniques, such as `ViewContainerRef.createComponent()`.
*
* @see [Entry Components](guide/entry-components)
* @deprecated Since 9.0.0. With Ivy, this property is no longer necessary.
*/
entryComponents?: Array<Type<any>|any[]>;
/**
* The set of components that are bootstrapped when
* this module is bootstrapped. The components listed here
* are automatically added to `entryComponents`.
*/
bootstrap?: Array<Type<any>|any[]>;
/**
* The set of schemas that declare elements to be allowed in the NgModule.
* Elements and properties that are neither Angular components nor directives
* must be declared in a schema.
*
* Allowed value are `NO_ERRORS_SCHEMA` and `CUSTOM_ELEMENTS_SCHEMA`.
*
* @security When using one of `NO_ERRORS_SCHEMA` or `CUSTOM_ELEMENTS_SCHEMA`
* you must ensure that allowed elements and properties securely escape inputs.
*/
schemas?: Array<SchemaMetadata|any[]>;
/**
* A name or path that uniquely identifies this NgModule in `getModuleFactory`.
* If left `undefined`, the NgModule is not registered with
* `getModuleFactory`.
*/
id?: string;
/**
* If true, this module will be skipped by the AOT compiler and so will always be compiled
* using JIT.
*
* This exists to support future Ivy work and has no effect currently.
*/
jit?: true;
}
/**
* @Annotation
* @publicApi
*/
export const NgModule: NgModuleDecorator = makeDecorator(
'NgModule', (ngModule: NgModule) => ngModule, undefined, undefined,
/**
* Decorator that marks the following class as an NgModule, and supplies
* configuration metadata for it.
*
* * The `declarations` and `entryComponents` options configure the compiler
* with information about what belongs to the NgModule.
* * The `providers` options configures the NgModule's injector to provide
* dependencies the NgModule members.
* * The `imports` and `exports` options bring in members from other modules, and make
* this module's members available to others.
*/
(type: Type<any>, meta: NgModule) => SWITCH_COMPILE_NGMODULE(type, meta));
/**
* @description
* Hook for manual bootstrapping of the application instead of using bootstrap array in @NgModule
* annotation.
*
* Reference to the current application is provided as a parameter.
*
* See ["Bootstrapping"](guide/bootstrapping) and ["Entry components"](guide/entry-components).
*
* @usageNotes
* ```typescript
* class AppModule implements DoBootstrap {
* ngDoBootstrap(appRef: ApplicationRef) {
* appRef.bootstrap(AppComponent); // Or some other component
* }
* }
* ```
*
* @publicApi
*/
export interface DoBootstrap { ngDoBootstrap(appRef: ApplicationRef): void; }
function preR3NgModuleCompile(moduleType: Type<any>, metadata?: NgModule): void {
le
|
const SWITCH_COMPILE_NGMODULE__POST_R3__ = render3CompileNgModule;
const SWITCH_COMPILE_NGMODULE__PRE_R3__ = preR3NgModuleCompile;
const SWITCH_COMPILE_NGMODULE: typeof render3CompileNgModule = SWITCH_COMPILE_NGMODULE__PRE_R3__;
|
t imports = (metadata && metadata.imports) || [];
if (metadata && metadata.exports) {
imports = [...imports, metadata.exports];
}
(moduleType as InjectorType<any>).ɵinj = ɵɵdefineInjector({
factory: convertInjectableProviderToFactory(moduleType, {useClass: moduleType}),
providers: metadata && metadata.providers,
imports: imports,
});
}
export
|
identifier_body
|
ng_module.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 {ApplicationRef} from '../application_ref';
import {InjectorType, ɵɵdefineInjector} from '../di/interface/defs';
import {Provider} from '../di/interface/provider';
import {convertInjectableProviderToFactory} from '../di/util';
import {Type} from '../interface/type';
import {SchemaMetadata} from '../metadata/schema';
import {NgModuleType} from '../render3';
import {compileNgModule as render3CompileNgModule} from '../render3/jit/module';
import {TypeDecorator, makeDecorator} from '../util/decorators';
/**
* Represents the expansion of an `NgModule` into its scopes.
*
* A scope is a set of directives and pipes that are visible in a particular context. Each
* `NgModule` has two scopes. The `compilation` scope is the set of directives and pipes that will
* be recognized in the templates of components declared by the module. The `exported` scope is the
* set of directives and pipes exported by a module (that is, module B's exported scope gets added
* to module A's compilation scope when module A imports B).
*/
export interface NgModuleTransitiveScopes {
compilation: {directives: Set<any>; pipes: Set<any>;};
exported: {directives: Set<any>; pipes: Set<any>;};
schemas: SchemaMetadata[]|null;
}
/**
* @publicApi
*/
export type ɵɵNgModuleDefWithMeta<T, Declarations, Imports, Exports> = NgModuleDef<T>;
/**
* Runtime link information for NgModules.
*
* This is the internal data structure used by the runtime to assemble components, directives,
* pipes, and injectors.
*
* NOTE: Always use `ɵɵdefineNgModule` function to create this object,
* never create the object directly since the shape of this object
* can change between versions.
*/
export interface NgModuleDef<T> {
/** Token representing the module. Used by DI. */
type: T;
/** List of components to bootstrap. */
bootstrap: Type<any>[]|(() => Type<any>[]);
/** List of components, directives, and pipes declared by this module. */
declarations: Type<any>[]|(() => Type<any>[]);
/** List of modules or `ModuleWithProviders` imported by this module. */
imports: Type<any>[]|(() => Type<any>[]);
/**
* List of modules, `ModuleWithProviders`, components, directives, or pipes exported by this
* module.
*/
exports: Type<any>[]|(() => Type<any>[]);
/**
* Cached value of computed `transitiveCompileScopes` for this module.
*
* This should never be read directly, but accessed via `transitiveScopesFor`.
*/
transitiveCompileScopes: NgModuleTransitiveScopes|null;
/** The set of schemas that declare elements to be allowed in the NgModule. */
schemas: SchemaMetadata[]|null;
/** Unique ID for the module with which it should be registered. */
id: string|null;
}
/**
* A wrapper around an NgModule that associates it with the providers.
*
* @param T the module type. In Ivy applications, this must be explicitly
* provided.
*
* @publicApi
*/
export interface ModuleWithProviders<
T = any /** TODO(alxhub): remove default when callers pass explicit type param */> {
ngModule: Type<T>;
providers?: Provider[];
}
/**
* Type of the NgModule decorator / constructor function.
*
* @publicApi
*/
export interface NgModuleDecorator {
/**
* Decorator that marks a class as an NgModule and supplies configuration metadata.
*/
(obj?: NgModule): TypeDecorator;
new (obj?: NgModule): NgModule;
}
/**
* Type of the NgModule metadata.
*
* @publicApi
*/
export interface NgModule {
/**
* The set of injectable objects that are available in the injector
* of this module.
*
* @see [Dependency Injection guide](guide/dependency-injection)
* @see [NgModule guide](guide/providers)
*
* @usageNotes
*
* Dependencies whose providers are listed here become available for injection
* into any component, directive, pipe or service that is a child of this injector.
* The NgModule used for bootstrapping uses the root injector, and can provide dependencies
* to any part of the app.
*
* A lazy-loaded module has its own injector, typically a child of the app root injector.
* Lazy-loaded services are scoped to the lazy-loaded module's injector.
* If a lazy-loaded module also provides the `UserService`, any component created
* within that module's context (such as by router navigation) gets the local instance
* of the service, not the instance in the root injector.
* Components in external modules continue to receive the instance provided by their injectors.
*
* ### Example
*
* The following example defines a class that is injected in
* the HelloWorld NgModule:
*
* ```
* class Greeter {
* greet(name:string) {
* return 'Hello ' + name + '!';
* }
* }
*
* @NgModule({
* providers: [
* Greeter
* ]
* })
* class HelloWorld {
* greeter:Greeter;
*
* constructor(greeter:Greeter) {
* this.greeter = greeter;
* }
* }
* ```
*/
providers?: Provider[];
/**
* The set of components, directives, and pipes ([declarables](guide/glossary#declarable))
* that belong to this module.
*
* @usageNotes
*
* The set of selectors that are available to a template include those declared here, and
* those that are exported from imported NgModules.
*
* Declarables must belong to exactly one module.
* The compiler emits an error if you try to declare the same class in more than one module.
* Be careful not to declare a class that is imported from another module.
*
* ### Example
*
* The following example allows the CommonModule to use the `NgFor`
* directive.
*
* ```javascript
* @NgModule({
* declarations: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
declarations?: Array<Type<any>|any[]>;
/**
* The set of NgModules whose exported [declarables](guide/glossary#declarable)
* are available to templates in this module.
*
* @usageNotes
*
* A template can use exported declarables from any
* imported module, including those from modules that are imported indirectly
* and re-exported.
* For example, `ModuleA` imports `ModuleB`, and also exports
* it, which makes the declarables from `ModuleB` available
* wherever `ModuleA` is imported.
*
* ### Example
*
* The following example allows MainModule to use anything exported by
* `CommonModule`:
*
* ```javascript
* @NgModule({
* imports: [CommonModule]
* })
* class MainModule {
* }
* ```
*
*/
imports?: Array<Type<any>|ModuleWithProviders<{}>|any[]>;
/**
* The set of components, directives, and pipes declared in this
* NgModule that can be used in the template of any component that is part of an
* NgModule that imports this NgModule. Exported declarations are the module's public API.
*
* A declarable belongs to one and only one NgModule.
* A module can list another module among its exports, in which case all of that module's
* public declaration are exported.
*
* @usageNotes
*
* Declarations are private by default.
* If this ModuleA does not export UserComponent, then only the components within this
* ModuleA can use UserComponent.
*
* ModuleA can import ModuleB and also export it, making exports from ModuleB
* available to an NgModule that imports ModuleA.
*
* ### Example
*
* The following example exports the `NgFor` directive from CommonModule.
*
* ```javascript
* @NgModule({
* exports: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
exports?: Array<Type<any>|any[]>;
/**
* The set of components to compile when this NgModule is defined,
* so that they can be dynamically loaded into the view.
*
* For each component listed here, Angular creates a `ComponentFactory`
* and stores it in the `ComponentFactoryResolver`.
*
* Angular automatically adds components in the module's bootstrap
* and route definitions into the `entryComponents` list. Use this
* option to add components that are bootstrapped
* using one of the imperative techniques, such as `ViewContainerRef.createComponent()`.
*
* @see [Entry Components](guide/entry-components)
* @deprecated Since 9.0.0. With Ivy, this property is no longer necessary.
*/
entryComponents?: Array<Type<any>|any[]>;
/**
* The set of components that are bootstrapped when
* this module is bootstrapped. The components listed here
* are automatically added to `entryComponents`.
*/
bootstrap?: Array<Type<any>|any[]>;
/**
* The set of schemas that declare elements to be allowed in the NgModule.
* Elements and properties that are neither Angular components nor directives
* must be declared in a schema.
*
* Allowed value are `NO_ERRORS_SCHEMA` and `CUSTOM_ELEMENTS_SCHEMA`.
*
* @security When using one of `NO_ERRORS_SCHEMA` or `CUSTOM_ELEMENTS_SCHEMA`
* you must ensure that allowed elements and properties securely escape inputs.
*/
schemas?: Array<SchemaMetadata|any[]>;
/**
* A name or path that uniquely identifies this NgModule in `getModuleFactory`.
* If left `undefined`, the NgModule is not registered with
* `getModuleFactory`.
*/
id?: string;
/**
* If true, this module will be skipped by the AOT compiler and so will always be compiled
* using JIT.
*
* This exists to support future Ivy work and has no effect currently.
*/
jit?: true;
}
/**
* @Annotation
* @publicApi
*/
export const NgModule: NgModuleDecorator = makeDecorator(
'NgModule', (ngModule: NgModule) => ngModule, undefined, undefined,
/**
* Decorator that marks the following class as an NgModule, and supplies
* configuration metadata for it.
*
* * The `declarations` and `entryComponents` options configure the compiler
* with information about what belongs to the NgModule.
* * The `providers` options configures the NgModule's injector to provide
* dependencies the NgModule members.
* * The `imports` and `exports` options bring in members from other modules, and make
* this module's members available to others.
*/
(type: Type<any>, meta: NgModule) => SWITCH_COMPILE_NGMODULE(type, meta));
/**
* @description
* Hook for manual bootstrapping of the application instead of using bootstrap array in @NgModule
* annotation.
*
* Reference to the current application is provided as a parameter.
*
* See ["Bootstrapping"](guide/bootstrapping) and ["Entry components"](guide/entry-components).
*
* @usageNotes
* ```typescript
* class AppModule implements DoBootstrap {
* ngDoBootstrap(appRef: ApplicationRef) {
* appRef.bootstrap(AppComponent); // Or some other component
* }
* }
* ```
*
* @publicApi
*/
export interface DoBootstrap { ngDoBootstrap(appRef: ApplicationRef): void; }
function preR3NgModuleCompile(moduleType: Type<any>, metadata?: NgModule): void {
let imports = (metadata && metadata.imports) || [];
if (metadata && metadata.exports) {
|
oduleType as InjectorType<any>).ɵinj = ɵɵdefineInjector({
factory: convertInjectableProviderToFactory(moduleType, {useClass: moduleType}),
providers: metadata && metadata.providers,
imports: imports,
});
}
export const SWITCH_COMPILE_NGMODULE__POST_R3__ = render3CompileNgModule;
const SWITCH_COMPILE_NGMODULE__PRE_R3__ = preR3NgModuleCompile;
const SWITCH_COMPILE_NGMODULE: typeof render3CompileNgModule = SWITCH_COMPILE_NGMODULE__PRE_R3__;
|
imports = [...imports, metadata.exports];
}
(m
|
conditional_block
|
paper-action-button-option.js
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import contrast from 'contrast';
import Icon from './icon';
export default class PaperActionButtonOption extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
this.props.onClick(e);
this.props.__close();
}
render()
|
}
PaperActionButtonOption.defaultProps = {
onClick: () => {},
__close: () => {}
};
PaperActionButtonOption.propTypes = {
__badgeStyle: PropTypes.object,
color: PropTypes.string,
iconName: PropTypes.string.isRequired,
__labelStyle: PropTypes.object,
label: PropTypes.string.isRequired,
onClick: PropTypes.func,
__close: PropTypes.func
};
|
{
const {
label,
color,
__badgeStyle,
__labelStyle,
onClick,
iconName,
__close,
...props
} = this.props;
const bgColorShade = color ? contrast(color) : 'light';
return (
<div className="paper-action-button__option" {...props}>
<label style={__labelStyle} className="paper-action-button__label">
{label}
</label>
<button
className={classNames(
'paper-action-button__option-button',
`paper-action-button__option-button--${bgColorShade === 'light' ? 'light' : 'dark'}`
)}
style={{ backgroundColor: color, ...__badgeStyle }}
onClick={this.handleClick}
onMouseUp={() => this.myRef.blur()}
ref={myRef => {
this.myRef = myRef;
}}
>
<Icon>{iconName}</Icon>
</button>
</div>
);
}
|
identifier_body
|
paper-action-button-option.js
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import contrast from 'contrast';
import Icon from './icon';
export default class PaperActionButtonOption extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
this.props.onClick(e);
this.props.__close();
}
render() {
const {
label,
color,
__badgeStyle,
__labelStyle,
onClick,
iconName,
__close,
...props
} = this.props;
const bgColorShade = color ? contrast(color) : 'light';
return (
<div className="paper-action-button__option" {...props}>
<label style={__labelStyle} className="paper-action-button__label">
{label}
</label>
<button
className={classNames(
'paper-action-button__option-button',
`paper-action-button__option-button--${bgColorShade === 'light' ? 'light' : 'dark'}`
)}
style={{ backgroundColor: color, ...__badgeStyle }}
|
>
<Icon>{iconName}</Icon>
</button>
</div>
);
}
}
PaperActionButtonOption.defaultProps = {
onClick: () => {},
__close: () => {}
};
PaperActionButtonOption.propTypes = {
__badgeStyle: PropTypes.object,
color: PropTypes.string,
iconName: PropTypes.string.isRequired,
__labelStyle: PropTypes.object,
label: PropTypes.string.isRequired,
onClick: PropTypes.func,
__close: PropTypes.func
};
|
onClick={this.handleClick}
onMouseUp={() => this.myRef.blur()}
ref={myRef => {
this.myRef = myRef;
}}
|
random_line_split
|
paper-action-button-option.js
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import contrast from 'contrast';
import Icon from './icon';
export default class PaperActionButtonOption extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
|
(e) {
this.props.onClick(e);
this.props.__close();
}
render() {
const {
label,
color,
__badgeStyle,
__labelStyle,
onClick,
iconName,
__close,
...props
} = this.props;
const bgColorShade = color ? contrast(color) : 'light';
return (
<div className="paper-action-button__option" {...props}>
<label style={__labelStyle} className="paper-action-button__label">
{label}
</label>
<button
className={classNames(
'paper-action-button__option-button',
`paper-action-button__option-button--${bgColorShade === 'light' ? 'light' : 'dark'}`
)}
style={{ backgroundColor: color, ...__badgeStyle }}
onClick={this.handleClick}
onMouseUp={() => this.myRef.blur()}
ref={myRef => {
this.myRef = myRef;
}}
>
<Icon>{iconName}</Icon>
</button>
</div>
);
}
}
PaperActionButtonOption.defaultProps = {
onClick: () => {},
__close: () => {}
};
PaperActionButtonOption.propTypes = {
__badgeStyle: PropTypes.object,
color: PropTypes.string,
iconName: PropTypes.string.isRequired,
__labelStyle: PropTypes.object,
label: PropTypes.string.isRequired,
onClick: PropTypes.func,
__close: PropTypes.func
};
|
handleClick
|
identifier_name
|
values.test.js
|
const StitchMongoFixture = require('../fixtures/stitch_mongo_fixture');
import {getAuthenticatedClient} from '../testutil';
describe('Values V2', ()=>{
let test = new StitchMongoFixture();
let apps;
let app;
beforeAll(() => test.setup({createApp: false}));
afterAll(() => test.teardown());
beforeEach(async () =>{
let adminClient = await getAuthenticatedClient(test.userData.apiKey.key);
test.groupId = test.userData.group.groupId;
apps = await adminClient.v2().apps(test.groupId);
app = await apps.create({name: 'testname'});
appValues = adminClient.v2().apps(test.groupId).app(app._id).values();
});
afterEach(async () => {
await apps.app(app._id).remove();
});
let appValues;
const testValueName = 'testvaluename';
it('listing values should return empty list', async () => {
let values = await appValues.list();
expect(values).toEqual([]);
});
it('creating value should make it appear in list', async () => {
let value = await appValues.create({name: testValueName});
expect(value.name).toEqual(testValueName);
let values = await appValues.list();
expect(values).toHaveLength(1);
expect(values[0]).toEqual(value);
});
it('fetching a value returns deep value data', async () => {
|
expect(deepValue.value).toEqual('foo');
delete deepValue.value;
expect(value).toEqual(deepValue);
});
it('can update a value', async () => {
let value = await appValues.create({name: testValueName, value: 'foo'});
value.value = '"abcdefgh"';
await appValues.value(value._id).update(value);
const deepValue = await appValues.value(value._id).get();
expect(deepValue.value).toEqual('"abcdefgh"');
});
it('can delete a value', async () => {
let value = await appValues.create({name: testValueName});
expect(value.name).toEqual(testValueName);
let values = await appValues.list();
expect(values).toHaveLength(1);
await appValues.value(value._id).remove();
values = await appValues.list();
expect(values).toHaveLength(0);
});
});
|
let value = await appValues.create({name: testValueName, value: 'foo'});
const deepValue = await appValues.value(value._id).get();
|
random_line_split
|
NetTest.js
|
var numberOfPagesToOpen = 10;
var url = '';
var system = require('system');
var args = system.args;
var failures = 0;
if (args.length === 1) {
console.log('Usage:\nphantomjs http://url 100\nReturns how long it takes to load url 100 times.');
phantom.exit(0);
} else {
var url = args[1] || 'https://google.com/';
numberOfPagesToOpen = args[2] ? args[2] : 10;
}
var page = require('webpage').create();
var startTime = new Date();
var numberOfPagesOpened = 0;
|
var getElapsedTime = function(date) {
return date - startTime;
};
var startTest = function() {
startTime = new Date();
console.log('Testing ' + url + ' ' + numberOfPagesToOpen + ' times.');
openPage();
};
var continueTest = function() {
console.log('page ' + numberOfPagesOpened + ': ' + getElapsedTime(new Date()));
numberOfPagesOpened++;
if (numberOfPagesOpened < numberOfPagesToOpen) {
openPage();
} else {
endTest();
}
};
var openPage = function() {
page.open(url, function (status) {
switch (status) {
case 'error':
console.log(url + ' failed to load.');
phantom.exit(1);
break;
case 'fail':
failures++;
default:
break;
}
console.log('Loading page: ' + numberOfPagesOpened + ': ' + new Date() + '\nstatus: ' + status);
page.evaluate(function(data) {
document.addEventListener('DOMContentLoaded', function() {
window.callPhantom('DOMContentLoaded');
}, false);
});
continueTest();
});
page.onCallback = function(data) {
continueTest();
};
};
var getFailureMessage = function(fails) {
if (!fails) {
return;
}
var percentFail = numberOfPagesToOpen / fails * 100;
return 'Failures: ' + fails + ' (' + Math.round(percentFail) + '%)';
};
var endTest = function() {
var endTime = new Date();
var elapsedTime = endTime - startTime;
var failureMessage = '';
console.log('\n\n***************\nLoaded ' + url + ' '
+ numberOfPagesToOpen + ' times\n'
+ '\tElapsed: ' + elapsedTime + 'ms'
+ '\n\t' + getFailureMessage(failures)
+'\n***************');
phantom.exit();
};
// page.onLoadFinished = function(status) {
// console.log('loadFinished');
// continueTest();
// };
startTest();
|
random_line_split
|
|
NetTest.js
|
var numberOfPagesToOpen = 10;
var url = '';
var system = require('system');
var args = system.args;
var failures = 0;
if (args.length === 1)
|
else {
var url = args[1] || 'https://google.com/';
numberOfPagesToOpen = args[2] ? args[2] : 10;
}
var page = require('webpage').create();
var startTime = new Date();
var numberOfPagesOpened = 0;
var getElapsedTime = function(date) {
return date - startTime;
};
var startTest = function() {
startTime = new Date();
console.log('Testing ' + url + ' ' + numberOfPagesToOpen + ' times.');
openPage();
};
var continueTest = function() {
console.log('page ' + numberOfPagesOpened + ': ' + getElapsedTime(new Date()));
numberOfPagesOpened++;
if (numberOfPagesOpened < numberOfPagesToOpen) {
openPage();
} else {
endTest();
}
};
var openPage = function() {
page.open(url, function (status) {
switch (status) {
case 'error':
console.log(url + ' failed to load.');
phantom.exit(1);
break;
case 'fail':
failures++;
default:
break;
}
console.log('Loading page: ' + numberOfPagesOpened + ': ' + new Date() + '\nstatus: ' + status);
page.evaluate(function(data) {
document.addEventListener('DOMContentLoaded', function() {
window.callPhantom('DOMContentLoaded');
}, false);
});
continueTest();
});
page.onCallback = function(data) {
continueTest();
};
};
var getFailureMessage = function(fails) {
if (!fails) {
return;
}
var percentFail = numberOfPagesToOpen / fails * 100;
return 'Failures: ' + fails + ' (' + Math.round(percentFail) + '%)';
};
var endTest = function() {
var endTime = new Date();
var elapsedTime = endTime - startTime;
var failureMessage = '';
console.log('\n\n***************\nLoaded ' + url + ' '
+ numberOfPagesToOpen + ' times\n'
+ '\tElapsed: ' + elapsedTime + 'ms'
+ '\n\t' + getFailureMessage(failures)
+'\n***************');
phantom.exit();
};
// page.onLoadFinished = function(status) {
// console.log('loadFinished');
// continueTest();
// };
startTest();
|
{
console.log('Usage:\nphantomjs http://url 100\nReturns how long it takes to load url 100 times.');
phantom.exit(0);
}
|
conditional_block
|
turkish.ts
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="tr">
<context>
<name>U2::OpenCLSupportPlugin</name>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="52"/>
<source>Problem occurred loading the OpenCL driver. Please try to update drivers if you're going to make calculations on your video card. For details see this page: <a href="%1">%1</a></source>
<translation>OpenCL sürücüsünü yüklerken sorun oluştu. Lütfen ekran kartınızda hesaplamalar yapacaksanız sürücüleri güncellemeyi deneyin.. Ayrıntılar için şu sayfaya bakın: <a href="%1">%1</a></translation>
</message>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="61"/>
<source>OpenCL Support</source>
<translation>OpenCL Desteği</translation>
</message>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="62"/>
<source>Plugin provides support for OpenCL-enabled GPUs.</source>
<translation>Eklenti, OpenCL etkin GPU'lar için destek sağlar.</translation>
</message>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="113"/>
<source>Cannot load OpenCL driver dynamic library.<p> Install the latest video GPU driver.</source>
<translation>OpenCL sürücü dinamik kitaplığı yüklenemiyor.<p> En son video GPU sürücüsünü yükleyin.</translation>
</message>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="117"/>
<source>An error has occurred while obtaining information about installed OpenCL GPUs.<br> See OpenCL Support plugin log for details.</source>
<translation>Yüklü OpenCL GPU'lar hakkında bilgi alınırken bir hata oluştu.<br> Ayrıntılar için OpenCL Desteği eklenti günlüğüne bakın.</translation>
</message>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="136"/>
<source>Initializing OpenCL</source>
<translation>OpenCL'yi Başlatma</translation>
</message>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="147"/>
<source>Number of OpenCL platforms: %1</source>
<translation>OpenCL platformlarının sayısı: %1</translation>
</message>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="161"/>
<source>Number of OpenCL devices: %1</source>
<translation>OpenCL cihazlarının sayısı: %1</translation>
</message>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="261"/>
<source>Registering OpenCL-enabled GPU: %1, global mem: %2 Mb, local mem: %3 Kb, max compute units: %4, max work group size: %5, max frequency: %6 Hz</source>
<translation>OpenCL etkin GPU kaydetme: %1, global hafıza: %2 Mb, yerel hafıza: %3 Kb, max Hesaplama birimi: %4, Çalışma grubu boyutu: %5, max frekans: %6 Hz</translation>
</message>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="279"/>
<source>OpenCL error code (%1)</source>
<translation>OpenCL hata kodu (%1)</translation>
|
</context>
<context>
<name>U2::OpenCLSupportSettingsPageController</name>
<message>
<location filename="../src/OpenCLSupportSettingsController.cpp" line="36"/>
<source>OpenCL</source>
<translation>OpenCL</translation>
</message>
</context>
</TS>
|
</message>
|
random_line_split
|
pickadate.tr_TR.js
|
// Turkish
$.extend( $.fn.pickadate.defaults, {
monthsFull: [ 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık' ],
monthsShort: [ 'Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara' ],
weekdaysFull: [ 'Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi' ],
weekdaysShort: [ 'Pzr', 'Pzt', 'Sal', 'Çrş', 'Prş', 'Cum', 'Cmt' ],
today: 'bugün',
clear: 'sil',
firstDay: 1,
|
formatSubmit: 'yyyy/mm/dd'
})
|
format: 'dd mmmm yyyy dddd',
|
random_line_split
|
index.d.ts
|
// Type definitions for watchify 3.11
// Project: https://github.com/substack/watchify
// Definitions by: TeamworkGuy2 <https://github.com/TeamworkGuy2>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import Browserify = require('browserify');
declare module 'browserify' {
interface BrowserifyObject extends NodeJS.EventEmitter {
/**
* When the bundle changes, emit the array of bundle ids that changed.
*/
on(event: 'update', listener: (ids: string[]) => any): this;
/**
* When a bundle is generated, this event fires with the number of bytes
*/
on(event: 'bytes', listener: (bytes: number) => any): this;
/**
* When a bundle is generated, this event fires with the time it took to create the bundle in milliseconds.
*/
on(event: 'time', listener: (time: number) => any): this;
/**
* This event fires after a bundle was created with messages of the form:
* ```text
* X bytes written (Y seconds)
* ```
* with the number of bytes in the bundle X and the time in seconds Y.
*/
on(event: 'log', listener: (msg: string) => any): this;
}
}
declare var Watchify: Watchify.Constructor;
/**
* Watch mode for browserify builds.
* Update any source file and your browserify bundle will be recompiled on the spot
*/
declare namespace Watchify {
/**
* Watch mode for browserify builds.
* Update any source file and your browserify bundle will be recompiled on the spot
*/
interface Constructor {
args: { cache: any; packageCache: any };
<T extends Browserify.BrowserifyObject>(b: T, opts?: Options): T;
(b: Browserify.BrowserifyObject, opts?: Options): Browserify.BrowserifyObject;
/** Close all the open watch handles. */
close(): void;
}
interface Options {
/**
* The amount of time in milliseconds to wait before emitting an "update" event after a change.
* @default 100
*/
delay?: number | undefined;
/**
* Ignores monitoring files for changes. If set to `true`, then ** /node_modules/ ** will be ignored.
* For other possible values see Chokidar's documentation on "ignored"
* Also see anymatch package: https://github.com/es128/anymatch#usage
*/
ignoreWatch?:
| boolean
| (
| string
| RegExp
| ((...values: any[]) => boolean)
| Array<string | RegExp | ((...values: any[]) => boolean)>
) | undefined;
|
* Enables polling to monitor for changes. If set to `true`, then a polling interval of 100 ms is used.
* If set to a number, then that amount of milliseconds will be the polling interval. For more info see
* Chokidar's documentation on "usePolling" and "interval".
* This option is useful if you're watching an NFS volume
* Also see chokidar package: https://github.com/paulmillr/chokidar#path-filtering
*/
poll?: boolean | number | undefined;
}
}
export = Watchify;
|
/**
|
random_line_split
|
roger.py
|
#!/usr/bin/python
from __future__ import print_function
import os
import sys
import subprocess
import re
import importlib
from cli.utils import Utils
def print_help_opt(opt, desc):
print(" {} {}".format(opt.ljust(13), desc))
def roger_help(root, commands):
print("usage: roger [-h] [-v] command [arg...]\n")
print("a command line interface to work with roger mesos.")
print("\npositional arguments:")
print_help_opt("command", "command to run.")
print_help_opt("arg", "arguments to pass to the command.")
print("\noptional arguments:")
print_help_opt("-h, --help", "show this help message and exit.")
print_help_opt("-v, --version", "show version information and exit.")
print("\ncommands:")
sys.path.append("{}/cli".format(root))
for command in commands:
description = ""
module_name = "roger_" + command
cmd_module = importlib.import_module(module_name)
try:
description = cmd_module.describe()
except Exception as e:
pass
print_help_opt(command, description)
print("\nrun: 'roger < command > -h' for more information on a command.")
def getFiles(directory):
filenames = next(os.walk(directory))[2]
return filenames
def getCommands(files):
|
def getScriptCall(root, command, command_args):
script_call = "roger_{}.py".format(command)
for command_arg in command_args:
script_call = script_call + " {}".format(command_arg)
return script_call
def main():
root = ''
utilsObj = Utils()
own_dir = os.path.dirname(os.path.realpath(__file__))
root = os.path.abspath(os.path.join(own_dir, os.pardir))
files = getFiles("{}/cli/".format(root))
commands = getCommands(files)
if len(sys.argv) > 1:
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
roger_help(root, commands)
elif sys.argv[1] == "-v" or sys.argv[1] == "--version":
version = utilsObj.roger_version(root)
print(version)
else:
command = sys.argv[1]
command_args = sys.argv[2:]
if command in commands:
print("root: {} command: {} args: {}".format(
root, command, command_args
))
script_call = getScriptCall(root, command, command_args)
os.system(script_call)
else:
raise SystemExit("Command is not valid. Exiting.")
else:
raise SystemExit("No arguments found. Please refer to usage: roger -h")
if __name__ == "__main__":
main()
|
commands = set()
for filename in files:
if filename.startswith("roger_"):
commands.add(re.split("roger_|\.", filename)[1])
return sorted(commands)
|
identifier_body
|
roger.py
|
#!/usr/bin/python
from __future__ import print_function
import os
import sys
import subprocess
import re
import importlib
from cli.utils import Utils
def print_help_opt(opt, desc):
print(" {} {}".format(opt.ljust(13), desc))
def roger_help(root, commands):
print("usage: roger [-h] [-v] command [arg...]\n")
print("a command line interface to work with roger mesos.")
print("\npositional arguments:")
print_help_opt("command", "command to run.")
print_help_opt("arg", "arguments to pass to the command.")
print("\noptional arguments:")
print_help_opt("-h, --help", "show this help message and exit.")
print_help_opt("-v, --version", "show version information and exit.")
print("\ncommands:")
sys.path.append("{}/cli".format(root))
for command in commands:
description = ""
module_name = "roger_" + command
cmd_module = importlib.import_module(module_name)
try:
description = cmd_module.describe()
except Exception as e:
pass
print_help_opt(command, description)
print("\nrun: 'roger < command > -h' for more information on a command.")
def getFiles(directory):
filenames = next(os.walk(directory))[2]
return filenames
def
|
(files):
commands = set()
for filename in files:
if filename.startswith("roger_"):
commands.add(re.split("roger_|\.", filename)[1])
return sorted(commands)
def getScriptCall(root, command, command_args):
script_call = "roger_{}.py".format(command)
for command_arg in command_args:
script_call = script_call + " {}".format(command_arg)
return script_call
def main():
root = ''
utilsObj = Utils()
own_dir = os.path.dirname(os.path.realpath(__file__))
root = os.path.abspath(os.path.join(own_dir, os.pardir))
files = getFiles("{}/cli/".format(root))
commands = getCommands(files)
if len(sys.argv) > 1:
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
roger_help(root, commands)
elif sys.argv[1] == "-v" or sys.argv[1] == "--version":
version = utilsObj.roger_version(root)
print(version)
else:
command = sys.argv[1]
command_args = sys.argv[2:]
if command in commands:
print("root: {} command: {} args: {}".format(
root, command, command_args
))
script_call = getScriptCall(root, command, command_args)
os.system(script_call)
else:
raise SystemExit("Command is not valid. Exiting.")
else:
raise SystemExit("No arguments found. Please refer to usage: roger -h")
if __name__ == "__main__":
main()
|
getCommands
|
identifier_name
|
roger.py
|
#!/usr/bin/python
from __future__ import print_function
import os
import sys
import subprocess
import re
import importlib
from cli.utils import Utils
def print_help_opt(opt, desc):
print(" {} {}".format(opt.ljust(13), desc))
def roger_help(root, commands):
print("usage: roger [-h] [-v] command [arg...]\n")
print("a command line interface to work with roger mesos.")
print("\npositional arguments:")
print_help_opt("command", "command to run.")
print_help_opt("arg", "arguments to pass to the command.")
print("\noptional arguments:")
print_help_opt("-h, --help", "show this help message and exit.")
print_help_opt("-v, --version", "show version information and exit.")
print("\ncommands:")
sys.path.append("{}/cli".format(root))
for command in commands:
description = ""
module_name = "roger_" + command
cmd_module = importlib.import_module(module_name)
try:
description = cmd_module.describe()
except Exception as e:
pass
print_help_opt(command, description)
print("\nrun: 'roger < command > -h' for more information on a command.")
def getFiles(directory):
filenames = next(os.walk(directory))[2]
return filenames
def getCommands(files):
commands = set()
for filename in files:
if filename.startswith("roger_"):
commands.add(re.split("roger_|\.", filename)[1])
return sorted(commands)
def getScriptCall(root, command, command_args):
script_call = "roger_{}.py".format(command)
for command_arg in command_args:
script_call = script_call + " {}".format(command_arg)
return script_call
def main():
root = ''
utilsObj = Utils()
own_dir = os.path.dirname(os.path.realpath(__file__))
root = os.path.abspath(os.path.join(own_dir, os.pardir))
files = getFiles("{}/cli/".format(root))
commands = getCommands(files)
if len(sys.argv) > 1:
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
roger_help(root, commands)
elif sys.argv[1] == "-v" or sys.argv[1] == "--version":
version = utilsObj.roger_version(root)
print(version)
else:
command = sys.argv[1]
command_args = sys.argv[2:]
if command in commands:
print("root: {} command: {} args: {}".format(
root, command, command_args
))
script_call = getScriptCall(root, command, command_args)
os.system(script_call)
else:
raise SystemExit("Command is not valid. Exiting.")
else:
raise SystemExit("No arguments found. Please refer to usage: roger -h")
if __name__ == "__main__":
|
main()
|
conditional_block
|
|
roger.py
|
#!/usr/bin/python
from __future__ import print_function
import os
import sys
import subprocess
import re
import importlib
from cli.utils import Utils
def print_help_opt(opt, desc):
print(" {} {}".format(opt.ljust(13), desc))
def roger_help(root, commands):
print("usage: roger [-h] [-v] command [arg...]\n")
print("a command line interface to work with roger mesos.")
print("\npositional arguments:")
print_help_opt("command", "command to run.")
print_help_opt("arg", "arguments to pass to the command.")
print("\noptional arguments:")
print_help_opt("-h, --help", "show this help message and exit.")
print_help_opt("-v, --version", "show version information and exit.")
print("\ncommands:")
sys.path.append("{}/cli".format(root))
for command in commands:
description = ""
module_name = "roger_" + command
cmd_module = importlib.import_module(module_name)
try:
description = cmd_module.describe()
except Exception as e:
pass
print_help_opt(command, description)
print("\nrun: 'roger < command > -h' for more information on a command.")
def getFiles(directory):
filenames = next(os.walk(directory))[2]
return filenames
def getCommands(files):
commands = set()
for filename in files:
if filename.startswith("roger_"):
commands.add(re.split("roger_|\.", filename)[1])
return sorted(commands)
def getScriptCall(root, command, command_args):
script_call = "roger_{}.py".format(command)
for command_arg in command_args:
script_call = script_call + " {}".format(command_arg)
return script_call
def main():
root = ''
utilsObj = Utils()
own_dir = os.path.dirname(os.path.realpath(__file__))
root = os.path.abspath(os.path.join(own_dir, os.pardir))
files = getFiles("{}/cli/".format(root))
commands = getCommands(files)
if len(sys.argv) > 1:
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
roger_help(root, commands)
elif sys.argv[1] == "-v" or sys.argv[1] == "--version":
version = utilsObj.roger_version(root)
print(version)
else:
command = sys.argv[1]
|
if command in commands:
print("root: {} command: {} args: {}".format(
root, command, command_args
))
script_call = getScriptCall(root, command, command_args)
os.system(script_call)
else:
raise SystemExit("Command is not valid. Exiting.")
else:
raise SystemExit("No arguments found. Please refer to usage: roger -h")
if __name__ == "__main__":
main()
|
command_args = sys.argv[2:]
|
random_line_split
|
maptune.GoogleV2.js
|
/**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter Richter $
Copyright (c) Guenter Richter
$Log:map_GoogleV2.js,v $
**********************************************************************/
/**
* @fileoverview This is the interface to the Google maps API v2
*
* @author Guenter Richter [email protected]
* @version 0.9
*/
/* ...................................................................*
* global vars *
* ...................................................................*/
/* ...................................................................*
* Google directions *
* ...................................................................*/
function __directions_handleErrors(){
var result = $("#directions-result")[0];
if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
result.innerHTML = ("Indirizzo sconosciuto. Forse è troppo nuovo o sbagliato.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
result.innerHTML = ("Richiesta non riuscita.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
result.innerHTML = ("Inserire indirizzi! \n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_KEY)
result.innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
result.innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
else result.innerHTML = ("Errore sconosciuto!");
}
function _map_setDirections(map,fromAddress, toAddress, toHidden, locale) {
var result = $("#directions-result")[0];
result.innerHTML = "";
gdir.loadFromWaypoints([fromAddress,toHidden],
{ "locale": locale, "preserveViewport":true });
}
function _map_setDestinationWaypoint(marker){
if ( marker ){
var form = $("#directionsform")[0];
if ( form ){
form.to.value = marker.data.name;
if ( marker.getLatLng ){
form.toHidden.value = marker.getLatLng();
}
else if( marker.getVertex ){
form.toHidden.value = marker.getVertex(0);
}
}
}
}
/**
* Is called 'onload' to start creating the map
*/
function _map_loadMap(target){
var __map = null;
// if google maps API v2 is loaded
if ( GMap2 ){
// check if browser can handle Google Maps
if ( !GBrowserIsCompatible()) {
alert("sorry - your browser cannot handle Google Maps !");
return null;
}
__map = new GMap2(target);
if ( __map ){
// configure user map interface
__map.addControl(new GMapTypeControl());
// map.addControl(new GMenuMapTypeControl());
__map.addControl(new GLargeMapControl3D());
__map.addControl(new GScaleControl());
__map.addMapType(G_PHYSICAL_MAP);
__map.addMapType(G_SATELLITE_3D_MAP);
__map.enableDoubleClickZoom();
__map.enableScrollWheelZoom();
}
}
return __map;
}
/**
* Is called to set up directions query
*/
function _map_addDirections(map,target){
if (map){
gdir = new GDirections(map,target);
GEvent.addListener(gdir, "error", __directions_handleErrors);
}
}
/**
* Is called to set up traffic information layer
*/
function _map_addTrafficLayer(map,target){
|
/**
* Is called to set event handler
*/
function _map_addEventListner(map,szEvent,callback,mapUp){
if (map){
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
// set map center and zoom
//
function _map_setMapExtension(map,bBox){
if (map){
var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) };
var mapZoom = map.getBoundsZoomLevel(new GLatLngBounds( new GLatLng(bBox[2],bBox[0]),
new GLatLng(bBox[3],bBox[1]) ) );
map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lon), mapZoom);
}
}
// get map zoom
//
function _map_getZoom(map){
if (map){
return map.getZoom();
}
return 0;
}
// get map center
//
function _map_getCenter(map){
if (map){
return map.getCenter();
}
return null;
}
// set map zoom
//
function _map_setZoom(map,nZoom){
if (map){
map.setZoom(nZoom);
}
}
// set map center
//
function _map_setCenter(map,center){
if (map){
map.setCenter(center);
}
}
// set map center and zoom
//
function _map_setCenterAndZoom(map,center,nZoom){
if (map){
map.setCenter(center,nZoom);
}
}
// create custom tooltip
//
function _map_createMyTooltip(marker, text, padding){
var tooltip = new Tooltip(marker, text, padding);
marker.tooltip = tooltip;
map.addOverlay(tooltip);
}
function _map_createMyTooltipListener(element, tooltip){
GEvent.addDomListener(element,'mouseover',GEvent.callback(tooltip,
Tooltip.prototype.show));
GEvent.addDomListener(element,'mouseout',GEvent.callback(tooltip,
Tooltip.prototype.hide));
}
// -----------------------------
// EOF
// -----------------------------
|
/* tbd */
}
|
identifier_body
|
maptune.GoogleV2.js
|
/**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter Richter $
Copyright (c) Guenter Richter
$Log:map_GoogleV2.js,v $
**********************************************************************/
/**
* @fileoverview This is the interface to the Google maps API v2
*
* @author Guenter Richter [email protected]
* @version 0.9
*/
/* ...................................................................*
* global vars *
* ...................................................................*/
/* ...................................................................*
* Google directions *
* ...................................................................*/
function __directions_handleErrors(){
var result = $("#directions-result")[0];
if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
result.innerHTML = ("Indirizzo sconosciuto. Forse è troppo nuovo o sbagliato.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
result.innerHTML = ("Richiesta non riuscita.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
result.innerHTML = ("Inserire indirizzi! \n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_KEY)
result.innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
result.innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
else result.innerHTML = ("Errore sconosciuto!");
}
function _map_setDirections(map,fromAddress, toAddress, toHidden, locale) {
var result = $("#directions-result")[0];
result.innerHTML = "";
gdir.loadFromWaypoints([fromAddress,toHidden],
{ "locale": locale, "preserveViewport":true });
}
function _map_setDestinationWaypoint(marker){
if ( marker ){
var form = $("#directionsform")[0];
if ( form ){
form.to.value = marker.data.name;
if ( marker.getLatLng ){
form.toHidden.value = marker.getLatLng();
}
else if( marker.getVertex ){
form.toHidden.value = marker.getVertex(0);
}
}
}
}
/**
* Is called 'onload' to start creating the map
*/
function _map_loadMap(target){
var __map = null;
// if google maps API v2 is loaded
if ( GMap2 ){
// check if browser can handle Google Maps
if ( !GBrowserIsCompatible()) {
alert("sorry - your browser cannot handle Google Maps !");
return null;
}
__map = new GMap2(target);
if ( __map ){
// configure user map interface
__map.addControl(new GMapTypeControl());
// map.addControl(new GMenuMapTypeControl());
__map.addControl(new GLargeMapControl3D());
__map.addControl(new GScaleControl());
__map.addMapType(G_PHYSICAL_MAP);
__map.addMapType(G_SATELLITE_3D_MAP);
__map.enableDoubleClickZoom();
__map.enableScrollWheelZoom();
}
}
return __map;
}
/**
* Is called to set up directions query
*/
function _map_addDirections(map,target){
if (map){
gdir = new GDirections(map,target);
GEvent.addListener(gdir, "error", __directions_handleErrors);
}
}
/**
* Is called to set up traffic information layer
*/
function _map_addTrafficLayer(map,target){
/* tbd */
}
/**
* Is called to set event handler
*/
function _map_addEventListner(map,szEvent,callback,mapUp){
if (map){
|
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
// set map center and zoom
//
function _map_setMapExtension(map,bBox){
if (map){
var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) };
var mapZoom = map.getBoundsZoomLevel(new GLatLngBounds( new GLatLng(bBox[2],bBox[0]),
new GLatLng(bBox[3],bBox[1]) ) );
map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lon), mapZoom);
}
}
// get map zoom
//
function _map_getZoom(map){
if (map){
return map.getZoom();
}
return 0;
}
// get map center
//
function _map_getCenter(map){
if (map){
return map.getCenter();
}
return null;
}
// set map zoom
//
function _map_setZoom(map,nZoom){
if (map){
map.setZoom(nZoom);
}
}
// set map center
//
function _map_setCenter(map,center){
if (map){
map.setCenter(center);
}
}
// set map center and zoom
//
function _map_setCenterAndZoom(map,center,nZoom){
if (map){
map.setCenter(center,nZoom);
}
}
// create custom tooltip
//
function _map_createMyTooltip(marker, text, padding){
var tooltip = new Tooltip(marker, text, padding);
marker.tooltip = tooltip;
map.addOverlay(tooltip);
}
function _map_createMyTooltipListener(element, tooltip){
GEvent.addDomListener(element,'mouseover',GEvent.callback(tooltip,
Tooltip.prototype.show));
GEvent.addDomListener(element,'mouseout',GEvent.callback(tooltip,
Tooltip.prototype.hide));
}
// -----------------------------
// EOF
// -----------------------------
|
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
|
conditional_block
|
maptune.GoogleV2.js
|
/**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter Richter $
Copyright (c) Guenter Richter
$Log:map_GoogleV2.js,v $
**********************************************************************/
/**
* @fileoverview This is the interface to the Google maps API v2
*
* @author Guenter Richter [email protected]
* @version 0.9
*/
/* ...................................................................*
* global vars *
* ...................................................................*/
/* ...................................................................*
* Google directions *
* ...................................................................*/
function __directions_handleErrors(){
var result = $("#directions-result")[0];
if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
result.innerHTML = ("Indirizzo sconosciuto. Forse è troppo nuovo o sbagliato.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
result.innerHTML = ("Richiesta non riuscita.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
result.innerHTML = ("Inserire indirizzi! \n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_KEY)
result.innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
result.innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
else result.innerHTML = ("Errore sconosciuto!");
}
function _map_setDirections(map,fromAddress, toAddress, toHidden, locale) {
var result = $("#directions-result")[0];
result.innerHTML = "";
gdir.loadFromWaypoints([fromAddress,toHidden],
{ "locale": locale, "preserveViewport":true });
}
function _map_setDestinationWaypoint(marker){
if ( marker ){
var form = $("#directionsform")[0];
if ( form ){
form.to.value = marker.data.name;
if ( marker.getLatLng ){
form.toHidden.value = marker.getLatLng();
}
else if( marker.getVertex ){
form.toHidden.value = marker.getVertex(0);
}
}
}
}
/**
* Is called 'onload' to start creating the map
*/
function _map_loadMap(target){
var __map = null;
// if google maps API v2 is loaded
if ( GMap2 ){
// check if browser can handle Google Maps
if ( !GBrowserIsCompatible()) {
alert("sorry - your browser cannot handle Google Maps !");
return null;
}
__map = new GMap2(target);
if ( __map ){
// configure user map interface
__map.addControl(new GMapTypeControl());
// map.addControl(new GMenuMapTypeControl());
__map.addControl(new GLargeMapControl3D());
__map.addControl(new GScaleControl());
__map.addMapType(G_PHYSICAL_MAP);
__map.addMapType(G_SATELLITE_3D_MAP);
__map.enableDoubleClickZoom();
__map.enableScrollWheelZoom();
}
}
return __map;
}
/**
* Is called to set up directions query
*/
function _map_addDirections(map,target){
if (map){
gdir = new GDirections(map,target);
GEvent.addListener(gdir, "error", __directions_handleErrors);
}
}
/**
* Is called to set up traffic information layer
*/
function _map_addTrafficLayer(map,target){
/* tbd */
}
/**
* Is called to set event handler
*/
function _
|
map,szEvent,callback,mapUp){
if (map){
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
// set map center and zoom
//
function _map_setMapExtension(map,bBox){
if (map){
var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) };
var mapZoom = map.getBoundsZoomLevel(new GLatLngBounds( new GLatLng(bBox[2],bBox[0]),
new GLatLng(bBox[3],bBox[1]) ) );
map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lon), mapZoom);
}
}
// get map zoom
//
function _map_getZoom(map){
if (map){
return map.getZoom();
}
return 0;
}
// get map center
//
function _map_getCenter(map){
if (map){
return map.getCenter();
}
return null;
}
// set map zoom
//
function _map_setZoom(map,nZoom){
if (map){
map.setZoom(nZoom);
}
}
// set map center
//
function _map_setCenter(map,center){
if (map){
map.setCenter(center);
}
}
// set map center and zoom
//
function _map_setCenterAndZoom(map,center,nZoom){
if (map){
map.setCenter(center,nZoom);
}
}
// create custom tooltip
//
function _map_createMyTooltip(marker, text, padding){
var tooltip = new Tooltip(marker, text, padding);
marker.tooltip = tooltip;
map.addOverlay(tooltip);
}
function _map_createMyTooltipListener(element, tooltip){
GEvent.addDomListener(element,'mouseover',GEvent.callback(tooltip,
Tooltip.prototype.show));
GEvent.addDomListener(element,'mouseout',GEvent.callback(tooltip,
Tooltip.prototype.hide));
}
// -----------------------------
// EOF
// -----------------------------
|
map_addEventListner(
|
identifier_name
|
maptune.GoogleV2.js
|
/**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter Richter $
Copyright (c) Guenter Richter
$Log:map_GoogleV2.js,v $
**********************************************************************/
/**
* @fileoverview This is the interface to the Google maps API v2
*
* @author Guenter Richter [email protected]
* @version 0.9
*/
/* ...................................................................*
* global vars *
* ...................................................................*/
/* ...................................................................*
* Google directions *
* ...................................................................*/
function __directions_handleErrors(){
var result = $("#directions-result")[0];
if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
result.innerHTML = ("Indirizzo sconosciuto. Forse è troppo nuovo o sbagliato.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
result.innerHTML = ("Richiesta non riuscita.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
result.innerHTML = ("Inserire indirizzi! \n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_KEY)
result.innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
result.innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
else result.innerHTML = ("Errore sconosciuto!");
}
function _map_setDirections(map,fromAddress, toAddress, toHidden, locale) {
var result = $("#directions-result")[0];
result.innerHTML = "";
gdir.loadFromWaypoints([fromAddress,toHidden],
{ "locale": locale, "preserveViewport":true });
}
function _map_setDestinationWaypoint(marker){
if ( marker ){
var form = $("#directionsform")[0];
if ( form ){
form.to.value = marker.data.name;
if ( marker.getLatLng ){
form.toHidden.value = marker.getLatLng();
}
else if( marker.getVertex ){
form.toHidden.value = marker.getVertex(0);
}
}
}
}
/**
* Is called 'onload' to start creating the map
*/
function _map_loadMap(target){
var __map = null;
// if google maps API v2 is loaded
if ( GMap2 ){
// check if browser can handle Google Maps
if ( !GBrowserIsCompatible()) {
alert("sorry - your browser cannot handle Google Maps !");
return null;
}
__map = new GMap2(target);
if ( __map ){
// configure user map interface
__map.addControl(new GMapTypeControl());
// map.addControl(new GMenuMapTypeControl());
__map.addControl(new GLargeMapControl3D());
__map.addControl(new GScaleControl());
__map.addMapType(G_PHYSICAL_MAP);
__map.addMapType(G_SATELLITE_3D_MAP);
__map.enableDoubleClickZoom();
__map.enableScrollWheelZoom();
}
}
return __map;
}
/**
* Is called to set up directions query
*/
function _map_addDirections(map,target){
if (map){
gdir = new GDirections(map,target);
GEvent.addListener(gdir, "error", __directions_handleErrors);
}
}
/**
* Is called to set up traffic information layer
*/
function _map_addTrafficLayer(map,target){
/* tbd */
}
/**
* Is called to set event handler
*/
function _map_addEventListner(map,szEvent,callback,mapUp){
if (map){
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
// set map center and zoom
//
function _map_setMapExtension(map,bBox){
if (map){
var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) };
var mapZoom = map.getBoundsZoomLevel(new GLatLngBounds( new GLatLng(bBox[2],bBox[0]),
new GLatLng(bBox[3],bBox[1]) ) );
map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lon), mapZoom);
}
}
// get map zoom
//
function _map_getZoom(map){
if (map){
return map.getZoom();
}
return 0;
}
// get map center
//
function _map_getCenter(map){
if (map){
return map.getCenter();
|
//
function _map_setZoom(map,nZoom){
if (map){
map.setZoom(nZoom);
}
}
// set map center
//
function _map_setCenter(map,center){
if (map){
map.setCenter(center);
}
}
// set map center and zoom
//
function _map_setCenterAndZoom(map,center,nZoom){
if (map){
map.setCenter(center,nZoom);
}
}
// create custom tooltip
//
function _map_createMyTooltip(marker, text, padding){
var tooltip = new Tooltip(marker, text, padding);
marker.tooltip = tooltip;
map.addOverlay(tooltip);
}
function _map_createMyTooltipListener(element, tooltip){
GEvent.addDomListener(element,'mouseover',GEvent.callback(tooltip,
Tooltip.prototype.show));
GEvent.addDomListener(element,'mouseout',GEvent.callback(tooltip,
Tooltip.prototype.hide));
}
// -----------------------------
// EOF
// -----------------------------
|
}
return null;
}
// set map zoom
|
random_line_split
|
plot_ticpe_accises.py
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 15:48:31 2015
@author: thomas.douenne
"""
# L'objectif est de décrire l'évolution des montants des accises de la TICPE depuis 1993
|
# Recherche des paramètres de la législation
liste = ['ticpe_gazole', 'ticpe_super9598', 'super_plombe_ticpe']
df_accises = get_accise_ticpe_majoree()
# Réalisation des graphiques
graph_builder_bar_list(df_accises['accise majoree sans plomb'], 1, 1)
graph_builder_bar_list(df_accises['accise majoree diesel'], 1, 1)
graph_builder_bar_list(df_accises['accise majoree super plombe'], 1, 1)
|
# Import de fonctions spécifiques à Openfisca Indirect Taxation
from openfisca_france_indirect_taxation.examples.utils_example import graph_builder_bar_list
from openfisca_france_indirect_taxation.examples.dataframes_from_legislation.get_accises import \
get_accise_ticpe_majoree
|
random_line_split
|
canvaslayerrenderer.test.js
|
goog.provide('ol.test.renderer.canvas.Layer');
describe('ol.renderer.canvas.Layer', function() {
describe('#composeFrame()', function() {
it('clips to layer extent and draws image', function() {
var layer = new ol.layer.Image({
extent: [1, 2, 3, 4]
});
var renderer = new ol.renderer.canvas.Layer(layer);
var image = new Image();
image.width = 3;
image.height = 3;
renderer.getImage = function() {
return image;
};
var frameState = {
viewState: {
center: [2, 3],
resolution: 1,
rotation: 0
},
size: [10, 10],
pixelRatio: 1,
coordinateToPixelMatrix: goog.vec.Mat4.createNumber(),
pixelToCoordinateMatrix: goog.vec.Mat4.createNumber()
};
renderer.getImageTransform = function() {
return goog.vec.Mat4.createNumberIdentity();
|
save: sinon.spy(),
restore: sinon.spy(),
translate: sinon.spy(),
rotate: sinon.spy(),
beginPath: sinon.spy(),
moveTo: sinon.spy(),
lineTo: sinon.spy(),
clip: sinon.spy(),
drawImage: sinon.spy()
};
renderer.composeFrame(frameState, layerState, context);
expect(context.save.callCount).to.be(1);
expect(context.translate.callCount).to.be(0);
expect(context.rotate.callCount).to.be(0);
expect(context.beginPath.callCount).to.be(1);
expect(context.moveTo.firstCall.args).to.eql([4, 4]);
expect(context.lineTo.firstCall.args).to.eql([6, 4]);
expect(context.lineTo.secondCall.args).to.eql([6, 6]);
expect(context.lineTo.thirdCall.args).to.eql([4, 6]);
expect(context.clip.callCount).to.be(1);
expect(context.drawImage.firstCall.args).to.eql(
[renderer.getImage(), 0, 0, 3, 3, 0, 0, 3, 3]);
expect(context.restore.callCount).to.be(1);
});
});
});
goog.require('ol.render.canvas');
goog.require('goog.vec.Mat4');
goog.require('ol.layer.Image');
goog.require('ol.renderer.Map');
goog.require('ol.renderer.canvas.Layer');
|
};
ol.renderer.Map.prototype.calculateMatrices2D(frameState);
var layerState = layer.getLayerState();
var context = {
|
random_line_split
|
2_3_Spec.js
|
require('../../test_helper');
describe('2.3 #FindMiddle', function () {
describe('return middle Node', function () {
var sll;
beforeEach(function() {
sll = new MyLinkedList();
for(var i=1; i < 6; i++) {
sll.addNode( i + 'Node', null);
}
});
|
});
it('should return correct length of LinkedList', function () {
expect(sll).length.to.be(5);
});
it('should remove the middle node with aceess to the head of SLL', function () {
sll.findMiddleAndRemove(sll.head);
expect(sll).length.to.be(4);
});
it('should remove the middle node with access to the middle_node not head', function () {
sll.removeMiddleNode(sll.head.next.next);
expect(sll).length.to.be(4);
});
});
});
|
afterEach(function() {
sll = null;
|
random_line_split
|
2_3_Spec.js
|
require('../../test_helper');
describe('2.3 #FindMiddle', function () {
describe('return middle Node', function () {
var sll;
beforeEach(function() {
sll = new MyLinkedList();
for(var i=1; i < 6; i++)
|
});
afterEach(function() {
sll = null;
});
it('should return correct length of LinkedList', function () {
expect(sll).length.to.be(5);
});
it('should remove the middle node with aceess to the head of SLL', function () {
sll.findMiddleAndRemove(sll.head);
expect(sll).length.to.be(4);
});
it('should remove the middle node with access to the middle_node not head', function () {
sll.removeMiddleNode(sll.head.next.next);
expect(sll).length.to.be(4);
});
});
});
|
{
sll.addNode( i + 'Node', null);
}
|
conditional_block
|
setup.py
|
import os
from setuptools import setup
from setuptools import find_packages
|
shortdesc = "Klarna Payment for bda.plone.shop"
setup(
name='bda.plone.klarnapayment',
version=version,
description=shortdesc,
classifiers=[
'Environment :: Web Environment',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
author='Espen Moe-Nilssen',
author_email='[email protected]',
license='GNU General Public Licence',
packages=find_packages('src'),
package_dir = {'': 'src'},
namespace_packages=['bda', 'bda.plone'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'Plone',
'bda.plone.shop',
'klarnacheckout',
],
extras_require={
'test': [
'plone.app.testing',
]
},
entry_points="""
[z3c.autoinclude.plugin]
target = plone
""",
)
|
version = '0.1'
|
random_line_split
|
views.py
|
from django.core import serializers
from rest_framework.response import Response
from django.http import JsonResponse
try:
from urllib import quote_plus # python 2
except:
pass
try:
from urllib.parse import quote_plus # python 3
except:
pass
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from comments.forms import CommentForm
from comments.models import Comment
from .forms import PostForm
from .models import Post
|
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "post_form.html", context)
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = quote_plus(instance.content)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid() and request.user.is_authenticated():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user=request.user,
content_type=content_type,
object_id=obj_id,
content=content_data,
parent=parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
comments = instance.comments
context = {
"title": instance.title,
"instance": instance,
"share_string": share_string,
"comments": comments,
"comment_form": form,
}
return render(request, "post_detail.html", context)
def post_list(request):
today = timezone.now().date()
queryset_list = Post.objects.active() # .order_by("-timestamp")
if request.user.is_staff or request.user.is_superuser:
queryset_list = Post.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query) |
Q(content__icontains=query) |
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var,
"today": today,
}
return render(request, "post_list.html", context)
def post_update(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None,
request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "<a href='#'>Item</a> Saved",
extra_tags='html_safe')
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form": form,
}
return render(request, "post_form.html", context)
def post_delete(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Successfully deleted")
return redirect("posts:list")
|
def post_create(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
|
random_line_split
|
views.py
|
from django.core import serializers
from rest_framework.response import Response
from django.http import JsonResponse
try:
from urllib import quote_plus # python 2
except:
pass
try:
from urllib.parse import quote_plus # python 3
except:
pass
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from comments.forms import CommentForm
from comments.models import Comment
from .forms import PostForm
from .models import Post
def post_create(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
|
context = {
"form": form,
}
return render(request, "post_form.html", context)
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = quote_plus(instance.content)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid() and request.user.is_authenticated():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user=request.user,
content_type=content_type,
object_id=obj_id,
content=content_data,
parent=parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
comments = instance.comments
context = {
"title": instance.title,
"instance": instance,
"share_string": share_string,
"comments": comments,
"comment_form": form,
}
return render(request, "post_detail.html", context)
def post_list(request):
today = timezone.now().date()
queryset_list = Post.objects.active() # .order_by("-timestamp")
if request.user.is_staff or request.user.is_superuser:
queryset_list = Post.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query) |
Q(content__icontains=query) |
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var,
"today": today,
}
return render(request, "post_list.html", context)
def post_update(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None,
request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "<a href='#'>Item</a> Saved",
extra_tags='html_safe')
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form": form,
}
return render(request, "post_form.html", context)
def post_delete(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Successfully deleted")
return redirect("posts:list")
|
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
|
conditional_block
|
views.py
|
from django.core import serializers
from rest_framework.response import Response
from django.http import JsonResponse
try:
from urllib import quote_plus # python 2
except:
pass
try:
from urllib.parse import quote_plus # python 3
except:
pass
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from comments.forms import CommentForm
from comments.models import Comment
from .forms import PostForm
from .models import Post
def post_create(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "post_form.html", context)
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = quote_plus(instance.content)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid() and request.user.is_authenticated():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user=request.user,
content_type=content_type,
object_id=obj_id,
content=content_data,
parent=parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
comments = instance.comments
context = {
"title": instance.title,
"instance": instance,
"share_string": share_string,
"comments": comments,
"comment_form": form,
}
return render(request, "post_detail.html", context)
def post_list(request):
|
def post_update(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None,
request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "<a href='#'>Item</a> Saved",
extra_tags='html_safe')
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form": form,
}
return render(request, "post_form.html", context)
def post_delete(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Successfully deleted")
return redirect("posts:list")
|
today = timezone.now().date()
queryset_list = Post.objects.active() # .order_by("-timestamp")
if request.user.is_staff or request.user.is_superuser:
queryset_list = Post.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query) |
Q(content__icontains=query) |
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var,
"today": today,
}
return render(request, "post_list.html", context)
|
identifier_body
|
views.py
|
from django.core import serializers
from rest_framework.response import Response
from django.http import JsonResponse
try:
from urllib import quote_plus # python 2
except:
pass
try:
from urllib.parse import quote_plus # python 3
except:
pass
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from comments.forms import CommentForm
from comments.models import Comment
from .forms import PostForm
from .models import Post
def
|
(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "post_form.html", context)
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = quote_plus(instance.content)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid() and request.user.is_authenticated():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user=request.user,
content_type=content_type,
object_id=obj_id,
content=content_data,
parent=parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
comments = instance.comments
context = {
"title": instance.title,
"instance": instance,
"share_string": share_string,
"comments": comments,
"comment_form": form,
}
return render(request, "post_detail.html", context)
def post_list(request):
today = timezone.now().date()
queryset_list = Post.objects.active() # .order_by("-timestamp")
if request.user.is_staff or request.user.is_superuser:
queryset_list = Post.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query) |
Q(content__icontains=query) |
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var,
"today": today,
}
return render(request, "post_list.html", context)
def post_update(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None,
request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "<a href='#'>Item</a> Saved",
extra_tags='html_safe')
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form": form,
}
return render(request, "post_form.html", context)
def post_delete(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Successfully deleted")
return redirect("posts:list")
|
post_create
|
identifier_name
|
LogRowContext.tsx
|
import React, { useRef, useState, useLayoutEffect, useEffect } from 'react';
import { GrafanaTheme, DataQueryError, LogRowModel, textUtil } from '@grafana/data';
import { css, cx } from '@emotion/css';
import { Alert } from '../Alert/Alert';
import { LogRowContextRows, LogRowContextQueryErrors, HasMoreContextRows } from './LogRowContextProvider';
import { useStyles, useTheme } from '../../themes/ThemeContext';
import { CustomScrollbar } from '../CustomScrollbar/CustomScrollbar';
import { List } from '../List/List';
import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper';
import { LogMessageAnsi } from './LogMessageAnsi';
interface LogRowContextProps {
row: LogRowModel;
context: LogRowContextRows;
wrapLogMessage: boolean;
errors?: LogRowContextQueryErrors;
hasMoreContextRows?: HasMoreContextRows;
onOutsideClick: () => void;
onLoadMoreContext: () => void;
}
const getLogRowContextStyles = (theme: GrafanaTheme, wrapLogMessage?: boolean) => {
/**
* This is workaround for displaying uncropped context when we have unwrapping log messages.
* We are using margins to correctly position context. Because non-wrapped logs have always 1 line of log
* and 1 line of Show/Hide context switch. Therefore correct position can be reliably achieved by margins.
* We also adjust width to 75%.
*/
const afterContext = wrapLogMessage
? css`
top: -250px;
`
: css`
margin-top: -250px;
width: 75%;
`;
const beforeContext = wrapLogMessage
? css`
top: 100%;
`
: css`
margin-top: 40px;
width: 75%;
`;
return {
commonStyles: css`
position: absolute;
height: 250px;
z-index: ${theme.zIndex.dropdown};
overflow: hidden;
background: ${theme.colors.bg1};
box-shadow: 0 0 10px ${theme.colors.dropdownShadow};
border: 1px solid ${theme.colors.bg2};
border-radius: ${theme.border.radius.md};
width: 100%;
`,
header: css`
height: 30px;
padding: 0 10px;
display: flex;
align-items: center;
background: ${theme.colors.bg2};
`,
logs: css`
height: 220px;
padding: 10px;
`,
afterContext,
beforeContext,
};
};
interface LogRowContextGroupHeaderProps {
row: LogRowModel;
rows: Array<string | DataQueryError>;
onLoadMoreContext: () => void;
shouldScrollToBottom?: boolean;
canLoadMoreRows?: boolean;
}
interface LogRowContextGroupProps extends LogRowContextGroupHeaderProps {
rows: Array<string | DataQueryError>;
className?: string;
error?: string;
}
const LogRowContextGroupHeader: React.FunctionComponent<LogRowContextGroupHeaderProps> = ({
row,
rows,
onLoadMoreContext,
canLoadMoreRows,
}) => {
const { header } = useStyles(getLogRowContextStyles);
return (
<div className={header}>
<span
className={css`
opacity: 0.6;
`}
>
Found {rows.length} rows.
</span>
{(rows.length >= 10 || (rows.length > 10 && rows.length % 10 !== 0)) && canLoadMoreRows && (
<span
className={css`
margin-left: 10px;
&:hover {
text-decoration: underline;
cursor: pointer;
}
`}
onClick={onLoadMoreContext}
>
Load 10 more
</span>
)}
</div>
);
};
export const LogRowContextGroup: React.FunctionComponent<LogRowContextGroupProps> = ({
row,
rows,
error,
className,
shouldScrollToBottom,
canLoadMoreRows,
onLoadMoreContext,
}) => {
const { commonStyles, logs } = useStyles(getLogRowContextStyles);
const [scrollTop, setScrollTop] = useState(0);
const listContainerRef = useRef<HTMLDivElement>() as React.RefObject<HTMLDivElement>;
useLayoutEffect(() => {
if (shouldScrollToBottom && listContainerRef.current) {
setScrollTop(listContainerRef.current.offsetHeight);
}
}, [shouldScrollToBottom]);
const headerProps = {
row,
rows,
onLoadMoreContext,
canLoadMoreRows,
};
return (
<div className={cx(commonStyles, className)}>
{/* When displaying "after" context */}
{shouldScrollToBottom && !error && <LogRowContextGroupHeader {...headerProps} />}
<div className={logs}>
<CustomScrollbar autoHide scrollTop={scrollTop} autoHeightMin={'210px'}>
<div ref={listContainerRef}>
{!error && (
<List
items={rows}
renderItem={(item) => {
return (
<div
className={css`
padding: 5px 0;
`}
>
{typeof item === 'string' && textUtil.hasAnsiCodes(item) ? <LogMessageAnsi value={item} /> : item}
</div>
);
}}
/>
)}
{error && <Alert title={error} />}
</div>
</CustomScrollbar>
</div>
{/* When displaying "before" context */}
{!shouldScrollToBottom && !error && <LogRowContextGroupHeader {...headerProps} />}
</div>
);
};
export const LogRowContext: React.FunctionComponent<LogRowContextProps> = ({
row,
context,
errors,
onOutsideClick,
onLoadMoreContext,
hasMoreContextRows,
wrapLogMessage,
}) => {
useEffect(() => {
const handleEscKeyDown = (e: KeyboardEvent): void => {
if (e.keyCode === 27)
|
};
document.addEventListener('keydown', handleEscKeyDown, false);
return () => {
document.removeEventListener('keydown', handleEscKeyDown, false);
};
}, [onOutsideClick]);
const theme = useTheme();
const { afterContext, beforeContext } = getLogRowContextStyles(theme, wrapLogMessage);
return (
<ClickOutsideWrapper onClick={onOutsideClick}>
{/* e.stopPropagation is necessary so the log details doesn't open when clicked on log line in context
* and/or when context log line is being highlighted */}
<div onClick={(e) => e.stopPropagation()}>
{context.after && (
<LogRowContextGroup
rows={context.after}
error={errors && errors.after}
row={row}
className={afterContext}
shouldScrollToBottom
canLoadMoreRows={hasMoreContextRows ? hasMoreContextRows.after : false}
onLoadMoreContext={onLoadMoreContext}
/>
)}
{context.before && (
<LogRowContextGroup
onLoadMoreContext={onLoadMoreContext}
canLoadMoreRows={hasMoreContextRows ? hasMoreContextRows.before : false}
row={row}
rows={context.before}
error={errors && errors.before}
className={beforeContext}
/>
)}
</div>
</ClickOutsideWrapper>
);
};
|
{
onOutsideClick();
}
|
conditional_block
|
LogRowContext.tsx
|
import React, { useRef, useState, useLayoutEffect, useEffect } from 'react';
import { GrafanaTheme, DataQueryError, LogRowModel, textUtil } from '@grafana/data';
import { css, cx } from '@emotion/css';
import { Alert } from '../Alert/Alert';
import { LogRowContextRows, LogRowContextQueryErrors, HasMoreContextRows } from './LogRowContextProvider';
import { useStyles, useTheme } from '../../themes/ThemeContext';
import { CustomScrollbar } from '../CustomScrollbar/CustomScrollbar';
import { List } from '../List/List';
import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper';
import { LogMessageAnsi } from './LogMessageAnsi';
|
interface LogRowContextProps {
row: LogRowModel;
context: LogRowContextRows;
wrapLogMessage: boolean;
errors?: LogRowContextQueryErrors;
hasMoreContextRows?: HasMoreContextRows;
onOutsideClick: () => void;
onLoadMoreContext: () => void;
}
const getLogRowContextStyles = (theme: GrafanaTheme, wrapLogMessage?: boolean) => {
/**
* This is workaround for displaying uncropped context when we have unwrapping log messages.
* We are using margins to correctly position context. Because non-wrapped logs have always 1 line of log
* and 1 line of Show/Hide context switch. Therefore correct position can be reliably achieved by margins.
* We also adjust width to 75%.
*/
const afterContext = wrapLogMessage
? css`
top: -250px;
`
: css`
margin-top: -250px;
width: 75%;
`;
const beforeContext = wrapLogMessage
? css`
top: 100%;
`
: css`
margin-top: 40px;
width: 75%;
`;
return {
commonStyles: css`
position: absolute;
height: 250px;
z-index: ${theme.zIndex.dropdown};
overflow: hidden;
background: ${theme.colors.bg1};
box-shadow: 0 0 10px ${theme.colors.dropdownShadow};
border: 1px solid ${theme.colors.bg2};
border-radius: ${theme.border.radius.md};
width: 100%;
`,
header: css`
height: 30px;
padding: 0 10px;
display: flex;
align-items: center;
background: ${theme.colors.bg2};
`,
logs: css`
height: 220px;
padding: 10px;
`,
afterContext,
beforeContext,
};
};
interface LogRowContextGroupHeaderProps {
row: LogRowModel;
rows: Array<string | DataQueryError>;
onLoadMoreContext: () => void;
shouldScrollToBottom?: boolean;
canLoadMoreRows?: boolean;
}
interface LogRowContextGroupProps extends LogRowContextGroupHeaderProps {
rows: Array<string | DataQueryError>;
className?: string;
error?: string;
}
const LogRowContextGroupHeader: React.FunctionComponent<LogRowContextGroupHeaderProps> = ({
row,
rows,
onLoadMoreContext,
canLoadMoreRows,
}) => {
const { header } = useStyles(getLogRowContextStyles);
return (
<div className={header}>
<span
className={css`
opacity: 0.6;
`}
>
Found {rows.length} rows.
</span>
{(rows.length >= 10 || (rows.length > 10 && rows.length % 10 !== 0)) && canLoadMoreRows && (
<span
className={css`
margin-left: 10px;
&:hover {
text-decoration: underline;
cursor: pointer;
}
`}
onClick={onLoadMoreContext}
>
Load 10 more
</span>
)}
</div>
);
};
export const LogRowContextGroup: React.FunctionComponent<LogRowContextGroupProps> = ({
row,
rows,
error,
className,
shouldScrollToBottom,
canLoadMoreRows,
onLoadMoreContext,
}) => {
const { commonStyles, logs } = useStyles(getLogRowContextStyles);
const [scrollTop, setScrollTop] = useState(0);
const listContainerRef = useRef<HTMLDivElement>() as React.RefObject<HTMLDivElement>;
useLayoutEffect(() => {
if (shouldScrollToBottom && listContainerRef.current) {
setScrollTop(listContainerRef.current.offsetHeight);
}
}, [shouldScrollToBottom]);
const headerProps = {
row,
rows,
onLoadMoreContext,
canLoadMoreRows,
};
return (
<div className={cx(commonStyles, className)}>
{/* When displaying "after" context */}
{shouldScrollToBottom && !error && <LogRowContextGroupHeader {...headerProps} />}
<div className={logs}>
<CustomScrollbar autoHide scrollTop={scrollTop} autoHeightMin={'210px'}>
<div ref={listContainerRef}>
{!error && (
<List
items={rows}
renderItem={(item) => {
return (
<div
className={css`
padding: 5px 0;
`}
>
{typeof item === 'string' && textUtil.hasAnsiCodes(item) ? <LogMessageAnsi value={item} /> : item}
</div>
);
}}
/>
)}
{error && <Alert title={error} />}
</div>
</CustomScrollbar>
</div>
{/* When displaying "before" context */}
{!shouldScrollToBottom && !error && <LogRowContextGroupHeader {...headerProps} />}
</div>
);
};
export const LogRowContext: React.FunctionComponent<LogRowContextProps> = ({
row,
context,
errors,
onOutsideClick,
onLoadMoreContext,
hasMoreContextRows,
wrapLogMessage,
}) => {
useEffect(() => {
const handleEscKeyDown = (e: KeyboardEvent): void => {
if (e.keyCode === 27) {
onOutsideClick();
}
};
document.addEventListener('keydown', handleEscKeyDown, false);
return () => {
document.removeEventListener('keydown', handleEscKeyDown, false);
};
}, [onOutsideClick]);
const theme = useTheme();
const { afterContext, beforeContext } = getLogRowContextStyles(theme, wrapLogMessage);
return (
<ClickOutsideWrapper onClick={onOutsideClick}>
{/* e.stopPropagation is necessary so the log details doesn't open when clicked on log line in context
* and/or when context log line is being highlighted */}
<div onClick={(e) => e.stopPropagation()}>
{context.after && (
<LogRowContextGroup
rows={context.after}
error={errors && errors.after}
row={row}
className={afterContext}
shouldScrollToBottom
canLoadMoreRows={hasMoreContextRows ? hasMoreContextRows.after : false}
onLoadMoreContext={onLoadMoreContext}
/>
)}
{context.before && (
<LogRowContextGroup
onLoadMoreContext={onLoadMoreContext}
canLoadMoreRows={hasMoreContextRows ? hasMoreContextRows.before : false}
row={row}
rows={context.before}
error={errors && errors.before}
className={beforeContext}
/>
)}
</div>
</ClickOutsideWrapper>
);
};
|
random_line_split
|
|
debuggerEventsProtocol.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// This contains the definition of messages that VsDbg-UI can send back to a listener which registers itself via the 'debuggerEventsPipeName'
// property on a launch or attach request.
//
// All messages are sent as UTF-8 JSON text with a tailing '\n'
export namespace DebuggerEventsProtocol {
export module EventType {
// Indicates that the vsdbg-ui has received the attach or launch request and is starting up
export const Starting = "starting";
// Indicates that vsdbg-ui has successfully launched the specified process.
// The ProcessLaunchedEvent interface details the event payload.
export const ProcessLaunched = "processLaunched";
// Debug session is ending
export const DebuggingStopped = "debuggingStopped";
}
export interface DebuggerEvent {
// Contains one of the 'DebuggerEventsProtocol.EventType' values
eventType: string;
}
export interface ProcessLaunchedEvent extends DebuggerEvent {
// Process id of the newly-launched target process
targetProcessId: number;
}
// Decodes a packet received from the debugger into an event
export function decodePacket(packet: Buffer): DebuggerEvent {
// Verify the message ends in a newline
if (packet[packet.length - 1] != 10 /*\n*/) {
throw new Error("Unexpected message received from debugger.");
}
|
const message = packet.toString('utf-8', 0, packet.length - 1);
return JSON.parse(message);
}
}
|
random_line_split
|
|
debuggerEventsProtocol.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// This contains the definition of messages that VsDbg-UI can send back to a listener which registers itself via the 'debuggerEventsPipeName'
// property on a launch or attach request.
//
// All messages are sent as UTF-8 JSON text with a tailing '\n'
export namespace DebuggerEventsProtocol {
export module EventType {
// Indicates that the vsdbg-ui has received the attach or launch request and is starting up
export const Starting = "starting";
// Indicates that vsdbg-ui has successfully launched the specified process.
// The ProcessLaunchedEvent interface details the event payload.
export const ProcessLaunched = "processLaunched";
// Debug session is ending
export const DebuggingStopped = "debuggingStopped";
}
export interface DebuggerEvent {
// Contains one of the 'DebuggerEventsProtocol.EventType' values
eventType: string;
}
export interface ProcessLaunchedEvent extends DebuggerEvent {
// Process id of the newly-launched target process
targetProcessId: number;
}
// Decodes a packet received from the debugger into an event
export function decodePacket(packet: Buffer): DebuggerEvent
|
}
|
{
// Verify the message ends in a newline
if (packet[packet.length - 1] != 10 /*\n*/) {
throw new Error("Unexpected message received from debugger.");
}
const message = packet.toString('utf-8', 0, packet.length - 1);
return JSON.parse(message);
}
|
identifier_body
|
debuggerEventsProtocol.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// This contains the definition of messages that VsDbg-UI can send back to a listener which registers itself via the 'debuggerEventsPipeName'
// property on a launch or attach request.
//
// All messages are sent as UTF-8 JSON text with a tailing '\n'
export namespace DebuggerEventsProtocol {
export module EventType {
// Indicates that the vsdbg-ui has received the attach or launch request and is starting up
export const Starting = "starting";
// Indicates that vsdbg-ui has successfully launched the specified process.
// The ProcessLaunchedEvent interface details the event payload.
export const ProcessLaunched = "processLaunched";
// Debug session is ending
export const DebuggingStopped = "debuggingStopped";
}
export interface DebuggerEvent {
// Contains one of the 'DebuggerEventsProtocol.EventType' values
eventType: string;
}
export interface ProcessLaunchedEvent extends DebuggerEvent {
// Process id of the newly-launched target process
targetProcessId: number;
}
// Decodes a packet received from the debugger into an event
export function
|
(packet: Buffer): DebuggerEvent {
// Verify the message ends in a newline
if (packet[packet.length - 1] != 10 /*\n*/) {
throw new Error("Unexpected message received from debugger.");
}
const message = packet.toString('utf-8', 0, packet.length - 1);
return JSON.parse(message);
}
}
|
decodePacket
|
identifier_name
|
debuggerEventsProtocol.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// This contains the definition of messages that VsDbg-UI can send back to a listener which registers itself via the 'debuggerEventsPipeName'
// property on a launch or attach request.
//
// All messages are sent as UTF-8 JSON text with a tailing '\n'
export namespace DebuggerEventsProtocol {
export module EventType {
// Indicates that the vsdbg-ui has received the attach or launch request and is starting up
export const Starting = "starting";
// Indicates that vsdbg-ui has successfully launched the specified process.
// The ProcessLaunchedEvent interface details the event payload.
export const ProcessLaunched = "processLaunched";
// Debug session is ending
export const DebuggingStopped = "debuggingStopped";
}
export interface DebuggerEvent {
// Contains one of the 'DebuggerEventsProtocol.EventType' values
eventType: string;
}
export interface ProcessLaunchedEvent extends DebuggerEvent {
// Process id of the newly-launched target process
targetProcessId: number;
}
// Decodes a packet received from the debugger into an event
export function decodePacket(packet: Buffer): DebuggerEvent {
// Verify the message ends in a newline
if (packet[packet.length - 1] != 10 /*\n*/)
|
const message = packet.toString('utf-8', 0, packet.length - 1);
return JSON.parse(message);
}
}
|
{
throw new Error("Unexpected message received from debugger.");
}
|
conditional_block
|
ScratchPad.py
|
import sublime, sublime_plugin, tempfile, os, re;
global g_current_file;
global g_last_view;
g_current_file = None;
g_last_view = None;
# Two methods that could be used here:
# get language name
# check if .sublime-build exists for language name
# if it doesn't, somehow get the file extension
# check for .sublime-build using file extension
# wouldn't work if it's a scratch buffer
# create temp file
# change extension (just incase) of temp file to extension of running file
# quickly switch to that file and run_command("build")
# immediately after, run_command("close")
# path = sublime.packages_path().split("\\");
# path.pop();
# path.append(view.settings().get('syntax'));
# open("/".join(path).replace("tmLanguage", "sublime-build"));
# re.search("<string>(\w+)</string>", open(os.path.join("\\".join(sublime.packages_path().split("\\")[:-1]), view.settings().get('syntax'))).read()).group(1)
class
|
: # class to delegate the data to
def __init__(self, file):
self.file = file;
self.file_name = file.name;
def set_file(self, file):
self.file = file;
def unlink(self):
try:
os.unlink(self.file_name);
except OSError, e:
print("Couldn't remove file %s, %i, %s" % (self.file_name, e.errorno, e.strerror));
class ScratchpadCommand(sublime_plugin.TextCommand):
def __get_filetype(self):
syntaxpath = os.path.join( os.path.split( os.path.normcase(sublime.packages_path()) )[0], os.path.normcase(self.view.settings().get('syntax')) ); # obtain the absolute path to the syntax file
# so now we have a path where the last 3 entries are: packages / syntax folder / syntax.tmlanguage
# splitpath = syntaxpath.split(os.sep);
text = None;
with open(syntaxpath, "rt") as f:
text = f.read(); # not sure how the fileTypes array can be implemented in the file, but we will just read the entire file for now
if text != None:
filetype = re.search("<key>.*(\n?).*<array>.*(\n?).*<string>(\w+)<\/string>", text).group(3); # hacky regex to find first filetype result
return filetype;
# name = re.search("", text); # another to get the name (py.sublime-build doesn't exist, but python.sublime-build does)
# if os.path.exists(path):
# elif os.path.exists():
# syntax.sublime-build
# name/syntax.sublime-build
# name/name.sublime-build
def __get_selection(self):
selection = self.view.sel()[0]; # only the first selection, for now...
selectedText = "";
if selection.empty():
selectedText = self.view.substr(sublime.Region(0, self.view.size())); # grab entire file
else:
selectedText = self.view.substr(selection); # grab just the selected text
return selectedText;
def run(self, edit):
if self.view.sel()[0].empty() and not(self.view.is_dirty() or self.view.is_scratch()) and self.view.file_name() != None:
self.view.window().run_command("build");
return;
global g_current_file;
settings = sublime.load_settings("ScratchPad.sublime-settings");
filetype = "." + self.__get_filetype();
selectedText = self.__get_selection();
new_view = None;
with tempfile.NamedTemporaryFile(mode='w+t', delete=False, prefix="scratchpad", suffix=filetype) as f:
f.write(selectedText);
g_current_file = ScratchpadFile(f);
new_view = self.view.window().open_file(f.name);
global g_last_view;
g_last_view = self.view;
class ScratchpadEvent(sublime_plugin.EventListener):
def on_load(self, view):
global g_current_file;
if g_current_file != None and os.path.normcase(g_current_file.file_name) == os.path.normcase(view.file_name()):
window = view.window();
window.run_command("build");
window.run_command("close");
# g_current_file.unlink(); # build is an asynchronous call
global g_last_view;
if g_last_view != None and window.active_view() != g_last_view:
window.focus_view(g_last_view);
g_last_view = None;
g_current_file = None;
|
ScratchpadFile
|
identifier_name
|
ScratchPad.py
|
import sublime, sublime_plugin, tempfile, os, re;
global g_current_file;
global g_last_view;
g_current_file = None;
g_last_view = None;
# Two methods that could be used here:
# get language name
# check if .sublime-build exists for language name
# if it doesn't, somehow get the file extension
# check for .sublime-build using file extension
# wouldn't work if it's a scratch buffer
# create temp file
# change extension (just incase) of temp file to extension of running file
# quickly switch to that file and run_command("build")
# immediately after, run_command("close")
# path = sublime.packages_path().split("\\");
# path.pop();
# path.append(view.settings().get('syntax'));
# open("/".join(path).replace("tmLanguage", "sublime-build"));
# re.search("<string>(\w+)</string>", open(os.path.join("\\".join(sublime.packages_path().split("\\")[:-1]), view.settings().get('syntax'))).read()).group(1)
class ScratchpadFile: # class to delegate the data to
def __init__(self, file):
self.file = file;
self.file_name = file.name;
def set_file(self, file):
self.file = file;
def unlink(self):
try:
os.unlink(self.file_name);
except OSError, e:
|
def __get_filetype(self):
syntaxpath = os.path.join( os.path.split( os.path.normcase(sublime.packages_path()) )[0], os.path.normcase(self.view.settings().get('syntax')) ); # obtain the absolute path to the syntax file
# so now we have a path where the last 3 entries are: packages / syntax folder / syntax.tmlanguage
# splitpath = syntaxpath.split(os.sep);
text = None;
with open(syntaxpath, "rt") as f:
text = f.read(); # not sure how the fileTypes array can be implemented in the file, but we will just read the entire file for now
if text != None:
filetype = re.search("<key>.*(\n?).*<array>.*(\n?).*<string>(\w+)<\/string>", text).group(3); # hacky regex to find first filetype result
return filetype;
# name = re.search("", text); # another to get the name (py.sublime-build doesn't exist, but python.sublime-build does)
# if os.path.exists(path):
# elif os.path.exists():
# syntax.sublime-build
# name/syntax.sublime-build
# name/name.sublime-build
def __get_selection(self):
selection = self.view.sel()[0]; # only the first selection, for now...
selectedText = "";
if selection.empty():
selectedText = self.view.substr(sublime.Region(0, self.view.size())); # grab entire file
else:
selectedText = self.view.substr(selection); # grab just the selected text
return selectedText;
def run(self, edit):
if self.view.sel()[0].empty() and not(self.view.is_dirty() or self.view.is_scratch()) and self.view.file_name() != None:
self.view.window().run_command("build");
return;
global g_current_file;
settings = sublime.load_settings("ScratchPad.sublime-settings");
filetype = "." + self.__get_filetype();
selectedText = self.__get_selection();
new_view = None;
with tempfile.NamedTemporaryFile(mode='w+t', delete=False, prefix="scratchpad", suffix=filetype) as f:
f.write(selectedText);
g_current_file = ScratchpadFile(f);
new_view = self.view.window().open_file(f.name);
global g_last_view;
g_last_view = self.view;
class ScratchpadEvent(sublime_plugin.EventListener):
def on_load(self, view):
global g_current_file;
if g_current_file != None and os.path.normcase(g_current_file.file_name) == os.path.normcase(view.file_name()):
window = view.window();
window.run_command("build");
window.run_command("close");
# g_current_file.unlink(); # build is an asynchronous call
global g_last_view;
if g_last_view != None and window.active_view() != g_last_view:
window.focus_view(g_last_view);
g_last_view = None;
g_current_file = None;
|
print("Couldn't remove file %s, %i, %s" % (self.file_name, e.errorno, e.strerror));
class ScratchpadCommand(sublime_plugin.TextCommand):
|
random_line_split
|
ScratchPad.py
|
import sublime, sublime_plugin, tempfile, os, re;
global g_current_file;
global g_last_view;
g_current_file = None;
g_last_view = None;
# Two methods that could be used here:
# get language name
# check if .sublime-build exists for language name
# if it doesn't, somehow get the file extension
# check for .sublime-build using file extension
# wouldn't work if it's a scratch buffer
# create temp file
# change extension (just incase) of temp file to extension of running file
# quickly switch to that file and run_command("build")
# immediately after, run_command("close")
# path = sublime.packages_path().split("\\");
# path.pop();
# path.append(view.settings().get('syntax'));
# open("/".join(path).replace("tmLanguage", "sublime-build"));
# re.search("<string>(\w+)</string>", open(os.path.join("\\".join(sublime.packages_path().split("\\")[:-1]), view.settings().get('syntax'))).read()).group(1)
class ScratchpadFile: # class to delegate the data to
def __init__(self, file):
self.file = file;
self.file_name = file.name;
def set_file(self, file):
self.file = file;
def unlink(self):
try:
os.unlink(self.file_name);
except OSError, e:
print("Couldn't remove file %s, %i, %s" % (self.file_name, e.errorno, e.strerror));
class ScratchpadCommand(sublime_plugin.TextCommand):
def __get_filetype(self):
|
def __get_selection(self):
selection = self.view.sel()[0]; # only the first selection, for now...
selectedText = "";
if selection.empty():
selectedText = self.view.substr(sublime.Region(0, self.view.size())); # grab entire file
else:
selectedText = self.view.substr(selection); # grab just the selected text
return selectedText;
def run(self, edit):
if self.view.sel()[0].empty() and not(self.view.is_dirty() or self.view.is_scratch()) and self.view.file_name() != None:
self.view.window().run_command("build");
return;
global g_current_file;
settings = sublime.load_settings("ScratchPad.sublime-settings");
filetype = "." + self.__get_filetype();
selectedText = self.__get_selection();
new_view = None;
with tempfile.NamedTemporaryFile(mode='w+t', delete=False, prefix="scratchpad", suffix=filetype) as f:
f.write(selectedText);
g_current_file = ScratchpadFile(f);
new_view = self.view.window().open_file(f.name);
global g_last_view;
g_last_view = self.view;
class ScratchpadEvent(sublime_plugin.EventListener):
def on_load(self, view):
global g_current_file;
if g_current_file != None and os.path.normcase(g_current_file.file_name) == os.path.normcase(view.file_name()):
window = view.window();
window.run_command("build");
window.run_command("close");
# g_current_file.unlink(); # build is an asynchronous call
global g_last_view;
if g_last_view != None and window.active_view() != g_last_view:
window.focus_view(g_last_view);
g_last_view = None;
g_current_file = None;
|
syntaxpath = os.path.join( os.path.split( os.path.normcase(sublime.packages_path()) )[0], os.path.normcase(self.view.settings().get('syntax')) ); # obtain the absolute path to the syntax file
# so now we have a path where the last 3 entries are: packages / syntax folder / syntax.tmlanguage
# splitpath = syntaxpath.split(os.sep);
text = None;
with open(syntaxpath, "rt") as f:
text = f.read(); # not sure how the fileTypes array can be implemented in the file, but we will just read the entire file for now
if text != None:
filetype = re.search("<key>.*(\n?).*<array>.*(\n?).*<string>(\w+)<\/string>", text).group(3); # hacky regex to find first filetype result
return filetype;
# name = re.search("", text); # another to get the name (py.sublime-build doesn't exist, but python.sublime-build does)
# if os.path.exists(path):
# elif os.path.exists():
# syntax.sublime-build
# name/syntax.sublime-build
# name/name.sublime-build
|
identifier_body
|
ScratchPad.py
|
import sublime, sublime_plugin, tempfile, os, re;
global g_current_file;
global g_last_view;
g_current_file = None;
g_last_view = None;
# Two methods that could be used here:
# get language name
# check if .sublime-build exists for language name
# if it doesn't, somehow get the file extension
# check for .sublime-build using file extension
# wouldn't work if it's a scratch buffer
# create temp file
# change extension (just incase) of temp file to extension of running file
# quickly switch to that file and run_command("build")
# immediately after, run_command("close")
# path = sublime.packages_path().split("\\");
# path.pop();
# path.append(view.settings().get('syntax'));
# open("/".join(path).replace("tmLanguage", "sublime-build"));
# re.search("<string>(\w+)</string>", open(os.path.join("\\".join(sublime.packages_path().split("\\")[:-1]), view.settings().get('syntax'))).read()).group(1)
class ScratchpadFile: # class to delegate the data to
def __init__(self, file):
self.file = file;
self.file_name = file.name;
def set_file(self, file):
self.file = file;
def unlink(self):
try:
os.unlink(self.file_name);
except OSError, e:
print("Couldn't remove file %s, %i, %s" % (self.file_name, e.errorno, e.strerror));
class ScratchpadCommand(sublime_plugin.TextCommand):
def __get_filetype(self):
syntaxpath = os.path.join( os.path.split( os.path.normcase(sublime.packages_path()) )[0], os.path.normcase(self.view.settings().get('syntax')) ); # obtain the absolute path to the syntax file
# so now we have a path where the last 3 entries are: packages / syntax folder / syntax.tmlanguage
# splitpath = syntaxpath.split(os.sep);
text = None;
with open(syntaxpath, "rt") as f:
text = f.read(); # not sure how the fileTypes array can be implemented in the file, but we will just read the entire file for now
if text != None:
filetype = re.search("<key>.*(\n?).*<array>.*(\n?).*<string>(\w+)<\/string>", text).group(3); # hacky regex to find first filetype result
return filetype;
# name = re.search("", text); # another to get the name (py.sublime-build doesn't exist, but python.sublime-build does)
# if os.path.exists(path):
# elif os.path.exists():
# syntax.sublime-build
# name/syntax.sublime-build
# name/name.sublime-build
def __get_selection(self):
selection = self.view.sel()[0]; # only the first selection, for now...
selectedText = "";
if selection.empty():
selectedText = self.view.substr(sublime.Region(0, self.view.size())); # grab entire file
else:
selectedText = self.view.substr(selection); # grab just the selected text
return selectedText;
def run(self, edit):
if self.view.sel()[0].empty() and not(self.view.is_dirty() or self.view.is_scratch()) and self.view.file_name() != None:
self.view.window().run_command("build");
return;
global g_current_file;
settings = sublime.load_settings("ScratchPad.sublime-settings");
filetype = "." + self.__get_filetype();
selectedText = self.__get_selection();
new_view = None;
with tempfile.NamedTemporaryFile(mode='w+t', delete=False, prefix="scratchpad", suffix=filetype) as f:
f.write(selectedText);
g_current_file = ScratchpadFile(f);
new_view = self.view.window().open_file(f.name);
global g_last_view;
g_last_view = self.view;
class ScratchpadEvent(sublime_plugin.EventListener):
def on_load(self, view):
global g_current_file;
if g_current_file != None and os.path.normcase(g_current_file.file_name) == os.path.normcase(view.file_name()):
window = view.window();
window.run_command("build");
window.run_command("close");
# g_current_file.unlink(); # build is an asynchronous call
global g_last_view;
if g_last_view != None and window.active_view() != g_last_view:
|
g_last_view = None;
g_current_file = None;
|
window.focus_view(g_last_view);
|
conditional_block
|
parser.rs
|
use std::error::Error;
use std::fmt;
use unicode_width::UnicodeWidthStr;
#[derive(Clone)]
pub enum AST {
Output,
Input,
Loop(Vec<AST>),
Right,
Left,
Inc,
Dec,
}
#[derive(Debug)]
pub enum ParseErrorType {
UnclosedLoop,
ExtraCloseLoop,
}
use ParseErrorType::*;
#[derive(Debug)]
pub struct ParseError {
err: ParseErrorType,
line: Vec<u8>,
linenum: usize,
offset: usize,
}
impl ParseError {
fn new(err: ParseErrorType, code: &[u8], i: usize) -> Self {
let (line, linenum, offset) = find_line(code, i);
Self {
err,
line: line.into(),
linenum,
offset,
}
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let line = String::from_utf8_lossy(&self.line);
let width = UnicodeWidthStr::width(&line[0..self.offset]);
match self.err {
UnclosedLoop => {
writeln!(f, "reached EOF with unterminated loop")?;
writeln!(f, "Loop started at {}:{}", self.linenum, self.offset)?;
}
ExtraCloseLoop => {
writeln!(
f,
"[ found at {}:{} when not in a loop",
self.linenum, self.offset
)?;
}
};
writeln!(f, "{}", line)?;
write!(f, "{}^", " ".repeat(width))?;
Ok(())
}
}
impl Error for ParseError {}
/// Parses a string of brainfuck code to unoptimized AST
pub fn parse(code: &[u8]) -> Result<Vec<AST>, ParseError> {
let mut i = 0;
_parse(code, &mut i, 0)
}
fn _parse(code: &[u8], i: &mut usize, level: u32) -> Result<Vec<AST>, ParseError> {
// Starting [ of the loop
let start = i.saturating_sub(1);
let mut tokens = Vec::new();
while let Some(c) = code.get(*i) {
*i += 1;
|
b'<' => tokens.push(AST::Left),
b'[' => tokens.push(AST::Loop(_parse(code, i, level + 1)?)),
b']' => {
return if level == 0 {
Err(ParseError::new(ExtraCloseLoop, code, *i - 1))
} else {
Ok(tokens)
};
}
b',' => tokens.push(AST::Input),
b'.' => tokens.push(AST::Output),
_ => (),
};
}
if level != 0 {
Err(ParseError::new(UnclosedLoop, code, start))
} else {
Ok(tokens)
}
}
fn find_line(code: &[u8], i: usize) -> (&[u8], usize, usize) {
let offset = code[0..i].iter().rev().take_while(|x| **x != b'\n').count();
let end = i + code[i..].iter().take_while(|x| **x != b'\n').count();
let linenum = code[0..(i - offset)]
.iter()
.filter(|x| **x == b'\n')
.count();
(&code[(i - offset)..end], linenum, offset)
}
|
match c {
b'+' => tokens.push(AST::Inc),
b'-' => tokens.push(AST::Dec),
b'>' => tokens.push(AST::Right),
|
random_line_split
|
parser.rs
|
use std::error::Error;
use std::fmt;
use unicode_width::UnicodeWidthStr;
#[derive(Clone)]
pub enum AST {
Output,
Input,
Loop(Vec<AST>),
Right,
Left,
Inc,
Dec,
}
#[derive(Debug)]
pub enum ParseErrorType {
UnclosedLoop,
ExtraCloseLoop,
}
use ParseErrorType::*;
#[derive(Debug)]
pub struct
|
{
err: ParseErrorType,
line: Vec<u8>,
linenum: usize,
offset: usize,
}
impl ParseError {
fn new(err: ParseErrorType, code: &[u8], i: usize) -> Self {
let (line, linenum, offset) = find_line(code, i);
Self {
err,
line: line.into(),
linenum,
offset,
}
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let line = String::from_utf8_lossy(&self.line);
let width = UnicodeWidthStr::width(&line[0..self.offset]);
match self.err {
UnclosedLoop => {
writeln!(f, "reached EOF with unterminated loop")?;
writeln!(f, "Loop started at {}:{}", self.linenum, self.offset)?;
}
ExtraCloseLoop => {
writeln!(
f,
"[ found at {}:{} when not in a loop",
self.linenum, self.offset
)?;
}
};
writeln!(f, "{}", line)?;
write!(f, "{}^", " ".repeat(width))?;
Ok(())
}
}
impl Error for ParseError {}
/// Parses a string of brainfuck code to unoptimized AST
pub fn parse(code: &[u8]) -> Result<Vec<AST>, ParseError> {
let mut i = 0;
_parse(code, &mut i, 0)
}
fn _parse(code: &[u8], i: &mut usize, level: u32) -> Result<Vec<AST>, ParseError> {
// Starting [ of the loop
let start = i.saturating_sub(1);
let mut tokens = Vec::new();
while let Some(c) = code.get(*i) {
*i += 1;
match c {
b'+' => tokens.push(AST::Inc),
b'-' => tokens.push(AST::Dec),
b'>' => tokens.push(AST::Right),
b'<' => tokens.push(AST::Left),
b'[' => tokens.push(AST::Loop(_parse(code, i, level + 1)?)),
b']' => {
return if level == 0 {
Err(ParseError::new(ExtraCloseLoop, code, *i - 1))
} else {
Ok(tokens)
};
}
b',' => tokens.push(AST::Input),
b'.' => tokens.push(AST::Output),
_ => (),
};
}
if level != 0 {
Err(ParseError::new(UnclosedLoop, code, start))
} else {
Ok(tokens)
}
}
fn find_line(code: &[u8], i: usize) -> (&[u8], usize, usize) {
let offset = code[0..i].iter().rev().take_while(|x| **x != b'\n').count();
let end = i + code[i..].iter().take_while(|x| **x != b'\n').count();
let linenum = code[0..(i - offset)]
.iter()
.filter(|x| **x == b'\n')
.count();
(&code[(i - offset)..end], linenum, offset)
}
|
ParseError
|
identifier_name
|
parser.rs
|
use std::error::Error;
use std::fmt;
use unicode_width::UnicodeWidthStr;
#[derive(Clone)]
pub enum AST {
Output,
Input,
Loop(Vec<AST>),
Right,
Left,
Inc,
Dec,
}
#[derive(Debug)]
pub enum ParseErrorType {
UnclosedLoop,
ExtraCloseLoop,
}
use ParseErrorType::*;
#[derive(Debug)]
pub struct ParseError {
err: ParseErrorType,
line: Vec<u8>,
linenum: usize,
offset: usize,
}
impl ParseError {
fn new(err: ParseErrorType, code: &[u8], i: usize) -> Self {
let (line, linenum, offset) = find_line(code, i);
Self {
err,
line: line.into(),
linenum,
offset,
}
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let line = String::from_utf8_lossy(&self.line);
let width = UnicodeWidthStr::width(&line[0..self.offset]);
match self.err {
UnclosedLoop => {
writeln!(f, "reached EOF with unterminated loop")?;
writeln!(f, "Loop started at {}:{}", self.linenum, self.offset)?;
}
ExtraCloseLoop => {
writeln!(
f,
"[ found at {}:{} when not in a loop",
self.linenum, self.offset
)?;
}
};
writeln!(f, "{}", line)?;
write!(f, "{}^", " ".repeat(width))?;
Ok(())
}
}
impl Error for ParseError {}
/// Parses a string of brainfuck code to unoptimized AST
pub fn parse(code: &[u8]) -> Result<Vec<AST>, ParseError> {
let mut i = 0;
_parse(code, &mut i, 0)
}
fn _parse(code: &[u8], i: &mut usize, level: u32) -> Result<Vec<AST>, ParseError> {
// Starting [ of the loop
let start = i.saturating_sub(1);
let mut tokens = Vec::new();
while let Some(c) = code.get(*i) {
*i += 1;
match c {
b'+' => tokens.push(AST::Inc),
b'-' => tokens.push(AST::Dec),
b'>' => tokens.push(AST::Right),
b'<' => tokens.push(AST::Left),
b'[' => tokens.push(AST::Loop(_parse(code, i, level + 1)?)),
b']' => {
return if level == 0 {
Err(ParseError::new(ExtraCloseLoop, code, *i - 1))
} else {
Ok(tokens)
};
}
b',' => tokens.push(AST::Input),
b'.' => tokens.push(AST::Output),
_ => (),
};
}
if level != 0 {
Err(ParseError::new(UnclosedLoop, code, start))
} else
|
}
fn find_line(code: &[u8], i: usize) -> (&[u8], usize, usize) {
let offset = code[0..i].iter().rev().take_while(|x| **x != b'\n').count();
let end = i + code[i..].iter().take_while(|x| **x != b'\n').count();
let linenum = code[0..(i - offset)]
.iter()
.filter(|x| **x == b'\n')
.count();
(&code[(i - offset)..end], linenum, offset)
}
|
{
Ok(tokens)
}
|
conditional_block
|
parser.rs
|
use std::error::Error;
use std::fmt;
use unicode_width::UnicodeWidthStr;
#[derive(Clone)]
pub enum AST {
Output,
Input,
Loop(Vec<AST>),
Right,
Left,
Inc,
Dec,
}
#[derive(Debug)]
pub enum ParseErrorType {
UnclosedLoop,
ExtraCloseLoop,
}
use ParseErrorType::*;
#[derive(Debug)]
pub struct ParseError {
err: ParseErrorType,
line: Vec<u8>,
linenum: usize,
offset: usize,
}
impl ParseError {
fn new(err: ParseErrorType, code: &[u8], i: usize) -> Self {
let (line, linenum, offset) = find_line(code, i);
Self {
err,
line: line.into(),
linenum,
offset,
}
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let line = String::from_utf8_lossy(&self.line);
let width = UnicodeWidthStr::width(&line[0..self.offset]);
match self.err {
UnclosedLoop => {
writeln!(f, "reached EOF with unterminated loop")?;
writeln!(f, "Loop started at {}:{}", self.linenum, self.offset)?;
}
ExtraCloseLoop => {
writeln!(
f,
"[ found at {}:{} when not in a loop",
self.linenum, self.offset
)?;
}
};
writeln!(f, "{}", line)?;
write!(f, "{}^", " ".repeat(width))?;
Ok(())
}
}
impl Error for ParseError {}
/// Parses a string of brainfuck code to unoptimized AST
pub fn parse(code: &[u8]) -> Result<Vec<AST>, ParseError>
|
fn _parse(code: &[u8], i: &mut usize, level: u32) -> Result<Vec<AST>, ParseError> {
// Starting [ of the loop
let start = i.saturating_sub(1);
let mut tokens = Vec::new();
while let Some(c) = code.get(*i) {
*i += 1;
match c {
b'+' => tokens.push(AST::Inc),
b'-' => tokens.push(AST::Dec),
b'>' => tokens.push(AST::Right),
b'<' => tokens.push(AST::Left),
b'[' => tokens.push(AST::Loop(_parse(code, i, level + 1)?)),
b']' => {
return if level == 0 {
Err(ParseError::new(ExtraCloseLoop, code, *i - 1))
} else {
Ok(tokens)
};
}
b',' => tokens.push(AST::Input),
b'.' => tokens.push(AST::Output),
_ => (),
};
}
if level != 0 {
Err(ParseError::new(UnclosedLoop, code, start))
} else {
Ok(tokens)
}
}
fn find_line(code: &[u8], i: usize) -> (&[u8], usize, usize) {
let offset = code[0..i].iter().rev().take_while(|x| **x != b'\n').count();
let end = i + code[i..].iter().take_while(|x| **x != b'\n').count();
let linenum = code[0..(i - offset)]
.iter()
.filter(|x| **x == b'\n')
.count();
(&code[(i - offset)..end], linenum, offset)
}
|
{
let mut i = 0;
_parse(code, &mut i, 0)
}
|
identifier_body
|
RealdebridCom.py
|
# -*- coding: utf-8 -*-
from module.plugins.internal.MultiHook import MultiHook
class RealdebridCom(MultiHook):
__name__ = "RealdebridCom"
__type__ = "hook"
__version__ = "0.46"
__config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" , "all"),
("pluginlist" , "str" , "Plugin list (comma separated)" , "" ),
("revertfailed" , "bool" , "Revert to standard download if fails", True ),
("retry" , "int" , "Number of retries before revert" , 10 ),
("retryinterval" , "int" , "Retry interval in minutes" , 1 ),
("reload" , "bool" , "Reload plugin list" , True ),
("reloadinterval", "int" , "Reload interval in hours" , 12 ),
("ssl" , "bool" , "Use HTTPS" , True )]
__description__ = """Real-Debrid.com hook plugin"""
__license__ = "GPLv3"
__authors__ = [("Devirex Hazzard", "[email protected]")]
def getHosters(self):
|
https = "https" if self.getConfig("ssl") else "http"
html = self.getURL(https + "://real-debrid.com/api/hosters.php").replace("\"", "").strip()
return [x.strip() for x in html.split(",") if x.strip()]
|
identifier_body
|
|
RealdebridCom.py
|
# -*- coding: utf-8 -*-
from module.plugins.internal.MultiHook import MultiHook
class
|
(MultiHook):
__name__ = "RealdebridCom"
__type__ = "hook"
__version__ = "0.46"
__config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" , "all"),
("pluginlist" , "str" , "Plugin list (comma separated)" , "" ),
("revertfailed" , "bool" , "Revert to standard download if fails", True ),
("retry" , "int" , "Number of retries before revert" , 10 ),
("retryinterval" , "int" , "Retry interval in minutes" , 1 ),
("reload" , "bool" , "Reload plugin list" , True ),
("reloadinterval", "int" , "Reload interval in hours" , 12 ),
("ssl" , "bool" , "Use HTTPS" , True )]
__description__ = """Real-Debrid.com hook plugin"""
__license__ = "GPLv3"
__authors__ = [("Devirex Hazzard", "[email protected]")]
def getHosters(self):
https = "https" if self.getConfig("ssl") else "http"
html = self.getURL(https + "://real-debrid.com/api/hosters.php").replace("\"", "").strip()
return [x.strip() for x in html.split(",") if x.strip()]
|
RealdebridCom
|
identifier_name
|
RealdebridCom.py
|
# -*- coding: utf-8 -*-
from module.plugins.internal.MultiHook import MultiHook
class RealdebridCom(MultiHook):
__name__ = "RealdebridCom"
__type__ = "hook"
__version__ = "0.46"
|
("retry" , "int" , "Number of retries before revert" , 10 ),
("retryinterval" , "int" , "Retry interval in minutes" , 1 ),
("reload" , "bool" , "Reload plugin list" , True ),
("reloadinterval", "int" , "Reload interval in hours" , 12 ),
("ssl" , "bool" , "Use HTTPS" , True )]
__description__ = """Real-Debrid.com hook plugin"""
__license__ = "GPLv3"
__authors__ = [("Devirex Hazzard", "[email protected]")]
def getHosters(self):
https = "https" if self.getConfig("ssl") else "http"
html = self.getURL(https + "://real-debrid.com/api/hosters.php").replace("\"", "").strip()
return [x.strip() for x in html.split(",") if x.strip()]
|
__config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" , "all"),
("pluginlist" , "str" , "Plugin list (comma separated)" , "" ),
("revertfailed" , "bool" , "Revert to standard download if fails", True ),
|
random_line_split
|
widgets.py
|
import os.path
import itertools
import pkg_resources
from turbogears.widgets import Widget, TextField
from turbogears.widgets import CSSSource, JSSource, register_static_directory
from turbogears import config
from turbojson import jsonify
from util import CSSLink, JSLink
__all__ = ['YUIBaseCSS', 'YUIResetCSS', 'YUIFontsCSS', 'YUIGrids', 'YUIResetFontsGrids',
'YUIAnimation', 'YUIMenuBar', 'YUIAutoComplete', 'YUITreeView',
'yuibasecss', 'yuiresetcss', 'yuifontscss', 'yuigridscss', 'yui_reset_fonts_grids',
'YUIMenuLeftNav',
]
pkg_path = pkg_resources.resource_filename(__name__, os.path.join("static", "yui"))
register_static_directory("TGYUI", pkg_path)
skin = config.get('app.yui.skin', None)
skin_method = config.get('app.yui.skin_method', 'minimized')
idcounter = itertools.count()
def unique_id(prefix='tgyui'):
"""This function lets us have a new unique id each time a widget is rendered,
to be used by generated css & javascript snippets (e.g. initializing functions,
or instance-specific appearance).
If you have no widgets that are fetched by XMLHttpRequest and inserted into
the document at runtime (e.g. with innerHTML or MochiKit.DOM.swapDOM()), you
can stop reading here.
If you have such widgets, please note:
- if a page retrieves a new widget after the server has been restarted,
the idcounter variable will be reset and an old id could potentially
be recycled.
In order to avoid this, for widgets that are sent by XMLHttpRequest,
you should specify an id.
- CSSLink and JSLink directives will not be processed: you must make sure
the exising page already contains those (i.e. by returing another widget
instance from the controller, even if the page does not display it at first).
- CSSSource and JSSource will be inserted in the HTML fragment as usual,
but the browser will not run the javascript fragment. If the widget needs
to be initialized, you might want to do that in the code that retrives and
inserts the fragment.
There are ways to parse the HTML fragment, extract the <script> tags and execute them,
but it's outside the scope of this module."""
return '%s_%d' % (prefix, idcounter.next())
def skinned(pth, resource_name):
if not skin:
return [
CSSLink("TGYUI", '%s/assets/%s' % (pth, resource_name)),
]
base, ext = resource_name.rsplit('.', 1)
skin_methods = {
'minimized': [
CSSLink("TGYUI", '%s/assets/skins/%s/%s' % (pth, skin, resource_name)),
],
'core': [
CSSLink("TGYUI", '%s/assets/%s-core.%s' % (pth, base, ext)),
CSSLink("TGYUI", '%s/assets/skins/%s/%s-skin.%s' % (pth, skin, base, ext)),
],
'uber': [
CSSLink("TGYUI", '%s/assets/%s-core.%s' % (pth, base, ext)),
CSSLink("TGYUI", 'assets/skins/%s/skin.css' % skin),
],
}
if skin_method in skin_methods:
return skin_methods[skin_method]
else:
raise ValueError("app.yui.skin_method must be one of '%s'" % "', '".join(skin_methods.keys()))
class YUIBaseCSS(Widget):
css = [CSSLink("TGYUI", "base/base-min.css")]
yuibasecss = YUIBaseCSS()
class YUIResetCSS(Widget):
css = [CSSLink("TGYUI", "reset/reset-min.css")]
yuiresetcss = YUIResetCSS()
class YUIFontsCSS(Widget):
css = [CSSLink("TGYUI", "fonts/fonts-min.css")]
yuifontscss = YUIFontsCSS()
class YUIGrids(Widget):
css = [CSSLink("TGYUI", "grids/grids-min.css")]
yuigridscss = YUIGrids()
class YUIResetFontsGrids(Widget):
"""Use this in place of using all the three YUIResetCSS, YUIFontsCSS,
YUIGrids. You might want to explicitly include all three if you use other
widgets that depend on one of them, to avoid duplications."""
css = [CSSLink("TGYUI", "reset-fonts-grids/reset-fonts-grids.css")]
yui_reset_fonts_grids = YUIResetFontsGrids()
class YUIAnimation(Widget):
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "animation/animation-min.js"),
JSLink("TGYUI", "thirdparty/effects-min.js"),
]
class YUIMenuBar(Widget):
template = 'TGYUI.templates.menubar'
params = ['id', 'entries', 'as_bar']
css = ([CSSLink("TGYUI", "reset-fonts-grids/reset-fonts-grids.css"),
CSSLink("TGYUI", "menu/assets/menu.css"),
] + skinned('menu', 'menu.css'))
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "container/container_core-min.js"),
JSLink("TGYUI", "menu/menu-min.js"),
]
id = unique_id(prefix='mbar')
as_bar = True # set to False for e.g., leftNav
entries = [('Companies', '/companies', [
('add new', '/companies/add_new', []),
('browse', '/companies/browse', [
('by name', '/companies/browse/by_name'),
('by date', '/companies/browse/by_date'),
]),
('list', '/companies/list', []),
]),
('Contacts', '/contacts', []),
('Queries', '/queries', []),
('Mailings', '/mailings', []),
('Search', '/search', []),
]
def __init__(self, entries=None, *args, **kw):
super(YUIMenuBar, self).__init__(*args, **kw)
if entries:
self.entries = entries
class YUIMenuLeftNav(YUIMenuBar):
as_bar = False
class YUIAutoComplete(TextField):
"A standard, single-line text field with YUI AutoComplete enhancements."
template = 'TGYUI.templates.autocomplete'
params = ["attrs", "id", "search_controller", "result_schema", "search_param"]
params_doc = {'attrs' : 'Dictionary containing extra (X)HTML attributes for'
' the input tag',
'id' : 'ID for the entire AutoComplete construct.'}
attrs = {}
id = 'noid'
search_param = 'input'
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "json/json-min.js"),
JSLink("TGYUI", "autocomplete/autocomplete-min.js"),
]
class YUITreeView(Widget):
css = (skinned('treeview', 'treeview.css') +
(skin and [CSSSource(".ygtvitem td {padding:0}.ygtvitem table {margin-bottom: 0}")] or []))
javascript = [
JSLink('TGYUI','yahoo/yahoo-min.js'),
JSLink('TGYUI','event/event-min.js'),
JSLink('TGYUI','treeview/treeview-min.js'),
JSSource("""
function yui_tree_init(id, entries) {
function yui_add_branch(node, branch) {
var newnode = new YAHOO.widget.TextNode(branch.data, node, branch.expanded);
if (branch.children) {
for (var i=0; i<branch.children.length; i++) {
yui_add_branch(newnode, branch.children[i]);
}
}
}
|
tree.draw();
}
""")
]
template = """
<div xmlns:py="http://purl.org/kid/ns#"
py:strip="True">
<div id="${id}" />
<script type="text/javascript">
yui_tree_init('${id}', ${entries});
</script>
</div>
"""
entries = {'expanded': True,
'data': {'href': '/stuff/foo', 'label': 'Foo'},
'children': [
{'expanded': True,
'data': {'href': '/stuff/foo/bar', 'label': 'Bar'},
'children': [
{'expanded': True,
'data': {'href': '/stuff/foo/baz', 'label': 'Baz'},
'children': []
}]
},
{'expanded': True,
'data': {'href': '/stuff/foo/gazonk', 'label': 'Gazonk'},
'children': []
}]}
id = None
params = ['entries', 'id']
def update_params(self, d):
super(YUITreeView, self).update_params(d)
if d['id'] is None:
d['id'] = unique_id()
d['entries'] = jsonify.encode(d['entries'])
# Yahoo DP: http://developer.yahoo.com/ypatterns/pattern.php?pattern=moduletabs
class YUITabView(Widget):
css = (skinned('tabview', 'tabview.css') +
(skin and [CSSSource(".yui-navset .yui-nav a:hover {color: #000}")] or []) +
[CSSLink('TGYUI','tabview/assets/border_tabs.css')]
)
javascript = [
JSLink('TGYUI','yahoo-dom-event/yahoo-dom-event.js'),
JSLink('TGYUI','element/element-beta-min.js'),
JSLink('TGYUI','connection/connection-min.js'),
JSLink('TGYUI','tabview/tabview-min.js'),
]
id = 'tgyui_tabber'
dynamic = [] # list of dictionaries with label (string), dataSrc (uri), cacheData (bool)
params = ['id', 'dynamic']
template = """
<script language="JavaScript" type="text/JavaScript">
(function() {
var tabview = new YAHOO.widget.TabView("${id}");
for each (var obj in ${dynamic}) {
tabview.addTab(new YAHOO.widget.Tab(obj))
}
})();
</script>
"""
def update_params(self, d):
super(YUITabView, self).update_params(d)
d['dynamic'] = jsonify.encode(d['dynamic'])
|
tree = new YAHOO.widget.TreeView(id);
yui_add_branch(tree.getRoot(), entries);
|
random_line_split
|
widgets.py
|
import os.path
import itertools
import pkg_resources
from turbogears.widgets import Widget, TextField
from turbogears.widgets import CSSSource, JSSource, register_static_directory
from turbogears import config
from turbojson import jsonify
from util import CSSLink, JSLink
__all__ = ['YUIBaseCSS', 'YUIResetCSS', 'YUIFontsCSS', 'YUIGrids', 'YUIResetFontsGrids',
'YUIAnimation', 'YUIMenuBar', 'YUIAutoComplete', 'YUITreeView',
'yuibasecss', 'yuiresetcss', 'yuifontscss', 'yuigridscss', 'yui_reset_fonts_grids',
'YUIMenuLeftNav',
]
pkg_path = pkg_resources.resource_filename(__name__, os.path.join("static", "yui"))
register_static_directory("TGYUI", pkg_path)
skin = config.get('app.yui.skin', None)
skin_method = config.get('app.yui.skin_method', 'minimized')
idcounter = itertools.count()
def unique_id(prefix='tgyui'):
|
def skinned(pth, resource_name):
if not skin:
return [
CSSLink("TGYUI", '%s/assets/%s' % (pth, resource_name)),
]
base, ext = resource_name.rsplit('.', 1)
skin_methods = {
'minimized': [
CSSLink("TGYUI", '%s/assets/skins/%s/%s' % (pth, skin, resource_name)),
],
'core': [
CSSLink("TGYUI", '%s/assets/%s-core.%s' % (pth, base, ext)),
CSSLink("TGYUI", '%s/assets/skins/%s/%s-skin.%s' % (pth, skin, base, ext)),
],
'uber': [
CSSLink("TGYUI", '%s/assets/%s-core.%s' % (pth, base, ext)),
CSSLink("TGYUI", 'assets/skins/%s/skin.css' % skin),
],
}
if skin_method in skin_methods:
return skin_methods[skin_method]
else:
raise ValueError("app.yui.skin_method must be one of '%s'" % "', '".join(skin_methods.keys()))
class YUIBaseCSS(Widget):
css = [CSSLink("TGYUI", "base/base-min.css")]
yuibasecss = YUIBaseCSS()
class YUIResetCSS(Widget):
css = [CSSLink("TGYUI", "reset/reset-min.css")]
yuiresetcss = YUIResetCSS()
class YUIFontsCSS(Widget):
css = [CSSLink("TGYUI", "fonts/fonts-min.css")]
yuifontscss = YUIFontsCSS()
class YUIGrids(Widget):
css = [CSSLink("TGYUI", "grids/grids-min.css")]
yuigridscss = YUIGrids()
class YUIResetFontsGrids(Widget):
"""Use this in place of using all the three YUIResetCSS, YUIFontsCSS,
YUIGrids. You might want to explicitly include all three if you use other
widgets that depend on one of them, to avoid duplications."""
css = [CSSLink("TGYUI", "reset-fonts-grids/reset-fonts-grids.css")]
yui_reset_fonts_grids = YUIResetFontsGrids()
class YUIAnimation(Widget):
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "animation/animation-min.js"),
JSLink("TGYUI", "thirdparty/effects-min.js"),
]
class YUIMenuBar(Widget):
template = 'TGYUI.templates.menubar'
params = ['id', 'entries', 'as_bar']
css = ([CSSLink("TGYUI", "reset-fonts-grids/reset-fonts-grids.css"),
CSSLink("TGYUI", "menu/assets/menu.css"),
] + skinned('menu', 'menu.css'))
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "container/container_core-min.js"),
JSLink("TGYUI", "menu/menu-min.js"),
]
id = unique_id(prefix='mbar')
as_bar = True # set to False for e.g., leftNav
entries = [('Companies', '/companies', [
('add new', '/companies/add_new', []),
('browse', '/companies/browse', [
('by name', '/companies/browse/by_name'),
('by date', '/companies/browse/by_date'),
]),
('list', '/companies/list', []),
]),
('Contacts', '/contacts', []),
('Queries', '/queries', []),
('Mailings', '/mailings', []),
('Search', '/search', []),
]
def __init__(self, entries=None, *args, **kw):
super(YUIMenuBar, self).__init__(*args, **kw)
if entries:
self.entries = entries
class YUIMenuLeftNav(YUIMenuBar):
as_bar = False
class YUIAutoComplete(TextField):
"A standard, single-line text field with YUI AutoComplete enhancements."
template = 'TGYUI.templates.autocomplete'
params = ["attrs", "id", "search_controller", "result_schema", "search_param"]
params_doc = {'attrs' : 'Dictionary containing extra (X)HTML attributes for'
' the input tag',
'id' : 'ID for the entire AutoComplete construct.'}
attrs = {}
id = 'noid'
search_param = 'input'
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "json/json-min.js"),
JSLink("TGYUI", "autocomplete/autocomplete-min.js"),
]
class YUITreeView(Widget):
css = (skinned('treeview', 'treeview.css') +
(skin and [CSSSource(".ygtvitem td {padding:0}.ygtvitem table {margin-bottom: 0}")] or []))
javascript = [
JSLink('TGYUI','yahoo/yahoo-min.js'),
JSLink('TGYUI','event/event-min.js'),
JSLink('TGYUI','treeview/treeview-min.js'),
JSSource("""
function yui_tree_init(id, entries) {
function yui_add_branch(node, branch) {
var newnode = new YAHOO.widget.TextNode(branch.data, node, branch.expanded);
if (branch.children) {
for (var i=0; i<branch.children.length; i++) {
yui_add_branch(newnode, branch.children[i]);
}
}
}
tree = new YAHOO.widget.TreeView(id);
yui_add_branch(tree.getRoot(), entries);
tree.draw();
}
""")
]
template = """
<div xmlns:py="http://purl.org/kid/ns#"
py:strip="True">
<div id="${id}" />
<script type="text/javascript">
yui_tree_init('${id}', ${entries});
</script>
</div>
"""
entries = {'expanded': True,
'data': {'href': '/stuff/foo', 'label': 'Foo'},
'children': [
{'expanded': True,
'data': {'href': '/stuff/foo/bar', 'label': 'Bar'},
'children': [
{'expanded': True,
'data': {'href': '/stuff/foo/baz', 'label': 'Baz'},
'children': []
}]
},
{'expanded': True,
'data': {'href': '/stuff/foo/gazonk', 'label': 'Gazonk'},
'children': []
}]}
id = None
params = ['entries', 'id']
def update_params(self, d):
super(YUITreeView, self).update_params(d)
if d['id'] is None:
d['id'] = unique_id()
d['entries'] = jsonify.encode(d['entries'])
# Yahoo DP: http://developer.yahoo.com/ypatterns/pattern.php?pattern=moduletabs
class YUITabView(Widget):
css = (skinned('tabview', 'tabview.css') +
(skin and [CSSSource(".yui-navset .yui-nav a:hover {color: #000}")] or []) +
[CSSLink('TGYUI','tabview/assets/border_tabs.css')]
)
javascript = [
JSLink('TGYUI','yahoo-dom-event/yahoo-dom-event.js'),
JSLink('TGYUI','element/element-beta-min.js'),
JSLink('TGYUI','connection/connection-min.js'),
JSLink('TGYUI','tabview/tabview-min.js'),
]
id = 'tgyui_tabber'
dynamic = [] # list of dictionaries with label (string), dataSrc (uri), cacheData (bool)
params = ['id', 'dynamic']
template = """
<script language="JavaScript" type="text/JavaScript">
(function() {
var tabview = new YAHOO.widget.TabView("${id}");
for each (var obj in ${dynamic}) {
tabview.addTab(new YAHOO.widget.Tab(obj))
}
})();
</script>
"""
def update_params(self, d):
super(YUITabView, self).update_params(d)
d['dynamic'] = jsonify.encode(d['dynamic'])
|
"""This function lets us have a new unique id each time a widget is rendered,
to be used by generated css & javascript snippets (e.g. initializing functions,
or instance-specific appearance).
If you have no widgets that are fetched by XMLHttpRequest and inserted into
the document at runtime (e.g. with innerHTML or MochiKit.DOM.swapDOM()), you
can stop reading here.
If you have such widgets, please note:
- if a page retrieves a new widget after the server has been restarted,
the idcounter variable will be reset and an old id could potentially
be recycled.
In order to avoid this, for widgets that are sent by XMLHttpRequest,
you should specify an id.
- CSSLink and JSLink directives will not be processed: you must make sure
the exising page already contains those (i.e. by returing another widget
instance from the controller, even if the page does not display it at first).
- CSSSource and JSSource will be inserted in the HTML fragment as usual,
but the browser will not run the javascript fragment. If the widget needs
to be initialized, you might want to do that in the code that retrives and
inserts the fragment.
There are ways to parse the HTML fragment, extract the <script> tags and execute them,
but it's outside the scope of this module."""
return '%s_%d' % (prefix, idcounter.next())
|
identifier_body
|
widgets.py
|
import os.path
import itertools
import pkg_resources
from turbogears.widgets import Widget, TextField
from turbogears.widgets import CSSSource, JSSource, register_static_directory
from turbogears import config
from turbojson import jsonify
from util import CSSLink, JSLink
__all__ = ['YUIBaseCSS', 'YUIResetCSS', 'YUIFontsCSS', 'YUIGrids', 'YUIResetFontsGrids',
'YUIAnimation', 'YUIMenuBar', 'YUIAutoComplete', 'YUITreeView',
'yuibasecss', 'yuiresetcss', 'yuifontscss', 'yuigridscss', 'yui_reset_fonts_grids',
'YUIMenuLeftNav',
]
pkg_path = pkg_resources.resource_filename(__name__, os.path.join("static", "yui"))
register_static_directory("TGYUI", pkg_path)
skin = config.get('app.yui.skin', None)
skin_method = config.get('app.yui.skin_method', 'minimized')
idcounter = itertools.count()
def unique_id(prefix='tgyui'):
"""This function lets us have a new unique id each time a widget is rendered,
to be used by generated css & javascript snippets (e.g. initializing functions,
or instance-specific appearance).
If you have no widgets that are fetched by XMLHttpRequest and inserted into
the document at runtime (e.g. with innerHTML or MochiKit.DOM.swapDOM()), you
can stop reading here.
If you have such widgets, please note:
- if a page retrieves a new widget after the server has been restarted,
the idcounter variable will be reset and an old id could potentially
be recycled.
In order to avoid this, for widgets that are sent by XMLHttpRequest,
you should specify an id.
- CSSLink and JSLink directives will not be processed: you must make sure
the exising page already contains those (i.e. by returing another widget
instance from the controller, even if the page does not display it at first).
- CSSSource and JSSource will be inserted in the HTML fragment as usual,
but the browser will not run the javascript fragment. If the widget needs
to be initialized, you might want to do that in the code that retrives and
inserts the fragment.
There are ways to parse the HTML fragment, extract the <script> tags and execute them,
but it's outside the scope of this module."""
return '%s_%d' % (prefix, idcounter.next())
def skinned(pth, resource_name):
if not skin:
return [
CSSLink("TGYUI", '%s/assets/%s' % (pth, resource_name)),
]
base, ext = resource_name.rsplit('.', 1)
skin_methods = {
'minimized': [
CSSLink("TGYUI", '%s/assets/skins/%s/%s' % (pth, skin, resource_name)),
],
'core': [
CSSLink("TGYUI", '%s/assets/%s-core.%s' % (pth, base, ext)),
CSSLink("TGYUI", '%s/assets/skins/%s/%s-skin.%s' % (pth, skin, base, ext)),
],
'uber': [
CSSLink("TGYUI", '%s/assets/%s-core.%s' % (pth, base, ext)),
CSSLink("TGYUI", 'assets/skins/%s/skin.css' % skin),
],
}
if skin_method in skin_methods:
|
else:
raise ValueError("app.yui.skin_method must be one of '%s'" % "', '".join(skin_methods.keys()))
class YUIBaseCSS(Widget):
css = [CSSLink("TGYUI", "base/base-min.css")]
yuibasecss = YUIBaseCSS()
class YUIResetCSS(Widget):
css = [CSSLink("TGYUI", "reset/reset-min.css")]
yuiresetcss = YUIResetCSS()
class YUIFontsCSS(Widget):
css = [CSSLink("TGYUI", "fonts/fonts-min.css")]
yuifontscss = YUIFontsCSS()
class YUIGrids(Widget):
css = [CSSLink("TGYUI", "grids/grids-min.css")]
yuigridscss = YUIGrids()
class YUIResetFontsGrids(Widget):
"""Use this in place of using all the three YUIResetCSS, YUIFontsCSS,
YUIGrids. You might want to explicitly include all three if you use other
widgets that depend on one of them, to avoid duplications."""
css = [CSSLink("TGYUI", "reset-fonts-grids/reset-fonts-grids.css")]
yui_reset_fonts_grids = YUIResetFontsGrids()
class YUIAnimation(Widget):
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "animation/animation-min.js"),
JSLink("TGYUI", "thirdparty/effects-min.js"),
]
class YUIMenuBar(Widget):
template = 'TGYUI.templates.menubar'
params = ['id', 'entries', 'as_bar']
css = ([CSSLink("TGYUI", "reset-fonts-grids/reset-fonts-grids.css"),
CSSLink("TGYUI", "menu/assets/menu.css"),
] + skinned('menu', 'menu.css'))
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "container/container_core-min.js"),
JSLink("TGYUI", "menu/menu-min.js"),
]
id = unique_id(prefix='mbar')
as_bar = True # set to False for e.g., leftNav
entries = [('Companies', '/companies', [
('add new', '/companies/add_new', []),
('browse', '/companies/browse', [
('by name', '/companies/browse/by_name'),
('by date', '/companies/browse/by_date'),
]),
('list', '/companies/list', []),
]),
('Contacts', '/contacts', []),
('Queries', '/queries', []),
('Mailings', '/mailings', []),
('Search', '/search', []),
]
def __init__(self, entries=None, *args, **kw):
super(YUIMenuBar, self).__init__(*args, **kw)
if entries:
self.entries = entries
class YUIMenuLeftNav(YUIMenuBar):
as_bar = False
class YUIAutoComplete(TextField):
"A standard, single-line text field with YUI AutoComplete enhancements."
template = 'TGYUI.templates.autocomplete'
params = ["attrs", "id", "search_controller", "result_schema", "search_param"]
params_doc = {'attrs' : 'Dictionary containing extra (X)HTML attributes for'
' the input tag',
'id' : 'ID for the entire AutoComplete construct.'}
attrs = {}
id = 'noid'
search_param = 'input'
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "json/json-min.js"),
JSLink("TGYUI", "autocomplete/autocomplete-min.js"),
]
class YUITreeView(Widget):
css = (skinned('treeview', 'treeview.css') +
(skin and [CSSSource(".ygtvitem td {padding:0}.ygtvitem table {margin-bottom: 0}")] or []))
javascript = [
JSLink('TGYUI','yahoo/yahoo-min.js'),
JSLink('TGYUI','event/event-min.js'),
JSLink('TGYUI','treeview/treeview-min.js'),
JSSource("""
function yui_tree_init(id, entries) {
function yui_add_branch(node, branch) {
var newnode = new YAHOO.widget.TextNode(branch.data, node, branch.expanded);
if (branch.children) {
for (var i=0; i<branch.children.length; i++) {
yui_add_branch(newnode, branch.children[i]);
}
}
}
tree = new YAHOO.widget.TreeView(id);
yui_add_branch(tree.getRoot(), entries);
tree.draw();
}
""")
]
template = """
<div xmlns:py="http://purl.org/kid/ns#"
py:strip="True">
<div id="${id}" />
<script type="text/javascript">
yui_tree_init('${id}', ${entries});
</script>
</div>
"""
entries = {'expanded': True,
'data': {'href': '/stuff/foo', 'label': 'Foo'},
'children': [
{'expanded': True,
'data': {'href': '/stuff/foo/bar', 'label': 'Bar'},
'children': [
{'expanded': True,
'data': {'href': '/stuff/foo/baz', 'label': 'Baz'},
'children': []
}]
},
{'expanded': True,
'data': {'href': '/stuff/foo/gazonk', 'label': 'Gazonk'},
'children': []
}]}
id = None
params = ['entries', 'id']
def update_params(self, d):
super(YUITreeView, self).update_params(d)
if d['id'] is None:
d['id'] = unique_id()
d['entries'] = jsonify.encode(d['entries'])
# Yahoo DP: http://developer.yahoo.com/ypatterns/pattern.php?pattern=moduletabs
class YUITabView(Widget):
css = (skinned('tabview', 'tabview.css') +
(skin and [CSSSource(".yui-navset .yui-nav a:hover {color: #000}")] or []) +
[CSSLink('TGYUI','tabview/assets/border_tabs.css')]
)
javascript = [
JSLink('TGYUI','yahoo-dom-event/yahoo-dom-event.js'),
JSLink('TGYUI','element/element-beta-min.js'),
JSLink('TGYUI','connection/connection-min.js'),
JSLink('TGYUI','tabview/tabview-min.js'),
]
id = 'tgyui_tabber'
dynamic = [] # list of dictionaries with label (string), dataSrc (uri), cacheData (bool)
params = ['id', 'dynamic']
template = """
<script language="JavaScript" type="text/JavaScript">
(function() {
var tabview = new YAHOO.widget.TabView("${id}");
for each (var obj in ${dynamic}) {
tabview.addTab(new YAHOO.widget.Tab(obj))
}
})();
</script>
"""
def update_params(self, d):
super(YUITabView, self).update_params(d)
d['dynamic'] = jsonify.encode(d['dynamic'])
|
return skin_methods[skin_method]
|
conditional_block
|
widgets.py
|
import os.path
import itertools
import pkg_resources
from turbogears.widgets import Widget, TextField
from turbogears.widgets import CSSSource, JSSource, register_static_directory
from turbogears import config
from turbojson import jsonify
from util import CSSLink, JSLink
__all__ = ['YUIBaseCSS', 'YUIResetCSS', 'YUIFontsCSS', 'YUIGrids', 'YUIResetFontsGrids',
'YUIAnimation', 'YUIMenuBar', 'YUIAutoComplete', 'YUITreeView',
'yuibasecss', 'yuiresetcss', 'yuifontscss', 'yuigridscss', 'yui_reset_fonts_grids',
'YUIMenuLeftNav',
]
pkg_path = pkg_resources.resource_filename(__name__, os.path.join("static", "yui"))
register_static_directory("TGYUI", pkg_path)
skin = config.get('app.yui.skin', None)
skin_method = config.get('app.yui.skin_method', 'minimized')
idcounter = itertools.count()
def unique_id(prefix='tgyui'):
"""This function lets us have a new unique id each time a widget is rendered,
to be used by generated css & javascript snippets (e.g. initializing functions,
or instance-specific appearance).
If you have no widgets that are fetched by XMLHttpRequest and inserted into
the document at runtime (e.g. with innerHTML or MochiKit.DOM.swapDOM()), you
can stop reading here.
If you have such widgets, please note:
- if a page retrieves a new widget after the server has been restarted,
the idcounter variable will be reset and an old id could potentially
be recycled.
In order to avoid this, for widgets that are sent by XMLHttpRequest,
you should specify an id.
- CSSLink and JSLink directives will not be processed: you must make sure
the exising page already contains those (i.e. by returing another widget
instance from the controller, even if the page does not display it at first).
- CSSSource and JSSource will be inserted in the HTML fragment as usual,
but the browser will not run the javascript fragment. If the widget needs
to be initialized, you might want to do that in the code that retrives and
inserts the fragment.
There are ways to parse the HTML fragment, extract the <script> tags and execute them,
but it's outside the scope of this module."""
return '%s_%d' % (prefix, idcounter.next())
def skinned(pth, resource_name):
if not skin:
return [
CSSLink("TGYUI", '%s/assets/%s' % (pth, resource_name)),
]
base, ext = resource_name.rsplit('.', 1)
skin_methods = {
'minimized': [
CSSLink("TGYUI", '%s/assets/skins/%s/%s' % (pth, skin, resource_name)),
],
'core': [
CSSLink("TGYUI", '%s/assets/%s-core.%s' % (pth, base, ext)),
CSSLink("TGYUI", '%s/assets/skins/%s/%s-skin.%s' % (pth, skin, base, ext)),
],
'uber': [
CSSLink("TGYUI", '%s/assets/%s-core.%s' % (pth, base, ext)),
CSSLink("TGYUI", 'assets/skins/%s/skin.css' % skin),
],
}
if skin_method in skin_methods:
return skin_methods[skin_method]
else:
raise ValueError("app.yui.skin_method must be one of '%s'" % "', '".join(skin_methods.keys()))
class YUIBaseCSS(Widget):
css = [CSSLink("TGYUI", "base/base-min.css")]
yuibasecss = YUIBaseCSS()
class YUIResetCSS(Widget):
css = [CSSLink("TGYUI", "reset/reset-min.css")]
yuiresetcss = YUIResetCSS()
class YUIFontsCSS(Widget):
css = [CSSLink("TGYUI", "fonts/fonts-min.css")]
yuifontscss = YUIFontsCSS()
class YUIGrids(Widget):
css = [CSSLink("TGYUI", "grids/grids-min.css")]
yuigridscss = YUIGrids()
class YUIResetFontsGrids(Widget):
"""Use this in place of using all the three YUIResetCSS, YUIFontsCSS,
YUIGrids. You might want to explicitly include all three if you use other
widgets that depend on one of them, to avoid duplications."""
css = [CSSLink("TGYUI", "reset-fonts-grids/reset-fonts-grids.css")]
yui_reset_fonts_grids = YUIResetFontsGrids()
class YUIAnimation(Widget):
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "animation/animation-min.js"),
JSLink("TGYUI", "thirdparty/effects-min.js"),
]
class YUIMenuBar(Widget):
template = 'TGYUI.templates.menubar'
params = ['id', 'entries', 'as_bar']
css = ([CSSLink("TGYUI", "reset-fonts-grids/reset-fonts-grids.css"),
CSSLink("TGYUI", "menu/assets/menu.css"),
] + skinned('menu', 'menu.css'))
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "container/container_core-min.js"),
JSLink("TGYUI", "menu/menu-min.js"),
]
id = unique_id(prefix='mbar')
as_bar = True # set to False for e.g., leftNav
entries = [('Companies', '/companies', [
('add new', '/companies/add_new', []),
('browse', '/companies/browse', [
('by name', '/companies/browse/by_name'),
('by date', '/companies/browse/by_date'),
]),
('list', '/companies/list', []),
]),
('Contacts', '/contacts', []),
('Queries', '/queries', []),
('Mailings', '/mailings', []),
('Search', '/search', []),
]
def
|
(self, entries=None, *args, **kw):
super(YUIMenuBar, self).__init__(*args, **kw)
if entries:
self.entries = entries
class YUIMenuLeftNav(YUIMenuBar):
as_bar = False
class YUIAutoComplete(TextField):
"A standard, single-line text field with YUI AutoComplete enhancements."
template = 'TGYUI.templates.autocomplete'
params = ["attrs", "id", "search_controller", "result_schema", "search_param"]
params_doc = {'attrs' : 'Dictionary containing extra (X)HTML attributes for'
' the input tag',
'id' : 'ID for the entire AutoComplete construct.'}
attrs = {}
id = 'noid'
search_param = 'input'
javascript = [JSLink("TGYUI", "yahoo-dom-event/yahoo-dom-event.js"),
JSLink("TGYUI", "json/json-min.js"),
JSLink("TGYUI", "autocomplete/autocomplete-min.js"),
]
class YUITreeView(Widget):
css = (skinned('treeview', 'treeview.css') +
(skin and [CSSSource(".ygtvitem td {padding:0}.ygtvitem table {margin-bottom: 0}")] or []))
javascript = [
JSLink('TGYUI','yahoo/yahoo-min.js'),
JSLink('TGYUI','event/event-min.js'),
JSLink('TGYUI','treeview/treeview-min.js'),
JSSource("""
function yui_tree_init(id, entries) {
function yui_add_branch(node, branch) {
var newnode = new YAHOO.widget.TextNode(branch.data, node, branch.expanded);
if (branch.children) {
for (var i=0; i<branch.children.length; i++) {
yui_add_branch(newnode, branch.children[i]);
}
}
}
tree = new YAHOO.widget.TreeView(id);
yui_add_branch(tree.getRoot(), entries);
tree.draw();
}
""")
]
template = """
<div xmlns:py="http://purl.org/kid/ns#"
py:strip="True">
<div id="${id}" />
<script type="text/javascript">
yui_tree_init('${id}', ${entries});
</script>
</div>
"""
entries = {'expanded': True,
'data': {'href': '/stuff/foo', 'label': 'Foo'},
'children': [
{'expanded': True,
'data': {'href': '/stuff/foo/bar', 'label': 'Bar'},
'children': [
{'expanded': True,
'data': {'href': '/stuff/foo/baz', 'label': 'Baz'},
'children': []
}]
},
{'expanded': True,
'data': {'href': '/stuff/foo/gazonk', 'label': 'Gazonk'},
'children': []
}]}
id = None
params = ['entries', 'id']
def update_params(self, d):
super(YUITreeView, self).update_params(d)
if d['id'] is None:
d['id'] = unique_id()
d['entries'] = jsonify.encode(d['entries'])
# Yahoo DP: http://developer.yahoo.com/ypatterns/pattern.php?pattern=moduletabs
class YUITabView(Widget):
css = (skinned('tabview', 'tabview.css') +
(skin and [CSSSource(".yui-navset .yui-nav a:hover {color: #000}")] or []) +
[CSSLink('TGYUI','tabview/assets/border_tabs.css')]
)
javascript = [
JSLink('TGYUI','yahoo-dom-event/yahoo-dom-event.js'),
JSLink('TGYUI','element/element-beta-min.js'),
JSLink('TGYUI','connection/connection-min.js'),
JSLink('TGYUI','tabview/tabview-min.js'),
]
id = 'tgyui_tabber'
dynamic = [] # list of dictionaries with label (string), dataSrc (uri), cacheData (bool)
params = ['id', 'dynamic']
template = """
<script language="JavaScript" type="text/JavaScript">
(function() {
var tabview = new YAHOO.widget.TabView("${id}");
for each (var obj in ${dynamic}) {
tabview.addTab(new YAHOO.widget.Tab(obj))
}
})();
</script>
"""
def update_params(self, d):
super(YUITabView, self).update_params(d)
d['dynamic'] = jsonify.encode(d['dynamic'])
|
__init__
|
identifier_name
|
tocfilter.py
|
import os
import finder
import re
import sys
def makefilter(name, xtrapath=None):
typ, nm, fullname = finder.identify(name, xtrapath)
if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE):
return ModFilter([os.path.splitext(nm)[0]])
if typ == finder.PACKAGE:
return PkgFilter([fullname])
if typ == finder.DIRECTORY:
|
if typ in (finder.BINARY, finder.PBINARY):
return FileFilter([nm])
return FileFilter([fullname])
class _Filter:
def __repr__(self):
return '<'+self.__class__.__name__+' '+repr(self.elements)+'>'
class _NameFilter(_Filter):
""" A filter mixin that matches (exactly) on name """
def matches(self, res):
return self.elements.get(res.name, 0)
class _PathFilter(_Filter):
""" A filter mixin that matches if the resource is below any of the paths"""
def matches(self, res):
p = os.path.normcase(os.path.abspath(res.path))
while len(p) > 3:
p = os.path.dirname(p)
if self.elements.get(p, 0):
return 1
return 0
class _ExtFilter(_Filter):
""" A filter mixin that matches based on file extensions (either way) """
include = 0
def matches(self, res):
fnd = self.elements.get(os.path.splitext(res.path)[1], 0)
if self.include:
return not fnd
return fnd
class _TypeFilter(_Filter):
""" A filter mixin that matches on resource type (either way) """
include = 0
def matches(self, res):
fnd = self.elements.get(res.typ, 0)
if self.include:
return not fnd
return fnd
class _PatternFilter(_Filter):
""" A filter that matches if re.search succeeds on the resource path """
def matches(self, res):
for regex in self.elements:
if regex.search(res.path):
return 1
return 0
class ExtFilter(_ExtFilter):
""" A file extension filter.
ExtFilter(extlist, include=0)
where extlist is a list of file extensions """
def __init__(self, extlist, include=0):
self.elements = {}
for ext in extlist:
if ext[0:1] != '.':
ext = '.'+ext
self.elements[ext] = 1
self.include = include
class TypeFilter(_TypeFilter):
""" A filter for resource types.
TypeFilter(typlist, include=0)
where typlist is a subset of ['a','b','d','m','p','s','x','z'] """
def __init__(self, typlist, include=0):
self.elements = {}
for typ in typlist:
self.elements[typ] = 1
self.include = include
class FileFilter(_NameFilter):
""" A filter for data files """
def __init__(self, filelist):
self.elements = {}
for f in filelist:
self.elements[f] = 1
class ModFilter(_NameFilter):
""" A filter for Python modules.
ModFilter(modlist) where modlist is eg ['macpath', 'dospath'] """
def __init__(self, modlist):
self.elements = {}
for mod in modlist:
self.elements[mod] = 1
class DirFilter(_PathFilter):
""" A filter based on directories.
DirFilter(dirlist)
dirs may be relative and will be normalized.
Subdirectories of dirs will be excluded. """
def __init__(self, dirlist):
self.elements = {}
for pth in dirlist:
pth = os.path.normcase(os.path.abspath(pth))
self.elements[pth] = 1
class PkgFilter(_PathFilter):
"""At this time, identical to a DirFilter (being lazy) """
def __init__(self, pkglist):
#warning - pkgs are expected to be full directories
self.elements = {}
for pkg in pkglist:
pth = os.path.normcase(os.path.abspath(pkg))
self.elements[pth] = 1
class StdLibFilter(_PathFilter):
""" A filter that excludes anything found in the standard library """
def __init__(self):
pth = os.path.normcase(os.path.join(sys.exec_prefix, 'lib'))
self.elements = {pth:1}
class PatternFilter(_PatternFilter):
""" A filter that excludes if any pattern is found in resource's path """
def __init__(self, patterns):
self.elements = []
for pat in patterns:
self.elements.append(re.compile(pat))
|
return DirFilter([fullname])
|
conditional_block
|
tocfilter.py
|
import os
import finder
import re
import sys
def makefilter(name, xtrapath=None):
typ, nm, fullname = finder.identify(name, xtrapath)
if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE):
return ModFilter([os.path.splitext(nm)[0]])
if typ == finder.PACKAGE:
return PkgFilter([fullname])
if typ == finder.DIRECTORY:
return DirFilter([fullname])
if typ in (finder.BINARY, finder.PBINARY):
return FileFilter([nm])
return FileFilter([fullname])
class _Filter:
def __repr__(self):
return '<'+self.__class__.__name__+' '+repr(self.elements)+'>'
class _NameFilter(_Filter):
""" A filter mixin that matches (exactly) on name """
def matches(self, res):
return self.elements.get(res.name, 0)
class _PathFilter(_Filter):
""" A filter mixin that matches if the resource is below any of the paths"""
def matches(self, res):
p = os.path.normcase(os.path.abspath(res.path))
while len(p) > 3:
p = os.path.dirname(p)
if self.elements.get(p, 0):
return 1
return 0
class _ExtFilter(_Filter):
""" A filter mixin that matches based on file extensions (either way) """
include = 0
def matches(self, res):
fnd = self.elements.get(os.path.splitext(res.path)[1], 0)
if self.include:
return not fnd
return fnd
class _TypeFilter(_Filter):
""" A filter mixin that matches on resource type (either way) """
include = 0
def matches(self, res):
fnd = self.elements.get(res.typ, 0)
if self.include:
return not fnd
return fnd
class _PatternFilter(_Filter):
""" A filter that matches if re.search succeeds on the resource path """
def matches(self, res):
for regex in self.elements:
if regex.search(res.path):
return 1
return 0
class ExtFilter(_ExtFilter):
""" A file extension filter.
ExtFilter(extlist, include=0)
where extlist is a list of file extensions """
def __init__(self, extlist, include=0):
self.elements = {}
for ext in extlist:
if ext[0:1] != '.':
ext = '.'+ext
self.elements[ext] = 1
self.include = include
class TypeFilter(_TypeFilter):
""" A filter for resource types.
TypeFilter(typlist, include=0)
where typlist is a subset of ['a','b','d','m','p','s','x','z'] """
def __init__(self, typlist, include=0):
self.elements = {}
for typ in typlist:
self.elements[typ] = 1
self.include = include
class FileFilter(_NameFilter):
|
class ModFilter(_NameFilter):
""" A filter for Python modules.
ModFilter(modlist) where modlist is eg ['macpath', 'dospath'] """
def __init__(self, modlist):
self.elements = {}
for mod in modlist:
self.elements[mod] = 1
class DirFilter(_PathFilter):
""" A filter based on directories.
DirFilter(dirlist)
dirs may be relative and will be normalized.
Subdirectories of dirs will be excluded. """
def __init__(self, dirlist):
self.elements = {}
for pth in dirlist:
pth = os.path.normcase(os.path.abspath(pth))
self.elements[pth] = 1
class PkgFilter(_PathFilter):
"""At this time, identical to a DirFilter (being lazy) """
def __init__(self, pkglist):
#warning - pkgs are expected to be full directories
self.elements = {}
for pkg in pkglist:
pth = os.path.normcase(os.path.abspath(pkg))
self.elements[pth] = 1
class StdLibFilter(_PathFilter):
""" A filter that excludes anything found in the standard library """
def __init__(self):
pth = os.path.normcase(os.path.join(sys.exec_prefix, 'lib'))
self.elements = {pth:1}
class PatternFilter(_PatternFilter):
""" A filter that excludes if any pattern is found in resource's path """
def __init__(self, patterns):
self.elements = []
for pat in patterns:
self.elements.append(re.compile(pat))
|
""" A filter for data files """
def __init__(self, filelist):
self.elements = {}
for f in filelist:
self.elements[f] = 1
|
identifier_body
|
tocfilter.py
|
import os
import finder
import re
import sys
def makefilter(name, xtrapath=None):
typ, nm, fullname = finder.identify(name, xtrapath)
if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE):
return ModFilter([os.path.splitext(nm)[0]])
if typ == finder.PACKAGE:
return PkgFilter([fullname])
if typ == finder.DIRECTORY:
return DirFilter([fullname])
if typ in (finder.BINARY, finder.PBINARY):
return FileFilter([nm])
return FileFilter([fullname])
class _Filter:
def __repr__(self):
return '<'+self.__class__.__name__+' '+repr(self.elements)+'>'
class _NameFilter(_Filter):
""" A filter mixin that matches (exactly) on name """
def matches(self, res):
return self.elements.get(res.name, 0)
class _PathFilter(_Filter):
""" A filter mixin that matches if the resource is below any of the paths"""
def matches(self, res):
p = os.path.normcase(os.path.abspath(res.path))
while len(p) > 3:
p = os.path.dirname(p)
if self.elements.get(p, 0):
return 1
return 0
class _ExtFilter(_Filter):
""" A filter mixin that matches based on file extensions (either way) """
include = 0
def matches(self, res):
fnd = self.elements.get(os.path.splitext(res.path)[1], 0)
if self.include:
return not fnd
return fnd
class _TypeFilter(_Filter):
""" A filter mixin that matches on resource type (either way) """
include = 0
def matches(self, res):
fnd = self.elements.get(res.typ, 0)
if self.include:
return not fnd
return fnd
class _PatternFilter(_Filter):
""" A filter that matches if re.search succeeds on the resource path """
def matches(self, res):
for regex in self.elements:
if regex.search(res.path):
return 1
return 0
class ExtFilter(_ExtFilter):
""" A file extension filter.
ExtFilter(extlist, include=0)
where extlist is a list of file extensions """
def __init__(self, extlist, include=0):
self.elements = {}
for ext in extlist:
if ext[0:1] != '.':
ext = '.'+ext
self.elements[ext] = 1
self.include = include
class TypeFilter(_TypeFilter):
""" A filter for resource types.
TypeFilter(typlist, include=0)
where typlist is a subset of ['a','b','d','m','p','s','x','z'] """
def __init__(self, typlist, include=0):
self.elements = {}
for typ in typlist:
self.elements[typ] = 1
self.include = include
class FileFilter(_NameFilter):
""" A filter for data files """
def __init__(self, filelist):
self.elements = {}
for f in filelist:
self.elements[f] = 1
class ModFilter(_NameFilter):
""" A filter for Python modules.
ModFilter(modlist) where modlist is eg ['macpath', 'dospath'] """
def __init__(self, modlist):
self.elements = {}
for mod in modlist:
self.elements[mod] = 1
class DirFilter(_PathFilter):
""" A filter based on directories.
DirFilter(dirlist)
dirs may be relative and will be normalized.
Subdirectories of dirs will be excluded. """
def __init__(self, dirlist):
self.elements = {}
for pth in dirlist:
pth = os.path.normcase(os.path.abspath(pth))
self.elements[pth] = 1
class PkgFilter(_PathFilter):
"""At this time, identical to a DirFilter (being lazy) """
def __init__(self, pkglist):
#warning - pkgs are expected to be full directories
self.elements = {}
for pkg in pkglist:
pth = os.path.normcase(os.path.abspath(pkg))
self.elements[pth] = 1
class StdLibFilter(_PathFilter):
""" A filter that excludes anything found in the standard library """
def __init__(self):
pth = os.path.normcase(os.path.join(sys.exec_prefix, 'lib'))
self.elements = {pth:1}
class PatternFilter(_PatternFilter):
""" A filter that excludes if any pattern is found in resource's path """
def __init__(self, patterns):
self.elements = []
for pat in patterns:
|
self.elements.append(re.compile(pat))
|
random_line_split
|
|
tocfilter.py
|
import os
import finder
import re
import sys
def makefilter(name, xtrapath=None):
typ, nm, fullname = finder.identify(name, xtrapath)
if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE):
return ModFilter([os.path.splitext(nm)[0]])
if typ == finder.PACKAGE:
return PkgFilter([fullname])
if typ == finder.DIRECTORY:
return DirFilter([fullname])
if typ in (finder.BINARY, finder.PBINARY):
return FileFilter([nm])
return FileFilter([fullname])
class _Filter:
def __repr__(self):
return '<'+self.__class__.__name__+' '+repr(self.elements)+'>'
class _NameFilter(_Filter):
""" A filter mixin that matches (exactly) on name """
def matches(self, res):
return self.elements.get(res.name, 0)
class _PathFilter(_Filter):
""" A filter mixin that matches if the resource is below any of the paths"""
def matches(self, res):
p = os.path.normcase(os.path.abspath(res.path))
while len(p) > 3:
p = os.path.dirname(p)
if self.elements.get(p, 0):
return 1
return 0
class _ExtFilter(_Filter):
""" A filter mixin that matches based on file extensions (either way) """
include = 0
def matches(self, res):
fnd = self.elements.get(os.path.splitext(res.path)[1], 0)
if self.include:
return not fnd
return fnd
class _TypeFilter(_Filter):
""" A filter mixin that matches on resource type (either way) """
include = 0
def matches(self, res):
fnd = self.elements.get(res.typ, 0)
if self.include:
return not fnd
return fnd
class _PatternFilter(_Filter):
""" A filter that matches if re.search succeeds on the resource path """
def matches(self, res):
for regex in self.elements:
if regex.search(res.path):
return 1
return 0
class
|
(_ExtFilter):
""" A file extension filter.
ExtFilter(extlist, include=0)
where extlist is a list of file extensions """
def __init__(self, extlist, include=0):
self.elements = {}
for ext in extlist:
if ext[0:1] != '.':
ext = '.'+ext
self.elements[ext] = 1
self.include = include
class TypeFilter(_TypeFilter):
""" A filter for resource types.
TypeFilter(typlist, include=0)
where typlist is a subset of ['a','b','d','m','p','s','x','z'] """
def __init__(self, typlist, include=0):
self.elements = {}
for typ in typlist:
self.elements[typ] = 1
self.include = include
class FileFilter(_NameFilter):
""" A filter for data files """
def __init__(self, filelist):
self.elements = {}
for f in filelist:
self.elements[f] = 1
class ModFilter(_NameFilter):
""" A filter for Python modules.
ModFilter(modlist) where modlist is eg ['macpath', 'dospath'] """
def __init__(self, modlist):
self.elements = {}
for mod in modlist:
self.elements[mod] = 1
class DirFilter(_PathFilter):
""" A filter based on directories.
DirFilter(dirlist)
dirs may be relative and will be normalized.
Subdirectories of dirs will be excluded. """
def __init__(self, dirlist):
self.elements = {}
for pth in dirlist:
pth = os.path.normcase(os.path.abspath(pth))
self.elements[pth] = 1
class PkgFilter(_PathFilter):
"""At this time, identical to a DirFilter (being lazy) """
def __init__(self, pkglist):
#warning - pkgs are expected to be full directories
self.elements = {}
for pkg in pkglist:
pth = os.path.normcase(os.path.abspath(pkg))
self.elements[pth] = 1
class StdLibFilter(_PathFilter):
""" A filter that excludes anything found in the standard library """
def __init__(self):
pth = os.path.normcase(os.path.join(sys.exec_prefix, 'lib'))
self.elements = {pth:1}
class PatternFilter(_PatternFilter):
""" A filter that excludes if any pattern is found in resource's path """
def __init__(self, patterns):
self.elements = []
for pat in patterns:
self.elements.append(re.compile(pat))
|
ExtFilter
|
identifier_name
|
vi.js
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'table', 'vi', {
border: 'Kích thước đường viền',
caption: 'Đầu đề',
cell: {
menu: 'Ô',
insertBefore: 'Chèn ô Phía trước',
insertAfter: 'Chèn ô Phía sau',
deleteCell: 'Xoá ô',
merge: 'Kết hợp ô',
mergeRight: 'Kết hợp sang phải',
mergeDown: 'Kết hợp xuống dưới',
splitHorizontal: 'Phân tách ô theo chiều ngang',
splitVertical: 'Phân tách ô theo chiều dọc',
title: 'Thuộc tính của ô',
cellType: 'Kiểu của ô',
rowSpan: 'Kết hợp hàng',
colSpan: 'Kết hợp cột',
wordWrap: 'Chữ liền hàng',
hAlign: 'Canh lề ngang',
vAlign: 'Canh lề dọc',
alignBaseline: 'Đường cơ sở',
bgColor: 'Màu nền',
borderColor: 'Màu viền',
data: 'Dữ liệu',
header: 'Đầu đề',
yes: 'Có',
no: 'Không',
invalidWidth: 'Chiều rộng của ô phải là một số nguyên.',
invalidHeight: 'Chiều cao của ô phải là một số nguyên.',
invalidRowSpan: 'Số hàng kết hợp phải là một số nguyên.',
invalidColSpan: 'Số cột kết hợp phải là một số nguyên.',
chooseColor: 'Chọn màu'
},
cellPad: 'Khoảng đệm giữ ô và nội dung',
cellSpace: 'Khoảng cách giữa các ô',
column: {
menu: 'Cột',
insertBefore: 'Chèn cột phía trước',
insertAfter: 'Chèn cột phía sau',
deleteColumn: 'Xoá cột'
},
columns: 'Số cột',
deleteTable: 'Xóa bảng',
headers: 'Đầu đề',
headersBoth: 'Cả hai',
headersColumn: 'Cột đầu tiên',
headersNone: 'Không có',
headersRow: 'Hàng đầu tiên',
invalidBorder: 'Kích cỡ của đường biên phải là một số nguyên.',
invalidCellPadding: 'Khoảng đệm giữa ô và nội dung phải là một số nguyên.',
|
invalidCellSpacing: 'Khoảng cách giữa các ô phải là một số nguyên.',
invalidCols: 'Số lượng cột phải là một số lớn hơn 0.',
invalidHeight: 'Chiều cao của bảng phải là một số nguyên.',
invalidRows: 'Số lượng hàng phải là một số lớn hơn 0.',
invalidWidth: 'Chiều rộng của bảng phải là một số nguyên.',
menu: 'Thuộc tính bảng',
row: {
menu: 'Hàng',
insertBefore: 'Chèn hàng phía trước',
insertAfter: 'Chèn hàng phía sau',
deleteRow: 'Xoá hàng'
},
rows: 'Số hàng',
summary: 'Tóm lược',
title: 'Thuộc tính bảng',
toolbar: 'Bảng',
widthPc: 'Phần trăm (%)',
widthPx: 'Điểm ảnh (px)',
widthUnit: 'Đơn vị'
});
|
random_line_split
|
|
StreamService.ts
|
"use strict"
import * as request from 'request';
import * as ytdl from 'ytdl-core';
import { SpotifyTrack, BotConfig, Track } from "../../typings/index";
import { Users } from "../../models/Users";
import { YoutubeAPI } from "../api/YoutubeAPI";
import { Readable } from "stream";
export class StreamService {
private ytApi: YoutubeAPI;
|
(private users: Users, private config: BotConfig) {
this.ytApi = new YoutubeAPI(config.tokens.youtube);
}
public getTrackStream(track: Track, cb: (stream: Readable) => void) {
if (track.src === 'sc') return cb(request(`${track.url}?client_id=${this.config.tokens.soundcloud}`) as any);
else if (track.src === 'spot' && !(track as SpotifyTrack).loaded) {
return this.loadAndUpdateTrack(track as SpotifyTrack).then( (newTrack) => {
cb(ytdl(newTrack.url, { filter : 'audioonly' }));
});
}
return cb(ytdl(track.url, { filter : 'audioonly' }));
}
private async loadAndUpdateTrack(track: SpotifyTrack) {
const youtubeTracks = await this.ytApi.searchForVideo(`${track.title} ${track.poster}`);
track.url = youtubeTracks[0].url;
track.loaded = true;
await this.users.updateAllUsersSpotifyTrack(track);
return track;
}
}
|
constructor
|
identifier_name
|
StreamService.ts
|
"use strict"
import * as request from 'request';
import * as ytdl from 'ytdl-core';
import { SpotifyTrack, BotConfig, Track } from "../../typings/index";
import { Users } from "../../models/Users";
import { YoutubeAPI } from "../api/YoutubeAPI";
import { Readable } from "stream";
export class StreamService {
private ytApi: YoutubeAPI;
constructor(private users: Users, private config: BotConfig) {
this.ytApi = new YoutubeAPI(config.tokens.youtube);
}
public getTrackStream(track: Track, cb: (stream: Readable) => void) {
if (track.src === 'sc') return cb(request(`${track.url}?client_id=${this.config.tokens.soundcloud}`) as any);
else if (track.src === 'spot' && !(track as SpotifyTrack).loaded)
|
return cb(ytdl(track.url, { filter : 'audioonly' }));
}
private async loadAndUpdateTrack(track: SpotifyTrack) {
const youtubeTracks = await this.ytApi.searchForVideo(`${track.title} ${track.poster}`);
track.url = youtubeTracks[0].url;
track.loaded = true;
await this.users.updateAllUsersSpotifyTrack(track);
return track;
}
}
|
{
return this.loadAndUpdateTrack(track as SpotifyTrack).then( (newTrack) => {
cb(ytdl(newTrack.url, { filter : 'audioonly' }));
});
}
|
conditional_block
|
StreamService.ts
|
"use strict"
import * as request from 'request';
import * as ytdl from 'ytdl-core';
import { SpotifyTrack, BotConfig, Track } from "../../typings/index";
import { Users } from "../../models/Users";
import { YoutubeAPI } from "../api/YoutubeAPI";
import { Readable } from "stream";
export class StreamService {
private ytApi: YoutubeAPI;
constructor(private users: Users, private config: BotConfig) {
this.ytApi = new YoutubeAPI(config.tokens.youtube);
}
public getTrackStream(track: Track, cb: (stream: Readable) => void)
|
private async loadAndUpdateTrack(track: SpotifyTrack) {
const youtubeTracks = await this.ytApi.searchForVideo(`${track.title} ${track.poster}`);
track.url = youtubeTracks[0].url;
track.loaded = true;
await this.users.updateAllUsersSpotifyTrack(track);
return track;
}
}
|
{
if (track.src === 'sc') return cb(request(`${track.url}?client_id=${this.config.tokens.soundcloud}`) as any);
else if (track.src === 'spot' && !(track as SpotifyTrack).loaded) {
return this.loadAndUpdateTrack(track as SpotifyTrack).then( (newTrack) => {
cb(ytdl(newTrack.url, { filter : 'audioonly' }));
});
}
return cb(ytdl(track.url, { filter : 'audioonly' }));
}
|
identifier_body
|
StreamService.ts
|
"use strict"
import * as request from 'request';
|
import { SpotifyTrack, BotConfig, Track } from "../../typings/index";
import { Users } from "../../models/Users";
import { YoutubeAPI } from "../api/YoutubeAPI";
import { Readable } from "stream";
export class StreamService {
private ytApi: YoutubeAPI;
constructor(private users: Users, private config: BotConfig) {
this.ytApi = new YoutubeAPI(config.tokens.youtube);
}
public getTrackStream(track: Track, cb: (stream: Readable) => void) {
if (track.src === 'sc') return cb(request(`${track.url}?client_id=${this.config.tokens.soundcloud}`) as any);
else if (track.src === 'spot' && !(track as SpotifyTrack).loaded) {
return this.loadAndUpdateTrack(track as SpotifyTrack).then( (newTrack) => {
cb(ytdl(newTrack.url, { filter : 'audioonly' }));
});
}
return cb(ytdl(track.url, { filter : 'audioonly' }));
}
private async loadAndUpdateTrack(track: SpotifyTrack) {
const youtubeTracks = await this.ytApi.searchForVideo(`${track.title} ${track.poster}`);
track.url = youtubeTracks[0].url;
track.loaded = true;
await this.users.updateAllUsersSpotifyTrack(track);
return track;
}
}
|
import * as ytdl from 'ytdl-core';
|
random_line_split
|
reducer.spec.ts
|
import { FormGroup } from '@angular/forms';
import { Reset } from '~/actions/root.actions';
import { IUser } from '~/interfaces/user';
import { SetAuthorized } from './actions';
import { authReducer } from './reducer';
import { ResetError, SigninError, SigninRequest, SigninSuccess } from './signin/actions';
import { SignupError, SignupRequest } from './signup/actions';
describe('authReducer', () => {
it('SIGNIN_REQUEST', () => {
const user = {} as IUser;
const formGroup = { value: user } as FormGroup;
expect(authReducer({}, new SigninRequest(formGroup))).toEqual({ user, signinError: null });
});
it('SIGNIN_ERROR', () => {
const signinError = { error: 'bob' };
expect(authReducer({}, new SigninError(signinError))).toEqual({ signinError });
});
it('SIGNIN_ERROR', () => {
expect(authReducer({}, new ResetError())).toEqual({ signinError: null });
});
it('SIGNUP_REQUEST', () => {
const user = {} as IUser;
const formGroup = { value: user } as FormGroup;
expect(authReducer({}, new SignupRequest(formGroup))).toEqual({ user, signupError: null });
});
it('SIGNUP_ERROR', () => {
const signupError = { error: 'bob' };
expect(authReducer({}, new SignupError(signupError))).toEqual({ signupError });
});
it('SIGNIN_SUCCESS', () => {
expect(authReducer({}, new SigninSuccess(null, null))).toEqual({});
});
describe('SET_AUTHORIZED', () => {
it('doesn`t have provider', () => {
const authorized = true;
expect(authReducer({}, new SetAuthorized({ authorized }))).toEqual({ authorized, provider: undefined });
});
it('has provider', () => {
const authorized = true;
const provider = 'bob';
expect(authReducer({}, new SetAuthorized({ authorized, provider }))).toEqual({ authorized, provider });
});
|
});
it('RESET', () => {
expect(authReducer({}, new Reset())).toEqual({});
});
it('default', () => {
expect(authReducer({}, { type: null })).toEqual({});
});
});
|
random_line_split
|
|
SkillTree.js
|
angular.module('starter.controllers')
.controller('skillTreeControl', function ($scope, $storageServices, $ionicModal, $analytics, $window) {
$scope.showSkillMap = true;
$analytics.trackView('Skill Tree');
$scope.ratings = 0;
$scope.isInfinite = false;
$scope.learnedSkills = [];
$scope.modal = null;
$scope.openSkillsModal = function () {
$analytics.trackView('All Skills');
$ionicModal.fromTemplateUrl('templates/skills/my_skills.html', {
id: 'skills',
scope: $scope,
animation: 'slide-in-up'
}).then(function (modal) {
modal.show();
$scope.modal = modal;
});
};
$scope.closeSkillsModal = function () {
$scope.modal.hide();
};
$scope.$on('$ionicView.enter', function () {
// clear badge
$storageServices.set('badgePoints', 0);
var flareChild = {};
angular.forEach(ALL_SKILLS, function (skills, index) {
var skillFlareChild = {};
angular.forEach(skills, function (skill) {
$storageServices.get(skill.text, function (result) {
var rating = parseInt(result);
if (rating) {
$scope.showSkillMap = true;
skillFlareChild[skill.text] = [rating];
$scope.ratings = $scope.ratings + rating;
if (rating >= 0) {
$scope.learnedSkills.push({
skill: skill.text,
rating: rating
});
}
var MAX_SKILL_POINTS = 250;
if ($scope.ratings > MAX_SKILL_POINTS) {
$scope.isInfinite = true;
}
}
});
if (skillFlareChild) {
flareChild[index] = skillFlareChild
}
});
$storageServices.set('points', $scope.ratings);
});
if ($scope.ratings > 0) {
RenderSkillTree($window, {
"Skill": flareChild
});
RenderBubble($storageServices, $window);
} else
|
});
});
|
{
$scope.showSkillMap = false;
}
|
conditional_block
|
SkillTree.js
|
angular.module('starter.controllers')
.controller('skillTreeControl', function ($scope, $storageServices, $ionicModal, $analytics, $window) {
$scope.showSkillMap = true;
$analytics.trackView('Skill Tree');
$scope.ratings = 0;
$scope.isInfinite = false;
$scope.learnedSkills = [];
$scope.modal = null;
$scope.openSkillsModal = function () {
$analytics.trackView('All Skills');
$ionicModal.fromTemplateUrl('templates/skills/my_skills.html', {
id: 'skills',
scope: $scope,
animation: 'slide-in-up'
}).then(function (modal) {
modal.show();
$scope.modal = modal;
});
};
$scope.closeSkillsModal = function () {
$scope.modal.hide();
};
$scope.$on('$ionicView.enter', function () {
// clear badge
$storageServices.set('badgePoints', 0);
|
angular.forEach(ALL_SKILLS, function (skills, index) {
var skillFlareChild = {};
angular.forEach(skills, function (skill) {
$storageServices.get(skill.text, function (result) {
var rating = parseInt(result);
if (rating) {
$scope.showSkillMap = true;
skillFlareChild[skill.text] = [rating];
$scope.ratings = $scope.ratings + rating;
if (rating >= 0) {
$scope.learnedSkills.push({
skill: skill.text,
rating: rating
});
}
var MAX_SKILL_POINTS = 250;
if ($scope.ratings > MAX_SKILL_POINTS) {
$scope.isInfinite = true;
}
}
});
if (skillFlareChild) {
flareChild[index] = skillFlareChild
}
});
$storageServices.set('points', $scope.ratings);
});
if ($scope.ratings > 0) {
RenderSkillTree($window, {
"Skill": flareChild
});
RenderBubble($storageServices, $window);
} else {
$scope.showSkillMap = false;
}
});
});
|
var flareChild = {};
|
random_line_split
|
Paper.ts
|
import { Margin } from "./Margin";
import { PageFormat } from "./PageFormat";
import { StandardizedPageFormat } from "./StandardizedPageFormat";
/**
* Represents a document-layout.
*/
export class
|
{
/**
* The margin of the paper.
*/
private margin: Margin = new Margin("1cm");
/**
* The format of the paper.
*/
private format: PageFormat = new StandardizedPageFormat();
/**
* Initializes a new instance of the {@link Paper `Paper`} class.
*
* @param format
* Either the format of the paper or `null` to use the default format.
*
* @param margin
* Either the margin of the paper or `null` to use a default margin.
*/
public constructor(format?: PageFormat, margin?: Margin)
{
if (format)
{
this.format = format;
}
if (margin)
{
this.margin = margin;
}
}
/**
* Gets or sets the margin of the paper.
*/
public get Margin(): Margin
{
return this.margin;
}
/**
* @inheritdoc
*/
public set Margin(value: Margin)
{
this.margin = value;
}
/**
* Gets or sets the format of the paper.
*/
public get Format(): PageFormat
{
return this.format;
}
/**
* @inheritdoc
*/
public set Format(value: PageFormat)
{
this.format = value;
}
}
|
Paper
|
identifier_name
|
Paper.ts
|
import { Margin } from "./Margin";
import { PageFormat } from "./PageFormat";
import { StandardizedPageFormat } from "./StandardizedPageFormat";
/**
* Represents a document-layout.
*/
export class Paper
{
/**
* The margin of the paper.
*/
private margin: Margin = new Margin("1cm");
/**
* The format of the paper.
*/
private format: PageFormat = new StandardizedPageFormat();
/**
* Initializes a new instance of the {@link Paper `Paper`} class.
*
* @param format
* Either the format of the paper or `null` to use the default format.
*
* @param margin
* Either the margin of the paper or `null` to use a default margin.
*/
public constructor(format?: PageFormat, margin?: Margin)
{
if (format)
|
if (margin)
{
this.margin = margin;
}
}
/**
* Gets or sets the margin of the paper.
*/
public get Margin(): Margin
{
return this.margin;
}
/**
* @inheritdoc
*/
public set Margin(value: Margin)
{
this.margin = value;
}
/**
* Gets or sets the format of the paper.
*/
public get Format(): PageFormat
{
return this.format;
}
/**
* @inheritdoc
*/
public set Format(value: PageFormat)
{
this.format = value;
}
}
|
{
this.format = format;
}
|
conditional_block
|
Paper.ts
|
import { Margin } from "./Margin";
import { PageFormat } from "./PageFormat";
import { StandardizedPageFormat } from "./StandardizedPageFormat";
/**
* Represents a document-layout.
*/
export class Paper
{
/**
* The margin of the paper.
*/
private margin: Margin = new Margin("1cm");
/**
* The format of the paper.
*/
private format: PageFormat = new StandardizedPageFormat();
/**
* Initializes a new instance of the {@link Paper `Paper`} class.
*
* @param format
* Either the format of the paper or `null` to use the default format.
*
* @param margin
* Either the margin of the paper or `null` to use a default margin.
*/
public constructor(format?: PageFormat, margin?: Margin)
{
if (format)
{
this.format = format;
}
if (margin)
{
this.margin = margin;
}
}
/**
* Gets or sets the margin of the paper.
*/
public get Margin(): Margin
{
return this.margin;
}
/**
* @inheritdoc
*/
|
public set Margin(value: Margin)
{
this.margin = value;
}
/**
* Gets or sets the format of the paper.
*/
public get Format(): PageFormat
{
return this.format;
}
/**
* @inheritdoc
*/
public set Format(value: PageFormat)
{
this.format = value;
}
}
|
random_line_split
|
|
Paper.ts
|
import { Margin } from "./Margin";
import { PageFormat } from "./PageFormat";
import { StandardizedPageFormat } from "./StandardizedPageFormat";
/**
* Represents a document-layout.
*/
export class Paper
{
/**
* The margin of the paper.
*/
private margin: Margin = new Margin("1cm");
/**
* The format of the paper.
*/
private format: PageFormat = new StandardizedPageFormat();
/**
* Initializes a new instance of the {@link Paper `Paper`} class.
*
* @param format
* Either the format of the paper or `null` to use the default format.
*
* @param margin
* Either the margin of the paper or `null` to use a default margin.
*/
public constructor(format?: PageFormat, margin?: Margin)
{
if (format)
{
this.format = format;
}
if (margin)
{
this.margin = margin;
}
}
/**
* Gets or sets the margin of the paper.
*/
public get Margin(): Margin
{
return this.margin;
}
/**
* @inheritdoc
*/
public set Margin(value: Margin)
{
this.margin = value;
}
/**
* Gets or sets the format of the paper.
*/
public get Format(): PageFormat
{
return this.format;
}
/**
* @inheritdoc
*/
public set Format(value: PageFormat)
|
}
|
{
this.format = value;
}
|
identifier_body
|
FeatureHeader_feature.graphql.ts
|
/* tslint:disable */
import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type FeatureHeader_feature = {
readonly name: string;
readonly subheadline: string | null;
readonly image: {
|
readonly url: string | null;
} | null;
} | null;
readonly " $refType": "FeatureHeader_feature";
};
export type FeatureHeader_feature$data = FeatureHeader_feature;
export type FeatureHeader_feature$key = {
readonly " $data"?: FeatureHeader_feature$data;
readonly " $fragmentRefs": FragmentRefs<"FeatureHeader_feature">;
};
const node: ReaderFragment = {
"kind": "Fragment",
"name": "FeatureHeader_feature",
"type": "Feature",
"metadata": null,
"argumentDefinitions": [],
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "name",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "subheadline",
"args": [
{
"kind": "Literal",
"name": "format",
"value": "HTML"
}
],
"storageKey": "subheadline(format:\"HTML\")"
},
{
"kind": "LinkedField",
"alias": null,
"name": "image",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "cropped",
"storageKey": "cropped(height:2000,version:\"source\",width:2000)",
"args": [
{
"kind": "Literal",
"name": "height",
"value": 2000
},
{
"kind": "Literal",
"name": "version",
"value": "source"
},
{
"kind": "Literal",
"name": "width",
"value": 2000
}
],
"concreteType": "CroppedImageUrl",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "url",
"args": null,
"storageKey": null
}
]
}
]
}
]
};
(node as any).hash = '4fad4b2f3161c349788d91adc1fc72b3';
export default node;
|
readonly cropped: {
|
random_line_split
|
test_cisco_auto_enabled_switch.py
|
import unittest
from flexmock import flexmock_teardown
from tests.util.global_reactor import cisco_switch_ip, \
cisco_auto_enabled_switch_ssh_port, cisco_auto_enabled_switch_telnet_port
from tests.util.protocol_util import SshTester, TelnetTester, with_protocol
class TestCiscoAutoEnabledSwitchProtocol(unittest.TestCase):
__test__ = False
def setUp(self):
|
def tearDown(self):
flexmock_teardown()
@with_protocol
def test_enable_command_requires_a_password(self, t):
t.write("enable")
t.read("my_switch#")
t.write("terminal length 0")
t.read("my_switch#")
t.write("terminal width 0")
t.read("my_switch#")
t.write("configure terminal")
t.readln("Enter configuration commands, one per line. End with CNTL/Z.")
t.read("my_switch(config)#")
t.write("exit")
t.read("my_switch#")
def create_client(self):
raise NotImplemented()
class TestCiscoSwitchProtocolSSH(TestCiscoAutoEnabledSwitchProtocol):
__test__ = True
def create_client(self):
return SshTester("ssh", cisco_switch_ip, cisco_auto_enabled_switch_ssh_port, 'root', 'root')
class TestCiscoSwitchProtocolTelnet(TestCiscoAutoEnabledSwitchProtocol):
__test__ = True
def create_client(self):
return TelnetTester("telnet", cisco_switch_ip, cisco_auto_enabled_switch_telnet_port, 'root', 'root')
|
self.protocol = self.create_client()
|
identifier_body
|
test_cisco_auto_enabled_switch.py
|
import unittest
from flexmock import flexmock_teardown
from tests.util.global_reactor import cisco_switch_ip, \
cisco_auto_enabled_switch_ssh_port, cisco_auto_enabled_switch_telnet_port
from tests.util.protocol_util import SshTester, TelnetTester, with_protocol
class TestCiscoAutoEnabledSwitchProtocol(unittest.TestCase):
__test__ = False
def setUp(self):
self.protocol = self.create_client()
def tearDown(self):
flexmock_teardown()
@with_protocol
def test_enable_command_requires_a_password(self, t):
t.write("enable")
t.read("my_switch#")
t.write("terminal length 0")
t.read("my_switch#")
t.write("terminal width 0")
t.read("my_switch#")
t.write("configure terminal")
t.readln("Enter configuration commands, one per line. End with CNTL/Z.")
t.read("my_switch(config)#")
t.write("exit")
t.read("my_switch#")
def create_client(self):
raise NotImplemented()
class TestCiscoSwitchProtocolSSH(TestCiscoAutoEnabledSwitchProtocol):
__test__ = True
def
|
(self):
return SshTester("ssh", cisco_switch_ip, cisco_auto_enabled_switch_ssh_port, 'root', 'root')
class TestCiscoSwitchProtocolTelnet(TestCiscoAutoEnabledSwitchProtocol):
__test__ = True
def create_client(self):
return TelnetTester("telnet", cisco_switch_ip, cisco_auto_enabled_switch_telnet_port, 'root', 'root')
|
create_client
|
identifier_name
|
test_cisco_auto_enabled_switch.py
|
import unittest
from flexmock import flexmock_teardown
|
class TestCiscoAutoEnabledSwitchProtocol(unittest.TestCase):
__test__ = False
def setUp(self):
self.protocol = self.create_client()
def tearDown(self):
flexmock_teardown()
@with_protocol
def test_enable_command_requires_a_password(self, t):
t.write("enable")
t.read("my_switch#")
t.write("terminal length 0")
t.read("my_switch#")
t.write("terminal width 0")
t.read("my_switch#")
t.write("configure terminal")
t.readln("Enter configuration commands, one per line. End with CNTL/Z.")
t.read("my_switch(config)#")
t.write("exit")
t.read("my_switch#")
def create_client(self):
raise NotImplemented()
class TestCiscoSwitchProtocolSSH(TestCiscoAutoEnabledSwitchProtocol):
__test__ = True
def create_client(self):
return SshTester("ssh", cisco_switch_ip, cisco_auto_enabled_switch_ssh_port, 'root', 'root')
class TestCiscoSwitchProtocolTelnet(TestCiscoAutoEnabledSwitchProtocol):
__test__ = True
def create_client(self):
return TelnetTester("telnet", cisco_switch_ip, cisco_auto_enabled_switch_telnet_port, 'root', 'root')
|
from tests.util.global_reactor import cisco_switch_ip, \
cisco_auto_enabled_switch_ssh_port, cisco_auto_enabled_switch_telnet_port
from tests.util.protocol_util import SshTester, TelnetTester, with_protocol
|
random_line_split
|
htmllinkelement.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 cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference};
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::element::{AttributeMutation, Element, ElementCreator};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use encoding::EncodingRef;
use encoding::all::UTF_8;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use layout_interface::Msg;
use net_traits::{AsyncResponseListener, AsyncResponseTarget, Metadata, NetworkError};
use network_listener::{NetworkListener, PreInvoke};
use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg};
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::default::Default;
use std::mem;
use std::sync::{Arc, Mutex};
use string_cache::Atom;
use style::attr::AttrValue;
use style::media_queries::{MediaQueryList, parse_media_query_list};
use style::parser::ParserContextExtraData;
use style::servo::Stylesheet;
use style::stylesheets::Origin;
use url::Url;
use util::str::HTML_SPACE_CHARACTERS;
no_jsmanaged_fields!(Stylesheet);
#[dom_struct]
pub struct HTMLLinkElement {
htmlelement: HTMLElement,
rel_list: MutNullableHeap<JS<DOMTokenList>>,
stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>,
/// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts
parser_inserted: Cell<bool>,
}
impl HTMLLinkElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document,
creator: ElementCreator) -> HTMLLinkElement {
HTMLLinkElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
rel_list: Default::default(),
parser_inserted: Cell::new(creator == ElementCreator::ParserCreated),
stylesheet: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document,
creator: ElementCreator) -> Root<HTMLLinkElement> {
let element = HTMLLinkElement::new_inherited(localName, prefix, document, creator);
Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap)
}
pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
self.stylesheet.borrow().clone()
}
}
fn get_attr(element: &Element, local_name: &Atom) -> Option<String> {
let elem = element.get_attribute(&ns!(), local_name);
elem.map(|e| {
let value = e.value();
(**value).to_owned()
})
}
fn string_is_stylesheet(value: &Option<String>) -> bool {
match *value {
Some(ref value) => {
let mut found_stylesheet = false;
for s in value.split(HTML_SPACE_CHARACTERS).into_iter() {
if s.eq_ignore_ascii_case("alternate") {
return false;
}
if s.eq_ignore_ascii_case("stylesheet") {
found_stylesheet = true;
}
}
found_stylesheet
},
None => false,
}
}
/// Favicon spec usage in accordance with CEF implementation:
/// only url of icon is required/used
/// https://html.spec.whatwg.org/multipage/#rel-icon
fn is_favicon(value: &Option<String>) -> bool {
match *value {
Some(ref value) => {
value.split(HTML_SPACE_CHARACTERS)
.any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon"))
},
None => false,
}
}
impl VirtualMethods for HTMLLinkElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if !self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed {
return;
}
let rel = get_attr(self.upcast(), &atom!("rel"));
match attr.local_name() {
|
self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes);
}
},
&atom!("sizes") => {
if is_favicon(&rel) {
if let Some(ref href) = get_attr(self.upcast(), &atom!("href")) {
self.handle_favicon_url(rel.as_ref().unwrap(), href, &Some(attr.value().to_string()));
}
}
},
&atom!("media") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
}
},
_ => {},
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
let element = self.upcast();
let rel = get_attr(element, &atom!("rel"));
let href = get_attr(element, &atom!("href"));
let sizes = get_attr(self.upcast(), &atom!("sizes"));
match href {
Some(ref href) if string_is_stylesheet(&rel) => {
self.handle_stylesheet_url(href);
}
Some(ref href) if is_favicon(&rel) => {
self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes);
}
_ => {}
}
}
}
}
impl HTMLLinkElement {
fn handle_stylesheet_url(&self, href: &str) {
let document = document_from_node(self);
match document.base_url().join(href) {
Ok(url) => {
let element = self.upcast::<Element>();
let mq_attribute = element.get_attribute(&ns!(), &atom!("media"));
let value = mq_attribute.r().map(|a| a.value());
let mq_str = match value {
Some(ref value) => &***value,
None => "",
};
let mut css_parser = CssParser::new(&mq_str);
let media = parse_media_query_list(&mut css_parser);
// TODO: #8085 - Don't load external stylesheets if the node's mq doesn't match.
let elem = Trusted::new(self);
let context = Arc::new(Mutex::new(StylesheetContext {
elem: elem,
media: Some(media),
data: vec!(),
metadata: None,
url: url.clone(),
}));
let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener {
context: context,
script_chan: document.window().networking_task_source(),
};
let response_target = AsyncResponseTarget {
sender: action_sender,
};
ROUTER.add_route(action_receiver.to_opaque(), box move |message| {
listener.notify_action(message.to().unwrap());
});
if self.parser_inserted.get() {
document.increment_script_blocking_stylesheet_count();
}
document.load_async(LoadType::Stylesheet(url), response_target);
}
Err(e) => debug!("Parsing url {} failed: {}", href, e)
}
}
fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) {
let document = document_from_node(self);
match document.base_url().join(href) {
Ok(url) => {
let event = ConstellationMsg::NewFavicon(url.clone());
document.window().constellation_chan().send(event).unwrap();
let mozbrowser_event = match *sizes {
Some(ref sizes) => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), sizes.to_owned()),
None => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), "".to_owned())
};
document.trigger_mozbrowser_event(mozbrowser_event);
}
Err(e) => debug!("Parsing url {} failed: {}", href, e)
}
}
}
/// The context required for asynchronously loading an external stylesheet.
struct StylesheetContext {
/// The element that initiated the request.
elem: Trusted<HTMLLinkElement>,
media: Option<MediaQueryList>,
/// The response body received to date.
data: Vec<u8>,
/// The response metadata received to date.
metadata: Option<Metadata>,
/// The initial URL requested.
url: Url,
}
impl PreInvoke for StylesheetContext {}
impl AsyncResponseListener for StylesheetContext {
fn headers_available(&mut self, metadata: Result<Metadata, NetworkError>) {
self.metadata = metadata.ok();
if let Some(ref meta) = self.metadata {
if let Some(ContentType(Mime(TopLevel::Text, SubLevel::Css, _))) = meta.content_type {
} else {
self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
}
}
}
fn data_available(&mut self, payload: Vec<u8>) {
let mut payload = payload;
self.data.append(&mut payload);
}
fn response_complete(&mut self, status: Result<(), NetworkError>) {
if status.is_err() {
self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
return;
}
let data = mem::replace(&mut self.data, vec!());
let metadata = match self.metadata.take() {
Some(meta) => meta,
None => return,
};
// TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
let environment_encoding = UTF_8 as EncodingRef;
let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
let final_url = metadata.final_url;
let elem = self.elem.root();
let win = window_from_node(&*elem);
let mut sheet = Stylesheet::from_bytes(&data, final_url, protocol_encoding_label,
Some(environment_encoding), Origin::Author,
win.css_error_reporter(),
ParserContextExtraData::default());
let media = self.media.take().unwrap();
sheet.set_media(Some(media));
let sheet = Arc::new(sheet);
let elem = elem.r();
let document = document_from_node(elem);
let document = document.r();
let win = window_from_node(elem);
win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap();
*elem.stylesheet.borrow_mut() = Some(sheet);
document.invalidate_stylesheets();
if elem.parser_inserted.get() {
document.decrement_script_blocking_stylesheet_count();
}
document.finish_load(LoadType::Stylesheet(self.url.clone()));
}
}
impl HTMLLinkElementMethods for HTMLLinkElement {
// https://html.spec.whatwg.org/multipage/#dom-link-href
make_url_getter!(Href, "href");
// https://html.spec.whatwg.org/multipage/#dom-link-href
make_setter!(SetHref, "href");
// https://html.spec.whatwg.org/multipage/#dom-link-rel
make_getter!(Rel, "rel");
// https://html.spec.whatwg.org/multipage/#dom-link-rel
make_setter!(SetRel, "rel");
// https://html.spec.whatwg.org/multipage/#dom-link-media
make_getter!(Media, "media");
// https://html.spec.whatwg.org/multipage/#dom-link-media
make_setter!(SetMedia, "media");
// https://html.spec.whatwg.org/multipage/#dom-link-hreflang
make_getter!(Hreflang, "hreflang");
// https://html.spec.whatwg.org/multipage/#dom-link-hreflang
make_setter!(SetHreflang, "hreflang");
// https://html.spec.whatwg.org/multipage/#dom-link-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-link-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-link-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &atom!("rel")))
}
// https://html.spec.whatwg.org/multipage/#dom-link-charset
make_getter!(Charset, "charset");
// https://html.spec.whatwg.org/multipage/#dom-link-charset
make_setter!(SetCharset, "charset");
// https://html.spec.whatwg.org/multipage/#dom-link-rev
make_getter!(Rev, "rev");
// https://html.spec.whatwg.org/multipage/#dom-link-rev
make_setter!(SetRev, "rev");
// https://html.spec.whatwg.org/multipage/#dom-link-target
make_getter!(Target, "target");
// https://html.spec.whatwg.org/multipage/#dom-link-target
make_setter!(SetTarget, "target");
}
|
&atom!("href") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
} else if is_favicon(&rel) {
let sizes = get_attr(self.upcast(), &atom!("sizes"));
|
random_line_split
|
htmllinkelement.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 cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference};
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::element::{AttributeMutation, Element, ElementCreator};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use encoding::EncodingRef;
use encoding::all::UTF_8;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use layout_interface::Msg;
use net_traits::{AsyncResponseListener, AsyncResponseTarget, Metadata, NetworkError};
use network_listener::{NetworkListener, PreInvoke};
use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg};
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::default::Default;
use std::mem;
use std::sync::{Arc, Mutex};
use string_cache::Atom;
use style::attr::AttrValue;
use style::media_queries::{MediaQueryList, parse_media_query_list};
use style::parser::ParserContextExtraData;
use style::servo::Stylesheet;
use style::stylesheets::Origin;
use url::Url;
use util::str::HTML_SPACE_CHARACTERS;
no_jsmanaged_fields!(Stylesheet);
#[dom_struct]
pub struct HTMLLinkElement {
htmlelement: HTMLElement,
rel_list: MutNullableHeap<JS<DOMTokenList>>,
stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>,
/// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts
parser_inserted: Cell<bool>,
}
impl HTMLLinkElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document,
creator: ElementCreator) -> HTMLLinkElement {
HTMLLinkElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
rel_list: Default::default(),
parser_inserted: Cell::new(creator == ElementCreator::ParserCreated),
stylesheet: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document,
creator: ElementCreator) -> Root<HTMLLinkElement> {
let element = HTMLLinkElement::new_inherited(localName, prefix, document, creator);
Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap)
}
pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
self.stylesheet.borrow().clone()
}
}
fn get_attr(element: &Element, local_name: &Atom) -> Option<String> {
let elem = element.get_attribute(&ns!(), local_name);
elem.map(|e| {
let value = e.value();
(**value).to_owned()
})
}
fn string_is_stylesheet(value: &Option<String>) -> bool {
match *value {
Some(ref value) => {
let mut found_stylesheet = false;
for s in value.split(HTML_SPACE_CHARACTERS).into_iter() {
if s.eq_ignore_ascii_case("alternate") {
return false;
}
if s.eq_ignore_ascii_case("stylesheet") {
found_stylesheet = true;
}
}
found_stylesheet
},
None => false,
}
}
/// Favicon spec usage in accordance with CEF implementation:
/// only url of icon is required/used
/// https://html.spec.whatwg.org/multipage/#rel-icon
fn is_favicon(value: &Option<String>) -> bool
|
impl VirtualMethods for HTMLLinkElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if !self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed {
return;
}
let rel = get_attr(self.upcast(), &atom!("rel"));
match attr.local_name() {
&atom!("href") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
} else if is_favicon(&rel) {
let sizes = get_attr(self.upcast(), &atom!("sizes"));
self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes);
}
},
&atom!("sizes") => {
if is_favicon(&rel) {
if let Some(ref href) = get_attr(self.upcast(), &atom!("href")) {
self.handle_favicon_url(rel.as_ref().unwrap(), href, &Some(attr.value().to_string()));
}
}
},
&atom!("media") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
}
},
_ => {},
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
let element = self.upcast();
let rel = get_attr(element, &atom!("rel"));
let href = get_attr(element, &atom!("href"));
let sizes = get_attr(self.upcast(), &atom!("sizes"));
match href {
Some(ref href) if string_is_stylesheet(&rel) => {
self.handle_stylesheet_url(href);
}
Some(ref href) if is_favicon(&rel) => {
self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes);
}
_ => {}
}
}
}
}
impl HTMLLinkElement {
fn handle_stylesheet_url(&self, href: &str) {
let document = document_from_node(self);
match document.base_url().join(href) {
Ok(url) => {
let element = self.upcast::<Element>();
let mq_attribute = element.get_attribute(&ns!(), &atom!("media"));
let value = mq_attribute.r().map(|a| a.value());
let mq_str = match value {
Some(ref value) => &***value,
None => "",
};
let mut css_parser = CssParser::new(&mq_str);
let media = parse_media_query_list(&mut css_parser);
// TODO: #8085 - Don't load external stylesheets if the node's mq doesn't match.
let elem = Trusted::new(self);
let context = Arc::new(Mutex::new(StylesheetContext {
elem: elem,
media: Some(media),
data: vec!(),
metadata: None,
url: url.clone(),
}));
let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener {
context: context,
script_chan: document.window().networking_task_source(),
};
let response_target = AsyncResponseTarget {
sender: action_sender,
};
ROUTER.add_route(action_receiver.to_opaque(), box move |message| {
listener.notify_action(message.to().unwrap());
});
if self.parser_inserted.get() {
document.increment_script_blocking_stylesheet_count();
}
document.load_async(LoadType::Stylesheet(url), response_target);
}
Err(e) => debug!("Parsing url {} failed: {}", href, e)
}
}
fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) {
let document = document_from_node(self);
match document.base_url().join(href) {
Ok(url) => {
let event = ConstellationMsg::NewFavicon(url.clone());
document.window().constellation_chan().send(event).unwrap();
let mozbrowser_event = match *sizes {
Some(ref sizes) => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), sizes.to_owned()),
None => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), "".to_owned())
};
document.trigger_mozbrowser_event(mozbrowser_event);
}
Err(e) => debug!("Parsing url {} failed: {}", href, e)
}
}
}
/// The context required for asynchronously loading an external stylesheet.
struct StylesheetContext {
/// The element that initiated the request.
elem: Trusted<HTMLLinkElement>,
media: Option<MediaQueryList>,
/// The response body received to date.
data: Vec<u8>,
/// The response metadata received to date.
metadata: Option<Metadata>,
/// The initial URL requested.
url: Url,
}
impl PreInvoke for StylesheetContext {}
impl AsyncResponseListener for StylesheetContext {
fn headers_available(&mut self, metadata: Result<Metadata, NetworkError>) {
self.metadata = metadata.ok();
if let Some(ref meta) = self.metadata {
if let Some(ContentType(Mime(TopLevel::Text, SubLevel::Css, _))) = meta.content_type {
} else {
self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
}
}
}
fn data_available(&mut self, payload: Vec<u8>) {
let mut payload = payload;
self.data.append(&mut payload);
}
fn response_complete(&mut self, status: Result<(), NetworkError>) {
if status.is_err() {
self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
return;
}
let data = mem::replace(&mut self.data, vec!());
let metadata = match self.metadata.take() {
Some(meta) => meta,
None => return,
};
// TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
let environment_encoding = UTF_8 as EncodingRef;
let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
let final_url = metadata.final_url;
let elem = self.elem.root();
let win = window_from_node(&*elem);
let mut sheet = Stylesheet::from_bytes(&data, final_url, protocol_encoding_label,
Some(environment_encoding), Origin::Author,
win.css_error_reporter(),
ParserContextExtraData::default());
let media = self.media.take().unwrap();
sheet.set_media(Some(media));
let sheet = Arc::new(sheet);
let elem = elem.r();
let document = document_from_node(elem);
let document = document.r();
let win = window_from_node(elem);
win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap();
*elem.stylesheet.borrow_mut() = Some(sheet);
document.invalidate_stylesheets();
if elem.parser_inserted.get() {
document.decrement_script_blocking_stylesheet_count();
}
document.finish_load(LoadType::Stylesheet(self.url.clone()));
}
}
impl HTMLLinkElementMethods for HTMLLinkElement {
// https://html.spec.whatwg.org/multipage/#dom-link-href
make_url_getter!(Href, "href");
// https://html.spec.whatwg.org/multipage/#dom-link-href
make_setter!(SetHref, "href");
// https://html.spec.whatwg.org/multipage/#dom-link-rel
make_getter!(Rel, "rel");
// https://html.spec.whatwg.org/multipage/#dom-link-rel
make_setter!(SetRel, "rel");
// https://html.spec.whatwg.org/multipage/#dom-link-media
make_getter!(Media, "media");
// https://html.spec.whatwg.org/multipage/#dom-link-media
make_setter!(SetMedia, "media");
// https://html.spec.whatwg.org/multipage/#dom-link-hreflang
make_getter!(Hreflang, "hreflang");
// https://html.spec.whatwg.org/multipage/#dom-link-hreflang
make_setter!(SetHreflang, "hreflang");
// https://html.spec.whatwg.org/multipage/#dom-link-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-link-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-link-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &atom!("rel")))
}
// https://html.spec.whatwg.org/multipage/#dom-link-charset
make_getter!(Charset, "charset");
// https://html.spec.whatwg.org/multipage/#dom-link-charset
make_setter!(SetCharset, "charset");
// https://html.spec.whatwg.org/multipage/#dom-link-rev
make_getter!(Rev, "rev");
// https://html.spec.whatwg.org/multipage/#dom-link-rev
make_setter!(SetRev, "rev");
// https://html.spec.whatwg.org/multipage/#dom-link-target
make_getter!(Target, "target");
// https://html.spec.whatwg.org/multipage/#dom-link-target
make_setter!(SetTarget, "target");
}
|
{
match *value {
Some(ref value) => {
value.split(HTML_SPACE_CHARACTERS)
.any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon"))
},
None => false,
}
}
|
identifier_body
|
htmllinkelement.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 cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference};
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::element::{AttributeMutation, Element, ElementCreator};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use encoding::EncodingRef;
use encoding::all::UTF_8;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use layout_interface::Msg;
use net_traits::{AsyncResponseListener, AsyncResponseTarget, Metadata, NetworkError};
use network_listener::{NetworkListener, PreInvoke};
use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg};
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::default::Default;
use std::mem;
use std::sync::{Arc, Mutex};
use string_cache::Atom;
use style::attr::AttrValue;
use style::media_queries::{MediaQueryList, parse_media_query_list};
use style::parser::ParserContextExtraData;
use style::servo::Stylesheet;
use style::stylesheets::Origin;
use url::Url;
use util::str::HTML_SPACE_CHARACTERS;
no_jsmanaged_fields!(Stylesheet);
#[dom_struct]
pub struct HTMLLinkElement {
htmlelement: HTMLElement,
rel_list: MutNullableHeap<JS<DOMTokenList>>,
stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>,
/// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts
parser_inserted: Cell<bool>,
}
impl HTMLLinkElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document,
creator: ElementCreator) -> HTMLLinkElement {
HTMLLinkElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
rel_list: Default::default(),
parser_inserted: Cell::new(creator == ElementCreator::ParserCreated),
stylesheet: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document,
creator: ElementCreator) -> Root<HTMLLinkElement> {
let element = HTMLLinkElement::new_inherited(localName, prefix, document, creator);
Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap)
}
pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
self.stylesheet.borrow().clone()
}
}
fn get_attr(element: &Element, local_name: &Atom) -> Option<String> {
let elem = element.get_attribute(&ns!(), local_name);
elem.map(|e| {
let value = e.value();
(**value).to_owned()
})
}
fn string_is_stylesheet(value: &Option<String>) -> bool {
match *value {
Some(ref value) => {
let mut found_stylesheet = false;
for s in value.split(HTML_SPACE_CHARACTERS).into_iter() {
if s.eq_ignore_ascii_case("alternate") {
return false;
}
if s.eq_ignore_ascii_case("stylesheet") {
found_stylesheet = true;
}
}
found_stylesheet
},
None => false,
}
}
/// Favicon spec usage in accordance with CEF implementation:
/// only url of icon is required/used
/// https://html.spec.whatwg.org/multipage/#rel-icon
fn is_favicon(value: &Option<String>) -> bool {
match *value {
Some(ref value) => {
value.split(HTML_SPACE_CHARACTERS)
.any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon"))
},
None => false,
}
}
impl VirtualMethods for HTMLLinkElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if !self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed {
return;
}
let rel = get_attr(self.upcast(), &atom!("rel"));
match attr.local_name() {
&atom!("href") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
} else if is_favicon(&rel) {
let sizes = get_attr(self.upcast(), &atom!("sizes"));
self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes);
}
},
&atom!("sizes") => {
if is_favicon(&rel) {
if let Some(ref href) = get_attr(self.upcast(), &atom!("href")) {
self.handle_favicon_url(rel.as_ref().unwrap(), href, &Some(attr.value().to_string()));
}
}
},
&atom!("media") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
}
},
_ => {},
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn
|
(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
let element = self.upcast();
let rel = get_attr(element, &atom!("rel"));
let href = get_attr(element, &atom!("href"));
let sizes = get_attr(self.upcast(), &atom!("sizes"));
match href {
Some(ref href) if string_is_stylesheet(&rel) => {
self.handle_stylesheet_url(href);
}
Some(ref href) if is_favicon(&rel) => {
self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes);
}
_ => {}
}
}
}
}
impl HTMLLinkElement {
fn handle_stylesheet_url(&self, href: &str) {
let document = document_from_node(self);
match document.base_url().join(href) {
Ok(url) => {
let element = self.upcast::<Element>();
let mq_attribute = element.get_attribute(&ns!(), &atom!("media"));
let value = mq_attribute.r().map(|a| a.value());
let mq_str = match value {
Some(ref value) => &***value,
None => "",
};
let mut css_parser = CssParser::new(&mq_str);
let media = parse_media_query_list(&mut css_parser);
// TODO: #8085 - Don't load external stylesheets if the node's mq doesn't match.
let elem = Trusted::new(self);
let context = Arc::new(Mutex::new(StylesheetContext {
elem: elem,
media: Some(media),
data: vec!(),
metadata: None,
url: url.clone(),
}));
let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener {
context: context,
script_chan: document.window().networking_task_source(),
};
let response_target = AsyncResponseTarget {
sender: action_sender,
};
ROUTER.add_route(action_receiver.to_opaque(), box move |message| {
listener.notify_action(message.to().unwrap());
});
if self.parser_inserted.get() {
document.increment_script_blocking_stylesheet_count();
}
document.load_async(LoadType::Stylesheet(url), response_target);
}
Err(e) => debug!("Parsing url {} failed: {}", href, e)
}
}
fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) {
let document = document_from_node(self);
match document.base_url().join(href) {
Ok(url) => {
let event = ConstellationMsg::NewFavicon(url.clone());
document.window().constellation_chan().send(event).unwrap();
let mozbrowser_event = match *sizes {
Some(ref sizes) => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), sizes.to_owned()),
None => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), "".to_owned())
};
document.trigger_mozbrowser_event(mozbrowser_event);
}
Err(e) => debug!("Parsing url {} failed: {}", href, e)
}
}
}
/// The context required for asynchronously loading an external stylesheet.
struct StylesheetContext {
/// The element that initiated the request.
elem: Trusted<HTMLLinkElement>,
media: Option<MediaQueryList>,
/// The response body received to date.
data: Vec<u8>,
/// The response metadata received to date.
metadata: Option<Metadata>,
/// The initial URL requested.
url: Url,
}
impl PreInvoke for StylesheetContext {}
impl AsyncResponseListener for StylesheetContext {
fn headers_available(&mut self, metadata: Result<Metadata, NetworkError>) {
self.metadata = metadata.ok();
if let Some(ref meta) = self.metadata {
if let Some(ContentType(Mime(TopLevel::Text, SubLevel::Css, _))) = meta.content_type {
} else {
self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
}
}
}
fn data_available(&mut self, payload: Vec<u8>) {
let mut payload = payload;
self.data.append(&mut payload);
}
fn response_complete(&mut self, status: Result<(), NetworkError>) {
if status.is_err() {
self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
return;
}
let data = mem::replace(&mut self.data, vec!());
let metadata = match self.metadata.take() {
Some(meta) => meta,
None => return,
};
// TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
let environment_encoding = UTF_8 as EncodingRef;
let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
let final_url = metadata.final_url;
let elem = self.elem.root();
let win = window_from_node(&*elem);
let mut sheet = Stylesheet::from_bytes(&data, final_url, protocol_encoding_label,
Some(environment_encoding), Origin::Author,
win.css_error_reporter(),
ParserContextExtraData::default());
let media = self.media.take().unwrap();
sheet.set_media(Some(media));
let sheet = Arc::new(sheet);
let elem = elem.r();
let document = document_from_node(elem);
let document = document.r();
let win = window_from_node(elem);
win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap();
*elem.stylesheet.borrow_mut() = Some(sheet);
document.invalidate_stylesheets();
if elem.parser_inserted.get() {
document.decrement_script_blocking_stylesheet_count();
}
document.finish_load(LoadType::Stylesheet(self.url.clone()));
}
}
impl HTMLLinkElementMethods for HTMLLinkElement {
// https://html.spec.whatwg.org/multipage/#dom-link-href
make_url_getter!(Href, "href");
// https://html.spec.whatwg.org/multipage/#dom-link-href
make_setter!(SetHref, "href");
// https://html.spec.whatwg.org/multipage/#dom-link-rel
make_getter!(Rel, "rel");
// https://html.spec.whatwg.org/multipage/#dom-link-rel
make_setter!(SetRel, "rel");
// https://html.spec.whatwg.org/multipage/#dom-link-media
make_getter!(Media, "media");
// https://html.spec.whatwg.org/multipage/#dom-link-media
make_setter!(SetMedia, "media");
// https://html.spec.whatwg.org/multipage/#dom-link-hreflang
make_getter!(Hreflang, "hreflang");
// https://html.spec.whatwg.org/multipage/#dom-link-hreflang
make_setter!(SetHreflang, "hreflang");
// https://html.spec.whatwg.org/multipage/#dom-link-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-link-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-link-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &atom!("rel")))
}
// https://html.spec.whatwg.org/multipage/#dom-link-charset
make_getter!(Charset, "charset");
// https://html.spec.whatwg.org/multipage/#dom-link-charset
make_setter!(SetCharset, "charset");
// https://html.spec.whatwg.org/multipage/#dom-link-rev
make_getter!(Rev, "rev");
// https://html.spec.whatwg.org/multipage/#dom-link-rev
make_setter!(SetRev, "rev");
// https://html.spec.whatwg.org/multipage/#dom-link-target
make_getter!(Target, "target");
// https://html.spec.whatwg.org/multipage/#dom-link-target
make_setter!(SetTarget, "target");
}
|
bind_to_tree
|
identifier_name
|
test_msgs.py
|
# -*- coding: utf-8 -*-
import unittest
|
class MessagesTests(unittest.TestCase):
def test_messages(self):
""""""
self.assertEqual(EmailMsg.missing.value, 'emails.missing')
self.assertEqual(EmailMsg.dupe.value, 'emails.duplicated')
self.assertEqual(EmailMsg.get_success.value, 'emails.get-success')
self.assertEqual(EmailMsg.throttled.value, 'emails.throttled')
self.assertEqual(EmailMsg.still_valid_code.value, 'still-valid-code')
self.assertEqual(EmailMsg.added_and_throttled.value, 'emails.added-and-throttled')
self.assertEqual(EmailMsg.saved.value, 'emails.save-success')
self.assertEqual(EmailMsg.unconfirmed_not_primary.value, 'emails.unconfirmed_address_not_primary')
self.assertEqual(EmailMsg.success_primary.value, 'emails.primary-success')
self.assertEqual(EmailMsg.invalid_code.value, 'emails.code_invalid_or_expired')
self.assertEqual(EmailMsg.unknown_email.value, 'emails.unknown_email')
self.assertEqual(EmailMsg.verify_success.value, 'emails.verification-success')
self.assertEqual(EmailMsg.cannot_remove_last.value, 'emails.cannot_remove_unique')
self.assertEqual(EmailMsg.cannot_remove_last_verified.value, 'emails.cannot_remove_unique_verified')
self.assertEqual(EmailMsg.removal_success.value, 'emails.removal-success')
self.assertEqual(EmailMsg.code_sent.value, 'emails.code-sent')
|
from eduid_webapp.email.helpers import EmailMsg
|
random_line_split
|
test_msgs.py
|
# -*- coding: utf-8 -*-
import unittest
from eduid_webapp.email.helpers import EmailMsg
class MessagesTests(unittest.TestCase):
|
def test_messages(self):
""""""
self.assertEqual(EmailMsg.missing.value, 'emails.missing')
self.assertEqual(EmailMsg.dupe.value, 'emails.duplicated')
self.assertEqual(EmailMsg.get_success.value, 'emails.get-success')
self.assertEqual(EmailMsg.throttled.value, 'emails.throttled')
self.assertEqual(EmailMsg.still_valid_code.value, 'still-valid-code')
self.assertEqual(EmailMsg.added_and_throttled.value, 'emails.added-and-throttled')
self.assertEqual(EmailMsg.saved.value, 'emails.save-success')
self.assertEqual(EmailMsg.unconfirmed_not_primary.value, 'emails.unconfirmed_address_not_primary')
self.assertEqual(EmailMsg.success_primary.value, 'emails.primary-success')
self.assertEqual(EmailMsg.invalid_code.value, 'emails.code_invalid_or_expired')
self.assertEqual(EmailMsg.unknown_email.value, 'emails.unknown_email')
self.assertEqual(EmailMsg.verify_success.value, 'emails.verification-success')
self.assertEqual(EmailMsg.cannot_remove_last.value, 'emails.cannot_remove_unique')
self.assertEqual(EmailMsg.cannot_remove_last_verified.value, 'emails.cannot_remove_unique_verified')
self.assertEqual(EmailMsg.removal_success.value, 'emails.removal-success')
self.assertEqual(EmailMsg.code_sent.value, 'emails.code-sent')
|
identifier_body
|
|
test_msgs.py
|
# -*- coding: utf-8 -*-
import unittest
from eduid_webapp.email.helpers import EmailMsg
class
|
(unittest.TestCase):
def test_messages(self):
""""""
self.assertEqual(EmailMsg.missing.value, 'emails.missing')
self.assertEqual(EmailMsg.dupe.value, 'emails.duplicated')
self.assertEqual(EmailMsg.get_success.value, 'emails.get-success')
self.assertEqual(EmailMsg.throttled.value, 'emails.throttled')
self.assertEqual(EmailMsg.still_valid_code.value, 'still-valid-code')
self.assertEqual(EmailMsg.added_and_throttled.value, 'emails.added-and-throttled')
self.assertEqual(EmailMsg.saved.value, 'emails.save-success')
self.assertEqual(EmailMsg.unconfirmed_not_primary.value, 'emails.unconfirmed_address_not_primary')
self.assertEqual(EmailMsg.success_primary.value, 'emails.primary-success')
self.assertEqual(EmailMsg.invalid_code.value, 'emails.code_invalid_or_expired')
self.assertEqual(EmailMsg.unknown_email.value, 'emails.unknown_email')
self.assertEqual(EmailMsg.verify_success.value, 'emails.verification-success')
self.assertEqual(EmailMsg.cannot_remove_last.value, 'emails.cannot_remove_unique')
self.assertEqual(EmailMsg.cannot_remove_last_verified.value, 'emails.cannot_remove_unique_verified')
self.assertEqual(EmailMsg.removal_success.value, 'emails.removal-success')
self.assertEqual(EmailMsg.code_sent.value, 'emails.code-sent')
|
MessagesTests
|
identifier_name
|
speedtest.py
|
import sys
import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper
from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper
from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper
from pyscreenshot.util import run_mod_as_subproc
def run(force_backend, n, childprocess, bbox=None):
sys.stdout.write("%-20s\t" % force_backend)
sys.stdout.flush() # before any crash
if force_backend == "default":
force_backend = None
try:
start = time.time()
for _ in range(n):
pyscreenshot.grab(
backend=force_backend, childprocess=childprocess, bbox=bbox
)
end = time.time()
dt = end - start
s = "%-4.2g sec\t" % dt
s += "(%5d ms per call)" % (1000.0 * dt / n)
sys.stdout.write(s)
finally:
print("")
novirt = [GnomeDBusWrapper.name, KwinDBusWrapper.name, GnomeScreenshotWrapper.name]
def run_all(n, childprocess_param, virtual_only=True, bbox=None):
debug = True
print("")
print("n=%s" % n)
print("------------------------------------------------------")
if bbox:
x1, y1, x2, y2 = map(str, bbox)
bbox = ":".join(map(str, (x1, y1, x2, y2)))
bboxpar = ["--bbox", bbox]
else:
bboxpar = []
if debug:
debugpar = ["--debug"]
else:
debugpar = []
for x in ["default"] + pyscreenshot.backends():
backendpar = ["--backend", x]
# skip non X backends
if virtual_only and x in novirt:
continue
p = run_mod_as_subproc(
"pyscreenshot.check.speedtest",
["--childprocess", childprocess_param] + bboxpar + debugpar + backendpar,
)
print(p.stdout)
@entrypoint
def speedtest(virtual_display=False, backend="", childprocess="", bbox="", number=10):
"""Performance test of all back-ends.
:param virtual_display: run with Xvfb
:param bbox: bounding box coordinates x1:y1:x2:y2
:param backend: back-end can be forced if set (example:default, scrot, wx,..),
otherwise all back-ends are tested
:param childprocess: pyscreenshot parameter childprocess (0/1)
:param number: number of screenshots for each backend (default:10)
"""
childprocess_param = childprocess
if childprocess == "":
childprocess = True # default
elif childprocess == "0":
childprocess = False
elif childprocess == "1":
childprocess = True
else:
raise ValueError("invalid childprocess value")
if bbox:
x1, y1, x2, y2 = map(int, bbox.split(":"))
bbox = x1, y1, x2, y2
else:
bbox = None
def f(virtual_only):
if backend:
try:
run(backend, number, childprocess, bbox=bbox)
except pyscreenshot.FailedBackendError:
pass
else:
|
run_all(number, childprocess_param, virtual_only=virtual_only, bbox=bbox)
if virtual_display:
from pyvirtualdisplay import Display
with Display(visible=0):
f(virtual_only=True)
else:
f(virtual_only=False)
|
random_line_split
|
|
speedtest.py
|
import sys
import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper
from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper
from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper
from pyscreenshot.util import run_mod_as_subproc
def run(force_backend, n, childprocess, bbox=None):
sys.stdout.write("%-20s\t" % force_backend)
sys.stdout.flush() # before any crash
if force_backend == "default":
force_backend = None
try:
start = time.time()
for _ in range(n):
pyscreenshot.grab(
backend=force_backend, childprocess=childprocess, bbox=bbox
)
end = time.time()
dt = end - start
s = "%-4.2g sec\t" % dt
s += "(%5d ms per call)" % (1000.0 * dt / n)
sys.stdout.write(s)
finally:
print("")
novirt = [GnomeDBusWrapper.name, KwinDBusWrapper.name, GnomeScreenshotWrapper.name]
def
|
(n, childprocess_param, virtual_only=True, bbox=None):
debug = True
print("")
print("n=%s" % n)
print("------------------------------------------------------")
if bbox:
x1, y1, x2, y2 = map(str, bbox)
bbox = ":".join(map(str, (x1, y1, x2, y2)))
bboxpar = ["--bbox", bbox]
else:
bboxpar = []
if debug:
debugpar = ["--debug"]
else:
debugpar = []
for x in ["default"] + pyscreenshot.backends():
backendpar = ["--backend", x]
# skip non X backends
if virtual_only and x in novirt:
continue
p = run_mod_as_subproc(
"pyscreenshot.check.speedtest",
["--childprocess", childprocess_param] + bboxpar + debugpar + backendpar,
)
print(p.stdout)
@entrypoint
def speedtest(virtual_display=False, backend="", childprocess="", bbox="", number=10):
"""Performance test of all back-ends.
:param virtual_display: run with Xvfb
:param bbox: bounding box coordinates x1:y1:x2:y2
:param backend: back-end can be forced if set (example:default, scrot, wx,..),
otherwise all back-ends are tested
:param childprocess: pyscreenshot parameter childprocess (0/1)
:param number: number of screenshots for each backend (default:10)
"""
childprocess_param = childprocess
if childprocess == "":
childprocess = True # default
elif childprocess == "0":
childprocess = False
elif childprocess == "1":
childprocess = True
else:
raise ValueError("invalid childprocess value")
if bbox:
x1, y1, x2, y2 = map(int, bbox.split(":"))
bbox = x1, y1, x2, y2
else:
bbox = None
def f(virtual_only):
if backend:
try:
run(backend, number, childprocess, bbox=bbox)
except pyscreenshot.FailedBackendError:
pass
else:
run_all(number, childprocess_param, virtual_only=virtual_only, bbox=bbox)
if virtual_display:
from pyvirtualdisplay import Display
with Display(visible=0):
f(virtual_only=True)
else:
f(virtual_only=False)
|
run_all
|
identifier_name
|
speedtest.py
|
import sys
import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper
from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper
from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper
from pyscreenshot.util import run_mod_as_subproc
def run(force_backend, n, childprocess, bbox=None):
sys.stdout.write("%-20s\t" % force_backend)
sys.stdout.flush() # before any crash
if force_backend == "default":
force_backend = None
try:
start = time.time()
for _ in range(n):
pyscreenshot.grab(
backend=force_backend, childprocess=childprocess, bbox=bbox
)
end = time.time()
dt = end - start
s = "%-4.2g sec\t" % dt
s += "(%5d ms per call)" % (1000.0 * dt / n)
sys.stdout.write(s)
finally:
print("")
novirt = [GnomeDBusWrapper.name, KwinDBusWrapper.name, GnomeScreenshotWrapper.name]
def run_all(n, childprocess_param, virtual_only=True, bbox=None):
debug = True
print("")
print("n=%s" % n)
print("------------------------------------------------------")
if bbox:
x1, y1, x2, y2 = map(str, bbox)
bbox = ":".join(map(str, (x1, y1, x2, y2)))
bboxpar = ["--bbox", bbox]
else:
bboxpar = []
if debug:
debugpar = ["--debug"]
else:
debugpar = []
for x in ["default"] + pyscreenshot.backends():
backendpar = ["--backend", x]
# skip non X backends
if virtual_only and x in novirt:
continue
p = run_mod_as_subproc(
"pyscreenshot.check.speedtest",
["--childprocess", childprocess_param] + bboxpar + debugpar + backendpar,
)
print(p.stdout)
@entrypoint
def speedtest(virtual_display=False, backend="", childprocess="", bbox="", number=10):
"""Performance test of all back-ends.
:param virtual_display: run with Xvfb
:param bbox: bounding box coordinates x1:y1:x2:y2
:param backend: back-end can be forced if set (example:default, scrot, wx,..),
otherwise all back-ends are tested
:param childprocess: pyscreenshot parameter childprocess (0/1)
:param number: number of screenshots for each backend (default:10)
"""
childprocess_param = childprocess
if childprocess == "":
childprocess = True # default
elif childprocess == "0":
childprocess = False
elif childprocess == "1":
childprocess = True
else:
raise ValueError("invalid childprocess value")
if bbox:
|
else:
bbox = None
def f(virtual_only):
if backend:
try:
run(backend, number, childprocess, bbox=bbox)
except pyscreenshot.FailedBackendError:
pass
else:
run_all(number, childprocess_param, virtual_only=virtual_only, bbox=bbox)
if virtual_display:
from pyvirtualdisplay import Display
with Display(visible=0):
f(virtual_only=True)
else:
f(virtual_only=False)
|
x1, y1, x2, y2 = map(int, bbox.split(":"))
bbox = x1, y1, x2, y2
|
conditional_block
|
speedtest.py
|
import sys
import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper
from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper
from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper
from pyscreenshot.util import run_mod_as_subproc
def run(force_backend, n, childprocess, bbox=None):
sys.stdout.write("%-20s\t" % force_backend)
sys.stdout.flush() # before any crash
if force_backend == "default":
force_backend = None
try:
start = time.time()
for _ in range(n):
pyscreenshot.grab(
backend=force_backend, childprocess=childprocess, bbox=bbox
)
end = time.time()
dt = end - start
s = "%-4.2g sec\t" % dt
s += "(%5d ms per call)" % (1000.0 * dt / n)
sys.stdout.write(s)
finally:
print("")
novirt = [GnomeDBusWrapper.name, KwinDBusWrapper.name, GnomeScreenshotWrapper.name]
def run_all(n, childprocess_param, virtual_only=True, bbox=None):
debug = True
print("")
print("n=%s" % n)
print("------------------------------------------------------")
if bbox:
x1, y1, x2, y2 = map(str, bbox)
bbox = ":".join(map(str, (x1, y1, x2, y2)))
bboxpar = ["--bbox", bbox]
else:
bboxpar = []
if debug:
debugpar = ["--debug"]
else:
debugpar = []
for x in ["default"] + pyscreenshot.backends():
backendpar = ["--backend", x]
# skip non X backends
if virtual_only and x in novirt:
continue
p = run_mod_as_subproc(
"pyscreenshot.check.speedtest",
["--childprocess", childprocess_param] + bboxpar + debugpar + backendpar,
)
print(p.stdout)
@entrypoint
def speedtest(virtual_display=False, backend="", childprocess="", bbox="", number=10):
"""Performance test of all back-ends.
:param virtual_display: run with Xvfb
:param bbox: bounding box coordinates x1:y1:x2:y2
:param backend: back-end can be forced if set (example:default, scrot, wx,..),
otherwise all back-ends are tested
:param childprocess: pyscreenshot parameter childprocess (0/1)
:param number: number of screenshots for each backend (default:10)
"""
childprocess_param = childprocess
if childprocess == "":
childprocess = True # default
elif childprocess == "0":
childprocess = False
elif childprocess == "1":
childprocess = True
else:
raise ValueError("invalid childprocess value")
if bbox:
x1, y1, x2, y2 = map(int, bbox.split(":"))
bbox = x1, y1, x2, y2
else:
bbox = None
def f(virtual_only):
|
if virtual_display:
from pyvirtualdisplay import Display
with Display(visible=0):
f(virtual_only=True)
else:
f(virtual_only=False)
|
if backend:
try:
run(backend, number, childprocess, bbox=bbox)
except pyscreenshot.FailedBackendError:
pass
else:
run_all(number, childprocess_param, virtual_only=virtual_only, bbox=bbox)
|
identifier_body
|
dropout.py
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import sys
sys.path.append('./MNIST_data')
import os.path
from download import download
have_data = os.path.exists('MNIST_data/train-images-idx3-ubyte.gz')
if not have_data:
download('./MNIST_data')
# load data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
# batch
batch_size = 64
|
x = tf.placeholder(tf.float32, [None,784])
y = tf.placeholder(tf.float32, [None,10])
keep_prob = tf.placeholder(tf.float32)
# 神经网络结构 784-1000-500-10
w1 = tf.Variable(tf.truncated_normal([784,1000], stddev=0.1))
b1 = tf.Variable(tf.zeros([1000]) + 0.1)
l1 = tf.nn.tanh(tf.matmul(x, w1) + b1)
l1_drop = tf.nn.dropout(l1, keep_prob)
w2 = tf.Variable(tf.truncated_normal([1000, 500], stddev=0.1))
b2 = tf.Variable(tf.zeros([500]) + 0.1)
l2 = tf.nn.tanh(tf.matmul(l1_drop, w2) + b2)
l2_drop = tf.nn.dropout(l2, keep_prob)
w3 = tf.Variable(tf.truncated_normal([500, 10], stddev=0.1))
b3 = tf.Variable(tf.zeros([10]) + 0.1)
prediction = tf.nn.softmax(tf.matmul(l2_drop, w3) + b3)
# 二次代价函数 - 回归问题
# loss = tf.losses.mean_squared_error(y, prediction)
# 交叉墒-分类问题
loss = tf.losses.softmax_cross_entropy(y, prediction)
# 梯度下降法优化器
train = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
# save result to a bool array
# 1000 0000 00 -> 0
# 0100 0000 00 -> 1
# ...
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))
# correct rate, bool -> float ->mean
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
# init variable
sess.run(tf.global_variables_initializer())
for epoch in range(10):
for batch in range(n_batch):
# get a batch data and label
batch_x, batch_y = mnist.train.next_batch(batch_size)
sess.run(train, feed_dict={x:batch_x, y:batch_y, keep_prob:0.5})
acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels, keep_prob:1.0})
train_acc = sess.run(accuracy, feed_dict={x:mnist.train.images, y:mnist.train.labels, keep_prob:1.0})
print("Iter " + str(epoch + 1) + ", Testing Accuracy " + str(acc) + ", Training Accuracy " + str(train_acc))
|
n_batch = mnist.train.num_examples // batch_size
# in [60000, 28 * 28] out [60000, 10]
|
random_line_split
|
dropout.py
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import sys
sys.path.append('./MNIST_data')
import os.path
from download import download
have_data = os.path.exists('MNIST_data/train-images-idx3-ubyte.gz')
if not have_data:
download('./MNIST_data')
# load data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
# batch
batch_size = 64
n_batch = mnist.train.num_examples // batch_size
# in [60000, 28 * 28] out [60000, 10]
x = tf.placeholder(tf.float32, [None,784])
y = tf.placeholder(tf.float32, [None,10])
keep_prob = tf.placeholder(tf.float32)
# 神经网络结构 784-1000-500-10
w1 = tf.Variable(tf.truncated_normal([784,1000], stddev=0.1))
b1 = tf.Variable(tf.zeros([1000]) + 0.1)
l1 = tf.nn.tanh(tf.matmul(x, w1) + b1)
l1_drop = tf.nn.dropout(l1, keep_prob)
w2 = tf.Variable(tf.truncated_normal([1000, 500], stddev=0.1))
b2 = tf.Variable(tf.zeros([500]) + 0.1)
l2 = tf.nn.tanh(tf.matmul(l1_drop, w2) + b2)
l2_drop = tf.nn.dropout(l2, keep_prob)
w3 = tf.Variable(tf.truncated_normal([500, 10], stddev=0.1))
b3 = tf.Variable(tf.zeros([10]) + 0.1)
prediction = tf.nn.softmax(tf.matmul(l2_drop, w3) + b3)
# 二次代价函数 - 回归问题
# loss = tf.losses.mean_squared_error(y, prediction)
# 交叉墒-分类问题
loss = tf.losses.softmax_cross_entropy(y, prediction)
# 梯度下降法优化器
train = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
# save result to a bool array
# 1000 0000 00 -> 0
# 0100 0000 00 -> 1
# ...
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))
# correct rate, bool -> float ->mean
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
# init variable
sess.run(tf.global_variables_initializer())
for epoch in range(10):
for batch in range(n_batch):
# get a batch data and label
batch_x, batch_y = mnist.train.next_batch(batch_size)
|
ges, y:mnist.test.labels, keep_prob:1.0})
train_acc = sess.run(accuracy, feed_dict={x:mnist.train.images, y:mnist.train.labels, keep_prob:1.0})
print("Iter " + str(epoch + 1) + ", Testing Accuracy " + str(acc) + ", Training Accuracy " + str(train_acc))
|
sess.run(train, feed_dict={x:batch_x, y:batch_y, keep_prob:0.5})
acc = sess.run(accuracy, feed_dict={x:mnist.test.ima
|
conditional_block
|
message.js
|
var Message = function() {
this._data = {
'push_type': 1,
'android': {
'doings': 1
}
};
return this;
};
/*
* Notification bar上显示的标题
* 必须
*/
Message.prototype.title = function(title) {
return this.setAndroid('notification_title', title);
};
/*
* Notification bar上显示的内容
* 必须
*/
Message.prototype.content = function(content) {
return this.setAndroid('notification_content', content);
};
/*
* 系统小图标名称
* 该图标预置在客户端,在通知栏顶部展示
*/
Message.prototype.status_icon = function(status_icon) {
return this.setAndroid('notification_status_icon', status_icon);
};
/*
* 用户自定义 dict
* "extras":{"season":"Spring", "weather":"raining"}]
*/
Message.prototype.extras = function(extras) {
if (!Array.isArray(extras)) {
var extraArray = [];
var keys = Object.keys(extras);
keys.forEach(function(key){
var v = {};
v[key] = extras[key];
extraArray.push(v)
})
extras = extraArray
}
return this.setAndroid('extras', extras);
};
/*
* 推送范围
* 1:指定用户,必须指定tokens字段
* 2:所有人,无需指定tokens,tags,exclude_tags
* 3:一群人,必须指定tags或者exclude_tags字段
*/
Message.prototype.push_type = function(push_type) {
return this.set('push_type', push_type);
};
/*
* 用户标签,目前仅对android用户生效
* 样例:{"tags":[{"location":["ShangHai","GuangZhou"]},}"age":["20","30"]}]}
* 含义:在广州或者上海,并且年龄为20或30岁的用户
*/
Message.prototype.tags = function(tags) {
return this.set('tags', tags);
};
/*
* 需要剔除的用户的标签,目前仅对android用户生效
* 样例:{"exclude_tags":[{"music":["blue"]},{"fruit":["apple"]}]}
* 含义:不给喜欢蓝调音乐的用户,或者喜欢苹果的用户发送消息
*/
Message.prototype.exclude_tags = function(exclude_tags) {
return this.set('exclude_tags', exclude_tags);
};
/*
* 消息生效时间。如果不携带该字段,则表示消息实时生效。实际使用时,该字段精确到分
* 消息发送时间戳,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00
*/
Message.prototype.send_time = function(send_time) {
return this.set('send_time', send_time);
};
/*
* 消息过期删除时间
* 消息过期时间,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00
*/
Message.prototype.expire_time = function(expire_time) {
return this.set('expire_time', expire_time);
};
/*
* 目标设备类型
* 1:android
* 2:ios
* 默认为android
*/
Message.prototype.device_type = function(device_type) {
return this.set('device_type', device_type);
};
/*
* 1:直接打开应用
* 2:通过自定义动作打开应用
* 3:打开URL
* 4:富媒体消息
* 5:短信收件箱广告
* 6:彩信收件箱广告
* 注意:当手机收到短信、彩信收件箱广告后,在收件人一栏显示的是应用在联盟上注册的名字哦~
*/
Message.prototype.doings = function(doings) {
return this.setAndroid('doings', doings);
};
Message.prototype.setAndroid = function(key, value) {
this._data['android'][key] = value;
return this;
};
|
};
Message.prototype.getAndroidData = function() {
return this._data;
};
Message.prototype.getData = function() {
return this._data;
};
Message.prototype.toString = function() {
return JSON.stringify(this._data);
};
module.exports = Message;
|
Message.prototype.set = function(key, value) {
this._data[key] = value;
return this;
|
random_line_split
|
message.js
|
var Message = function() {
this._data = {
'push_type': 1,
'android': {
'doings': 1
}
};
return this;
};
/*
* Notification bar上显示的标题
* 必须
*/
Message.prototype.title = function(title) {
return this.setAndroid('notification_title', title);
};
/*
* Notification bar上显示的内容
* 必须
*/
Message.prototype.content = function(content) {
return this.setAndroid('notification_content', content);
};
/*
* 系统小图标名称
* 该图标预置在客户端,在通知栏顶部展示
*/
Message.prototype.status_icon = function(status_icon) {
return this.setAndroid('notification_status_icon', status_icon);
};
/*
* 用户自定义 dict
* "extras":{"season":"Spring", "weather":"raining"}]
*/
Message.prototype.extras = function(extras) {
if (!Array.isArray(extras)) {
var extraArray = [];
var keys = Object.keys(extras);
keys.forEach(function(key
|
无需指定tokens,tags,exclude_tags
* 3:一群人,必须指定tags或者exclude_tags字段
*/
Message.prototype.push_type = function(push_type) {
return this.set('push_type', push_type);
};
/*
* 用户标签,目前仅对android用户生效
* 样例:{"tags":[{"location":["ShangHai","GuangZhou"]},}"age":["20","30"]}]}
* 含义:在广州或者上海,并且年龄为20或30岁的用户
*/
Message.prototype.tags = function(tags) {
return this.set('tags', tags);
};
/*
* 需要剔除的用户的标签,目前仅对android用户生效
* 样例:{"exclude_tags":[{"music":["blue"]},{"fruit":["apple"]}]}
* 含义:不给喜欢蓝调音乐的用户,或者喜欢苹果的用户发送消息
*/
Message.prototype.exclude_tags = function(exclude_tags) {
return this.set('exclude_tags', exclude_tags);
};
/*
* 消息生效时间。如果不携带该字段,则表示消息实时生效。实际使用时,该字段精确到分
* 消息发送时间戳,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00
*/
Message.prototype.send_time = function(send_time) {
return this.set('send_time', send_time);
};
/*
* 消息过期删除时间
* 消息过期时间,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00
*/
Message.prototype.expire_time = function(expire_time) {
return this.set('expire_time', expire_time);
};
/*
* 目标设备类型
* 1:android
* 2:ios
* 默认为android
*/
Message.prototype.device_type = function(device_type) {
return this.set('device_type', device_type);
};
/*
* 1:直接打开应用
* 2:通过自定义动作打开应用
* 3:打开URL
* 4:富媒体消息
* 5:短信收件箱广告
* 6:彩信收件箱广告
* 注意:当手机收到短信、彩信收件箱广告后,在收件人一栏显示的是应用在联盟上注册的名字哦~
*/
Message.prototype.doings = function(doings) {
return this.setAndroid('doings', doings);
};
Message.prototype.setAndroid = function(key, value) {
this._data['android'][key] = value;
return this;
};
Message.prototype.set = function(key, value) {
this._data[key] = value;
return this;
};
Message.prototype.getAndroidData = function() {
return this._data;
};
Message.prototype.getData = function() {
return this._data;
};
Message.prototype.toString = function() {
return JSON.stringify(this._data);
};
module.exports = Message;
|
){
var v = {};
v[key] = extras[key];
extraArray.push(v)
})
extras = extraArray
}
return this.setAndroid('extras', extras);
};
/*
* 推送范围
* 1:指定用户,必须指定tokens字段
* 2:所有人,
|
conditional_block
|
asteroid-calendar.ja.ts
|
<?xml version="1.0" encoding="utf-8"?>
|
<message id="id-new-event">
<location filename="../src/EventDialog.qml" line="43"/>
<source>New Event</source>
<translation>新しいイベント</translation>
</message>
<message id="id-edit-event">
<location filename="../src/EventDialog.qml" line="45"/>
<source>Edit Event</source>
<translation>イベントを編集</translation>
</message>
<message id="id-title-field">
<location filename="../src/EventDialog.qml" line="90"/>
<source>Title</source>
<translation>タイトル</translation>
</message>
<message id="id-untitled-event">
<location filename="../src/EventDialog.qml" line="128"/>
<source>Untitled event</source>
<translation>無題のイベント</translation>
</message>
<message id="id-events-recap">
<location filename="../src/main.qml" line="238"/>
<source>%1 Events on %2 %3/%4/%5</source>
<translation>%1 のイベント %2 %3/%4/%5</translation>
</message>
<message id="id-app-launcher-name">
<location filename="asteroid-calendar.desktop.h" line="6"/>
<source>Agenda</source>
<translation>日程</translation>
</message>
<message id="id-month-page">
<location filename="../src/MonthSelector.qml" line="28"/>
<source>Month</source>
<translation>月</translation>
</message>
</context>
</TS>
|
<!DOCTYPE TS>
<TS version="2.1" language="ja">
<context>
<name></name>
|
random_line_split
|
tests.py
|
"""
Tests for course_info
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.tests.factories import UserFactory
from courseware.tests.tests import TEST_DATA_MONGO_MODULESTORE
@override_settings(MODULESTORE=TEST_DATA_MONGO_MODULESTORE)
class TestVideoOutline(ModuleStoreTestCase, APITestCase):
"""
Tests for /api/mobile/v0.5/course_info/...
"""
def setUp(self):
super(TestVideoOutline, self).setUp()
self.user = UserFactory.create()
self.course = CourseFactory.create(mobile_available=True)
self.client.login(username=self.user.username, password='test')
def test_about(self):
|
def test_handouts(self):
url = reverse('course-handouts-list', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_updates(self):
url = reverse('course-updates-list', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, []) # pylint: disable=E1103
# TODO: add handouts and updates, somehow
|
url = reverse('course-about-detail', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTrue('overview' in response.data) # pylint: disable=E1103
|
identifier_body
|
tests.py
|
"""
Tests for course_info
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.tests.factories import UserFactory
from courseware.tests.tests import TEST_DATA_MONGO_MODULESTORE
@override_settings(MODULESTORE=TEST_DATA_MONGO_MODULESTORE)
class TestVideoOutline(ModuleStoreTestCase, APITestCase):
"""
Tests for /api/mobile/v0.5/course_info/...
"""
|
self.course = CourseFactory.create(mobile_available=True)
self.client.login(username=self.user.username, password='test')
def test_about(self):
url = reverse('course-about-detail', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTrue('overview' in response.data) # pylint: disable=E1103
def test_handouts(self):
url = reverse('course-handouts-list', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_updates(self):
url = reverse('course-updates-list', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, []) # pylint: disable=E1103
# TODO: add handouts and updates, somehow
|
def setUp(self):
super(TestVideoOutline, self).setUp()
self.user = UserFactory.create()
|
random_line_split
|
tests.py
|
"""
Tests for course_info
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.tests.factories import UserFactory
from courseware.tests.tests import TEST_DATA_MONGO_MODULESTORE
@override_settings(MODULESTORE=TEST_DATA_MONGO_MODULESTORE)
class TestVideoOutline(ModuleStoreTestCase, APITestCase):
"""
Tests for /api/mobile/v0.5/course_info/...
"""
def setUp(self):
super(TestVideoOutline, self).setUp()
self.user = UserFactory.create()
self.course = CourseFactory.create(mobile_available=True)
self.client.login(username=self.user.username, password='test')
def
|
(self):
url = reverse('course-about-detail', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTrue('overview' in response.data) # pylint: disable=E1103
def test_handouts(self):
url = reverse('course-handouts-list', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_updates(self):
url = reverse('course-updates-list', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, []) # pylint: disable=E1103
# TODO: add handouts and updates, somehow
|
test_about
|
identifier_name
|
timer_scheduler.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 ipc_channel::ipc::{self, IpcSender};
use script_traits::{TimerEvent, TimerEventRequest, TimerSchedulerMsg};
use std::cmp::{self, Ord};
use std::collections::BinaryHeap;
use std::sync::mpsc;
use std::sync::mpsc::TryRecvError::{Disconnected, Empty};
use std::thread;
use std::time::{Duration, Instant};
pub struct TimerScheduler;
struct ScheduledEvent {
request: TimerEventRequest,
for_time: Instant,
}
impl Ord for ScheduledEvent {
fn cmp(&self, other: &ScheduledEvent) -> cmp::Ordering {
self.for_time.cmp(&other.for_time).reverse()
}
}
impl PartialOrd for ScheduledEvent {
fn partial_cmp(&self, other: &ScheduledEvent) -> Option<cmp::Ordering>
|
}
impl Eq for ScheduledEvent {}
impl PartialEq for ScheduledEvent {
fn eq(&self, other: &ScheduledEvent) -> bool {
self as *const ScheduledEvent == other as *const ScheduledEvent
}
}
impl TimerScheduler {
pub fn start() -> IpcSender<TimerSchedulerMsg> {
let (req_ipc_sender, req_ipc_receiver) = ipc::channel().expect("Channel creation failed.");
let (req_sender, req_receiver) = mpsc::sync_channel(1);
// We could do this much more directly with recv_timeout
// (https://github.com/rust-lang/rfcs/issues/962).
// util::thread doesn't give us access to the JoinHandle, which we need for park/unpark,
// so we use the builder directly.
let timeout_thread = thread::Builder::new()
.name(String::from("TimerScheduler"))
.spawn(move || {
// We maintain a priority queue of future events, sorted by due time.
let mut scheduled_events = BinaryHeap::<ScheduledEvent>::new();
loop {
let now = Instant::now();
// Dispatch any events whose due time is past
loop {
match scheduled_events.peek() {
// Dispatch the event if its due time is past
Some(event) if event.for_time <= now => {
let TimerEventRequest(ref sender, source, id, _) = event.request;
let _ = sender.send(TimerEvent(source, id));
},
// Otherwise, we're done dispatching events
_ => break,
}
// Remove the event from the priority queue
// (Note this only executes when the first event has been dispatched
scheduled_events.pop();
}
// Look to see if there are any incoming events
match req_receiver.try_recv() {
// If there is an event, add it to the priority queue
Ok(TimerSchedulerMsg::Request(req)) => {
let TimerEventRequest(_, _, _, delay) = req;
let schedule = Instant::now() + Duration::from_millis(delay.get());
let event = ScheduledEvent { request: req, for_time: schedule };
scheduled_events.push(event);
},
// If there is no incoming event, park the thread,
// it will either be unparked when a new event arrives,
// or by a timeout.
Err(Empty) => match scheduled_events.peek() {
None => thread::park(),
Some(event) => thread::park_timeout(event.for_time - now),
},
// If the channel is closed or we are shutting down, we are done.
Ok(TimerSchedulerMsg::Exit) |
Err(Disconnected) => break,
}
}
// This thread can terminate if the req_ipc_sender is dropped.
warn!("TimerScheduler thread terminated.");
})
.expect("Thread creation failed.")
.thread()
.clone();
// A proxy that just routes incoming IPC requests over the MPSC channel to the timeout thread,
// and unparks the timeout thread each time. Note that if unpark is called while the timeout
// thread isn't parked, this causes the next call to thread::park by the timeout thread
// not to block. This means that the timeout thread won't park when there is a request
// waiting in the MPSC channel buffer.
thread::Builder::new()
.name(String::from("TimerProxy"))
.spawn(move || {
while let Ok(req) = req_ipc_receiver.recv() {
let mut shutting_down = false;
match req {
TimerSchedulerMsg::Exit => shutting_down = true,
_ => {}
}
let _ = req_sender.send(req);
timeout_thread.unpark();
if shutting_down {
break;
}
}
// This thread can terminate if the req_ipc_sender is dropped.
warn!("TimerProxy thread terminated.");
})
.expect("Thread creation failed.");
// Return the IPC sender
req_ipc_sender
}
}
|
{
Some(self.cmp(other))
}
|
identifier_body
|
timer_scheduler.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 ipc_channel::ipc::{self, IpcSender};
use script_traits::{TimerEvent, TimerEventRequest, TimerSchedulerMsg};
use std::cmp::{self, Ord};
use std::collections::BinaryHeap;
use std::sync::mpsc;
use std::sync::mpsc::TryRecvError::{Disconnected, Empty};
use std::thread;
use std::time::{Duration, Instant};
pub struct
|
;
struct ScheduledEvent {
request: TimerEventRequest,
for_time: Instant,
}
impl Ord for ScheduledEvent {
fn cmp(&self, other: &ScheduledEvent) -> cmp::Ordering {
self.for_time.cmp(&other.for_time).reverse()
}
}
impl PartialOrd for ScheduledEvent {
fn partial_cmp(&self, other: &ScheduledEvent) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Eq for ScheduledEvent {}
impl PartialEq for ScheduledEvent {
fn eq(&self, other: &ScheduledEvent) -> bool {
self as *const ScheduledEvent == other as *const ScheduledEvent
}
}
impl TimerScheduler {
pub fn start() -> IpcSender<TimerSchedulerMsg> {
let (req_ipc_sender, req_ipc_receiver) = ipc::channel().expect("Channel creation failed.");
let (req_sender, req_receiver) = mpsc::sync_channel(1);
// We could do this much more directly with recv_timeout
// (https://github.com/rust-lang/rfcs/issues/962).
// util::thread doesn't give us access to the JoinHandle, which we need for park/unpark,
// so we use the builder directly.
let timeout_thread = thread::Builder::new()
.name(String::from("TimerScheduler"))
.spawn(move || {
// We maintain a priority queue of future events, sorted by due time.
let mut scheduled_events = BinaryHeap::<ScheduledEvent>::new();
loop {
let now = Instant::now();
// Dispatch any events whose due time is past
loop {
match scheduled_events.peek() {
// Dispatch the event if its due time is past
Some(event) if event.for_time <= now => {
let TimerEventRequest(ref sender, source, id, _) = event.request;
let _ = sender.send(TimerEvent(source, id));
},
// Otherwise, we're done dispatching events
_ => break,
}
// Remove the event from the priority queue
// (Note this only executes when the first event has been dispatched
scheduled_events.pop();
}
// Look to see if there are any incoming events
match req_receiver.try_recv() {
// If there is an event, add it to the priority queue
Ok(TimerSchedulerMsg::Request(req)) => {
let TimerEventRequest(_, _, _, delay) = req;
let schedule = Instant::now() + Duration::from_millis(delay.get());
let event = ScheduledEvent { request: req, for_time: schedule };
scheduled_events.push(event);
},
// If there is no incoming event, park the thread,
// it will either be unparked when a new event arrives,
// or by a timeout.
Err(Empty) => match scheduled_events.peek() {
None => thread::park(),
Some(event) => thread::park_timeout(event.for_time - now),
},
// If the channel is closed or we are shutting down, we are done.
Ok(TimerSchedulerMsg::Exit) |
Err(Disconnected) => break,
}
}
// This thread can terminate if the req_ipc_sender is dropped.
warn!("TimerScheduler thread terminated.");
})
.expect("Thread creation failed.")
.thread()
.clone();
// A proxy that just routes incoming IPC requests over the MPSC channel to the timeout thread,
// and unparks the timeout thread each time. Note that if unpark is called while the timeout
// thread isn't parked, this causes the next call to thread::park by the timeout thread
// not to block. This means that the timeout thread won't park when there is a request
// waiting in the MPSC channel buffer.
thread::Builder::new()
.name(String::from("TimerProxy"))
.spawn(move || {
while let Ok(req) = req_ipc_receiver.recv() {
let mut shutting_down = false;
match req {
TimerSchedulerMsg::Exit => shutting_down = true,
_ => {}
}
let _ = req_sender.send(req);
timeout_thread.unpark();
if shutting_down {
break;
}
}
// This thread can terminate if the req_ipc_sender is dropped.
warn!("TimerProxy thread terminated.");
})
.expect("Thread creation failed.");
// Return the IPC sender
req_ipc_sender
}
}
|
TimerScheduler
|
identifier_name
|
timer_scheduler.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 ipc_channel::ipc::{self, IpcSender};
use script_traits::{TimerEvent, TimerEventRequest, TimerSchedulerMsg};
use std::cmp::{self, Ord};
use std::collections::BinaryHeap;
use std::sync::mpsc;
use std::sync::mpsc::TryRecvError::{Disconnected, Empty};
use std::thread;
use std::time::{Duration, Instant};
pub struct TimerScheduler;
struct ScheduledEvent {
request: TimerEventRequest,
for_time: Instant,
}
impl Ord for ScheduledEvent {
fn cmp(&self, other: &ScheduledEvent) -> cmp::Ordering {
self.for_time.cmp(&other.for_time).reverse()
}
}
impl PartialOrd for ScheduledEvent {
fn partial_cmp(&self, other: &ScheduledEvent) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Eq for ScheduledEvent {}
impl PartialEq for ScheduledEvent {
fn eq(&self, other: &ScheduledEvent) -> bool {
self as *const ScheduledEvent == other as *const ScheduledEvent
}
}
impl TimerScheduler {
pub fn start() -> IpcSender<TimerSchedulerMsg> {
let (req_ipc_sender, req_ipc_receiver) = ipc::channel().expect("Channel creation failed.");
let (req_sender, req_receiver) = mpsc::sync_channel(1);
// We could do this much more directly with recv_timeout
// (https://github.com/rust-lang/rfcs/issues/962).
// util::thread doesn't give us access to the JoinHandle, which we need for park/unpark,
// so we use the builder directly.
let timeout_thread = thread::Builder::new()
.name(String::from("TimerScheduler"))
.spawn(move || {
|
// We maintain a priority queue of future events, sorted by due time.
let mut scheduled_events = BinaryHeap::<ScheduledEvent>::new();
loop {
let now = Instant::now();
// Dispatch any events whose due time is past
loop {
match scheduled_events.peek() {
// Dispatch the event if its due time is past
Some(event) if event.for_time <= now => {
let TimerEventRequest(ref sender, source, id, _) = event.request;
let _ = sender.send(TimerEvent(source, id));
},
// Otherwise, we're done dispatching events
_ => break,
}
// Remove the event from the priority queue
// (Note this only executes when the first event has been dispatched
scheduled_events.pop();
}
// Look to see if there are any incoming events
match req_receiver.try_recv() {
// If there is an event, add it to the priority queue
Ok(TimerSchedulerMsg::Request(req)) => {
let TimerEventRequest(_, _, _, delay) = req;
let schedule = Instant::now() + Duration::from_millis(delay.get());
let event = ScheduledEvent { request: req, for_time: schedule };
scheduled_events.push(event);
},
// If there is no incoming event, park the thread,
// it will either be unparked when a new event arrives,
// or by a timeout.
Err(Empty) => match scheduled_events.peek() {
None => thread::park(),
Some(event) => thread::park_timeout(event.for_time - now),
},
// If the channel is closed or we are shutting down, we are done.
Ok(TimerSchedulerMsg::Exit) |
Err(Disconnected) => break,
}
}
// This thread can terminate if the req_ipc_sender is dropped.
warn!("TimerScheduler thread terminated.");
})
.expect("Thread creation failed.")
.thread()
.clone();
// A proxy that just routes incoming IPC requests over the MPSC channel to the timeout thread,
// and unparks the timeout thread each time. Note that if unpark is called while the timeout
// thread isn't parked, this causes the next call to thread::park by the timeout thread
// not to block. This means that the timeout thread won't park when there is a request
// waiting in the MPSC channel buffer.
thread::Builder::new()
.name(String::from("TimerProxy"))
.spawn(move || {
while let Ok(req) = req_ipc_receiver.recv() {
let mut shutting_down = false;
match req {
TimerSchedulerMsg::Exit => shutting_down = true,
_ => {}
}
let _ = req_sender.send(req);
timeout_thread.unpark();
if shutting_down {
break;
}
}
// This thread can terminate if the req_ipc_sender is dropped.
warn!("TimerProxy thread terminated.");
})
.expect("Thread creation failed.");
// Return the IPC sender
req_ipc_sender
}
}
|
random_line_split
|
|
karma.conf.js
|
(function() {
'use strict';
var bowerFiles = require('bower-files')();
var config = require('./gulp/config');
function listFiles() {
var files = []
.concat(bowerFiles.dev().ext('js').files)
.concat([
config.sourceDir + 'app/**/*.html',
config.sourceDir + 'app/**/*.js',
]);
return files;
}
function listPreprocessors() {
var preprocessors = {};
preprocessors[config.sourceDir + 'app/**/*.html'] = ['ng-html2js'];
preprocessors[config.sourceDir + 'app/**/!(*.spec|*.mock).js'] = ['coverage'];
return preprocessors;
}
module.exports = function(karmaConfig) {
|
karmaConfig.set({
files: listFiles(),
browsers: ['PhantomJS'],
frameworks: ['jasmine', 'angular-filesort'],
preprocessors: listPreprocessors(),
ngHtml2JsPreprocessor: {
stripPrefix: config.sourceDir,
moduleName: 'templateCache'
},
angularFilesort: {
whitelist: [
config.sourceDir + 'app/**/!*.html',
config.sourceDir + 'app/**/!(*.spec|*.mock).js'
]
},
reporters: ['progress', 'coverage', 'html'],
coverageReporter: {
dir: config.coverageDir,
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
]
}
});
};
})();
|
random_line_split
|
|
karma.conf.js
|
(function() {
'use strict';
var bowerFiles = require('bower-files')();
var config = require('./gulp/config');
function
|
() {
var files = []
.concat(bowerFiles.dev().ext('js').files)
.concat([
config.sourceDir + 'app/**/*.html',
config.sourceDir + 'app/**/*.js',
]);
return files;
}
function listPreprocessors() {
var preprocessors = {};
preprocessors[config.sourceDir + 'app/**/*.html'] = ['ng-html2js'];
preprocessors[config.sourceDir + 'app/**/!(*.spec|*.mock).js'] = ['coverage'];
return preprocessors;
}
module.exports = function(karmaConfig) {
karmaConfig.set({
files: listFiles(),
browsers: ['PhantomJS'],
frameworks: ['jasmine', 'angular-filesort'],
preprocessors: listPreprocessors(),
ngHtml2JsPreprocessor: {
stripPrefix: config.sourceDir,
moduleName: 'templateCache'
},
angularFilesort: {
whitelist: [
config.sourceDir + 'app/**/!*.html',
config.sourceDir + 'app/**/!(*.spec|*.mock).js'
]
},
reporters: ['progress', 'coverage', 'html'],
coverageReporter: {
dir: config.coverageDir,
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
]
}
});
};
})();
|
listFiles
|
identifier_name
|
karma.conf.js
|
(function() {
'use strict';
var bowerFiles = require('bower-files')();
var config = require('./gulp/config');
function listFiles() {
var files = []
.concat(bowerFiles.dev().ext('js').files)
.concat([
config.sourceDir + 'app/**/*.html',
config.sourceDir + 'app/**/*.js',
]);
return files;
}
function listPreprocessors()
|
module.exports = function(karmaConfig) {
karmaConfig.set({
files: listFiles(),
browsers: ['PhantomJS'],
frameworks: ['jasmine', 'angular-filesort'],
preprocessors: listPreprocessors(),
ngHtml2JsPreprocessor: {
stripPrefix: config.sourceDir,
moduleName: 'templateCache'
},
angularFilesort: {
whitelist: [
config.sourceDir + 'app/**/!*.html',
config.sourceDir + 'app/**/!(*.spec|*.mock).js'
]
},
reporters: ['progress', 'coverage', 'html'],
coverageReporter: {
dir: config.coverageDir,
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
]
}
});
};
})();
|
{
var preprocessors = {};
preprocessors[config.sourceDir + 'app/**/*.html'] = ['ng-html2js'];
preprocessors[config.sourceDir + 'app/**/!(*.spec|*.mock).js'] = ['coverage'];
return preprocessors;
}
|
identifier_body
|
end-target.js
|
var BaseTween = require('tween-base')
var isArray = require('an-array')
var ownKeys = require('own-enumerable-keys')
var ignores = ownKeys(new BaseTween())
module.exports = function getTargets(element, opt) {
var targets = []
var optKeys = ownKeys(opt)
for (var k in opt) {
|
//copy properties as needed
if (optKeys.indexOf(k) >= 0 &&
k in element &&
ignores.indexOf(k) === -1) {
var startVal = element[k]
var endVal = opt[k]
if (typeof startVal === 'number'
&& typeof endVal === 'number') {
targets.push({
key: k,
start: startVal,
end: endVal
})
}
else if (isArray(startVal) && isArray(endVal)) {
targets.push({
key: k,
start: startVal.slice(),
end: endVal.slice()
})
}
}
}
return targets
}
|
random_line_split
|
|
overlay.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 {Directionality} from '@angular/cdk/bidi';
import {DomPortalOutlet} from '@angular/cdk/portal';
import {DOCUMENT, Location} from '@angular/common';
import {
ApplicationRef,
ComponentFactoryResolver,
Inject,
Injectable,
Injector,
NgZone,
Optional,
} from '@angular/core';
import {OverlayKeyboardDispatcher} from './keyboard/overlay-keyboard-dispatcher';
import {OverlayConfig} from './overlay-config';
import {OverlayContainer} from './overlay-container';
import {OverlayRef} from './overlay-ref';
import {OverlayPositionBuilder} from './position/overlay-position-builder';
import {ScrollStrategyOptions} from './scroll/index';
/** Next overlay unique ID. */
let nextUniqueId = 0;
// Note that Overlay is *not* scoped to the app root because the ComponentFactoryResolver
// it needs is different based on where OverlayModule is imported.
/**
* Service to create Overlays. Overlays are dynamically added pieces of floating UI, meant to be
* used as a low-level building block for other components. Dialogs, tooltips, menus,
* selects, etc. can all be built using overlays. The service should primarily be used by authors
* of re-usable components rather than developers building end-user applications.
*
* An overlay *is* a PortalOutlet, so any kind of Portal can be loaded into one.
*/
@Injectable()
export class Overlay {
private _appRef: ApplicationRef;
constructor(
/** Scrolling strategies that can be used when creating an overlay. */
public scrollStrategies: ScrollStrategyOptions,
private _overlayContainer: OverlayContainer,
private _componentFactoryResolver: ComponentFactoryResolver,
private _positionBuilder: OverlayPositionBuilder,
private _keyboardDispatcher: OverlayKeyboardDispatcher,
private _injector: Injector,
private _ngZone: NgZone,
@Inject(DOCUMENT) private _document: any,
private _directionality: Directionality,
// @breaking-change 8.0.0 `_location` parameter to be made required.
@Optional() private _location?: Location) { }
/**
* Creates an overlay.
* @param config Configuration applied to the overlay.
* @returns Reference to the created overlay.
*/
create(config?: OverlayConfig): OverlayRef {
const host = this._createHostElement();
const pane = this._createPaneElement(host);
const portalOutlet = this._createPortalOutlet(pane);
const overlayConfig = new OverlayConfig(config);
overlayConfig.direction = overlayConfig.direction || this._directionality.value;
return new OverlayRef(portalOutlet, host, pane, overlayConfig, this._ngZone,
this._keyboardDispatcher, this._document, this._location);
}
/**
* Gets a position builder that can be used, via fluent API,
* to construct and configure a position strategy.
* @returns An overlay position builder.
*/
position(): OverlayPositionBuilder {
return this._positionBuilder;
}
/**
* Creates the DOM element for an overlay and appends it to the overlay container.
* @returns Newly-created pane element
*/
private _createPaneElement(host: HTMLElement): HTMLElement {
const pane = this._document.createElement('div');
pane.id = `cdk-overlay-${nextUniqueId++}`;
pane.classList.add('cdk-overlay-pane');
host.appendChild(pane);
return pane;
}
/**
* Creates the host element that wraps around an overlay
* and can be used for advanced positioning.
* @returns Newly-create host element.
*/
private _createHostElement(): HTMLElement {
const host = this._document.createElement('div');
this._overlayContainer.getContainerElement().appendChild(host);
return host;
}
/**
* Create a DomPortalOutlet into which the overlay content can be loaded.
* @param pane The DOM element to turn into a portal outlet.
* @returns A portal outlet for the given DOM element.
*/
private _createPortalOutlet(pane: HTMLElement): DomPortalOutlet {
// We have to resolve the ApplicationRef later in order to allow people
// to use overlay-based providers during app initialization.
if (!this._appRef)
|
return new DomPortalOutlet(pane, this._componentFactoryResolver, this._appRef, this._injector);
}
}
|
{
this._appRef = this._injector.get<ApplicationRef>(ApplicationRef);
}
|
conditional_block
|
overlay.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 {Directionality} from '@angular/cdk/bidi';
import {DomPortalOutlet} from '@angular/cdk/portal';
import {DOCUMENT, Location} from '@angular/common';
import {
ApplicationRef,
ComponentFactoryResolver,
Inject,
Injectable,
Injector,
NgZone,
Optional,
} from '@angular/core';
import {OverlayKeyboardDispatcher} from './keyboard/overlay-keyboard-dispatcher';
import {OverlayConfig} from './overlay-config';
import {OverlayContainer} from './overlay-container';
import {OverlayRef} from './overlay-ref';
import {OverlayPositionBuilder} from './position/overlay-position-builder';
import {ScrollStrategyOptions} from './scroll/index';
/** Next overlay unique ID. */
let nextUniqueId = 0;
// Note that Overlay is *not* scoped to the app root because the ComponentFactoryResolver
// it needs is different based on where OverlayModule is imported.
/**
* Service to create Overlays. Overlays are dynamically added pieces of floating UI, meant to be
* used as a low-level building block for other components. Dialogs, tooltips, menus,
* selects, etc. can all be built using overlays. The service should primarily be used by authors
* of re-usable components rather than developers building end-user applications.
*
* An overlay *is* a PortalOutlet, so any kind of Portal can be loaded into one.
*/
@Injectable()
export class Overlay {
private _appRef: ApplicationRef;
constructor(
/** Scrolling strategies that can be used when creating an overlay. */
public scrollStrategies: ScrollStrategyOptions,
private _overlayContainer: OverlayContainer,
private _componentFactoryResolver: ComponentFactoryResolver,
private _positionBuilder: OverlayPositionBuilder,
private _keyboardDispatcher: OverlayKeyboardDispatcher,
private _injector: Injector,
private _ngZone: NgZone,
@Inject(DOCUMENT) private _document: any,
private _directionality: Directionality,
// @breaking-change 8.0.0 `_location` parameter to be made required.
@Optional() private _location?: Location) { }
/**
* Creates an overlay.
* @param config Configuration applied to the overlay.
* @returns Reference to the created overlay.
*/
create(config?: OverlayConfig): OverlayRef {
const host = this._createHostElement();
const pane = this._createPaneElement(host);
const portalOutlet = this._createPortalOutlet(pane);
const overlayConfig = new OverlayConfig(config);
overlayConfig.direction = overlayConfig.direction || this._directionality.value;
return new OverlayRef(portalOutlet, host, pane, overlayConfig, this._ngZone,
this._keyboardDispatcher, this._document, this._location);
}
/**
* Gets a position builder that can be used, via fluent API,
* to construct and configure a position strategy.
* @returns An overlay position builder.
*/
position(): OverlayPositionBuilder {
return this._positionBuilder;
}
/**
* Creates the DOM element for an overlay and appends it to the overlay container.
* @returns Newly-created pane element
*/
private _createPaneElement(host: HTMLElement): HTMLElement {
const pane = this._document.createElement('div');
pane.id = `cdk-overlay-${nextUniqueId++}`;
pane.classList.add('cdk-overlay-pane');
host.appendChild(pane);
return pane;
}
/**
* Creates the host element that wraps around an overlay
* and can be used for advanced positioning.
* @returns Newly-create host element.
*/
private
|
(): HTMLElement {
const host = this._document.createElement('div');
this._overlayContainer.getContainerElement().appendChild(host);
return host;
}
/**
* Create a DomPortalOutlet into which the overlay content can be loaded.
* @param pane The DOM element to turn into a portal outlet.
* @returns A portal outlet for the given DOM element.
*/
private _createPortalOutlet(pane: HTMLElement): DomPortalOutlet {
// We have to resolve the ApplicationRef later in order to allow people
// to use overlay-based providers during app initialization.
if (!this._appRef) {
this._appRef = this._injector.get<ApplicationRef>(ApplicationRef);
}
return new DomPortalOutlet(pane, this._componentFactoryResolver, this._appRef, this._injector);
}
}
|
_createHostElement
|
identifier_name
|
overlay.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 {Directionality} from '@angular/cdk/bidi';
import {DomPortalOutlet} from '@angular/cdk/portal';
import {DOCUMENT, Location} from '@angular/common';
import {
ApplicationRef,
ComponentFactoryResolver,
Inject,
Injectable,
Injector,
NgZone,
Optional,
} from '@angular/core';
import {OverlayKeyboardDispatcher} from './keyboard/overlay-keyboard-dispatcher';
import {OverlayConfig} from './overlay-config';
import {OverlayContainer} from './overlay-container';
import {OverlayRef} from './overlay-ref';
import {OverlayPositionBuilder} from './position/overlay-position-builder';
import {ScrollStrategyOptions} from './scroll/index';
/** Next overlay unique ID. */
let nextUniqueId = 0;
// Note that Overlay is *not* scoped to the app root because the ComponentFactoryResolver
|
/**
* Service to create Overlays. Overlays are dynamically added pieces of floating UI, meant to be
* used as a low-level building block for other components. Dialogs, tooltips, menus,
* selects, etc. can all be built using overlays. The service should primarily be used by authors
* of re-usable components rather than developers building end-user applications.
*
* An overlay *is* a PortalOutlet, so any kind of Portal can be loaded into one.
*/
@Injectable()
export class Overlay {
private _appRef: ApplicationRef;
constructor(
/** Scrolling strategies that can be used when creating an overlay. */
public scrollStrategies: ScrollStrategyOptions,
private _overlayContainer: OverlayContainer,
private _componentFactoryResolver: ComponentFactoryResolver,
private _positionBuilder: OverlayPositionBuilder,
private _keyboardDispatcher: OverlayKeyboardDispatcher,
private _injector: Injector,
private _ngZone: NgZone,
@Inject(DOCUMENT) private _document: any,
private _directionality: Directionality,
// @breaking-change 8.0.0 `_location` parameter to be made required.
@Optional() private _location?: Location) { }
/**
* Creates an overlay.
* @param config Configuration applied to the overlay.
* @returns Reference to the created overlay.
*/
create(config?: OverlayConfig): OverlayRef {
const host = this._createHostElement();
const pane = this._createPaneElement(host);
const portalOutlet = this._createPortalOutlet(pane);
const overlayConfig = new OverlayConfig(config);
overlayConfig.direction = overlayConfig.direction || this._directionality.value;
return new OverlayRef(portalOutlet, host, pane, overlayConfig, this._ngZone,
this._keyboardDispatcher, this._document, this._location);
}
/**
* Gets a position builder that can be used, via fluent API,
* to construct and configure a position strategy.
* @returns An overlay position builder.
*/
position(): OverlayPositionBuilder {
return this._positionBuilder;
}
/**
* Creates the DOM element for an overlay and appends it to the overlay container.
* @returns Newly-created pane element
*/
private _createPaneElement(host: HTMLElement): HTMLElement {
const pane = this._document.createElement('div');
pane.id = `cdk-overlay-${nextUniqueId++}`;
pane.classList.add('cdk-overlay-pane');
host.appendChild(pane);
return pane;
}
/**
* Creates the host element that wraps around an overlay
* and can be used for advanced positioning.
* @returns Newly-create host element.
*/
private _createHostElement(): HTMLElement {
const host = this._document.createElement('div');
this._overlayContainer.getContainerElement().appendChild(host);
return host;
}
/**
* Create a DomPortalOutlet into which the overlay content can be loaded.
* @param pane The DOM element to turn into a portal outlet.
* @returns A portal outlet for the given DOM element.
*/
private _createPortalOutlet(pane: HTMLElement): DomPortalOutlet {
// We have to resolve the ApplicationRef later in order to allow people
// to use overlay-based providers during app initialization.
if (!this._appRef) {
this._appRef = this._injector.get<ApplicationRef>(ApplicationRef);
}
return new DomPortalOutlet(pane, this._componentFactoryResolver, this._appRef, this._injector);
}
}
|
// it needs is different based on where OverlayModule is imported.
|
random_line_split
|
overlay.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 {Directionality} from '@angular/cdk/bidi';
import {DomPortalOutlet} from '@angular/cdk/portal';
import {DOCUMENT, Location} from '@angular/common';
import {
ApplicationRef,
ComponentFactoryResolver,
Inject,
Injectable,
Injector,
NgZone,
Optional,
} from '@angular/core';
import {OverlayKeyboardDispatcher} from './keyboard/overlay-keyboard-dispatcher';
import {OverlayConfig} from './overlay-config';
import {OverlayContainer} from './overlay-container';
import {OverlayRef} from './overlay-ref';
import {OverlayPositionBuilder} from './position/overlay-position-builder';
import {ScrollStrategyOptions} from './scroll/index';
/** Next overlay unique ID. */
let nextUniqueId = 0;
// Note that Overlay is *not* scoped to the app root because the ComponentFactoryResolver
// it needs is different based on where OverlayModule is imported.
/**
* Service to create Overlays. Overlays are dynamically added pieces of floating UI, meant to be
* used as a low-level building block for other components. Dialogs, tooltips, menus,
* selects, etc. can all be built using overlays. The service should primarily be used by authors
* of re-usable components rather than developers building end-user applications.
*
* An overlay *is* a PortalOutlet, so any kind of Portal can be loaded into one.
*/
@Injectable()
export class Overlay {
private _appRef: ApplicationRef;
constructor(
/** Scrolling strategies that can be used when creating an overlay. */
public scrollStrategies: ScrollStrategyOptions,
private _overlayContainer: OverlayContainer,
private _componentFactoryResolver: ComponentFactoryResolver,
private _positionBuilder: OverlayPositionBuilder,
private _keyboardDispatcher: OverlayKeyboardDispatcher,
private _injector: Injector,
private _ngZone: NgZone,
@Inject(DOCUMENT) private _document: any,
private _directionality: Directionality,
// @breaking-change 8.0.0 `_location` parameter to be made required.
@Optional() private _location?: Location) { }
/**
* Creates an overlay.
* @param config Configuration applied to the overlay.
* @returns Reference to the created overlay.
*/
create(config?: OverlayConfig): OverlayRef {
const host = this._createHostElement();
const pane = this._createPaneElement(host);
const portalOutlet = this._createPortalOutlet(pane);
const overlayConfig = new OverlayConfig(config);
overlayConfig.direction = overlayConfig.direction || this._directionality.value;
return new OverlayRef(portalOutlet, host, pane, overlayConfig, this._ngZone,
this._keyboardDispatcher, this._document, this._location);
}
/**
* Gets a position builder that can be used, via fluent API,
* to construct and configure a position strategy.
* @returns An overlay position builder.
*/
position(): OverlayPositionBuilder
|
/**
* Creates the DOM element for an overlay and appends it to the overlay container.
* @returns Newly-created pane element
*/
private _createPaneElement(host: HTMLElement): HTMLElement {
const pane = this._document.createElement('div');
pane.id = `cdk-overlay-${nextUniqueId++}`;
pane.classList.add('cdk-overlay-pane');
host.appendChild(pane);
return pane;
}
/**
* Creates the host element that wraps around an overlay
* and can be used for advanced positioning.
* @returns Newly-create host element.
*/
private _createHostElement(): HTMLElement {
const host = this._document.createElement('div');
this._overlayContainer.getContainerElement().appendChild(host);
return host;
}
/**
* Create a DomPortalOutlet into which the overlay content can be loaded.
* @param pane The DOM element to turn into a portal outlet.
* @returns A portal outlet for the given DOM element.
*/
private _createPortalOutlet(pane: HTMLElement): DomPortalOutlet {
// We have to resolve the ApplicationRef later in order to allow people
// to use overlay-based providers during app initialization.
if (!this._appRef) {
this._appRef = this._injector.get<ApplicationRef>(ApplicationRef);
}
return new DomPortalOutlet(pane, this._componentFactoryResolver, this._appRef, this._injector);
}
}
|
{
return this._positionBuilder;
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.