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 |
---|---|---|---|---|
typedParser.ts
|
import { IParser } from './iParser'
import { ParseFailure, ParseResult, ParseSuccess } from './parseResult'
export interface TypedValue {}
export interface TypedConstructor<T extends TypedValue> {
new (value: any): T
}
export class
|
<V, T extends TypedValue> implements IParser<T> {
ctor: TypedConstructor<T>
parser: IParser<any>
constructor(ctor: TypedConstructor<T>, parser: IParser<any>) {
this.ctor = ctor
this.parser = parser
}
parse(input: string): ParseResult<T> {
const result = this.parser.parse(input)
if (result instanceof ParseSuccess) {
try {
const value = new this.ctor(result.value)
return new ParseSuccess(value, result.next)
} catch (e) {
return new ParseFailure(this.ctor.toString() + 'can not parse: ' + result.value, result.next)
}
} else {
return result
}
}
}
export function typed<V, T extends TypedValue>(ctor: TypedConstructor<T>, parser: IParser<any>) {
return new TypedParser<V, T>(ctor, parser)
}
|
TypedParser
|
identifier_name
|
typedParser.ts
|
import { IParser } from './iParser'
import { ParseFailure, ParseResult, ParseSuccess } from './parseResult'
export interface TypedValue {}
export interface TypedConstructor<T extends TypedValue> {
new (value: any): T
}
export class TypedParser<V, T extends TypedValue> implements IParser<T> {
ctor: TypedConstructor<T>
parser: IParser<any>
constructor(ctor: TypedConstructor<T>, parser: IParser<any>) {
this.ctor = ctor
this.parser = parser
}
parse(input: string): ParseResult<T> {
const result = this.parser.parse(input)
if (result instanceof ParseSuccess) {
try {
const value = new this.ctor(result.value)
return new ParseSuccess(value, result.next)
} catch (e) {
return new ParseFailure(this.ctor.toString() + 'can not parse: ' + result.value, result.next)
}
} else
|
}
}
export function typed<V, T extends TypedValue>(ctor: TypedConstructor<T>, parser: IParser<any>) {
return new TypedParser<V, T>(ctor, parser)
}
|
{
return result
}
|
conditional_block
|
typedParser.ts
|
import { IParser } from './iParser'
import { ParseFailure, ParseResult, ParseSuccess } from './parseResult'
export interface TypedValue {}
|
export class TypedParser<V, T extends TypedValue> implements IParser<T> {
ctor: TypedConstructor<T>
parser: IParser<any>
constructor(ctor: TypedConstructor<T>, parser: IParser<any>) {
this.ctor = ctor
this.parser = parser
}
parse(input: string): ParseResult<T> {
const result = this.parser.parse(input)
if (result instanceof ParseSuccess) {
try {
const value = new this.ctor(result.value)
return new ParseSuccess(value, result.next)
} catch (e) {
return new ParseFailure(this.ctor.toString() + 'can not parse: ' + result.value, result.next)
}
} else {
return result
}
}
}
export function typed<V, T extends TypedValue>(ctor: TypedConstructor<T>, parser: IParser<any>) {
return new TypedParser<V, T>(ctor, parser)
}
|
export interface TypedConstructor<T extends TypedValue> {
new (value: any): T
}
|
random_line_split
|
completions_dev.py
|
import sys
import sublime_plugin
if sys.version_info < (3,):
from sublime_lib.path import root_at_packages, get_package_name
else:
from .sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = ("Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage"
% PLUGIN_NAME)
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger": "${2:some_trigger}", "contents": "${3:Hint: Use f, ff and fff plus Tab inside here.}" }$0
]
}""".replace(" ", "\t") # NOQA - line length
class
|
(sublime_plugin.WindowCommand):
def run(self):
v = self.window.new_file()
v.run_command('insert_snippet', {"contents": TPL})
v.set_syntax_file(COMPLETIONS_SYNTAX_DEF)
v.settings().set('default_dir', root_at_packages('User'))
|
NewCompletionsCommand
|
identifier_name
|
completions_dev.py
|
import sys
import sublime_plugin
if sys.version_info < (3,):
from sublime_lib.path import root_at_packages, get_package_name
else:
from .sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = ("Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage"
% PLUGIN_NAME)
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger": "${2:some_trigger}", "contents": "${3:Hint: Use f, ff and fff plus Tab inside here.}" }$0
]
}""".replace(" ", "\t") # NOQA - line length
class NewCompletionsCommand(sublime_plugin.WindowCommand):
def run(self):
|
v = self.window.new_file()
v.run_command('insert_snippet', {"contents": TPL})
v.set_syntax_file(COMPLETIONS_SYNTAX_DEF)
v.settings().set('default_dir', root_at_packages('User'))
|
identifier_body
|
|
completions_dev.py
|
import sys
import sublime_plugin
if sys.version_info < (3,):
|
else:
from .sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = ("Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage"
% PLUGIN_NAME)
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger": "${2:some_trigger}", "contents": "${3:Hint: Use f, ff and fff plus Tab inside here.}" }$0
]
}""".replace(" ", "\t") # NOQA - line length
class NewCompletionsCommand(sublime_plugin.WindowCommand):
def run(self):
v = self.window.new_file()
v.run_command('insert_snippet', {"contents": TPL})
v.set_syntax_file(COMPLETIONS_SYNTAX_DEF)
v.settings().set('default_dir', root_at_packages('User'))
|
from sublime_lib.path import root_at_packages, get_package_name
|
conditional_block
|
completions_dev.py
|
from sublime_lib.path import root_at_packages, get_package_name
else:
from .sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = ("Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage"
% PLUGIN_NAME)
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger": "${2:some_trigger}", "contents": "${3:Hint: Use f, ff and fff plus Tab inside here.}" }$0
]
}""".replace(" ", "\t") # NOQA - line length
class NewCompletionsCommand(sublime_plugin.WindowCommand):
def run(self):
v = self.window.new_file()
v.run_command('insert_snippet', {"contents": TPL})
v.set_syntax_file(COMPLETIONS_SYNTAX_DEF)
v.settings().set('default_dir', root_at_packages('User'))
|
import sys
import sublime_plugin
if sys.version_info < (3,):
|
random_line_split
|
|
cssstylerule.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use parking_lot::RwLock;
use std::sync::Arc;
use style::stylesheets::StyleRule;
use style_traits::ToCss;
#[dom_struct]
pub struct CSSStyleRule {
cssrule: CSSRule,
#[ignore_heap_size_of = "Arc"]
stylerule: Arc<RwLock<StyleRule>>,
}
impl CSSStyleRule {
fn new_inherited(parent: Option<&CSSStyleSheet>, stylerule: Arc<RwLock<StyleRule>>) -> CSSStyleRule {
CSSStyleRule {
cssrule: CSSRule::new_inherited(parent),
stylerule: stylerule,
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent: Option<&CSSStyleSheet>,
stylerule: Arc<RwLock<StyleRule>>) -> Root<CSSStyleRule> {
reflect_dom_object(box CSSStyleRule::new_inherited(parent, stylerule),
window,
CSSStyleRuleBinding::Wrap)
}
}
impl SpecificCSSRule for CSSStyleRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::STYLE_RULE
}
fn get_css(&self) -> DOMString
|
}
|
{
self.stylerule.read().to_css_string().into()
}
|
identifier_body
|
cssstylerule.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use parking_lot::RwLock;
use std::sync::Arc;
use style::stylesheets::StyleRule;
use style_traits::ToCss;
#[dom_struct]
pub struct CSSStyleRule {
cssrule: CSSRule,
#[ignore_heap_size_of = "Arc"]
stylerule: Arc<RwLock<StyleRule>>,
}
impl CSSStyleRule {
fn new_inherited(parent: Option<&CSSStyleSheet>, stylerule: Arc<RwLock<StyleRule>>) -> CSSStyleRule {
CSSStyleRule {
cssrule: CSSRule::new_inherited(parent),
stylerule: stylerule,
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent: Option<&CSSStyleSheet>,
stylerule: Arc<RwLock<StyleRule>>) -> Root<CSSStyleRule> {
reflect_dom_object(box CSSStyleRule::new_inherited(parent, stylerule),
window,
CSSStyleRuleBinding::Wrap)
}
}
impl SpecificCSSRule for CSSStyleRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::STYLE_RULE
}
fn get_css(&self) -> DOMString {
self.stylerule.read().to_css_string().into()
}
}
|
* 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/. */
|
random_line_split
|
cssstylerule.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use parking_lot::RwLock;
use std::sync::Arc;
use style::stylesheets::StyleRule;
use style_traits::ToCss;
#[dom_struct]
pub struct CSSStyleRule {
cssrule: CSSRule,
#[ignore_heap_size_of = "Arc"]
stylerule: Arc<RwLock<StyleRule>>,
}
impl CSSStyleRule {
fn new_inherited(parent: Option<&CSSStyleSheet>, stylerule: Arc<RwLock<StyleRule>>) -> CSSStyleRule {
CSSStyleRule {
cssrule: CSSRule::new_inherited(parent),
stylerule: stylerule,
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent: Option<&CSSStyleSheet>,
stylerule: Arc<RwLock<StyleRule>>) -> Root<CSSStyleRule> {
reflect_dom_object(box CSSStyleRule::new_inherited(parent, stylerule),
window,
CSSStyleRuleBinding::Wrap)
}
}
impl SpecificCSSRule for CSSStyleRule {
fn
|
(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::STYLE_RULE
}
fn get_css(&self) -> DOMString {
self.stylerule.read().to_css_string().into()
}
}
|
ty
|
identifier_name
|
completionListInvalidMemberNames3.ts
|
/// <reference path='fourslash.ts' />
// @allowjs: true
// @Filename: test.js
////interface Symbol {
//// /** Returns a string representation of an object. */
//// toString(): string;
//// /** Returns the primitive value of the specified object. */
//// valueOf(): Object;
////}
////interface SymbolConstructor {
//// /**
//// * A reference to the prototype.
//// */
//// readonly prototype: Symbol;
//// /**
|
//// (description?: string | number): symbol;
//// /**
//// * Returns a Symbol object from the global symbol registry matching the given key if found.
//// * Otherwise, returns a new symbol with this key.
//// * @param key key to search for.
//// */
//// for(key: string): symbol;
//// /**
//// * Returns a key from the global symbol registry matching the given Symbol if found.
//// * Otherwise, returns a undefined.
//// * @param sym Symbol to find the key for.
//// */
//// keyFor(sym: symbol): string | undefined;
////}
////declare var Symbol: SymbolConstructor;/// <reference path="lib.es2015.symbol.d.ts" />
////interface SymbolConstructor {
//// /**
//// * A method that determines if a constructor object recognizes an object as one of the
//// * constructors instances. Called by the semantics of the instanceof operator.
//// */
//// readonly hasInstance: symbol;
////}
////interface Function {
//// /**
//// * Determines whether the given value inherits from this function if this function was used
//// * as a constructor function.
//// *
//// * A constructor function can control which objects are recognized as its instances by
//// * 'instanceof' by overriding this method.
//// */
//// [Symbol.hasInstance](value: any): boolean;
////}
////interface SomeInterface {
//// (value: number): any;
////}
////var _ : SomeInterface;
////_./**/
goTo.marker();
verify.not.completionListContains("[Symbol.hasInstance]");
|
//// * Returns a new unique Symbol value.
//// * @param description Description of the new Symbol object.
//// */
|
random_line_split
|
index.js
|
/** PROMISIFY CALLBACK-STYLE FUNCTIONS TO ES6 PROMISES
*
* EXAMPLE:
* const fn = promisify( (callback) => callback(null, "Hello world!") );
* fn((err, str) => console.log(str));
* fn().then((str) => console.log(str));
* //Both functions, will log 'Hello world!'
*
* Note: The function you pass, may have any arguments you want, but the latest
* have to be the callback, which you will call with: next(err, value)
*
* @param method: Function/Array/Map = The function(s) to promisify
* @param options: Map =
* "context" (default is function): The context which to apply the called function
* "replace" (default is falsy): When passed an array/map, if to replace the original object
*
* @return: A promise if passed a function, otherwise the object with the promises
*
* @license: MIT
* @version: 1.0.3
* @author: Manuel Di Iorio
**/
var createCallback = function (method, context) {
return function () {
var args = Array.prototype.slice.call(arguments);
var lastIndex = args.length - 1;
var lastArg = args && args.length > 0 ? args[lastIndex] : null;
var cb = typeof lastArg === 'function' ? lastArg : null;
if (cb) {
return method.apply(context, args);
}
return new Promise(function (resolve, reject) {
args.push(function (err, val) {
if (err) return reject(err);
resolve(val);
});
method.apply(context, args);
});
};
};
if (typeof module === "undefined") module = {}; // Browserify this module
module.exports = function (methods, options) {
options = options || {};
var type = Object.prototype.toString.call(methods);
if (type === "[object Object]" || type === "[object Array]") {
var obj = options.replace ? methods : {};
for (var key in methods) {
if (methods.hasOwnProperty(key)) obj[key] = createCallback(methods[key]);
}return obj;
}
return createCallback(methods, options.context || methods);
};
// Browserify this module
if (typeof exports === "undefined")
|
{
this["promisify"] = module.exports;
}
|
conditional_block
|
|
index.js
|
/** PROMISIFY CALLBACK-STYLE FUNCTIONS TO ES6 PROMISES
*
* EXAMPLE:
* const fn = promisify( (callback) => callback(null, "Hello world!") );
* fn((err, str) => console.log(str));
* fn().then((str) => console.log(str));
* //Both functions, will log 'Hello world!'
*
* Note: The function you pass, may have any arguments you want, but the latest
* have to be the callback, which you will call with: next(err, value)
*
* @param method: Function/Array/Map = The function(s) to promisify
* @param options: Map =
* "context" (default is function): The context which to apply the called function
* "replace" (default is falsy): When passed an array/map, if to replace the original object
*
* @return: A promise if passed a function, otherwise the object with the promises
*
* @license: MIT
* @version: 1.0.3
* @author: Manuel Di Iorio
**/
var createCallback = function (method, context) {
return function () {
var args = Array.prototype.slice.call(arguments);
var lastIndex = args.length - 1;
var lastArg = args && args.length > 0 ? args[lastIndex] : null;
var cb = typeof lastArg === 'function' ? lastArg : null;
if (cb) {
return method.apply(context, args);
}
return new Promise(function (resolve, reject) {
args.push(function (err, val) {
if (err) return reject(err);
resolve(val);
});
method.apply(context, args);
});
|
if (typeof module === "undefined") module = {}; // Browserify this module
module.exports = function (methods, options) {
options = options || {};
var type = Object.prototype.toString.call(methods);
if (type === "[object Object]" || type === "[object Array]") {
var obj = options.replace ? methods : {};
for (var key in methods) {
if (methods.hasOwnProperty(key)) obj[key] = createCallback(methods[key]);
}return obj;
}
return createCallback(methods, options.context || methods);
};
// Browserify this module
if (typeof exports === "undefined") {
this["promisify"] = module.exports;
}
|
};
};
|
random_line_split
|
validations.ts
|
import { Action as ReduxAction, Dispatch } from 'redux';
import StateTree from './tree';
import { User } from './user';
const MIN_CACHE_SIZE = 2;
|
glob: string;
sentence: string;
audioSrc: string;
}
export interface State {
cache: Validation[];
next?: Validation;
loadError: boolean;
}
enum ActionType {
REFILL_CACHE = 'REFILL_VALIDATIONS_CACHE',
NEXT_VALIDATION = 'NEXT_VALIDATION',
}
interface RefillCacheAction extends ReduxAction {
type: ActionType.REFILL_CACHE;
validation?: Validation;
}
interface NewValidationAction extends ReduxAction {
type: ActionType.NEXT_VALIDATION;
}
export type Action = RefillCacheAction | NewValidationAction;
export const actions = {
refillCache: () => async (
dispatch: Dispatch<RefillCacheAction>,
getState: () => StateTree
) => {
const { api, validations } = getState();
if (validations.cache.length > MIN_CACHE_SIZE) {
return;
}
try {
for (let i = 0; i < MIN_CACHE_SIZE * 2; i++) {
const clip = await api.getRandomClip();
dispatch({
type: ActionType.REFILL_CACHE,
validation: {
glob: clip.glob,
sentence: decodeURIComponent(clip.text),
audioSrc: clip.sound,
},
});
await new Promise(resolve => {
const audioElement = document.createElement('audio');
audioElement.addEventListener('canplaythrough', () => {
audioElement.remove();
resolve();
});
audioElement.setAttribute('src', clip.sound);
});
}
} catch (err) {
if (err instanceof XMLHttpRequest) {
dispatch({ type: ActionType.REFILL_CACHE });
} else {
throw err;
}
}
},
vote: (isValid: boolean) => async (
dispatch: Dispatch<NewValidationAction | RefillCacheAction>,
getState: () => StateTree
) => {
const { api, validations } = getState();
await api.castVote(validations.next.glob, isValid);
dispatch(User.actions.tallyVerification());
dispatch({ type: ActionType.NEXT_VALIDATION });
actions.refillCache()(dispatch, getState);
},
};
export function reducer(
state: State = {
cache: [],
next: null,
loadError: false,
},
action: Action
): State {
switch (action.type) {
case ActionType.REFILL_CACHE: {
const { validation } = action;
const cache = validation ? state.cache.concat(validation) : state.cache;
const next = state.next || cache.shift();
return {
...state,
cache,
loadError: !next,
next,
};
}
case ActionType.NEXT_VALIDATION: {
const cache = state.cache.slice();
const next = cache.pop();
return { ...state, cache, next };
}
default:
return state;
}
}
}
|
export namespace Validations {
export interface Validation {
|
random_line_split
|
validations.ts
|
import { Action as ReduxAction, Dispatch } from 'redux';
import StateTree from './tree';
import { User } from './user';
const MIN_CACHE_SIZE = 2;
export namespace Validations {
export interface Validation {
glob: string;
sentence: string;
audioSrc: string;
}
export interface State {
cache: Validation[];
next?: Validation;
loadError: boolean;
}
enum ActionType {
REFILL_CACHE = 'REFILL_VALIDATIONS_CACHE',
NEXT_VALIDATION = 'NEXT_VALIDATION',
}
interface RefillCacheAction extends ReduxAction {
type: ActionType.REFILL_CACHE;
validation?: Validation;
}
interface NewValidationAction extends ReduxAction {
type: ActionType.NEXT_VALIDATION;
}
export type Action = RefillCacheAction | NewValidationAction;
export const actions = {
refillCache: () => async (
dispatch: Dispatch<RefillCacheAction>,
getState: () => StateTree
) => {
const { api, validations } = getState();
if (validations.cache.length > MIN_CACHE_SIZE) {
return;
}
try {
for (let i = 0; i < MIN_CACHE_SIZE * 2; i++)
|
} catch (err) {
if (err instanceof XMLHttpRequest) {
dispatch({ type: ActionType.REFILL_CACHE });
} else {
throw err;
}
}
},
vote: (isValid: boolean) => async (
dispatch: Dispatch<NewValidationAction | RefillCacheAction>,
getState: () => StateTree
) => {
const { api, validations } = getState();
await api.castVote(validations.next.glob, isValid);
dispatch(User.actions.tallyVerification());
dispatch({ type: ActionType.NEXT_VALIDATION });
actions.refillCache()(dispatch, getState);
},
};
export function reducer(
state: State = {
cache: [],
next: null,
loadError: false,
},
action: Action
): State {
switch (action.type) {
case ActionType.REFILL_CACHE: {
const { validation } = action;
const cache = validation ? state.cache.concat(validation) : state.cache;
const next = state.next || cache.shift();
return {
...state,
cache,
loadError: !next,
next,
};
}
case ActionType.NEXT_VALIDATION: {
const cache = state.cache.slice();
const next = cache.pop();
return { ...state, cache, next };
}
default:
return state;
}
}
}
|
{
const clip = await api.getRandomClip();
dispatch({
type: ActionType.REFILL_CACHE,
validation: {
glob: clip.glob,
sentence: decodeURIComponent(clip.text),
audioSrc: clip.sound,
},
});
await new Promise(resolve => {
const audioElement = document.createElement('audio');
audioElement.addEventListener('canplaythrough', () => {
audioElement.remove();
resolve();
});
audioElement.setAttribute('src', clip.sound);
});
}
|
conditional_block
|
validations.ts
|
import { Action as ReduxAction, Dispatch } from 'redux';
import StateTree from './tree';
import { User } from './user';
const MIN_CACHE_SIZE = 2;
export namespace Validations {
export interface Validation {
glob: string;
sentence: string;
audioSrc: string;
}
export interface State {
cache: Validation[];
next?: Validation;
loadError: boolean;
}
enum ActionType {
REFILL_CACHE = 'REFILL_VALIDATIONS_CACHE',
NEXT_VALIDATION = 'NEXT_VALIDATION',
}
interface RefillCacheAction extends ReduxAction {
type: ActionType.REFILL_CACHE;
validation?: Validation;
}
interface NewValidationAction extends ReduxAction {
type: ActionType.NEXT_VALIDATION;
}
export type Action = RefillCacheAction | NewValidationAction;
export const actions = {
refillCache: () => async (
dispatch: Dispatch<RefillCacheAction>,
getState: () => StateTree
) => {
const { api, validations } = getState();
if (validations.cache.length > MIN_CACHE_SIZE) {
return;
}
try {
for (let i = 0; i < MIN_CACHE_SIZE * 2; i++) {
const clip = await api.getRandomClip();
dispatch({
type: ActionType.REFILL_CACHE,
validation: {
glob: clip.glob,
sentence: decodeURIComponent(clip.text),
audioSrc: clip.sound,
},
});
await new Promise(resolve => {
const audioElement = document.createElement('audio');
audioElement.addEventListener('canplaythrough', () => {
audioElement.remove();
resolve();
});
audioElement.setAttribute('src', clip.sound);
});
}
} catch (err) {
if (err instanceof XMLHttpRequest) {
dispatch({ type: ActionType.REFILL_CACHE });
} else {
throw err;
}
}
},
vote: (isValid: boolean) => async (
dispatch: Dispatch<NewValidationAction | RefillCacheAction>,
getState: () => StateTree
) => {
const { api, validations } = getState();
await api.castVote(validations.next.glob, isValid);
dispatch(User.actions.tallyVerification());
dispatch({ type: ActionType.NEXT_VALIDATION });
actions.refillCache()(dispatch, getState);
},
};
export function
|
(
state: State = {
cache: [],
next: null,
loadError: false,
},
action: Action
): State {
switch (action.type) {
case ActionType.REFILL_CACHE: {
const { validation } = action;
const cache = validation ? state.cache.concat(validation) : state.cache;
const next = state.next || cache.shift();
return {
...state,
cache,
loadError: !next,
next,
};
}
case ActionType.NEXT_VALIDATION: {
const cache = state.cache.slice();
const next = cache.pop();
return { ...state, cache, next };
}
default:
return state;
}
}
}
|
reducer
|
identifier_name
|
validations.ts
|
import { Action as ReduxAction, Dispatch } from 'redux';
import StateTree from './tree';
import { User } from './user';
const MIN_CACHE_SIZE = 2;
export namespace Validations {
export interface Validation {
glob: string;
sentence: string;
audioSrc: string;
}
export interface State {
cache: Validation[];
next?: Validation;
loadError: boolean;
}
enum ActionType {
REFILL_CACHE = 'REFILL_VALIDATIONS_CACHE',
NEXT_VALIDATION = 'NEXT_VALIDATION',
}
interface RefillCacheAction extends ReduxAction {
type: ActionType.REFILL_CACHE;
validation?: Validation;
}
interface NewValidationAction extends ReduxAction {
type: ActionType.NEXT_VALIDATION;
}
export type Action = RefillCacheAction | NewValidationAction;
export const actions = {
refillCache: () => async (
dispatch: Dispatch<RefillCacheAction>,
getState: () => StateTree
) => {
const { api, validations } = getState();
if (validations.cache.length > MIN_CACHE_SIZE) {
return;
}
try {
for (let i = 0; i < MIN_CACHE_SIZE * 2; i++) {
const clip = await api.getRandomClip();
dispatch({
type: ActionType.REFILL_CACHE,
validation: {
glob: clip.glob,
sentence: decodeURIComponent(clip.text),
audioSrc: clip.sound,
},
});
await new Promise(resolve => {
const audioElement = document.createElement('audio');
audioElement.addEventListener('canplaythrough', () => {
audioElement.remove();
resolve();
});
audioElement.setAttribute('src', clip.sound);
});
}
} catch (err) {
if (err instanceof XMLHttpRequest) {
dispatch({ type: ActionType.REFILL_CACHE });
} else {
throw err;
}
}
},
vote: (isValid: boolean) => async (
dispatch: Dispatch<NewValidationAction | RefillCacheAction>,
getState: () => StateTree
) => {
const { api, validations } = getState();
await api.castVote(validations.next.glob, isValid);
dispatch(User.actions.tallyVerification());
dispatch({ type: ActionType.NEXT_VALIDATION });
actions.refillCache()(dispatch, getState);
},
};
export function reducer(
state: State = {
cache: [],
next: null,
loadError: false,
},
action: Action
): State
|
}
|
{
switch (action.type) {
case ActionType.REFILL_CACHE: {
const { validation } = action;
const cache = validation ? state.cache.concat(validation) : state.cache;
const next = state.next || cache.shift();
return {
...state,
cache,
loadError: !next,
next,
};
}
case ActionType.NEXT_VALIDATION: {
const cache = state.cache.slice();
const next = cache.pop();
return { ...state, cache, next };
}
default:
return state;
}
}
|
identifier_body
|
message.rs
|
//! JSONRPC message types
//! See https://www.jsonrpc.org/specification
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const VERSION: &str = "2.0";
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
jsonrpc: String,
#[serde(flatten)]
type_: Type,
}
impl Message {
pub fn make_request(method: &str, params: Option<Params>, id: Option<Value>) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Request(Request { method: method.to_string(), params, id }) }
}
pub fn make_error_response(error: Error, id: Value) -> Self
|
pub fn make_response(result: Option<Value>, id: Value) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result, error: None, id }) }
}
pub fn version(&self) -> &str {
self.jsonrpc.as_str()
}
pub fn is_request(&self) -> bool {
matches!(self.type_, Type::Request(_))
}
pub fn is_response(&self) -> bool {
matches!(self.type_, Type::Response(_))
}
pub fn request(self) -> Option<Request> {
match self.type_ {
Type::Request(req) => Some(req),
_ => None,
}
}
pub fn response(self) -> Option<Response> {
match self.type_ {
Type::Response(resp) => Some(resp),
_ => None,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Type {
Request(Request),
Response(Response),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Request {
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<Params>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<Value>
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(untagged)]
pub enum Params {
ByPosition(Vec<Value>),
ByName(Map<String, Value>)
}
impl Into<Value> for Params {
fn into(self) -> Value {
match self {
Params::ByPosition(array) => Value::Array(array),
Params::ByName(map) => Value::Object(map),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Response {
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<Error>,
pub id: Value
}
impl Response {
pub fn is_error(&self) -> bool {
self.error.is_some()
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Error {
code: i64,
message: String,
data: Option<Value>,
}
impl Error {
pub fn parse_error() -> Self {
Error { code: -32700, message: String::from("Parse error"), data: None }
}
pub fn invalid_request() -> Self {
Error { code: -32600, message: String::from("Invalid Request"), data: None }
}
pub fn method_not_found() -> Self {
Error { code: -32601, message: String::from("Method not found"), data: None }
}
pub fn invalid_params() -> Self {
Error { code: -32602, message: String::from("Invalid params"), data: None }
}
pub fn internal_error() -> Self {
Error { code: -32603, message: String::from("Internal error"), data: None }
}
}
|
{
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result: None, error: Some(error), id }) }
}
|
identifier_body
|
message.rs
|
//! JSONRPC message types
//! See https://www.jsonrpc.org/specification
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const VERSION: &str = "2.0";
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
jsonrpc: String,
#[serde(flatten)]
type_: Type,
}
impl Message {
pub fn make_request(method: &str, params: Option<Params>, id: Option<Value>) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Request(Request { method: method.to_string(), params, id }) }
}
pub fn make_error_response(error: Error, id: Value) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result: None, error: Some(error), id }) }
}
pub fn make_response(result: Option<Value>, id: Value) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result, error: None, id }) }
}
pub fn version(&self) -> &str {
self.jsonrpc.as_str()
}
pub fn is_request(&self) -> bool {
matches!(self.type_, Type::Request(_))
}
|
pub fn is_response(&self) -> bool {
matches!(self.type_, Type::Response(_))
}
pub fn request(self) -> Option<Request> {
match self.type_ {
Type::Request(req) => Some(req),
_ => None,
}
}
pub fn response(self) -> Option<Response> {
match self.type_ {
Type::Response(resp) => Some(resp),
_ => None,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Type {
Request(Request),
Response(Response),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Request {
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<Params>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<Value>
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(untagged)]
pub enum Params {
ByPosition(Vec<Value>),
ByName(Map<String, Value>)
}
impl Into<Value> for Params {
fn into(self) -> Value {
match self {
Params::ByPosition(array) => Value::Array(array),
Params::ByName(map) => Value::Object(map),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Response {
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<Error>,
pub id: Value
}
impl Response {
pub fn is_error(&self) -> bool {
self.error.is_some()
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Error {
code: i64,
message: String,
data: Option<Value>,
}
impl Error {
pub fn parse_error() -> Self {
Error { code: -32700, message: String::from("Parse error"), data: None }
}
pub fn invalid_request() -> Self {
Error { code: -32600, message: String::from("Invalid Request"), data: None }
}
pub fn method_not_found() -> Self {
Error { code: -32601, message: String::from("Method not found"), data: None }
}
pub fn invalid_params() -> Self {
Error { code: -32602, message: String::from("Invalid params"), data: None }
}
pub fn internal_error() -> Self {
Error { code: -32603, message: String::from("Internal error"), data: None }
}
}
|
random_line_split
|
|
message.rs
|
//! JSONRPC message types
//! See https://www.jsonrpc.org/specification
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const VERSION: &str = "2.0";
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
jsonrpc: String,
#[serde(flatten)]
type_: Type,
}
impl Message {
pub fn make_request(method: &str, params: Option<Params>, id: Option<Value>) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Request(Request { method: method.to_string(), params, id }) }
}
pub fn make_error_response(error: Error, id: Value) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result: None, error: Some(error), id }) }
}
pub fn make_response(result: Option<Value>, id: Value) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result, error: None, id }) }
}
pub fn version(&self) -> &str {
self.jsonrpc.as_str()
}
pub fn is_request(&self) -> bool {
matches!(self.type_, Type::Request(_))
}
pub fn is_response(&self) -> bool {
matches!(self.type_, Type::Response(_))
}
pub fn
|
(self) -> Option<Request> {
match self.type_ {
Type::Request(req) => Some(req),
_ => None,
}
}
pub fn response(self) -> Option<Response> {
match self.type_ {
Type::Response(resp) => Some(resp),
_ => None,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Type {
Request(Request),
Response(Response),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Request {
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<Params>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<Value>
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(untagged)]
pub enum Params {
ByPosition(Vec<Value>),
ByName(Map<String, Value>)
}
impl Into<Value> for Params {
fn into(self) -> Value {
match self {
Params::ByPosition(array) => Value::Array(array),
Params::ByName(map) => Value::Object(map),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Response {
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<Error>,
pub id: Value
}
impl Response {
pub fn is_error(&self) -> bool {
self.error.is_some()
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Error {
code: i64,
message: String,
data: Option<Value>,
}
impl Error {
pub fn parse_error() -> Self {
Error { code: -32700, message: String::from("Parse error"), data: None }
}
pub fn invalid_request() -> Self {
Error { code: -32600, message: String::from("Invalid Request"), data: None }
}
pub fn method_not_found() -> Self {
Error { code: -32601, message: String::from("Method not found"), data: None }
}
pub fn invalid_params() -> Self {
Error { code: -32602, message: String::from("Invalid params"), data: None }
}
pub fn internal_error() -> Self {
Error { code: -32603, message: String::from("Internal error"), data: None }
}
}
|
request
|
identifier_name
|
bootstrap.v3.datetimepicker-tests.ts
|
import * as moment from "moment";
const dp = $("#picker").datetimepicker().data("DateTimePicker");
function test_cases() {
$("#datetimepicker").datetimepicker();
$("#datetimepicker").datetimepicker({
minDate: "2012-12-31"
});
$("#datetimepicker").data("DateTimePicker").maxDate("2012-12-31");
let startDate = moment(new Date(2012, 1, 20));
const endDate = moment(new Date(2012, 1, 25));
$("#datetimepicker2")
.datetimepicker()
.on("dp.change", ev => {
if (ev.date.valueOf() > endDate.valueOf()) {
$("#alert").show().find("strong").text("The start date must be before the end date.");
} else {
$("#alert").hide();
startDate = ev.date;
$("#date-start-display").text($("#date-start").data("date"));
}
})
.on("dp.error", ev => {
console.log(`Error: ${ev.date.format("YYYY-MM-DD")}`);
})
.on("dp.update", ev => {
console.log(`Change: ${ev.change}, ${ev.viewDate.format("YYYY-MM-DD")}`);
});
}
function test_date() {
let momentObj = moment("20111031", "YYYYMMDD");
dp.date(null);
dp.date("1969-07-21");
dp.date(new Date());
dp.date(momentObj);
momentObj = dp.date();
}
function test_format() {
let boolFormat = false;
let strFormat = "YYYY-MM-DD";
let momentFormat = moment.ISO_8601;
$("#picker").datetimepicker({
format: boolFormat
});
$("#picker").datetimepicker({
format: strFormat
});
$("#picker").datetimepicker({
format: momentFormat
});
dp.format(boolFormat);
boolFormat = dp.format() as boolean;
dp.format(strFormat);
strFormat = dp.format() as string;
dp.format(momentFormat);
momentFormat = dp.format() as moment.MomentBuiltinFormat;
}
function test_extraFormats() {
let boolFormat = false;
let strFormats = ["YYYYMMDD", "YYYY/MM/DD"];
let mixFormats = ["YYYYMMDD", moment.ISO_8601];
$("#picker").datetimepicker({
extraFormats: boolFormat
});
$("#picker").datetimepicker({
extraFormats: strFormats
});
$("#picker").datetimepicker({
extraFormats: mixFormats
});
dp.extraFormats(boolFormat);
boolFormat = dp.extraFormats() as boolean;
dp.extraFormats(strFormats);
strFormats = dp.extraFormats() as string[];
dp.extraFormats(mixFormats);
mixFormats = dp.extraFormats() as Array<(string | moment.MomentBuiltinFormat)>;
}
function test_timeZone() {
let nullTz = null;
let strFormats = "Africa/Abidjan";
$("#picker").datetimepicker({
timeZone: nullTz
});
$("#picker").datetimepicker({
timeZone: strFormats
});
dp.timeZone(nullTz);
nullTz = dp.timeZone() as null;
dp.timeZone(strFormats);
strFormats = dp.timeZone() as string;
}
function test_widgetParent() {
let nullW: null = null;
let str: string = "myId";
let jquery = $("#element");
$("#picker").datetimepicker({
widgetParent: nullW
});
$("#picker").datetimepicker({
widgetParent: str
});
$("#picker").datetimepicker({
widgetParent: jquery
});
dp.widgetParent(nullW);
nullW = dp.widgetParent() as null;
dp.widgetParent(str);
str = dp.widgetParent() as string;
dp.widgetParent(jquery);
jquery = dp.widgetParent() as JQuery;
}
function inputParser(inputDate: string | Date | moment.Moment) {
const relativeDatePattern = /[0-9]+\s+(days ago)/;
if (moment.isMoment(inputDate) || inputDate instanceof Date) {
return moment(inputDate);
} else {
const relativeDate = inputDate.match(relativeDatePattern);
if (relativeDate !== null) {
const subDays = +relativeDate[0].replace("days ago", "").trim();
return moment().subtract(subDays, "day");
} else {
return moment();
}
}
}
function test_parseInputDate()
|
{
let undef: undefined;
let parser: BootstrapV3DatetimePicker.InputParser;
$("#picker").datetimepicker();
$("#picker").datetimepicker({
parseInputDate: inputParser
});
undef = dp.parseInputDate() as undefined;
parser = dp.parseInputDate() as BootstrapV3DatetimePicker.InputParser;
}
|
identifier_body
|
|
bootstrap.v3.datetimepicker-tests.ts
|
import * as moment from "moment";
const dp = $("#picker").datetimepicker().data("DateTimePicker");
function test_cases() {
$("#datetimepicker").datetimepicker();
$("#datetimepicker").datetimepicker({
minDate: "2012-12-31"
});
$("#datetimepicker").data("DateTimePicker").maxDate("2012-12-31");
let startDate = moment(new Date(2012, 1, 20));
const endDate = moment(new Date(2012, 1, 25));
$("#datetimepicker2")
.datetimepicker()
.on("dp.change", ev => {
if (ev.date.valueOf() > endDate.valueOf()) {
$("#alert").show().find("strong").text("The start date must be before the end date.");
|
$("#date-start-display").text($("#date-start").data("date"));
}
})
.on("dp.error", ev => {
console.log(`Error: ${ev.date.format("YYYY-MM-DD")}`);
})
.on("dp.update", ev => {
console.log(`Change: ${ev.change}, ${ev.viewDate.format("YYYY-MM-DD")}`);
});
}
function test_date() {
let momentObj = moment("20111031", "YYYYMMDD");
dp.date(null);
dp.date("1969-07-21");
dp.date(new Date());
dp.date(momentObj);
momentObj = dp.date();
}
function test_format() {
let boolFormat = false;
let strFormat = "YYYY-MM-DD";
let momentFormat = moment.ISO_8601;
$("#picker").datetimepicker({
format: boolFormat
});
$("#picker").datetimepicker({
format: strFormat
});
$("#picker").datetimepicker({
format: momentFormat
});
dp.format(boolFormat);
boolFormat = dp.format() as boolean;
dp.format(strFormat);
strFormat = dp.format() as string;
dp.format(momentFormat);
momentFormat = dp.format() as moment.MomentBuiltinFormat;
}
function test_extraFormats() {
let boolFormat = false;
let strFormats = ["YYYYMMDD", "YYYY/MM/DD"];
let mixFormats = ["YYYYMMDD", moment.ISO_8601];
$("#picker").datetimepicker({
extraFormats: boolFormat
});
$("#picker").datetimepicker({
extraFormats: strFormats
});
$("#picker").datetimepicker({
extraFormats: mixFormats
});
dp.extraFormats(boolFormat);
boolFormat = dp.extraFormats() as boolean;
dp.extraFormats(strFormats);
strFormats = dp.extraFormats() as string[];
dp.extraFormats(mixFormats);
mixFormats = dp.extraFormats() as Array<(string | moment.MomentBuiltinFormat)>;
}
function test_timeZone() {
let nullTz = null;
let strFormats = "Africa/Abidjan";
$("#picker").datetimepicker({
timeZone: nullTz
});
$("#picker").datetimepicker({
timeZone: strFormats
});
dp.timeZone(nullTz);
nullTz = dp.timeZone() as null;
dp.timeZone(strFormats);
strFormats = dp.timeZone() as string;
}
function test_widgetParent() {
let nullW: null = null;
let str: string = "myId";
let jquery = $("#element");
$("#picker").datetimepicker({
widgetParent: nullW
});
$("#picker").datetimepicker({
widgetParent: str
});
$("#picker").datetimepicker({
widgetParent: jquery
});
dp.widgetParent(nullW);
nullW = dp.widgetParent() as null;
dp.widgetParent(str);
str = dp.widgetParent() as string;
dp.widgetParent(jquery);
jquery = dp.widgetParent() as JQuery;
}
function inputParser(inputDate: string | Date | moment.Moment) {
const relativeDatePattern = /[0-9]+\s+(days ago)/;
if (moment.isMoment(inputDate) || inputDate instanceof Date) {
return moment(inputDate);
} else {
const relativeDate = inputDate.match(relativeDatePattern);
if (relativeDate !== null) {
const subDays = +relativeDate[0].replace("days ago", "").trim();
return moment().subtract(subDays, "day");
} else {
return moment();
}
}
}
function test_parseInputDate() {
let undef: undefined;
let parser: BootstrapV3DatetimePicker.InputParser;
$("#picker").datetimepicker();
$("#picker").datetimepicker({
parseInputDate: inputParser
});
undef = dp.parseInputDate() as undefined;
parser = dp.parseInputDate() as BootstrapV3DatetimePicker.InputParser;
}
|
} else {
$("#alert").hide();
startDate = ev.date;
|
random_line_split
|
bootstrap.v3.datetimepicker-tests.ts
|
import * as moment from "moment";
const dp = $("#picker").datetimepicker().data("DateTimePicker");
function test_cases() {
$("#datetimepicker").datetimepicker();
$("#datetimepicker").datetimepicker({
minDate: "2012-12-31"
});
$("#datetimepicker").data("DateTimePicker").maxDate("2012-12-31");
let startDate = moment(new Date(2012, 1, 20));
const endDate = moment(new Date(2012, 1, 25));
$("#datetimepicker2")
.datetimepicker()
.on("dp.change", ev => {
if (ev.date.valueOf() > endDate.valueOf()) {
$("#alert").show().find("strong").text("The start date must be before the end date.");
} else {
$("#alert").hide();
startDate = ev.date;
$("#date-start-display").text($("#date-start").data("date"));
}
})
.on("dp.error", ev => {
console.log(`Error: ${ev.date.format("YYYY-MM-DD")}`);
})
.on("dp.update", ev => {
console.log(`Change: ${ev.change}, ${ev.viewDate.format("YYYY-MM-DD")}`);
});
}
function test_date() {
let momentObj = moment("20111031", "YYYYMMDD");
dp.date(null);
dp.date("1969-07-21");
dp.date(new Date());
dp.date(momentObj);
momentObj = dp.date();
}
function test_format() {
let boolFormat = false;
let strFormat = "YYYY-MM-DD";
let momentFormat = moment.ISO_8601;
$("#picker").datetimepicker({
format: boolFormat
});
$("#picker").datetimepicker({
format: strFormat
});
$("#picker").datetimepicker({
format: momentFormat
});
dp.format(boolFormat);
boolFormat = dp.format() as boolean;
dp.format(strFormat);
strFormat = dp.format() as string;
dp.format(momentFormat);
momentFormat = dp.format() as moment.MomentBuiltinFormat;
}
function test_extraFormats() {
let boolFormat = false;
let strFormats = ["YYYYMMDD", "YYYY/MM/DD"];
let mixFormats = ["YYYYMMDD", moment.ISO_8601];
$("#picker").datetimepicker({
extraFormats: boolFormat
});
$("#picker").datetimepicker({
extraFormats: strFormats
});
$("#picker").datetimepicker({
extraFormats: mixFormats
});
dp.extraFormats(boolFormat);
boolFormat = dp.extraFormats() as boolean;
dp.extraFormats(strFormats);
strFormats = dp.extraFormats() as string[];
dp.extraFormats(mixFormats);
mixFormats = dp.extraFormats() as Array<(string | moment.MomentBuiltinFormat)>;
}
function test_timeZone() {
let nullTz = null;
let strFormats = "Africa/Abidjan";
$("#picker").datetimepicker({
timeZone: nullTz
});
$("#picker").datetimepicker({
timeZone: strFormats
});
dp.timeZone(nullTz);
nullTz = dp.timeZone() as null;
dp.timeZone(strFormats);
strFormats = dp.timeZone() as string;
}
function test_widgetParent() {
let nullW: null = null;
let str: string = "myId";
let jquery = $("#element");
$("#picker").datetimepicker({
widgetParent: nullW
});
$("#picker").datetimepicker({
widgetParent: str
});
$("#picker").datetimepicker({
widgetParent: jquery
});
dp.widgetParent(nullW);
nullW = dp.widgetParent() as null;
dp.widgetParent(str);
str = dp.widgetParent() as string;
dp.widgetParent(jquery);
jquery = dp.widgetParent() as JQuery;
}
function
|
(inputDate: string | Date | moment.Moment) {
const relativeDatePattern = /[0-9]+\s+(days ago)/;
if (moment.isMoment(inputDate) || inputDate instanceof Date) {
return moment(inputDate);
} else {
const relativeDate = inputDate.match(relativeDatePattern);
if (relativeDate !== null) {
const subDays = +relativeDate[0].replace("days ago", "").trim();
return moment().subtract(subDays, "day");
} else {
return moment();
}
}
}
function test_parseInputDate() {
let undef: undefined;
let parser: BootstrapV3DatetimePicker.InputParser;
$("#picker").datetimepicker();
$("#picker").datetimepicker({
parseInputDate: inputParser
});
undef = dp.parseInputDate() as undefined;
parser = dp.parseInputDate() as BootstrapV3DatetimePicker.InputParser;
}
|
inputParser
|
identifier_name
|
bootstrap.v3.datetimepicker-tests.ts
|
import * as moment from "moment";
const dp = $("#picker").datetimepicker().data("DateTimePicker");
function test_cases() {
$("#datetimepicker").datetimepicker();
$("#datetimepicker").datetimepicker({
minDate: "2012-12-31"
});
$("#datetimepicker").data("DateTimePicker").maxDate("2012-12-31");
let startDate = moment(new Date(2012, 1, 20));
const endDate = moment(new Date(2012, 1, 25));
$("#datetimepicker2")
.datetimepicker()
.on("dp.change", ev => {
if (ev.date.valueOf() > endDate.valueOf()) {
$("#alert").show().find("strong").text("The start date must be before the end date.");
} else {
$("#alert").hide();
startDate = ev.date;
$("#date-start-display").text($("#date-start").data("date"));
}
})
.on("dp.error", ev => {
console.log(`Error: ${ev.date.format("YYYY-MM-DD")}`);
})
.on("dp.update", ev => {
console.log(`Change: ${ev.change}, ${ev.viewDate.format("YYYY-MM-DD")}`);
});
}
function test_date() {
let momentObj = moment("20111031", "YYYYMMDD");
dp.date(null);
dp.date("1969-07-21");
dp.date(new Date());
dp.date(momentObj);
momentObj = dp.date();
}
function test_format() {
let boolFormat = false;
let strFormat = "YYYY-MM-DD";
let momentFormat = moment.ISO_8601;
$("#picker").datetimepicker({
format: boolFormat
});
$("#picker").datetimepicker({
format: strFormat
});
$("#picker").datetimepicker({
format: momentFormat
});
dp.format(boolFormat);
boolFormat = dp.format() as boolean;
dp.format(strFormat);
strFormat = dp.format() as string;
dp.format(momentFormat);
momentFormat = dp.format() as moment.MomentBuiltinFormat;
}
function test_extraFormats() {
let boolFormat = false;
let strFormats = ["YYYYMMDD", "YYYY/MM/DD"];
let mixFormats = ["YYYYMMDD", moment.ISO_8601];
$("#picker").datetimepicker({
extraFormats: boolFormat
});
$("#picker").datetimepicker({
extraFormats: strFormats
});
$("#picker").datetimepicker({
extraFormats: mixFormats
});
dp.extraFormats(boolFormat);
boolFormat = dp.extraFormats() as boolean;
dp.extraFormats(strFormats);
strFormats = dp.extraFormats() as string[];
dp.extraFormats(mixFormats);
mixFormats = dp.extraFormats() as Array<(string | moment.MomentBuiltinFormat)>;
}
function test_timeZone() {
let nullTz = null;
let strFormats = "Africa/Abidjan";
$("#picker").datetimepicker({
timeZone: nullTz
});
$("#picker").datetimepicker({
timeZone: strFormats
});
dp.timeZone(nullTz);
nullTz = dp.timeZone() as null;
dp.timeZone(strFormats);
strFormats = dp.timeZone() as string;
}
function test_widgetParent() {
let nullW: null = null;
let str: string = "myId";
let jquery = $("#element");
$("#picker").datetimepicker({
widgetParent: nullW
});
$("#picker").datetimepicker({
widgetParent: str
});
$("#picker").datetimepicker({
widgetParent: jquery
});
dp.widgetParent(nullW);
nullW = dp.widgetParent() as null;
dp.widgetParent(str);
str = dp.widgetParent() as string;
dp.widgetParent(jquery);
jquery = dp.widgetParent() as JQuery;
}
function inputParser(inputDate: string | Date | moment.Moment) {
const relativeDatePattern = /[0-9]+\s+(days ago)/;
if (moment.isMoment(inputDate) || inputDate instanceof Date) {
return moment(inputDate);
} else
|
}
function test_parseInputDate() {
let undef: undefined;
let parser: BootstrapV3DatetimePicker.InputParser;
$("#picker").datetimepicker();
$("#picker").datetimepicker({
parseInputDate: inputParser
});
undef = dp.parseInputDate() as undefined;
parser = dp.parseInputDate() as BootstrapV3DatetimePicker.InputParser;
}
|
{
const relativeDate = inputDate.match(relativeDatePattern);
if (relativeDate !== null) {
const subDays = +relativeDate[0].replace("days ago", "").trim();
return moment().subtract(subDays, "day");
} else {
return moment();
}
}
|
conditional_block
|
app.py
|
from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
' x == number of sides on each die\n' \
'e.g. `/roll 3d6` will roll 3 6-sided dice. ' \
'[options] may be any of (hide|hidden|invisible|ephemeral|private) ' \
'for a private roll.'
def do_roll(spec):
match = SPEC.match(spec)
if match is None:
return {
'response_type': 'ephemeral',
'text': 'ERROR: invalid roll command `%s`\n\n%s' % (
spec, USAGE)
}
num = int(match.group(1))
size = int(match.group(2))
|
}
vals = []
for i in range(0, num):
vals.append(random.randint(1, size))
data = {
'response_type': 'ephemeral' if flag in HIDDEN else 'in_channel'
}
if num == 1:
data['text'] = str(vals[0])
else:
data['text'] = '%s = %d' % (
' + '.join([str(v) for v in vals]), sum(vals))
return data
@app.route("/", methods=['GET', 'POST'])
def roll():
try:
if request.method == 'POST':
spec = request.form['text']
else:
spec = request.args['spec']
return jsonify(do_roll(spec))
except:
return jsonify({
'response_type': 'ephemeral',
'text': USAGE
})
if __name__ == "__main__":
app.run(debug=True)
|
flag = match.group(3)
if flag is not None and flag not in HIDDEN:
return {
'response_type': 'ephemeral',
'text': 'ERROR: unrecognized modifier `%s`' % flag
|
random_line_split
|
app.py
|
from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
' x == number of sides on each die\n' \
'e.g. `/roll 3d6` will roll 3 6-sided dice. ' \
'[options] may be any of (hide|hidden|invisible|ephemeral|private) ' \
'for a private roll.'
def do_roll(spec):
match = SPEC.match(spec)
if match is None:
return {
'response_type': 'ephemeral',
'text': 'ERROR: invalid roll command `%s`\n\n%s' % (
spec, USAGE)
}
num = int(match.group(1))
size = int(match.group(2))
flag = match.group(3)
if flag is not None and flag not in HIDDEN:
return {
'response_type': 'ephemeral',
'text': 'ERROR: unrecognized modifier `%s`' % flag
}
vals = []
for i in range(0, num):
vals.append(random.randint(1, size))
data = {
'response_type': 'ephemeral' if flag in HIDDEN else 'in_channel'
}
if num == 1:
data['text'] = str(vals[0])
else:
data['text'] = '%s = %d' % (
' + '.join([str(v) for v in vals]), sum(vals))
return data
@app.route("/", methods=['GET', 'POST'])
def roll():
|
if __name__ == "__main__":
app.run(debug=True)
|
try:
if request.method == 'POST':
spec = request.form['text']
else:
spec = request.args['spec']
return jsonify(do_roll(spec))
except:
return jsonify({
'response_type': 'ephemeral',
'text': USAGE
})
|
identifier_body
|
app.py
|
from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
' x == number of sides on each die\n' \
'e.g. `/roll 3d6` will roll 3 6-sided dice. ' \
'[options] may be any of (hide|hidden|invisible|ephemeral|private) ' \
'for a private roll.'
def do_roll(spec):
match = SPEC.match(spec)
if match is None:
return {
'response_type': 'ephemeral',
'text': 'ERROR: invalid roll command `%s`\n\n%s' % (
spec, USAGE)
}
num = int(match.group(1))
size = int(match.group(2))
flag = match.group(3)
if flag is not None and flag not in HIDDEN:
return {
'response_type': 'ephemeral',
'text': 'ERROR: unrecognized modifier `%s`' % flag
}
vals = []
for i in range(0, num):
vals.append(random.randint(1, size))
data = {
'response_type': 'ephemeral' if flag in HIDDEN else 'in_channel'
}
if num == 1:
data['text'] = str(vals[0])
else:
data['text'] = '%s = %d' % (
' + '.join([str(v) for v in vals]), sum(vals))
return data
@app.route("/", methods=['GET', 'POST'])
def
|
():
try:
if request.method == 'POST':
spec = request.form['text']
else:
spec = request.args['spec']
return jsonify(do_roll(spec))
except:
return jsonify({
'response_type': 'ephemeral',
'text': USAGE
})
if __name__ == "__main__":
app.run(debug=True)
|
roll
|
identifier_name
|
app.py
|
from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
' x == number of sides on each die\n' \
'e.g. `/roll 3d6` will roll 3 6-sided dice. ' \
'[options] may be any of (hide|hidden|invisible|ephemeral|private) ' \
'for a private roll.'
def do_roll(spec):
match = SPEC.match(spec)
if match is None:
return {
'response_type': 'ephemeral',
'text': 'ERROR: invalid roll command `%s`\n\n%s' % (
spec, USAGE)
}
num = int(match.group(1))
size = int(match.group(2))
flag = match.group(3)
if flag is not None and flag not in HIDDEN:
|
vals = []
for i in range(0, num):
vals.append(random.randint(1, size))
data = {
'response_type': 'ephemeral' if flag in HIDDEN else 'in_channel'
}
if num == 1:
data['text'] = str(vals[0])
else:
data['text'] = '%s = %d' % (
' + '.join([str(v) for v in vals]), sum(vals))
return data
@app.route("/", methods=['GET', 'POST'])
def roll():
try:
if request.method == 'POST':
spec = request.form['text']
else:
spec = request.args['spec']
return jsonify(do_roll(spec))
except:
return jsonify({
'response_type': 'ephemeral',
'text': USAGE
})
if __name__ == "__main__":
app.run(debug=True)
|
return {
'response_type': 'ephemeral',
'text': 'ERROR: unrecognized modifier `%s`' % flag
}
|
conditional_block
|
Layout.js
|
// @flow
/* eslint-disable react/no-danger */
// $FlowMeteor
import { find, propEq } from "ramda";
import { Link } from "react-router";
import Split, {
Left,
Right,
} from "../../../components/@primitives/layout/split";
import Meta from "../../../components/shared/meta";
import AddToCart from "../../../components/giving/add-to-cart";
type ILayout = {
account: Object,
};
const Layout = ({ account }: ILayout) => (
<div>
<Split nav classes={["background--light-primary"]}>
<Meta
title={account.name}
description={account.summary}
image={
account.images
? find(propEq("fileLabel", "2:1"), account.images).cloudfront
: account.image
}
meta={[{ property: "og:type", content: "article" }]}
/>
<Right
background={
account.images
? find(propEq("fileLabel", "2:1"), account.images).cloudfront
: account.image
}
mobile
/>
<Right
background={
account.images
? find(propEq("fileLabel", "2:1"), account.images).cloudfront
: account.image
}
mobile={false}
/>
</Split>
<Left scroll classes={["background--light-primary"]}>
<Link
to="/give/now"
className={
"locked-top locked-left soft-double@lap-and-up soft " +
"h7 text-dark-secondary plain visuallyhidden@handheld"
}
>
<i
className="icon-arrow-back soft-half-right display-inline-block"
style={{ verticalAlign: "middle" }}
/>
<span
className="display-inline-block"
style={{ verticalAlign: "middle", marginTop: "5px" }}
>
Back
</span>
</Link>
<div className="soft@lap-and-up soft-double-top@lap-and-up">
<div className="soft soft-double-bottom soft-double-top@lap-and-up">
<h2>{account.name}</h2>
|
<div className="constrain-copy soft-double@lap-and-up">
<div className="soft soft-double-bottom soft-double-top@lap-and-up">
<AddToCart accounts={[account]} donate />
</div>
</div>
</div>
</Left>
</div>
);
export default Layout;
|
<div dangerouslySetInnerHTML={{ __html: account.description }} />
</div>
</div>
<div className="background--light-secondary">
|
random_line_split
|
forms.py
|
from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class RegisterXForm(forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, label=u'Form Display Name')
class SubmitDataForm(forms.Form):
|
class FormDataGroupForm(forms.ModelForm):
"""Form for basic form group data"""
display_name = forms.CharField(widget=forms.TextInput(attrs={'size':'80'}))
view_name = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
def clean_view_name(self):
view_name = self.cleaned_data["view_name"]
if not re.match(r"^\w+$", view_name):
raise forms.ValidationError("View name can only contain numbers, letters, and underscores!")
# check that the view name is unique... if it was changed.
if self.instance.id:
if FormDataGroup.objects.get(id=self.instance.id).view_name != view_name and \
FormDataGroup.objects.filter(view_name=view_name).count() > 0:
raise forms.ValidationError("Sorry, view name %s is already in use! Please pick a new one." % view_name)
return self.cleaned_data["view_name"]
class Meta:
model = FormDataGroup
fields = ("display_name", "view_name")
|
file = forms.FileField()
|
identifier_body
|
forms.py
|
from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class RegisterXForm(forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, label=u'Form Display Name')
class SubmitDataForm(forms.Form):
file = forms.FileField()
class FormDataGroupForm(forms.ModelForm):
"""Form for basic form group data"""
display_name = forms.CharField(widget=forms.TextInput(attrs={'size':'80'}))
view_name = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
def clean_view_name(self):
view_name = self.cleaned_data["view_name"]
if not re.match(r"^\w+$", view_name):
raise forms.ValidationError("View name can only contain numbers, letters, and underscores!")
# check that the view name is unique... if it was changed.
if self.instance.id:
if FormDataGroup.objects.get(id=self.instance.id).view_name != view_name and \
|
model = FormDataGroup
fields = ("display_name", "view_name")
|
FormDataGroup.objects.filter(view_name=view_name).count() > 0:
raise forms.ValidationError("Sorry, view name %s is already in use! Please pick a new one." % view_name)
return self.cleaned_data["view_name"]
class Meta:
|
random_line_split
|
forms.py
|
from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class RegisterXForm(forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, label=u'Form Display Name')
class SubmitDataForm(forms.Form):
file = forms.FileField()
class FormDataGroupForm(forms.ModelForm):
"""Form for basic form group data"""
display_name = forms.CharField(widget=forms.TextInput(attrs={'size':'80'}))
view_name = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
def clean_view_name(self):
view_name = self.cleaned_data["view_name"]
if not re.match(r"^\w+$", view_name):
raise forms.ValidationError("View name can only contain numbers, letters, and underscores!")
# check that the view name is unique... if it was changed.
if self.instance.id:
|
return self.cleaned_data["view_name"]
class Meta:
model = FormDataGroup
fields = ("display_name", "view_name")
|
if FormDataGroup.objects.get(id=self.instance.id).view_name != view_name and \
FormDataGroup.objects.filter(view_name=view_name).count() > 0:
raise forms.ValidationError("Sorry, view name %s is already in use! Please pick a new one." % view_name)
|
conditional_block
|
forms.py
|
from django import forms
from models import FormDataGroup
import re
# On this page, users can upload an xsd file from their laptop
# Then they get redirected to a page where they can download the xsd
class
|
(forms.Form):
file = forms.FileField()
form_display_name= forms.CharField(max_length=128, label=u'Form Display Name')
class SubmitDataForm(forms.Form):
file = forms.FileField()
class FormDataGroupForm(forms.ModelForm):
"""Form for basic form group data"""
display_name = forms.CharField(widget=forms.TextInput(attrs={'size':'80'}))
view_name = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
def clean_view_name(self):
view_name = self.cleaned_data["view_name"]
if not re.match(r"^\w+$", view_name):
raise forms.ValidationError("View name can only contain numbers, letters, and underscores!")
# check that the view name is unique... if it was changed.
if self.instance.id:
if FormDataGroup.objects.get(id=self.instance.id).view_name != view_name and \
FormDataGroup.objects.filter(view_name=view_name).count() > 0:
raise forms.ValidationError("Sorry, view name %s is already in use! Please pick a new one." % view_name)
return self.cleaned_data["view_name"]
class Meta:
model = FormDataGroup
fields = ("display_name", "view_name")
|
RegisterXForm
|
identifier_name
|
android.py
|
# -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class
|
(Exception):
pass
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
raise GCMError(response.reason)
body = response.read()
if loads(body).get("failure") > 0:
raise GCMError(repr(body))
return True
|
GCMError
|
identifier_name
|
android.py
|
# -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
raise GCMError(response.reason)
body = response.read()
if loads(body).get("failure") > 0:
|
return True
|
raise GCMError(repr(body))
|
conditional_block
|
android.py
|
# -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
pass
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
|
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
raise GCMError(response.reason)
body = response.read()
if loads(body).get("failure") > 0:
raise GCMError(repr(body))
return True
|
random_line_split
|
|
android.py
|
# -*- encoding: utf-8 -*-
try:
from httplib import HTTPSConnection
from urlparse import urlparse
except ImportError:
from http.client import HTTPSConnection
from urllib.parse import urlparse
from json import dumps, loads
from django.conf import settings
class GCMError(Exception):
|
def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
headers = {
"Content-type": "application/json",
"Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY)
}
hook_url = 'https://android.googleapis.com/gcm/send'
data = {
"registration_ids": [user],
"data": {
"title": kwargs.pop("event"),
'message': message,
}
}
data['data'].update(kwargs)
up = urlparse(hook_url)
http = HTTPSConnection(up.netloc)
http.request(
"POST", up.path,
headers=headers,
body=dumps(data))
response = http.getresponse()
if response.status != 200:
raise GCMError(response.reason)
body = response.read()
if loads(body).get("failure") > 0:
raise GCMError(repr(body))
return True
|
pass
|
identifier_body
|
lib.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # The Rust core allocation library
//!
//! This is the lowest level library through which allocation in Rust can be
//! performed.
//!
//! This library, like libcore, is not intended for general usage, but rather as
//! a building block of other libraries. The types and interfaces in this
//! library are reexported through the [standard library](../std/index.html),
//! and should not be used through this library.
//!
//! Currently, there are four major definitions in this library.
//!
//! ## Boxed values
//!
//! The [`Box`](boxed/index.html) type is a smart pointer type. There can
//! only be one owner of a `Box`, and the owner can decide to mutate the
//! contents, which live on the heap.
//!
//! This type can be sent among threads efficiently as the size of a `Box` value
//! is the same as that of a pointer. Tree-like data structures are often built
//! with boxes because each node often has only one owner, the parent.
//!
//! ## Reference counted pointers
//!
//! The [`Rc`](rc/index.html) type is a non-threadsafe reference-counted pointer
//! type intended for sharing memory within a thread. An `Rc` pointer wraps a
//! type, `T`, and only allows access to `&T`, a shared reference.
//!
//! This type is useful when inherited mutability (such as using `Box`) is too
//! constraining for an application, and is often paired with the `Cell` or
//! `RefCell` types in order to allow mutation.
//!
//! ## Atomically reference counted pointers
//!
//! The [`Arc`](arc/index.html) type is the threadsafe equivalent of the `Rc`
//! type. It provides all the same functionality of `Rc`, except it requires
//! that the contained type `T` is shareable. Additionally, `Arc<T>` is itself
//! sendable while `Rc<T>` is not.
//!
//! This types allows for shared access to the contained data, and is often
//! paired with synchronization primitives such as mutexes to allow mutation of
//! shared resources.
//!
//! ## Heap interfaces
//!
//! The [`heap`](heap/index.html) module defines the low-level interface to the
//! default global allocator. It is not compatible with the libc allocator API.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "alloc"]
#![crate_type = "rlib"]
#![staged_api]
#![unstable(feature = "alloc",
reason = "this library is unlikely to be stabilized in its current \
form or name")]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
test(no_crate_inject))]
#![no_std]
#![feature(allocator)]
#![feature(box_syntax)]
#![feature(coerce_unsized)]
#![feature(core)]
#![feature(core_intrinsics)]
#![feature(core_prelude)]
#![feature(core_slice_ext)]
#![feature(custom_attribute)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(nonzero)]
#![feature(optin_builtin_traits)]
#![feature(placement_in_syntax)]
#![feature(placement_new_protocol)]
#![feature(raw)]
#![feature(staged_api)]
#![feature(unboxed_closures)]
#![feature(unique)]
#![feature(unsafe_no_drop_flag, filling_drop)]
#![feature(unsize)]
#![feature(core_slice_ext)]
#![feature(core_str_ext)]
#![cfg_attr(test, feature(test, alloc, rustc_private, box_raw))]
#![cfg_attr(all(not(feature = "external_funcs"), not(feature = "external_crate")),
feature(libc))]
#[macro_use]
extern crate core;
#[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate")))]
extern crate libc;
// Allow testing this library
#[cfg(test)] #[macro_use] extern crate std;
#[cfg(test)] #[macro_use] extern crate log;
// Heaps provided for low-level allocation strategies
pub mod heap;
// Primitive types using the heaps above
// Need to conditionally define the mod from `boxed.rs` to avoid
// duplicating the lang-items when building in test cfg; but also need
// to allow code to have `use boxed::HEAP;`
// and `use boxed::Box;` declarations.
#[cfg(not(test))]
pub mod boxed;
#[cfg(test)]
mod boxed { pub use std::boxed::{Box, HEAP}; }
#[cfg(test)]
mod boxed_test;
pub mod arc;
pub mod rc;
pub mod raw_vec;
/// Common out-of-memory routine
#[cold]
#[inline(never)]
#[unstable(feature = "oom", reason = "not a scrutinized interface")]
pub fn
|
() -> ! {
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// allocate.
unsafe { core::intrinsics::abort() }
}
|
oom
|
identifier_name
|
lib.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # The Rust core allocation library
//!
//! This is the lowest level library through which allocation in Rust can be
//! performed.
//!
//! This library, like libcore, is not intended for general usage, but rather as
//! a building block of other libraries. The types and interfaces in this
//! library are reexported through the [standard library](../std/index.html),
//! and should not be used through this library.
//!
//! Currently, there are four major definitions in this library.
//!
//! ## Boxed values
//!
//! The [`Box`](boxed/index.html) type is a smart pointer type. There can
//! only be one owner of a `Box`, and the owner can decide to mutate the
//! contents, which live on the heap.
//!
//! This type can be sent among threads efficiently as the size of a `Box` value
//! is the same as that of a pointer. Tree-like data structures are often built
//! with boxes because each node often has only one owner, the parent.
//!
//! ## Reference counted pointers
//!
//! The [`Rc`](rc/index.html) type is a non-threadsafe reference-counted pointer
//! type intended for sharing memory within a thread. An `Rc` pointer wraps a
//! type, `T`, and only allows access to `&T`, a shared reference.
//!
//! This type is useful when inherited mutability (such as using `Box`) is too
//! constraining for an application, and is often paired with the `Cell` or
//! `RefCell` types in order to allow mutation.
//!
//! ## Atomically reference counted pointers
//!
//! The [`Arc`](arc/index.html) type is the threadsafe equivalent of the `Rc`
//! type. It provides all the same functionality of `Rc`, except it requires
//! that the contained type `T` is shareable. Additionally, `Arc<T>` is itself
//! sendable while `Rc<T>` is not.
//!
//! This types allows for shared access to the contained data, and is often
//! paired with synchronization primitives such as mutexes to allow mutation of
//! shared resources.
//!
//! ## Heap interfaces
//!
//! The [`heap`](heap/index.html) module defines the low-level interface to the
//! default global allocator. It is not compatible with the libc allocator API.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "alloc"]
#![crate_type = "rlib"]
#![staged_api]
#![unstable(feature = "alloc",
reason = "this library is unlikely to be stabilized in its current \
form or name")]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
test(no_crate_inject))]
#![no_std]
#![feature(allocator)]
#![feature(box_syntax)]
#![feature(coerce_unsized)]
#![feature(core)]
#![feature(core_intrinsics)]
#![feature(core_prelude)]
#![feature(core_slice_ext)]
#![feature(custom_attribute)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(nonzero)]
#![feature(optin_builtin_traits)]
#![feature(placement_in_syntax)]
#![feature(placement_new_protocol)]
#![feature(raw)]
#![feature(staged_api)]
#![feature(unboxed_closures)]
#![feature(unique)]
#![feature(unsafe_no_drop_flag, filling_drop)]
#![feature(unsize)]
#![feature(core_slice_ext)]
#![feature(core_str_ext)]
#![cfg_attr(test, feature(test, alloc, rustc_private, box_raw))]
#![cfg_attr(all(not(feature = "external_funcs"), not(feature = "external_crate")),
feature(libc))]
#[macro_use]
extern crate core;
#[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate")))]
extern crate libc;
// Allow testing this library
#[cfg(test)] #[macro_use] extern crate std;
#[cfg(test)] #[macro_use] extern crate log;
// Heaps provided for low-level allocation strategies
pub mod heap;
// Primitive types using the heaps above
// Need to conditionally define the mod from `boxed.rs` to avoid
// duplicating the lang-items when building in test cfg; but also need
// to allow code to have `use boxed::HEAP;`
// and `use boxed::Box;` declarations.
#[cfg(not(test))]
pub mod boxed;
#[cfg(test)]
mod boxed { pub use std::boxed::{Box, HEAP}; }
#[cfg(test)]
mod boxed_test;
pub mod arc;
pub mod rc;
pub mod raw_vec;
/// Common out-of-memory routine
#[cold]
#[inline(never)]
#[unstable(feature = "oom", reason = "not a scrutinized interface")]
pub fn oom() -> !
|
{
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// allocate.
unsafe { core::intrinsics::abort() }
}
|
identifier_body
|
|
lib.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # The Rust core allocation library
//!
//! This is the lowest level library through which allocation in Rust can be
//! performed.
//!
//! This library, like libcore, is not intended for general usage, but rather as
//! a building block of other libraries. The types and interfaces in this
//! library are reexported through the [standard library](../std/index.html),
//! and should not be used through this library.
//!
//! Currently, there are four major definitions in this library.
//!
//! ## Boxed values
//!
//! The [`Box`](boxed/index.html) type is a smart pointer type. There can
//! only be one owner of a `Box`, and the owner can decide to mutate the
//! contents, which live on the heap.
//!
//! This type can be sent among threads efficiently as the size of a `Box` value
//! is the same as that of a pointer. Tree-like data structures are often built
//! with boxes because each node often has only one owner, the parent.
//!
//! ## Reference counted pointers
//!
//! The [`Rc`](rc/index.html) type is a non-threadsafe reference-counted pointer
//! type intended for sharing memory within a thread. An `Rc` pointer wraps a
//! type, `T`, and only allows access to `&T`, a shared reference.
//!
//! This type is useful when inherited mutability (such as using `Box`) is too
//! constraining for an application, and is often paired with the `Cell` or
//! `RefCell` types in order to allow mutation.
//!
//! ## Atomically reference counted pointers
//!
//! The [`Arc`](arc/index.html) type is the threadsafe equivalent of the `Rc`
//! type. It provides all the same functionality of `Rc`, except it requires
//! that the contained type `T` is shareable. Additionally, `Arc<T>` is itself
//! sendable while `Rc<T>` is not.
//!
//! This types allows for shared access to the contained data, and is often
//! paired with synchronization primitives such as mutexes to allow mutation of
//! shared resources.
//!
//! ## Heap interfaces
//!
//! The [`heap`](heap/index.html) module defines the low-level interface to the
//! default global allocator. It is not compatible with the libc allocator API.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "alloc"]
#![crate_type = "rlib"]
#![staged_api]
#![unstable(feature = "alloc",
reason = "this library is unlikely to be stabilized in its current \
form or name")]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
test(no_crate_inject))]
#![no_std]
#![feature(allocator)]
#![feature(box_syntax)]
#![feature(coerce_unsized)]
#![feature(core)]
#![feature(core_intrinsics)]
#![feature(core_prelude)]
#![feature(core_slice_ext)]
#![feature(custom_attribute)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(nonzero)]
#![feature(optin_builtin_traits)]
#![feature(placement_in_syntax)]
#![feature(placement_new_protocol)]
#![feature(raw)]
#![feature(staged_api)]
#![feature(unboxed_closures)]
#![feature(unique)]
#![feature(unsafe_no_drop_flag, filling_drop)]
#![feature(unsize)]
#![feature(core_slice_ext)]
#![feature(core_str_ext)]
#![cfg_attr(test, feature(test, alloc, rustc_private, box_raw))]
#![cfg_attr(all(not(feature = "external_funcs"), not(feature = "external_crate")),
feature(libc))]
#[macro_use]
extern crate core;
#[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate")))]
extern crate libc;
// Allow testing this library
#[cfg(test)] #[macro_use] extern crate std;
#[cfg(test)] #[macro_use] extern crate log;
// Heaps provided for low-level allocation strategies
pub mod heap;
// Primitive types using the heaps above
// Need to conditionally define the mod from `boxed.rs` to avoid
// duplicating the lang-items when building in test cfg; but also need
// to allow code to have `use boxed::HEAP;`
// and `use boxed::Box;` declarations.
#[cfg(not(test))]
pub mod boxed;
#[cfg(test)]
mod boxed { pub use std::boxed::{Box, HEAP}; }
#[cfg(test)]
mod boxed_test;
pub mod arc;
|
/// Common out-of-memory routine
#[cold]
#[inline(never)]
#[unstable(feature = "oom", reason = "not a scrutinized interface")]
pub fn oom() -> ! {
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// allocate.
unsafe { core::intrinsics::abort() }
}
|
pub mod rc;
pub mod raw_vec;
|
random_line_split
|
res_config.py
|
# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
class AccountPaymentConfig(osv.TransientModel):
_inherit = 'account.config.settings'
_columns = {
'module_payment_transfer': fields.boolean(
'Wire Transfer',
help='-This installs the module payment_transfer.'),
'module_payment_paypal': fields.boolean(
'Paypal',
help='-This installs the module payment_paypal.'),
'module_payment_ogone': fields.boolean(
'Ogone',
help='-This installs the module payment_ogone.'),
'module_payment_adyen': fields.boolean(
'Adyen',
help='-This installs the module payment_adyen.'),
'module_payment_buckaroo': fields.boolean(
'Buckaroo',
help='-This installs the module payment_buckaroo.'),
'module_payment_authorize': fields.boolean(
'Authorize.Net',
help='-This installs the module payment_authorize.'),
|
_defaults = {
'module_payment_transfer': True
}
|
'module_payment_sips': fields.boolean(
'Sips',
help='-This installs the module payment_sips.'),
}
|
random_line_split
|
res_config.py
|
# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
class
|
(osv.TransientModel):
_inherit = 'account.config.settings'
_columns = {
'module_payment_transfer': fields.boolean(
'Wire Transfer',
help='-This installs the module payment_transfer.'),
'module_payment_paypal': fields.boolean(
'Paypal',
help='-This installs the module payment_paypal.'),
'module_payment_ogone': fields.boolean(
'Ogone',
help='-This installs the module payment_ogone.'),
'module_payment_adyen': fields.boolean(
'Adyen',
help='-This installs the module payment_adyen.'),
'module_payment_buckaroo': fields.boolean(
'Buckaroo',
help='-This installs the module payment_buckaroo.'),
'module_payment_authorize': fields.boolean(
'Authorize.Net',
help='-This installs the module payment_authorize.'),
'module_payment_sips': fields.boolean(
'Sips',
help='-This installs the module payment_sips.'),
}
_defaults = {
'module_payment_transfer': True
}
|
AccountPaymentConfig
|
identifier_name
|
res_config.py
|
# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
class AccountPaymentConfig(osv.TransientModel):
|
_inherit = 'account.config.settings'
_columns = {
'module_payment_transfer': fields.boolean(
'Wire Transfer',
help='-This installs the module payment_transfer.'),
'module_payment_paypal': fields.boolean(
'Paypal',
help='-This installs the module payment_paypal.'),
'module_payment_ogone': fields.boolean(
'Ogone',
help='-This installs the module payment_ogone.'),
'module_payment_adyen': fields.boolean(
'Adyen',
help='-This installs the module payment_adyen.'),
'module_payment_buckaroo': fields.boolean(
'Buckaroo',
help='-This installs the module payment_buckaroo.'),
'module_payment_authorize': fields.boolean(
'Authorize.Net',
help='-This installs the module payment_authorize.'),
'module_payment_sips': fields.boolean(
'Sips',
help='-This installs the module payment_sips.'),
}
_defaults = {
'module_payment_transfer': True
}
|
identifier_body
|
|
lib.rs
|
#![warn(missing_docs)]
//! Simple and generic implementation of 2D vectors
//!
//! Intended for use in 2D game engines
extern crate num_traits;
#[cfg(feature="rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="serde_derive")]
#[cfg_attr(feature="serde_derive", macro_use)]
extern crate serde_derive;
use num_traits::Float;
/// Representation of a mathematical vector e.g. a position or velocity
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature="rustc-serialize", derive(RustcDecodable, RustcEncodable))]
#[cfg_attr(feature="serde_derive", derive(Serialize, Deserialize))]
pub struct Vector2<T>(pub T, pub T);
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
use std::convert::From;
/// Constants for common vectors
pub mod consts{
use super::Vector2;
/// The zero vector
pub const ZERO_F32: Vector2<f32> = Vector2(0., 0.);
/// A unit vector pointing upwards
pub const UP_F32: Vector2<f32> = Vector2(0., 1.);
/// A unit vector pointing downwards
pub const DOWN_F32: Vector2<f32> = Vector2(0., -1.);
/// A unit vector pointing to the right
pub const RIGHT_F32: Vector2<f32> = Vector2(1., 0.);
/// A unit vector pointing to the left
pub const LEFT_F32: Vector2<f32> = Vector2(-1., 0.);
/// The zero vector
pub const ZERO_F64: Vector2<f64> = Vector2(0., 0.);
/// A unit vector pointing upwards
pub const UP_F64: Vector2<f64> = Vector2(0., 1.);
/// A unit vector pointing downwards
pub const DOWN_F64: Vector2<f64> = Vector2(0., -1.);
/// A unit vector pointing to the right
pub const RIGHT_F64: Vector2<f64> = Vector2(1., 0.);
/// A unit vector pointing to the left
pub const LEFT_F64: Vector2<f64> = Vector2(-1., 0.);
}
impl<T: Float> Vector2<T>{
/// Creates a new unit vector in a specific direction
pub fn
|
(direction: T) -> Self{
let (y, x) = direction.sin_cos();
Vector2(x, y)
}
/// Normalises the vector
pub fn normalise(self) -> Self{
self / self.length()
}
/// Returns the magnitude/length of the vector
pub fn length(self) -> T{
// This is apparently faster than using hypot
self.length_squared().sqrt()
}
/// Returns the magnitude/length of the vector squared
pub fn length_squared(self) -> T{
self.0.powi(2) + self.1.powi(2)
}
/// Returns direction the vector is pointing
pub fn direction(self) -> T{
self.1.atan2(self.0)
}
/// Returns direction towards another vector
pub fn direction_to(self, other: Self) -> T{
(other-self).direction()
}
/// Returns the distance betweens two vectors
pub fn distance_to(self, other: Self) -> T{
(other-self).length()
}
/// Returns the distance betweens two vectors
pub fn distance_to_squared(self, other: Self) -> T{
(other-self).length_squared()
}
/// Returns `true` if either component is `NaN`.
pub fn is_any_nan(&self) -> bool{
self.0.is_nan() || self.1.is_nan()
}
/// Returns `true` if either component is positive or negative infinity.
pub fn is_any_infinite(&self) -> bool{
self.0.is_infinite() || self.1.is_infinite()
}
/// Returns `true` if both components are neither infinite nor `NaN`.
pub fn is_all_finite(&self) -> bool{
self.0.is_finite() && self.1.is_finite()
}
/// Returns `true` if both components are neither zero, infinite, subnormal nor `NaN`.
pub fn is_all_normal(&self) -> bool{
self.0.is_normal() && self.1.is_normal()
}
}
macro_rules! impl_for {
($($t:ty)*) => {$(
impl Mul<Vector2<$t>> for $t{
type Output = Vector2<$t>;
fn mul(self, rhs: Vector2<$t>) -> Vector2<$t>{
Vector2(self * rhs.0, self * rhs.1)
}
}
impl Div<Vector2<$t>> for $t{
type Output = Vector2<$t>;
fn div(self, rhs: Vector2<$t>) -> Vector2<$t>{
Vector2(self / rhs.0, self / rhs.1)
}
}
)*};
}impl_for!{f32 f64}
impl<T> Vector2<T> {
/// Returns the normal vector (aka. hat vector) of this vector i.e. a perpendicular vector
///
/// Not to be confused with `normalise` which returns a unit vector
///
/// Defined as (-y, x)
pub fn normal(self) -> Self
where T: Neg<Output=T> {
let Vector2(x, y) = self;
Vector2(-y, x)
}
/// Returns the dot product of two vectors
pub fn dot(self, other: Self) -> <<T as Mul>::Output as Add>::Output
where T: Mul, <T as Mul>::Output: Add{
self.0 * other.0 + self.1 * other.1
}
/// Returns the determinant of two vectors
pub fn det(self, other: Self) -> <<T as Mul>::Output as Sub>::Output
where T: Mul, <T as Mul>::Output: Sub {
self.0 * other.1 - self.1 * other.0
}
}
impl<T: Add> Add for Vector2<T>{
type Output = Vector2<T::Output>;
fn add(self, rhs: Self) -> Self::Output{
Vector2(self.0 + rhs.0, self.1 + rhs.1)
}
}
impl<T: Sub> Sub for Vector2<T>{
type Output = Vector2<T::Output>;
fn sub(self, rhs: Self) -> Self::Output{
Vector2(self.0 - rhs.0, self.1 - rhs.1)
}
}
impl<T: AddAssign> AddAssign for Vector2<T>{
fn add_assign(&mut self, rhs: Self){
self.0 += rhs.0;
self.1 += rhs.1;
}
}
impl<T: SubAssign> SubAssign for Vector2<T>{
fn sub_assign(&mut self, rhs: Self){
self.0 -= rhs.0;
self.1 -= rhs.1;
}
}
impl<T: MulAssign + Copy> MulAssign<T> for Vector2<T>{
fn mul_assign(&mut self, rhs: T){
self.0 *= rhs;
self.1 *= rhs;
}
}
impl<T: DivAssign + Copy> DivAssign<T> for Vector2<T>{
fn div_assign(&mut self, rhs: T){
self.0 /= rhs;
self.1 /= rhs;
}
}
impl<T: Mul + Copy> Mul<T> for Vector2<T>{
type Output = Vector2<T::Output>;
fn mul(self, rhs: T) -> Self::Output{
Vector2(self.0 * rhs, self.1 * rhs)
}
}
impl<T: Div + Copy> Div<T> for Vector2<T>{
type Output = Vector2<T::Output>;
fn div(self, rhs: T) -> Self::Output{
Vector2(self.0/rhs, self.1/rhs)
}
}
impl<T: Neg> Neg for Vector2<T>{
type Output = Vector2<T::Output>;
fn neg(self) -> Self::Output{
Vector2(-self.0, -self.1)
}
}
impl<T> Into<[T; 2]> for Vector2<T>{
#[inline]
fn into(self) -> [T; 2]{
[self.0, self.1]
}
}
impl<T: Copy> From<[T; 2]> for Vector2<T>{
#[inline]
fn from(array: [T; 2]) -> Self{
Vector2(array[0], array[1])
}
}
impl<T> Into<(T, T)> for Vector2<T>{
#[inline]
fn into(self) -> (T, T){
(self.0, self.1)
}
}
impl<T> From<(T, T)> for Vector2<T>{
#[inline]
fn from(tuple: (T, T)) -> Self{
Vector2(tuple.0, tuple.1)
}
}
|
unit_vector
|
identifier_name
|
lib.rs
|
#![warn(missing_docs)]
//! Simple and generic implementation of 2D vectors
//!
//! Intended for use in 2D game engines
extern crate num_traits;
#[cfg(feature="rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="serde_derive")]
#[cfg_attr(feature="serde_derive", macro_use)]
extern crate serde_derive;
use num_traits::Float;
/// Representation of a mathematical vector e.g. a position or velocity
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature="rustc-serialize", derive(RustcDecodable, RustcEncodable))]
#[cfg_attr(feature="serde_derive", derive(Serialize, Deserialize))]
pub struct Vector2<T>(pub T, pub T);
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
use std::convert::From;
/// Constants for common vectors
pub mod consts{
use super::Vector2;
/// The zero vector
pub const ZERO_F32: Vector2<f32> = Vector2(0., 0.);
/// A unit vector pointing upwards
pub const UP_F32: Vector2<f32> = Vector2(0., 1.);
/// A unit vector pointing downwards
pub const DOWN_F32: Vector2<f32> = Vector2(0., -1.);
/// A unit vector pointing to the right
pub const RIGHT_F32: Vector2<f32> = Vector2(1., 0.);
/// A unit vector pointing to the left
pub const LEFT_F32: Vector2<f32> = Vector2(-1., 0.);
/// The zero vector
pub const ZERO_F64: Vector2<f64> = Vector2(0., 0.);
/// A unit vector pointing upwards
pub const UP_F64: Vector2<f64> = Vector2(0., 1.);
/// A unit vector pointing downwards
pub const DOWN_F64: Vector2<f64> = Vector2(0., -1.);
/// A unit vector pointing to the right
pub const RIGHT_F64: Vector2<f64> = Vector2(1., 0.);
/// A unit vector pointing to the left
pub const LEFT_F64: Vector2<f64> = Vector2(-1., 0.);
}
impl<T: Float> Vector2<T>{
/// Creates a new unit vector in a specific direction
pub fn unit_vector(direction: T) -> Self{
let (y, x) = direction.sin_cos();
Vector2(x, y)
}
/// Normalises the vector
pub fn normalise(self) -> Self{
self / self.length()
}
/// Returns the magnitude/length of the vector
pub fn length(self) -> T{
// This is apparently faster than using hypot
self.length_squared().sqrt()
}
/// Returns the magnitude/length of the vector squared
pub fn length_squared(self) -> T{
self.0.powi(2) + self.1.powi(2)
}
/// Returns direction the vector is pointing
pub fn direction(self) -> T{
self.1.atan2(self.0)
}
/// Returns direction towards another vector
pub fn direction_to(self, other: Self) -> T{
(other-self).direction()
}
/// Returns the distance betweens two vectors
pub fn distance_to(self, other: Self) -> T{
(other-self).length()
}
/// Returns the distance betweens two vectors
pub fn distance_to_squared(self, other: Self) -> T{
(other-self).length_squared()
}
/// Returns `true` if either component is `NaN`.
pub fn is_any_nan(&self) -> bool{
self.0.is_nan() || self.1.is_nan()
}
/// Returns `true` if either component is positive or negative infinity.
pub fn is_any_infinite(&self) -> bool{
self.0.is_infinite() || self.1.is_infinite()
}
/// Returns `true` if both components are neither infinite nor `NaN`.
pub fn is_all_finite(&self) -> bool{
self.0.is_finite() && self.1.is_finite()
}
/// Returns `true` if both components are neither zero, infinite, subnormal nor `NaN`.
pub fn is_all_normal(&self) -> bool{
self.0.is_normal() && self.1.is_normal()
}
}
macro_rules! impl_for {
($($t:ty)*) => {$(
impl Mul<Vector2<$t>> for $t{
type Output = Vector2<$t>;
fn mul(self, rhs: Vector2<$t>) -> Vector2<$t>{
Vector2(self * rhs.0, self * rhs.1)
}
}
impl Div<Vector2<$t>> for $t{
type Output = Vector2<$t>;
fn div(self, rhs: Vector2<$t>) -> Vector2<$t>{
Vector2(self / rhs.0, self / rhs.1)
}
}
)*};
}impl_for!{f32 f64}
impl<T> Vector2<T> {
/// Returns the normal vector (aka. hat vector) of this vector i.e. a perpendicular vector
///
/// Not to be confused with `normalise` which returns a unit vector
///
/// Defined as (-y, x)
pub fn normal(self) -> Self
where T: Neg<Output=T> {
let Vector2(x, y) = self;
Vector2(-y, x)
}
/// Returns the dot product of two vectors
pub fn dot(self, other: Self) -> <<T as Mul>::Output as Add>::Output
where T: Mul, <T as Mul>::Output: Add{
self.0 * other.0 + self.1 * other.1
}
/// Returns the determinant of two vectors
pub fn det(self, other: Self) -> <<T as Mul>::Output as Sub>::Output
where T: Mul, <T as Mul>::Output: Sub {
self.0 * other.1 - self.1 * other.0
}
}
impl<T: Add> Add for Vector2<T>{
type Output = Vector2<T::Output>;
fn add(self, rhs: Self) -> Self::Output{
Vector2(self.0 + rhs.0, self.1 + rhs.1)
}
}
impl<T: Sub> Sub for Vector2<T>{
type Output = Vector2<T::Output>;
fn sub(self, rhs: Self) -> Self::Output{
Vector2(self.0 - rhs.0, self.1 - rhs.1)
}
}
impl<T: AddAssign> AddAssign for Vector2<T>{
fn add_assign(&mut self, rhs: Self){
self.0 += rhs.0;
self.1 += rhs.1;
}
}
impl<T: SubAssign> SubAssign for Vector2<T>{
fn sub_assign(&mut self, rhs: Self){
self.0 -= rhs.0;
self.1 -= rhs.1;
}
}
impl<T: MulAssign + Copy> MulAssign<T> for Vector2<T>{
fn mul_assign(&mut self, rhs: T){
self.0 *= rhs;
self.1 *= rhs;
}
}
impl<T: DivAssign + Copy> DivAssign<T> for Vector2<T>{
fn div_assign(&mut self, rhs: T){
self.0 /= rhs;
self.1 /= rhs;
}
}
impl<T: Mul + Copy> Mul<T> for Vector2<T>{
type Output = Vector2<T::Output>;
fn mul(self, rhs: T) -> Self::Output{
Vector2(self.0 * rhs, self.1 * rhs)
}
}
impl<T: Div + Copy> Div<T> for Vector2<T>{
type Output = Vector2<T::Output>;
fn div(self, rhs: T) -> Self::Output{
|
Vector2(self.0/rhs, self.1/rhs)
}
}
impl<T: Neg> Neg for Vector2<T>{
type Output = Vector2<T::Output>;
fn neg(self) -> Self::Output{
Vector2(-self.0, -self.1)
}
}
impl<T> Into<[T; 2]> for Vector2<T>{
#[inline]
fn into(self) -> [T; 2]{
[self.0, self.1]
}
}
impl<T: Copy> From<[T; 2]> for Vector2<T>{
#[inline]
fn from(array: [T; 2]) -> Self{
Vector2(array[0], array[1])
}
}
impl<T> Into<(T, T)> for Vector2<T>{
#[inline]
fn into(self) -> (T, T){
(self.0, self.1)
}
}
impl<T> From<(T, T)> for Vector2<T>{
#[inline]
fn from(tuple: (T, T)) -> Self{
Vector2(tuple.0, tuple.1)
}
}
|
random_line_split
|
|
lib.rs
|
#![warn(missing_docs)]
//! Simple and generic implementation of 2D vectors
//!
//! Intended for use in 2D game engines
extern crate num_traits;
#[cfg(feature="rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="serde_derive")]
#[cfg_attr(feature="serde_derive", macro_use)]
extern crate serde_derive;
use num_traits::Float;
/// Representation of a mathematical vector e.g. a position or velocity
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature="rustc-serialize", derive(RustcDecodable, RustcEncodable))]
#[cfg_attr(feature="serde_derive", derive(Serialize, Deserialize))]
pub struct Vector2<T>(pub T, pub T);
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
use std::convert::From;
/// Constants for common vectors
pub mod consts{
use super::Vector2;
/// The zero vector
pub const ZERO_F32: Vector2<f32> = Vector2(0., 0.);
/// A unit vector pointing upwards
pub const UP_F32: Vector2<f32> = Vector2(0., 1.);
/// A unit vector pointing downwards
pub const DOWN_F32: Vector2<f32> = Vector2(0., -1.);
/// A unit vector pointing to the right
pub const RIGHT_F32: Vector2<f32> = Vector2(1., 0.);
/// A unit vector pointing to the left
pub const LEFT_F32: Vector2<f32> = Vector2(-1., 0.);
/// The zero vector
pub const ZERO_F64: Vector2<f64> = Vector2(0., 0.);
/// A unit vector pointing upwards
pub const UP_F64: Vector2<f64> = Vector2(0., 1.);
/// A unit vector pointing downwards
pub const DOWN_F64: Vector2<f64> = Vector2(0., -1.);
/// A unit vector pointing to the right
pub const RIGHT_F64: Vector2<f64> = Vector2(1., 0.);
/// A unit vector pointing to the left
pub const LEFT_F64: Vector2<f64> = Vector2(-1., 0.);
}
impl<T: Float> Vector2<T>{
/// Creates a new unit vector in a specific direction
pub fn unit_vector(direction: T) -> Self{
let (y, x) = direction.sin_cos();
Vector2(x, y)
}
/// Normalises the vector
pub fn normalise(self) -> Self{
self / self.length()
}
/// Returns the magnitude/length of the vector
pub fn length(self) -> T{
// This is apparently faster than using hypot
self.length_squared().sqrt()
}
/// Returns the magnitude/length of the vector squared
pub fn length_squared(self) -> T
|
/// Returns direction the vector is pointing
pub fn direction(self) -> T{
self.1.atan2(self.0)
}
/// Returns direction towards another vector
pub fn direction_to(self, other: Self) -> T{
(other-self).direction()
}
/// Returns the distance betweens two vectors
pub fn distance_to(self, other: Self) -> T{
(other-self).length()
}
/// Returns the distance betweens two vectors
pub fn distance_to_squared(self, other: Self) -> T{
(other-self).length_squared()
}
/// Returns `true` if either component is `NaN`.
pub fn is_any_nan(&self) -> bool{
self.0.is_nan() || self.1.is_nan()
}
/// Returns `true` if either component is positive or negative infinity.
pub fn is_any_infinite(&self) -> bool{
self.0.is_infinite() || self.1.is_infinite()
}
/// Returns `true` if both components are neither infinite nor `NaN`.
pub fn is_all_finite(&self) -> bool{
self.0.is_finite() && self.1.is_finite()
}
/// Returns `true` if both components are neither zero, infinite, subnormal nor `NaN`.
pub fn is_all_normal(&self) -> bool{
self.0.is_normal() && self.1.is_normal()
}
}
macro_rules! impl_for {
($($t:ty)*) => {$(
impl Mul<Vector2<$t>> for $t{
type Output = Vector2<$t>;
fn mul(self, rhs: Vector2<$t>) -> Vector2<$t>{
Vector2(self * rhs.0, self * rhs.1)
}
}
impl Div<Vector2<$t>> for $t{
type Output = Vector2<$t>;
fn div(self, rhs: Vector2<$t>) -> Vector2<$t>{
Vector2(self / rhs.0, self / rhs.1)
}
}
)*};
}impl_for!{f32 f64}
impl<T> Vector2<T> {
/// Returns the normal vector (aka. hat vector) of this vector i.e. a perpendicular vector
///
/// Not to be confused with `normalise` which returns a unit vector
///
/// Defined as (-y, x)
pub fn normal(self) -> Self
where T: Neg<Output=T> {
let Vector2(x, y) = self;
Vector2(-y, x)
}
/// Returns the dot product of two vectors
pub fn dot(self, other: Self) -> <<T as Mul>::Output as Add>::Output
where T: Mul, <T as Mul>::Output: Add{
self.0 * other.0 + self.1 * other.1
}
/// Returns the determinant of two vectors
pub fn det(self, other: Self) -> <<T as Mul>::Output as Sub>::Output
where T: Mul, <T as Mul>::Output: Sub {
self.0 * other.1 - self.1 * other.0
}
}
impl<T: Add> Add for Vector2<T>{
type Output = Vector2<T::Output>;
fn add(self, rhs: Self) -> Self::Output{
Vector2(self.0 + rhs.0, self.1 + rhs.1)
}
}
impl<T: Sub> Sub for Vector2<T>{
type Output = Vector2<T::Output>;
fn sub(self, rhs: Self) -> Self::Output{
Vector2(self.0 - rhs.0, self.1 - rhs.1)
}
}
impl<T: AddAssign> AddAssign for Vector2<T>{
fn add_assign(&mut self, rhs: Self){
self.0 += rhs.0;
self.1 += rhs.1;
}
}
impl<T: SubAssign> SubAssign for Vector2<T>{
fn sub_assign(&mut self, rhs: Self){
self.0 -= rhs.0;
self.1 -= rhs.1;
}
}
impl<T: MulAssign + Copy> MulAssign<T> for Vector2<T>{
fn mul_assign(&mut self, rhs: T){
self.0 *= rhs;
self.1 *= rhs;
}
}
impl<T: DivAssign + Copy> DivAssign<T> for Vector2<T>{
fn div_assign(&mut self, rhs: T){
self.0 /= rhs;
self.1 /= rhs;
}
}
impl<T: Mul + Copy> Mul<T> for Vector2<T>{
type Output = Vector2<T::Output>;
fn mul(self, rhs: T) -> Self::Output{
Vector2(self.0 * rhs, self.1 * rhs)
}
}
impl<T: Div + Copy> Div<T> for Vector2<T>{
type Output = Vector2<T::Output>;
fn div(self, rhs: T) -> Self::Output{
Vector2(self.0/rhs, self.1/rhs)
}
}
impl<T: Neg> Neg for Vector2<T>{
type Output = Vector2<T::Output>;
fn neg(self) -> Self::Output{
Vector2(-self.0, -self.1)
}
}
impl<T> Into<[T; 2]> for Vector2<T>{
#[inline]
fn into(self) -> [T; 2]{
[self.0, self.1]
}
}
impl<T: Copy> From<[T; 2]> for Vector2<T>{
#[inline]
fn from(array: [T; 2]) -> Self{
Vector2(array[0], array[1])
}
}
impl<T> Into<(T, T)> for Vector2<T>{
#[inline]
fn into(self) -> (T, T){
(self.0, self.1)
}
}
impl<T> From<(T, T)> for Vector2<T>{
#[inline]
fn from(tuple: (T, T)) -> Self{
Vector2(tuple.0, tuple.1)
}
}
|
{
self.0.powi(2) + self.1.powi(2)
}
|
identifier_body
|
mongodbUpgrade.js
|
// This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb
// This code moves your data from NeDB to MongoDB
// You will first need to create the MongoDB connection in your /routes/config.json file
// You then need to ensure your MongoDB Database has been created.
// ** IMPORTANT **
// There are no duplication checks in place. Please only run this script once.
// ** IMPORTANT **
const Nedb = require('nedb');
const mongodb = require('mongodb');
const async = require('async');
const path = require('path');
const common = require('../routes/common');
const config = common.read_config();
let ndb;
|
process.exit(1);
}
// Connect to the MongoDB database
mongodb.connect(config.settings.database.connection_string, {}, (err, mdb) => {
if(err){
console.log('Couldn\'t connect to the Mongo database');
console.log(err);
process.exit(1);
}
console.log('Connected to: ' + config.settings.database.connection_string);
console.log('');
insertKB(mdb, (KBerr, report) => {
insertUsers(mdb, (Usererr, report) => {
if(KBerr || Usererr){
console.log('There was an error upgrading to MongoDB. Check the console output');
}else{
console.log('MongoDB upgrade completed successfully');
process.exit();
}
});
});
});
function insertKB(db, callback){
const collection = db.collection('kb');
console.log(path.join(__dirname, 'kb.db'));
ndb = new Nedb(path.join(__dirname, 'kb.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' article(s) data from the NeDB database');
console.log('');
}
console.log('Inserting articles into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('Article inserted: ' + doc.kb_title);
// check for permalink. If it is not set we set the old NeDB _id to the permalink to stop links from breaking.
if(!doc.kb_permalink || doc.kb_permalink === ''){
doc.kb_permalink = doc._id;
}
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.log('An error happened while inserting data');
callback(err, null);
}else{
console.log('All articles successfully inserted');
console.log('');
callback(null, 'All articles successfully inserted');
}
});
});
});
};
function insertUsers(db, callback){
const collection = db.collection('users');
ndb = new Nedb(path.join(__dirname, 'users.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' user(s) data from the NeDB database');
console.log('');
}
console.log('Inserting users into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('User inserted: ' + doc.user_email);
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.error('An error happened while inserting user data');
callback(err, null);
}else{
console.log('All users successfully inserted');
console.log('');
callback(null, 'All users successfully inserted');
}
});
});
});
};
|
// check for DB config
if(!config.settings.database.connection_string){
console.log('No MongoDB configured. Please see README.md for help');
|
random_line_split
|
mongodbUpgrade.js
|
// This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb
// This code moves your data from NeDB to MongoDB
// You will first need to create the MongoDB connection in your /routes/config.json file
// You then need to ensure your MongoDB Database has been created.
// ** IMPORTANT **
// There are no duplication checks in place. Please only run this script once.
// ** IMPORTANT **
const Nedb = require('nedb');
const mongodb = require('mongodb');
const async = require('async');
const path = require('path');
const common = require('../routes/common');
const config = common.read_config();
let ndb;
// check for DB config
if(!config.settings.database.connection_string){
console.log('No MongoDB configured. Please see README.md for help');
process.exit(1);
}
// Connect to the MongoDB database
mongodb.connect(config.settings.database.connection_string, {}, (err, mdb) => {
if(err){
console.log('Couldn\'t connect to the Mongo database');
console.log(err);
process.exit(1);
}
console.log('Connected to: ' + config.settings.database.connection_string);
console.log('');
insertKB(mdb, (KBerr, report) => {
insertUsers(mdb, (Usererr, report) => {
if(KBerr || Usererr){
console.log('There was an error upgrading to MongoDB. Check the console output');
}else{
console.log('MongoDB upgrade completed successfully');
process.exit();
}
});
});
});
function insertKB(db, callback){
const collection = db.collection('kb');
console.log(path.join(__dirname, 'kb.db'));
ndb = new Nedb(path.join(__dirname, 'kb.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' article(s) data from the NeDB database');
console.log('');
}
console.log('Inserting articles into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('Article inserted: ' + doc.kb_title);
// check for permalink. If it is not set we set the old NeDB _id to the permalink to stop links from breaking.
if(!doc.kb_permalink || doc.kb_permalink === ''){
doc.kb_permalink = doc._id;
}
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.log('An error happened while inserting data');
callback(err, null);
}else{
console.log('All articles successfully inserted');
console.log('');
callback(null, 'All articles successfully inserted');
}
});
});
});
};
function insertUsers(db, callback){
const collection = db.collection('users');
ndb = new Nedb(path.join(__dirname, 'users.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' user(s) data from the NeDB database');
console.log('');
}
console.log('Inserting users into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('User inserted: ' + doc.user_email);
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.error('An error happened while inserting user data');
callback(err, null);
}else
|
});
});
});
};
|
{
console.log('All users successfully inserted');
console.log('');
callback(null, 'All users successfully inserted');
}
|
conditional_block
|
mongodbUpgrade.js
|
// This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb
// This code moves your data from NeDB to MongoDB
// You will first need to create the MongoDB connection in your /routes/config.json file
// You then need to ensure your MongoDB Database has been created.
// ** IMPORTANT **
// There are no duplication checks in place. Please only run this script once.
// ** IMPORTANT **
const Nedb = require('nedb');
const mongodb = require('mongodb');
const async = require('async');
const path = require('path');
const common = require('../routes/common');
const config = common.read_config();
let ndb;
// check for DB config
if(!config.settings.database.connection_string){
console.log('No MongoDB configured. Please see README.md for help');
process.exit(1);
}
// Connect to the MongoDB database
mongodb.connect(config.settings.database.connection_string, {}, (err, mdb) => {
if(err){
console.log('Couldn\'t connect to the Mongo database');
console.log(err);
process.exit(1);
}
console.log('Connected to: ' + config.settings.database.connection_string);
console.log('');
insertKB(mdb, (KBerr, report) => {
insertUsers(mdb, (Usererr, report) => {
if(KBerr || Usererr){
console.log('There was an error upgrading to MongoDB. Check the console output');
}else{
console.log('MongoDB upgrade completed successfully');
process.exit();
}
});
});
});
function insertKB(db, callback)
|
;
function insertUsers(db, callback){
const collection = db.collection('users');
ndb = new Nedb(path.join(__dirname, 'users.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' user(s) data from the NeDB database');
console.log('');
}
console.log('Inserting users into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('User inserted: ' + doc.user_email);
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.error('An error happened while inserting user data');
callback(err, null);
}else{
console.log('All users successfully inserted');
console.log('');
callback(null, 'All users successfully inserted');
}
});
});
});
};
|
{
const collection = db.collection('kb');
console.log(path.join(__dirname, 'kb.db'));
ndb = new Nedb(path.join(__dirname, 'kb.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' article(s) data from the NeDB database');
console.log('');
}
console.log('Inserting articles into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('Article inserted: ' + doc.kb_title);
// check for permalink. If it is not set we set the old NeDB _id to the permalink to stop links from breaking.
if(!doc.kb_permalink || doc.kb_permalink === ''){
doc.kb_permalink = doc._id;
}
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.log('An error happened while inserting data');
callback(err, null);
}else{
console.log('All articles successfully inserted');
console.log('');
callback(null, 'All articles successfully inserted');
}
});
});
});
}
|
identifier_body
|
mongodbUpgrade.js
|
// This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb
// This code moves your data from NeDB to MongoDB
// You will first need to create the MongoDB connection in your /routes/config.json file
// You then need to ensure your MongoDB Database has been created.
// ** IMPORTANT **
// There are no duplication checks in place. Please only run this script once.
// ** IMPORTANT **
const Nedb = require('nedb');
const mongodb = require('mongodb');
const async = require('async');
const path = require('path');
const common = require('../routes/common');
const config = common.read_config();
let ndb;
// check for DB config
if(!config.settings.database.connection_string){
console.log('No MongoDB configured. Please see README.md for help');
process.exit(1);
}
// Connect to the MongoDB database
mongodb.connect(config.settings.database.connection_string, {}, (err, mdb) => {
if(err){
console.log('Couldn\'t connect to the Mongo database');
console.log(err);
process.exit(1);
}
console.log('Connected to: ' + config.settings.database.connection_string);
console.log('');
insertKB(mdb, (KBerr, report) => {
insertUsers(mdb, (Usererr, report) => {
if(KBerr || Usererr){
console.log('There was an error upgrading to MongoDB. Check the console output');
}else{
console.log('MongoDB upgrade completed successfully');
process.exit();
}
});
});
});
function insertKB(db, callback){
const collection = db.collection('kb');
console.log(path.join(__dirname, 'kb.db'));
ndb = new Nedb(path.join(__dirname, 'kb.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' article(s) data from the NeDB database');
console.log('');
}
console.log('Inserting articles into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('Article inserted: ' + doc.kb_title);
// check for permalink. If it is not set we set the old NeDB _id to the permalink to stop links from breaking.
if(!doc.kb_permalink || doc.kb_permalink === ''){
doc.kb_permalink = doc._id;
}
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.log('An error happened while inserting data');
callback(err, null);
}else{
console.log('All articles successfully inserted');
console.log('');
callback(null, 'All articles successfully inserted');
}
});
});
});
};
function
|
(db, callback){
const collection = db.collection('users');
ndb = new Nedb(path.join(__dirname, 'users.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' user(s) data from the NeDB database');
console.log('');
}
console.log('Inserting users into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('User inserted: ' + doc.user_email);
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.error('An error happened while inserting user data');
callback(err, null);
}else{
console.log('All users successfully inserted');
console.log('');
callback(null, 'All users successfully inserted');
}
});
});
});
};
|
insertUsers
|
identifier_name
|
nf.rs
|
use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.parse::<IpHeader>()
.transform(box |pkt| {
let h = pkt.get_mut_header();
let ttl = h.ttl();
h.set_ttl(ttl - 1);
})
.filter(box |pkt| {
let h = pkt.get_header();
h.ttl() != 0
})
.compose()
}
#[inline]
pub fn
|
<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T,
len: u32,
pos: u32)
-> CompositionBatch {
let mut chained = chain_nf(parent);
for _ in 1..len {
chained = chain_nf(chained);
}
if len % 2 == 0 || pos % 2 == 1 {
chained.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.compose()
} else {
chained
}
}
|
chain
|
identifier_name
|
nf.rs
|
use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.parse::<IpHeader>()
.transform(box |pkt| {
let h = pkt.get_mut_header();
let ttl = h.ttl();
h.set_ttl(ttl - 1);
})
.filter(box |pkt| {
let h = pkt.get_header();
h.ttl() != 0
})
.compose()
}
#[inline]
pub fn chain<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T,
len: u32,
pos: u32)
-> CompositionBatch
|
{
let mut chained = chain_nf(parent);
for _ in 1..len {
chained = chain_nf(chained);
}
if len % 2 == 0 || pos % 2 == 1 {
chained.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.compose()
} else {
chained
}
}
|
identifier_body
|
|
nf.rs
|
use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.parse::<IpHeader>()
.transform(box |pkt| {
let h = pkt.get_mut_header();
let ttl = h.ttl();
h.set_ttl(ttl - 1);
})
.filter(box |pkt| {
let h = pkt.get_header();
h.ttl() != 0
})
.compose()
}
#[inline]
pub fn chain<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T,
len: u32,
pos: u32)
-> CompositionBatch {
let mut chained = chain_nf(parent);
|
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.compose()
} else {
chained
}
}
|
for _ in 1..len {
chained = chain_nf(chained);
}
if len % 2 == 0 || pos % 2 == 1 {
chained.parse::<MacHeader>()
|
random_line_split
|
nf.rs
|
use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.parse::<IpHeader>()
.transform(box |pkt| {
let h = pkt.get_mut_header();
let ttl = h.ttl();
h.set_ttl(ttl - 1);
})
.filter(box |pkt| {
let h = pkt.get_header();
h.ttl() != 0
})
.compose()
}
#[inline]
pub fn chain<T: 'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T,
len: u32,
pos: u32)
-> CompositionBatch {
let mut chained = chain_nf(parent);
for _ in 1..len {
chained = chain_nf(chained);
}
if len % 2 == 0 || pos % 2 == 1
|
else {
chained
}
}
|
{
chained.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.compose()
}
|
conditional_block
|
toc.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Table-of-contents creation.
use std::fmt;
use std::string::String;
/// A (recursive) table of contents
#[derive(PartialEq)]
pub struct Toc {
/// The levels are strictly decreasing, i.e.
///
/// entries[0].level >= entries[1].level >= ...
///
/// Normally they are equal, but can differ in cases like A and B,
/// both of which end up in the same `Toc` as they have the same
/// parent (Main).
///
/// ```text
/// # Main
/// ### A
/// ## B
/// ```
entries: Vec<TocEntry>
}
impl Toc {
fn count_entries_with_level(&self, level: u32) -> usize {
self.entries.iter().filter(|e| e.level == level).count()
}
}
#[derive(PartialEq)]
pub struct TocEntry {
level: u32,
sec_number: String,
name: String,
id: String,
children: Toc,
}
/// Progressive construction of a table of contents.
#[derive(PartialEq)]
pub struct TocBuilder {
top_level: Toc,
/// The current hierarchy of parent headings, the levels are
/// strictly increasing (i.e., chain[0].level < chain[1].level <
/// ...) with each entry being the most recent occurrence of a
/// heading with that level (it doesn't include the most recent
/// occurrences of every level, just, if it *is* in `chain` then
/// it is the most recent one).
///
/// We also have `chain[0].level <= top_level.entries[last]`.
chain: Vec<TocEntry>
}
impl TocBuilder {
pub fn new() -> TocBuilder {
TocBuilder { top_level: Toc { entries: Vec::new() }, chain: Vec::new() }
}
/// Convert into a true `Toc` struct.
pub fn into_toc(mut self) -> Toc {
// we know all levels are >= 1.
self.fold_until(0);
self.top_level
|
}
/// Collapse the chain until the first heading more important than
/// `level` (i.e., lower level)
///
/// Example:
///
/// ```text
/// ## A
/// # B
/// # C
/// ## D
/// ## E
/// ### F
/// #### G
/// ### H
/// ```
///
/// If we are considering H (i.e., level 3), then A and B are in
/// self.top_level, D is in C.children, and C, E, F, G are in
/// self.chain.
///
/// When we attempt to push H, we realize that first G is not the
/// parent (level is too high) so it is popped from chain and put
/// into F.children, then F isn't the parent (level is equal, aka
/// sibling), so it's also popped and put into E.children.
///
/// This leaves us looking at E, which does have a smaller level,
/// and, by construction, it's the most recent thing with smaller
/// level, i.e., it's the immediate parent of H.
fn fold_until(&mut self, level: u32) {
let mut this = None;
loop {
match self.chain.pop() {
Some(mut next) => {
this.map(|e| next.children.entries.push(e));
if next.level < level {
// this is the parent we want, so return it to
// its rightful place.
self.chain.push(next);
return
} else {
this = Some(next);
}
}
None => {
this.map(|e| self.top_level.entries.push(e));
return
}
}
}
}
/// Push a level `level` heading into the appropriate place in the
/// hierarchy, returning a string containing the section number in
/// `<num>.<num>.<num>` format.
pub fn push<'a>(&'a mut self, level: u32, name: String, id: String) -> &'a str {
assert!(level >= 1);
// collapse all previous sections into their parents until we
// get to relevant heading (i.e., the first one with a smaller
// level than us)
self.fold_until(level);
let mut sec_number;
{
let (toc_level, toc) = match self.chain.last() {
None => {
sec_number = String::new();
(0, &self.top_level)
}
Some(entry) => {
sec_number = entry.sec_number.clone();
sec_number.push_str(".");
(entry.level, &entry.children)
}
};
// fill in any missing zeros, e.g., for
// # Foo (1)
// ### Bar (1.0.1)
for _ in toc_level..level - 1 {
sec_number.push_str("0.");
}
let number = toc.count_entries_with_level(level);
sec_number.push_str(&(number + 1).to_string())
}
self.chain.push(TocEntry {
level,
name,
sec_number,
id,
children: Toc { entries: Vec::new() }
});
// get the thing we just pushed, so we can borrow the string
// out of it with the right lifetime
let just_inserted = self.chain.last_mut().unwrap();
&just_inserted.sec_number
}
}
impl fmt::Debug for Toc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for Toc {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "<ul>")?;
for entry in &self.entries {
// recursively format this table of contents (the
// `{children}` is the key).
write!(fmt,
"\n<li><a href=\"#{id}\">{num} {name}</a>{children}</li>",
id = entry.id,
num = entry.sec_number, name = entry.name,
children = entry.children)?
}
write!(fmt, "</ul>")
}
}
#[cfg(test)]
mod tests {
use super::{TocBuilder, Toc, TocEntry};
#[test]
fn builder_smoke() {
let mut builder = TocBuilder::new();
// this is purposely not using a fancy macro like below so
// that we're sure that this is doing the correct thing, and
// there's been no macro mistake.
macro_rules! push {
($level: expr, $name: expr) => {
assert_eq!(builder.push($level,
$name.to_string(),
"".to_string()),
$name);
}
}
push!(2, "0.1");
push!(1, "1");
{
push!(2, "1.1");
{
push!(3, "1.1.1");
push!(3, "1.1.2");
}
push!(2, "1.2");
{
push!(3, "1.2.1");
push!(3, "1.2.2");
}
}
push!(1, "2");
push!(1, "3");
{
push!(4, "3.0.0.1");
{
push!(6, "3.0.0.1.0.1");
}
push!(4, "3.0.0.2");
push!(2, "3.1");
{
push!(4, "3.1.0.1");
}
}
macro_rules! toc {
($(($level: expr, $name: expr, $(($sub: tt))* )),*) => {
Toc {
entries: vec![
$(
TocEntry {
level: $level,
name: $name.to_string(),
sec_number: $name.to_string(),
id: "".to_string(),
children: toc!($($sub),*)
}
),*
]
}
}
}
let expected = toc!(
(2, "0.1", ),
(1, "1",
((2, "1.1", ((3, "1.1.1", )) ((3, "1.1.2", ))))
((2, "1.2", ((3, "1.2.1", )) ((3, "1.2.2", ))))
),
(1, "2", ),
(1, "3",
((4, "3.0.0.1", ((6, "3.0.0.1.0.1", ))))
((4, "3.0.0.2", ))
((2, "3.1", ((4, "3.1.0.1", ))))
)
);
assert_eq!(expected, builder.into_toc());
}
}
|
random_line_split
|
|
toc.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Table-of-contents creation.
use std::fmt;
use std::string::String;
/// A (recursive) table of contents
#[derive(PartialEq)]
pub struct Toc {
/// The levels are strictly decreasing, i.e.
///
/// entries[0].level >= entries[1].level >= ...
///
/// Normally they are equal, but can differ in cases like A and B,
/// both of which end up in the same `Toc` as they have the same
/// parent (Main).
///
/// ```text
/// # Main
/// ### A
/// ## B
/// ```
entries: Vec<TocEntry>
}
impl Toc {
fn count_entries_with_level(&self, level: u32) -> usize {
self.entries.iter().filter(|e| e.level == level).count()
}
}
#[derive(PartialEq)]
pub struct TocEntry {
level: u32,
sec_number: String,
name: String,
id: String,
children: Toc,
}
/// Progressive construction of a table of contents.
#[derive(PartialEq)]
pub struct TocBuilder {
top_level: Toc,
/// The current hierarchy of parent headings, the levels are
/// strictly increasing (i.e., chain[0].level < chain[1].level <
/// ...) with each entry being the most recent occurrence of a
/// heading with that level (it doesn't include the most recent
/// occurrences of every level, just, if it *is* in `chain` then
/// it is the most recent one).
///
/// We also have `chain[0].level <= top_level.entries[last]`.
chain: Vec<TocEntry>
}
impl TocBuilder {
pub fn new() -> TocBuilder {
TocBuilder { top_level: Toc { entries: Vec::new() }, chain: Vec::new() }
}
/// Convert into a true `Toc` struct.
pub fn into_toc(mut self) -> Toc {
// we know all levels are >= 1.
self.fold_until(0);
self.top_level
}
/// Collapse the chain until the first heading more important than
/// `level` (i.e., lower level)
///
/// Example:
///
/// ```text
/// ## A
/// # B
/// # C
/// ## D
/// ## E
/// ### F
/// #### G
/// ### H
/// ```
///
/// If we are considering H (i.e., level 3), then A and B are in
/// self.top_level, D is in C.children, and C, E, F, G are in
/// self.chain.
///
/// When we attempt to push H, we realize that first G is not the
/// parent (level is too high) so it is popped from chain and put
/// into F.children, then F isn't the parent (level is equal, aka
/// sibling), so it's also popped and put into E.children.
///
/// This leaves us looking at E, which does have a smaller level,
/// and, by construction, it's the most recent thing with smaller
/// level, i.e., it's the immediate parent of H.
fn
|
(&mut self, level: u32) {
let mut this = None;
loop {
match self.chain.pop() {
Some(mut next) => {
this.map(|e| next.children.entries.push(e));
if next.level < level {
// this is the parent we want, so return it to
// its rightful place.
self.chain.push(next);
return
} else {
this = Some(next);
}
}
None => {
this.map(|e| self.top_level.entries.push(e));
return
}
}
}
}
/// Push a level `level` heading into the appropriate place in the
/// hierarchy, returning a string containing the section number in
/// `<num>.<num>.<num>` format.
pub fn push<'a>(&'a mut self, level: u32, name: String, id: String) -> &'a str {
assert!(level >= 1);
// collapse all previous sections into their parents until we
// get to relevant heading (i.e., the first one with a smaller
// level than us)
self.fold_until(level);
let mut sec_number;
{
let (toc_level, toc) = match self.chain.last() {
None => {
sec_number = String::new();
(0, &self.top_level)
}
Some(entry) => {
sec_number = entry.sec_number.clone();
sec_number.push_str(".");
(entry.level, &entry.children)
}
};
// fill in any missing zeros, e.g., for
// # Foo (1)
// ### Bar (1.0.1)
for _ in toc_level..level - 1 {
sec_number.push_str("0.");
}
let number = toc.count_entries_with_level(level);
sec_number.push_str(&(number + 1).to_string())
}
self.chain.push(TocEntry {
level,
name,
sec_number,
id,
children: Toc { entries: Vec::new() }
});
// get the thing we just pushed, so we can borrow the string
// out of it with the right lifetime
let just_inserted = self.chain.last_mut().unwrap();
&just_inserted.sec_number
}
}
impl fmt::Debug for Toc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for Toc {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "<ul>")?;
for entry in &self.entries {
// recursively format this table of contents (the
// `{children}` is the key).
write!(fmt,
"\n<li><a href=\"#{id}\">{num} {name}</a>{children}</li>",
id = entry.id,
num = entry.sec_number, name = entry.name,
children = entry.children)?
}
write!(fmt, "</ul>")
}
}
#[cfg(test)]
mod tests {
use super::{TocBuilder, Toc, TocEntry};
#[test]
fn builder_smoke() {
let mut builder = TocBuilder::new();
// this is purposely not using a fancy macro like below so
// that we're sure that this is doing the correct thing, and
// there's been no macro mistake.
macro_rules! push {
($level: expr, $name: expr) => {
assert_eq!(builder.push($level,
$name.to_string(),
"".to_string()),
$name);
}
}
push!(2, "0.1");
push!(1, "1");
{
push!(2, "1.1");
{
push!(3, "1.1.1");
push!(3, "1.1.2");
}
push!(2, "1.2");
{
push!(3, "1.2.1");
push!(3, "1.2.2");
}
}
push!(1, "2");
push!(1, "3");
{
push!(4, "3.0.0.1");
{
push!(6, "3.0.0.1.0.1");
}
push!(4, "3.0.0.2");
push!(2, "3.1");
{
push!(4, "3.1.0.1");
}
}
macro_rules! toc {
($(($level: expr, $name: expr, $(($sub: tt))* )),*) => {
Toc {
entries: vec![
$(
TocEntry {
level: $level,
name: $name.to_string(),
sec_number: $name.to_string(),
id: "".to_string(),
children: toc!($($sub),*)
}
),*
]
}
}
}
let expected = toc!(
(2, "0.1", ),
(1, "1",
((2, "1.1", ((3, "1.1.1", )) ((3, "1.1.2", ))))
((2, "1.2", ((3, "1.2.1", )) ((3, "1.2.2", ))))
),
(1, "2", ),
(1, "3",
((4, "3.0.0.1", ((6, "3.0.0.1.0.1", ))))
((4, "3.0.0.2", ))
((2, "3.1", ((4, "3.1.0.1", ))))
)
);
assert_eq!(expected, builder.into_toc());
}
}
|
fold_until
|
identifier_name
|
customizer-preview.js
|
/**
* The Customizer-specific functionality of the plugin.
* Handles the selective refresh logic for widgets in the Customizer.
*
* @since 1.1.5
* @author Weston Ruter <[email protected]>
*/
( function( $ ) {
if ( 'undefined' === typeof wp || ! wp.customize || ! wp.customize.selectiveRefresh || ! wp.customize.widgetsPreview || ! wp.customize.widgetsPreview.WidgetPartial )
|
// Check the value of the attribute after partial content has been rendered.
wp.customize.selectiveRefresh.bind( 'partial-content-rendered', function( placement ) {
// Abort if the partial is not for a widget.
if ( ! placement.partial.extended( wp.customize.widgetsPreview.WidgetPartial ) ) {
return;
}
// Abort if the widget was not refreshed but rather just re-initialized.
if ( ! placement.removedNodes ) {
return;
}
// Refresh the page if the attribute has changed.
if ( placement.container.attr( 'data-column' ) !== placement.removedNodes.attr( 'data-column' ) ) {
wp.customize.selectiveRefresh.requestFullRefresh();
}
// Debugging
// console.log( 'old attribute: ' + placement.removedNodes.attr( 'data-column' ) );
// console.log( 'new attribute: ' + placement.container.attr( 'data-column' ) );
} );
} ) ( jQuery );
|
{
return;
}
|
conditional_block
|
pilha.py
|
import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
except IndexError:
raise PilhaVaziaErro
def desempilhar(self):
|
class PilhaTestes(unittest.TestCase):
def test_topo_lista_vazia(self):
pilha = Pilha()
self.assertTrue(pilha.vazia())
self.assertRaises(PilhaVaziaErro, pilha.topo)
def test_empilhar_um_elemento(self):
pilha = Pilha()
pilha.empilhar('A')
self.assertFalse(pilha.vazia())
self.assertEqual('A', pilha.topo())
def test_empilhar_dois_elementos(self):
pilha = Pilha()
pilha.empilhar('A')
pilha.empilhar('B')
self.assertFalse(pilha.vazia())
self.assertEqual('B', pilha.topo())
def test_desempilhar_pilha_vazia(self):
pilha = Pilha()
self.assertRaises(PilhaVaziaErro, pilha.desempilhar)
def test_desempilhar(self):
pilha = Pilha()
letras = 'ABCDE'
for letra in letras:
pilha.empilhar(letra)
for letra_em_ordem_reversa in reversed(letras):
letra_desempilhada = pilha.desempilhar()
self.assertEqual(letra_em_ordem_reversa, letra_desempilhada)
|
if (self.lista):
return self.lista.pop(-1)
else:
raise PilhaVaziaErro
|
identifier_body
|
pilha.py
|
import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
except IndexError:
raise PilhaVaziaErro
def desempilhar(self):
if (self.lista):
return self.lista.pop(-1)
else:
raise PilhaVaziaErro
class PilhaTestes(unittest.TestCase):
def test_topo_lista_vazia(self):
pilha = Pilha()
|
pilha.empilhar('A')
self.assertFalse(pilha.vazia())
self.assertEqual('A', pilha.topo())
def test_empilhar_dois_elementos(self):
pilha = Pilha()
pilha.empilhar('A')
pilha.empilhar('B')
self.assertFalse(pilha.vazia())
self.assertEqual('B', pilha.topo())
def test_desempilhar_pilha_vazia(self):
pilha = Pilha()
self.assertRaises(PilhaVaziaErro, pilha.desempilhar)
def test_desempilhar(self):
pilha = Pilha()
letras = 'ABCDE'
for letra in letras:
pilha.empilhar(letra)
for letra_em_ordem_reversa in reversed(letras):
letra_desempilhada = pilha.desempilhar()
self.assertEqual(letra_em_ordem_reversa, letra_desempilhada)
|
self.assertTrue(pilha.vazia())
self.assertRaises(PilhaVaziaErro, pilha.topo)
def test_empilhar_um_elemento(self):
pilha = Pilha()
|
random_line_split
|
pilha.py
|
import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
except IndexError:
raise PilhaVaziaErro
def desempilhar(self):
if (self.lista):
return self.lista.pop(-1)
else:
raise PilhaVaziaErro
class PilhaTestes(unittest.TestCase):
def test_topo_lista_vazia(self):
pilha = Pilha()
self.assertTrue(pilha.vazia())
self.assertRaises(PilhaVaziaErro, pilha.topo)
def test_empilhar_um_elemento(self):
pilha = Pilha()
pilha.empilhar('A')
self.assertFalse(pilha.vazia())
self.assertEqual('A', pilha.topo())
def test_empilhar_dois_elementos(self):
pilha = Pilha()
pilha.empilhar('A')
pilha.empilhar('B')
self.assertFalse(pilha.vazia())
self.assertEqual('B', pilha.topo())
def test_desempilhar_pilha_vazia(self):
pilha = Pilha()
self.assertRaises(PilhaVaziaErro, pilha.desempilhar)
def test_desempilhar(self):
pilha = Pilha()
letras = 'ABCDE'
for letra in letras:
pilha.empilhar(letra)
for letra_em_ordem_reversa in reversed(letras):
|
letra_desempilhada = pilha.desempilhar()
self.assertEqual(letra_em_ordem_reversa, letra_desempilhada)
|
conditional_block
|
|
pilha.py
|
import unittest
class
|
(Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
except IndexError:
raise PilhaVaziaErro
def desempilhar(self):
if (self.lista):
return self.lista.pop(-1)
else:
raise PilhaVaziaErro
class PilhaTestes(unittest.TestCase):
def test_topo_lista_vazia(self):
pilha = Pilha()
self.assertTrue(pilha.vazia())
self.assertRaises(PilhaVaziaErro, pilha.topo)
def test_empilhar_um_elemento(self):
pilha = Pilha()
pilha.empilhar('A')
self.assertFalse(pilha.vazia())
self.assertEqual('A', pilha.topo())
def test_empilhar_dois_elementos(self):
pilha = Pilha()
pilha.empilhar('A')
pilha.empilhar('B')
self.assertFalse(pilha.vazia())
self.assertEqual('B', pilha.topo())
def test_desempilhar_pilha_vazia(self):
pilha = Pilha()
self.assertRaises(PilhaVaziaErro, pilha.desempilhar)
def test_desempilhar(self):
pilha = Pilha()
letras = 'ABCDE'
for letra in letras:
pilha.empilhar(letra)
for letra_em_ordem_reversa in reversed(letras):
letra_desempilhada = pilha.desempilhar()
self.assertEqual(letra_em_ordem_reversa, letra_desempilhada)
|
PilhaVaziaErro
|
identifier_name
|
manifest.rs
|
/*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
/*!
This module is concerned with how `cargo-script` extracts the manfiest from a script file.
*/
extern crate hoedown;
extern crate regex;
use self::regex::Regex;
use toml;
use consts;
use error::{Blame, Result};
use Input;
lazy_static! {
static ref RE_SHORT_MANIFEST: Regex = Regex::new(
r"^(?i)\s*//\s*cargo-deps\s*:(.*?)(\r\n|\n)").unwrap();
static ref RE_MARGIN: Regex = Regex::new(r"^\s*\*( |$)").unwrap();
static ref RE_SPACE: Regex = Regex::new(r"^(\s+)").unwrap();
static ref RE_NESTING: Regex = Regex::new(r"/\*|\*/").unwrap();
static ref RE_COMMENT: Regex = Regex::new(r"^\s*//!").unwrap();
static ref RE_HASHBANG: Regex = Regex::new(r"^#![^[].*?(\r\n|\n)").unwrap();
static ref RE_CRATE_COMMENT: Regex = {
Regex::new(
r"(?x)
# We need to find the first `/*!` or `//!` that *isn't* preceeded by something that would make it apply to anything other than the crate itself. Because we can't do this accurately, we'll just require that the doc comment is the *first* thing in the file (after the optional hashbang, which should already have been stripped).
^\s*
(/\*!|//!)
"
).unwrap()
};
}
/**
Splits input into a complete Cargo manifest and unadultered Rust source.
Unless we have prelude items to inject, in which case it will be *slightly* adulterated.
*/
pub fn split_input(input: &Input, deps: &[(String, String)], prelude_items: &[String]) -> Result<(String, String)> {
let (part_mani, source, template, sub_prelude) = match *input {
Input::File(_, _, content, _) => {
assert_eq!(prelude_items.len(), 0);
let content = strip_hashbang(content);
let (manifest, source) = find_embedded_manifest(content)
.unwrap_or((Manifest::Toml(""), content));
(manifest, source, consts::FILE_TEMPLATE, false)
},
Input::Expr(content) => {
(Manifest::Toml(""), content, consts::EXPR_TEMPLATE, true)
},
Input::Loop(content, count) => {
let templ = if count { consts::LOOP_COUNT_TEMPLATE } else { consts::LOOP_TEMPLATE };
(Manifest::Toml(""), content, templ, true)
},
};
let source = template.replace("%b", source);
/*
We are doing it this way because we can guarantee that %p *always* appears before %b, *and* that we don't attempt this when we don't want to allow prelude substitution.
The problem with doing it the other way around is that the user could specify a prelude item that contains `%b` (which would do *weird things*).
Also, don't use `str::replace` because it replaces *all* occurrences, not just the first.
*/
let source = match sub_prelude {
false => source,
true => {
const PRELUDE_PAT: &'static str = "%p";
let offset = source.find(PRELUDE_PAT).expect("template doesn't have %p");
let mut new_source = String::new();
new_source.push_str(&source[..offset]);
for i in prelude_items {
new_source.push_str(i);
new_source.push_str("\n");
}
new_source.push_str(&source[offset + PRELUDE_PAT.len()..]);
new_source
}
};
info!("part_mani: {:?}", part_mani);
info!("source: {:?}", source);
let part_mani = try!(part_mani.into_toml());
info!("part_mani: {:?}", part_mani);
// It's-a mergin' time!
let def_mani = try!(default_manifest(input));
let dep_mani = try!(deps_manifest(deps));
let mani = try!(merge_manifest(def_mani, part_mani));
let mani = try!(merge_manifest(mani, dep_mani));
info!("mani: {:?}", mani);
let mani_str = format!("{}", toml::Value::Table(mani));
info!("mani_str: {}", mani_str);
Ok((mani_str, source))
}
#[test]
fn test_split_input() {
macro_rules! si {
($i:expr) => (split_input(&$i, &[], &[]).ok())
}
let dummy_path: ::std::path::PathBuf = "p".into();
let dummy_path = &dummy_path;
let f = |c| Input::File("n", &dummy_path, c, 0);
macro_rules! r {
($m:expr, $r:expr) => (Some(($m.into(), $r.into())));
}
assert_eq!(si!(f(
r#"fn main() {}"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"fn main() {}"#
)
);
// Ensure removed prefix manifests don't work.
assert_eq!(si!(f(
r#"
---
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
---
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"[dependencies]
time="0.1.25"
---
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"[dependencies]
time="0.1.25"
---
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"
// Cargo-Deps: time="0.1.25"
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
time = "0.1.25"
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
// Cargo-Deps: time="0.1.25"
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"
// Cargo-Deps: time="0.1.25", libc="0.2.5"
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
libc = "0.2.5"
time = "0.1.25"
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
// Cargo-Deps: time="0.1.25", libc="0.2.5"
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"
/*!
Here is a manifest:
```cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
time = "0.1.25"
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
/*!
Here is a manifest:
```cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#
)
);
}
/**
Returns a slice of the input string with the leading hashbang, if there is one, omitted.
*/
fn strip_hashbang(s: &str) -> &str {
match RE_HASHBANG.find(s) {
Some((_, end)) => &s[end..],
None => s
}
}
#[test]
fn test_strip_hashbang() {
assert_eq!(strip_hashbang("\
#!/usr/bin/env run-cargo-script
and the rest
\
"), "\
and the rest
\
");
assert_eq!(strip_hashbang("\
#![thingy]
and the rest
\
"), "\
#![thingy]
and the rest
\
");
}
/**
Represents the kind, and content of, an embedded manifest.
*/
#[derive(Debug, Eq, PartialEq)]
enum Manifest<'s> {
/// The manifest is a valid TOML fragment.
Toml(&'s str),
/// The manifest is a valid TOML fragment (owned).
// TODO: Change to Cow<'s, str>.
TomlOwned(String),
/// The manifest is a comma-delimited list of dependencies.
DepList(&'s str),
}
impl<'s> Manifest<'s> {
pub fn into_toml(self) -> Result<toml::Table> {
use self::Manifest::*;
match self {
Toml(s) => Ok(try!(toml::Parser::new(s).parse()
.ok_or("could not parse embedded manifest"))),
TomlOwned(ref s) => Ok(try!(toml::Parser::new(s).parse()
.ok_or("could not parse embedded manifest"))),
DepList(s) => Manifest::dep_list_to_toml(s),
}
}
fn dep_list_to_toml(s: &str) -> Result<toml::Table> {
let mut r = String::new();
r.push_str("[dependencies]\n");
for dep in s.trim().split(',') {
// If there's no version specified, add one.
match dep.contains('=') {
true => {
r.push_str(dep);
r.push_str("\n");
},
false => {
r.push_str(dep);
r.push_str("=\"*\"\n");
}
}
}
Ok(try!(toml::Parser::new(&r).parse()
.ok_or("could not parse embedded manifest")))
}
}
/**
Locates a manifest embedded in Rust source.
Returns `Some((manifest, source))` if it finds a manifest, `None` otherwise.
*/
fn find_embedded_manifest(s: &str) -> Option<(Manifest, &str)> {
find_short_comment_manifest(s)
.or_else(|| find_code_block_manifest(s))
}
#[test]
fn test_find_embedded_manifest() {
use self::Manifest::*;
let fem = find_embedded_manifest;
assert_eq!(fem("fn main() {}"), None);
assert_eq!(fem(
"
fn main() {}
"),
None);
// Ensure removed prefix manifests don't work.
assert_eq!(fem(
r#"
---
fn main() {}
"#),
None);
assert_eq!(fem(
"[dependencies]
time = \"0.1.25\"
---
fn main() {}
"),
None);
assert_eq!(fem(
"[dependencies]
time = \"0.1.25\"
fn main() {}
"),
None);
// Make sure we aren't just grabbing the *last* line.
assert_eq!(fem(
"[dependencies]
time = \"0.1.25\"
fn main() {
println!(\"Hi!\");
}
"),
None);
assert_eq!(fem(
"// cargo-deps: time=\"0.1.25\"
fn main() {}
"),
Some((
DepList(" time=\"0.1.25\""),
"// cargo-deps: time=\"0.1.25\"
fn main() {}
"
)));
assert_eq!(fem(
"// cargo-deps: time=\"0.1.25\", libc=\"0.2.5\"
fn main() {}
"),
Some((
DepList(" time=\"0.1.25\", libc=\"0.2.5\""),
"// cargo-deps: time=\"0.1.25\", libc=\"0.2.5\"
fn main() {}
"
)));
assert_eq!(fem(
"
// cargo-deps: time=\"0.1.25\" \n\
fn main() {}
"),
Some((
DepList(" time=\"0.1.25\" "),
"
// cargo-deps: time=\"0.1.25\" \n\
fn main() {}
"
)));
assert_eq!(fem(
"/* cargo-deps: time=\"0.1.25\" */
fn main() {}
"),
None);
assert_eq!(fem(
r#"//! [dependencies]
//! time = "0.1.25"
fn main() {}
"#),
None);
assert_eq!(fem(
r#"//! ```Cargo
//! [dependencies]
//! time = "0.1.25"
//! ```
fn main() {}
"#),
Some((
TomlOwned(r#"[dependencies]
time = "0.1.25"
"#.into()),
r#"//! ```Cargo
//! [dependencies]
//! time = "0.1.25"
//! ```
fn main() {}
"#
)));
assert_eq!(fem(
r#"/*!
[dependencies]
time = "0.1.25"
*/
fn main() {}
"#),
None);
assert_eq!(fem(
r#"/*!
```Cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#),
Some((
TomlOwned(r#"[dependencies]
time = "0.1.25"
"#.into()),
r#"/*!
```Cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#
)));
assert_eq!(fem(
r#"/*!
* [dependencies]
* time = "0.1.25"
*/
fn main() {}
"#),
None);
assert_eq!(fem(
r#"/*!
* ```Cargo
* [dependencies]
* time = "0.1.25"
* ```
*/
fn main() {}
"#),
Some((
TomlOwned(r#"[dependencies]
time = "0.1.25"
"#.into()),
r#"/*!
* ```Cargo
* [dependencies]
* time = "0.1.25"
* ```
*/
fn main() {}
"#
)));
}
/**
Locates a "short comment manifest" in Rust source.
*/
fn find_short_comment_manifest(s: &str) -> Option<(Manifest, &str)> {
/*
This is pretty simple: the only valid syntax for this is for the first, non-blank line to contain a single-line comment whose first token is `cargo-deps:`. That's it.
*/
let re = &*RE_SHORT_MANIFEST;
if let Some(cap) = re.captures(s) {
if let Some((a, b)) = cap.pos(1) {
return Some((Manifest::DepList(&s[a..b]), &s[..]))
}
}
None
}
/**
Locates a "code block manifest" in Rust source.
*/
fn find_code_block_manifest(s: &str) -> Option<(Manifest, &str)> {
/*
This has to happen in a few steps.
First, we will look for and slice out a contiguous, inner doc comment which must be *the very first thing* in the file. `#[doc(...)]` attributes *are not supported*. Multiple single-line comments cannot have any blank lines between them.
Then, we need to strip off the actual comment markers from the content. Including indentation removal, and taking out the (optional) leading line markers for block comments. *sigh*
Then, we need to take the contents of this doc comment and feed it to a Markdown parser. We are looking for *the first* fenced code block with a language token of `cargo`. This is extracted and pasted back together into the manifest.
*/
let start = match RE_CRATE_COMMENT.captures(s) {
Some(cap) => match cap.pos(1) {
Some((a, _)) => a,
None => return None
},
None => return None
};
let comment = match extract_comment(&s[start..]) {
Ok(s) => s,
Err(err) => {
error!("error slicing comment: {}", err);
return None
}
};
scrape_markdown_manifest(&comment)
.unwrap_or(None)
.map(|m| (Manifest::TomlOwned(m), s))
}
/**
Extracts the first `Cargo` fenced code block from a chunk of Markdown.
*/
fn scrape_markdown_manifest(content: &str) -> Result<Option<String>> {
use self::hoedown::{Buffer, Markdown, Render};
// To match librustdoc/html/markdown.rs, HOEDOWN_EXTENSIONS.
let exts
= hoedown::NO_INTRA_EMPHASIS
| hoedown::TABLES
| hoedown::FENCED_CODE
| hoedown::AUTOLINK
| hoedown::STRIKETHROUGH
| hoedown::SUPERSCRIPT
| hoedown::FOOTNOTES;
let md = Markdown::new(&content).extensions(exts);
struct ManifestScraper {
seen_manifest: bool,
}
impl Render for ManifestScraper {
fn code_block(&mut self, output: &mut Buffer, text: &Buffer, lang: &Buffer) {
use std::ascii::AsciiExt;
let lang = lang.to_str().unwrap();
if !self.seen_manifest && lang.eq_ignore_ascii_case("cargo") {
// Pass it through.
info!("found code block manifest");
output.pipe(text);
self.seen_manifest = true;
}
}
}
let mut ms = ManifestScraper { seen_manifest: false };
let mani_buf = ms.render(&md);
if !ms.seen_manifest { return Ok(None) }
mani_buf.to_str().map(|s| Some(s.into()))
.map_err(|_| "error decoding manifest as UTF-8".into())
}
#[test]
fn test_scrape_markdown_manifest() {
macro_rules! smm {
($c:expr) => (scrape_markdown_manifest($c).map_err(|e| e.to_string()));
}
assert_eq!(smm!(
r#"There is no manifest in this comment.
"#
),
Ok(None)
);
assert_eq!(smm!(
r#"There is no manifest in this comment.
```
This is not a manifest.
```
```rust
println!("Nor is this.");
```
Or this.
"#
),
Ok(None)
);
assert_eq!(smm!(
r#"This is a manifest:
```cargo
dependencies = { time = "*" }
```
"#
),
Ok(Some(r#"dependencies = { time = "*" }
"#.into()))
);
assert_eq!(smm!(
r#"This is *not* a manifest:
```
He's lying, I'm *totally* a manifest!
```
This *is*:
```cargo
dependencies = { time = "*" }
```
"#
),
Ok(Some(r#"dependencies = { time = "*" }
"#.into()))
);
assert_eq!(smm!(
r#"This is a manifest:
```cargo
dependencies = { time = "*" }
```
So is this, but it doesn't count:
```cargo
dependencies = { explode = true }
```
"#
),
Ok(Some(r#"dependencies = { time = "*" }
"#.into()))
);
}
/**
Extracts the contents of a Rust doc comment.
*/
fn extract_comment(s: &str) -> Result<String> {
use std::cmp::min;
fn n_
|
: &str, n: usize) -> Result<()> {
if !s.chars().take(n).all(|c| c == ' ') {
return Err(format!("leading {:?} chars aren't all spaces: {:?}", n, s).into())
}
Ok(())
}
fn extract_block(s: &str) -> Result<String> {
/*
On every line:
- update nesting level and detect end-of-comment
- if margin is None:
- if there appears to be a margin, set margin.
- strip off margin marker
- update the leading space counter
- strip leading space
- append content
*/
let mut r = String::new();
let margin_re = &*RE_MARGIN;
let space_re = &*RE_SPACE;
let nesting_re = &*RE_NESTING;
let mut leading_space = None;
let mut margin = None;
let mut depth: u32 = 1;
for line in s.lines() {
if depth == 0 { break }
// Update nesting and look for end-of-comment.
let mut end_of_comment = None;
for (end, marker) in nesting_re.find_iter(line).map(|(a,b)| (a, &line[a..b])) {
match (marker, depth) {
("/*", _) => depth += 1,
("*/", 1) => {
end_of_comment = Some(end);
depth = 0;
break;
},
("*/", _) => depth -= 1,
_ => panic!("got a comment marker other than /* or */")
}
}
let line = end_of_comment.map(|end| &line[..end]).unwrap_or(line);
// Detect and strip margin.
margin = margin
.or_else(|| margin_re.find(line)
.and_then(|(b, e)| Some(&line[b..e])));
let line = if let Some(margin) = margin {
let end = line.char_indices().take(margin.len())
.map(|(i,c)| i + c.len_utf8()).last().unwrap_or(0);
&line[end..]
} else {
line
};
// Detect and strip leading indentation.
leading_space = leading_space
.or_else(|| space_re.find(line)
.map(|(_,n)| n));
/*
Make sure we have only leading spaces.
If we see a tab, fall over. I *would* expand them, but that gets into the question of how *many* spaces to expand them to, and *where* is the tab, because tabs are tab stops and not just N spaces.
Eurgh.
*/
try!(n_leading_spaces(line, leading_space.unwrap_or(0)));
let strip_len = min(leading_space.unwrap_or(0), line.len());
let line = &line[strip_len..];
// Done.
r.push_str(line);
// `lines` removes newlines. Ideally, it wouldn't do that, but hopefully this shouldn't cause any *real* problems.
r.push_str("\n");
}
Ok(r)
}
fn extract_line(s: &str) -> Result<String> {
let mut r = String::new();
let comment_re = &*RE_COMMENT;
let space_re = &*RE_SPACE;
let mut leading_space = None;
for line in s.lines() {
// Strip leading comment marker.
let content = match comment_re.find(line) {
Some((_, end)) => &line[end..],
None => break
};
// Detect and strip leading indentation.
leading_space = leading_space
.or_else(|| space_re.captures(content)
.and_then(|c| c.pos(1))
.map(|(_,n)| n));
/*
Make sure we have only leading spaces.
If we see a tab, fall over. I *would* expand them, but that gets into the question of how *many* spaces to expand them to, and *where* is the tab, because tabs are tab stops and not just N spaces.
Eurgh.
*/
try!(n_leading_spaces(content, leading_space.unwrap_or(0)));
let strip_len = min(leading_space.unwrap_or(0), content.len());
let content = &content[strip_len..];
// Done.
r.push_str(content);
// `lines` removes newlines. Ideally, it wouldn't do that, but hopefully this shouldn't cause any *real* problems.
r.push_str("\n");
}
Ok(r)
}
if s.starts_with("/*!") {
extract_block(&s[3..])
} else if s.starts_with("//!") {
extract_line(s)
} else {
Err("no doc comment found".into())
}
}
#[test]
fn test_extract_comment() {
macro_rules! ec {
($s:expr) => (extract_comment($s).map_err(|e| e.to_string()))
}
assert_eq!(ec!(
r#"fn main () {}"#
),
Err("no doc comment found".into())
);
assert_eq!(ec!(
r#"/*!
Here is a manifest:
```cargo
[dependencies]
time = "*"
```
*/
fn main() {}
"#
),
Ok(r#"
Here is a manifest:
```cargo
[dependencies]
time = "*"
```
"#.into())
);
assert_eq!(ec!(
r#"/*!
* Here is a manifest:
*
* ```cargo
* [dependencies]
* time = "*"
* ```
*/
fn main() {}
"#
),
Ok(r#"
Here is a manifest:
```cargo
[dependencies]
time = "*"
```
"#.into())
);
assert_eq!(ec!(
r#"//! Here is a manifest:
//!
//! ```cargo
//! [dependencies]
//! time = "*"
//! ```
fn main() {}
"#
),
Ok(r#"Here is a manifest:
```cargo
[dependencies]
time = "*"
```
"#.into())
);
}
/**
Generates a default Cargo manifest for the given input.
*/
fn default_manifest(input: &Input) -> Result<toml::Table> {
let mani_str = consts::DEFAULT_MANIFEST.replace("%n", input.safe_name());
toml::Parser::new(&mani_str).parse()
.ok_or("could not parse default manifest, somehow".into())
}
/**
Generates a partial Cargo manifest containing the specified dependencies.
*/
fn deps_manifest(deps: &[(String, String)]) -> Result<toml::Table> {
let mut mani_str = String::new();
mani_str.push_str("[dependencies]\n");
for &(ref name, ref ver) in deps {
mani_str.push_str(name);
mani_str.push_str("=");
// We only want to quote the version if it *isn't* a table.
let quotes = match ver.starts_with("{") { true => "", false => "\"" };
mani_str.push_str(quotes);
mani_str.push_str(ver);
mani_str.push_str(quotes);
mani_str.push_str("\n");
}
toml::Parser::new(&mani_str).parse()
.ok_or("could not parse dependency manifest".into())
}
/**
Given two Cargo manifests, merges the second *into* the first.
Note that the "merge" in this case is relatively simple: only *top-level* tables are actually merged; everything else is just outright replaced.
*/
fn merge_manifest(mut into_t: toml::Table, from_t: toml::Table) -> Result<toml::Table> {
for (k, v) in from_t {
match v {
toml::Value::Table(from_t) => {
use std::collections::btree_map::Entry::*;
// Merge.
match into_t.entry(k) {
Vacant(e) => {
e.insert(toml::Value::Table(from_t));
},
Occupied(e) => {
let into_t = try!(as_table_mut(e.into_mut())
.ok_or((Blame::Human, "cannot merge manifests: cannot merge \
table and non-table values")));
into_t.extend(from_t);
}
}
},
v => {
// Just replace.
into_t.insert(k, v);
},
}
}
return Ok(into_t);
fn as_table_mut(t: &mut toml::Value) -> Option<&mut toml::Table> {
match *t {
toml::Value::Table(ref mut t) => Some(t),
_ => None
}
}
}
|
leading_spaces(s
|
identifier_name
|
manifest.rs
|
/*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
/*!
This module is concerned with how `cargo-script` extracts the manfiest from a script file.
*/
extern crate hoedown;
extern crate regex;
use self::regex::Regex;
use toml;
use consts;
use error::{Blame, Result};
use Input;
lazy_static! {
static ref RE_SHORT_MANIFEST: Regex = Regex::new(
r"^(?i)\s*//\s*cargo-deps\s*:(.*?)(\r\n|\n)").unwrap();
static ref RE_MARGIN: Regex = Regex::new(r"^\s*\*( |$)").unwrap();
static ref RE_SPACE: Regex = Regex::new(r"^(\s+)").unwrap();
static ref RE_NESTING: Regex = Regex::new(r"/\*|\*/").unwrap();
static ref RE_COMMENT: Regex = Regex::new(r"^\s*//!").unwrap();
static ref RE_HASHBANG: Regex = Regex::new(r"^#![^[].*?(\r\n|\n)").unwrap();
static ref RE_CRATE_COMMENT: Regex = {
Regex::new(
r"(?x)
# We need to find the first `/*!` or `//!` that *isn't* preceeded by something that would make it apply to anything other than the crate itself. Because we can't do this accurately, we'll just require that the doc comment is the *first* thing in the file (after the optional hashbang, which should already have been stripped).
^\s*
(/\*!|//!)
"
).unwrap()
};
}
/**
Splits input into a complete Cargo manifest and unadultered Rust source.
Unless we have prelude items to inject, in which case it will be *slightly* adulterated.
*/
pub fn split_input(input: &Input, deps: &[(String, String)], prelude_items: &[String]) -> Result<(String, String)> {
let (part_mani, source, template, sub_prelude) = match *input {
Input::File(_, _, content, _) => {
assert_eq!(prelude_items.len(), 0);
let content = strip_hashbang(content);
let (manifest, source) = find_embedded_manifest(content)
.unwrap_or((Manifest::Toml(""), content));
(manifest, source, consts::FILE_TEMPLATE, false)
},
Input::Expr(content) => {
(Manifest::Toml(""), content, consts::EXPR_TEMPLATE, true)
},
Input::Loop(content, count) => {
let templ = if count { consts::LOOP_COUNT_TEMPLATE } else { consts::LOOP_TEMPLATE };
(Manifest::Toml(""), content, templ, true)
},
};
let source = template.replace("%b", source);
/*
We are doing it this way because we can guarantee that %p *always* appears before %b, *and* that we don't attempt this when we don't want to allow prelude substitution.
The problem with doing it the other way around is that the user could specify a prelude item that contains `%b` (which would do *weird things*).
Also, don't use `str::replace` because it replaces *all* occurrences, not just the first.
*/
let source = match sub_prelude {
false => source,
true => {
const PRELUDE_PAT: &'static str = "%p";
let offset = source.find(PRELUDE_PAT).expect("template doesn't have %p");
let mut new_source = String::new();
new_source.push_str(&source[..offset]);
for i in prelude_items {
new_source.push_str(i);
new_source.push_str("\n");
}
new_source.push_str(&source[offset + PRELUDE_PAT.len()..]);
new_source
}
};
info!("part_mani: {:?}", part_mani);
info!("source: {:?}", source);
let part_mani = try!(part_mani.into_toml());
info!("part_mani: {:?}", part_mani);
// It's-a mergin' time!
let def_mani = try!(default_manifest(input));
let dep_mani = try!(deps_manifest(deps));
let mani = try!(merge_manifest(def_mani, part_mani));
let mani = try!(merge_manifest(mani, dep_mani));
info!("mani: {:?}", mani);
let mani_str = format!("{}", toml::Value::Table(mani));
info!("mani_str: {}", mani_str);
Ok((mani_str, source))
}
#[test]
fn test_split_input() {
macro_rules! si {
($i:expr) => (split_input(&$i, &[], &[]).ok())
}
let dummy_path: ::std::path::PathBuf = "p".into();
let dummy_path = &dummy_path;
let f = |c| Input::File("n", &dummy_path, c, 0);
macro_rules! r {
($m:expr, $r:expr) => (Some(($m.into(), $r.into())));
}
assert_eq!(si!(f(
r#"fn main() {}"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"fn main() {}"#
)
);
// Ensure removed prefix manifests don't work.
assert_eq!(si!(f(
r#"
---
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
---
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"[dependencies]
time="0.1.25"
---
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"[dependencies]
time="0.1.25"
---
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"
// Cargo-Deps: time="0.1.25"
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
time = "0.1.25"
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
// Cargo-Deps: time="0.1.25"
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"
// Cargo-Deps: time="0.1.25", libc="0.2.5"
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
libc = "0.2.5"
time = "0.1.25"
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
// Cargo-Deps: time="0.1.25", libc="0.2.5"
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"
/*!
Here is a manifest:
```cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
time = "0.1.25"
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
/*!
Here is a manifest:
```cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#
)
);
}
/**
Returns a slice of the input string with the leading hashbang, if there is one, omitted.
*/
fn strip_hashbang(s: &str) -> &str {
match RE_HASHBANG.find(s) {
Some((_, end)) => &s[end..],
None => s
}
}
#[test]
fn test_strip_hashbang() {
assert_eq!(strip_hashbang("\
#!/usr/bin/env run-cargo-script
and the rest
\
"), "\
and the rest
\
");
assert_eq!(strip_hashbang("\
#![thingy]
and the rest
\
"), "\
#![thingy]
and the rest
\
");
}
/**
Represents the kind, and content of, an embedded manifest.
*/
#[derive(Debug, Eq, PartialEq)]
enum Manifest<'s> {
/// The manifest is a valid TOML fragment.
Toml(&'s str),
/// The manifest is a valid TOML fragment (owned).
// TODO: Change to Cow<'s, str>.
TomlOwned(String),
/// The manifest is a comma-delimited list of dependencies.
DepList(&'s str),
}
impl<'s> Manifest<'s> {
pub fn into_toml(self) -> Result<toml::Table> {
use self::Manifest::*;
match self {
Toml(s) => Ok(try!(toml::Parser::new(s).parse()
.ok_or("could not parse embedded manifest"))),
TomlOwned(ref s) => Ok(try!(toml::Parser::new(s).parse()
.ok_or("could not parse embedded manifest"))),
DepList(s) => Manifest::dep_list_to_toml(s),
}
}
fn dep_list_to_toml(s: &str) -> Result<toml::Table> {
let mut r = String::new();
r.push_str("[dependencies]\n");
for dep in s.trim().split(',') {
// If there's no version specified, add one.
match dep.contains('=') {
true => {
r.push_str(dep);
r.push_str("\n");
},
false => {
r.push_str(dep);
r.push_str("=\"*\"\n");
}
}
}
Ok(try!(toml::Parser::new(&r).parse()
.ok_or("could not parse embedded manifest")))
}
}
/**
Locates a manifest embedded in Rust source.
Returns `Some((manifest, source))` if it finds a manifest, `None` otherwise.
*/
fn find_embedded_manifest(s: &str) -> Option<(Manifest, &str)> {
find_short_comment_manifest(s)
.or_else(|| find_code_block_manifest(s))
}
#[test]
fn test_find_embedded_manifest() {
use self::Manifest::*;
let fem = find_embedded_manifest;
assert_eq!(fem("fn main() {}"), None);
assert_eq!(fem(
"
fn main() {}
"),
None);
// Ensure removed prefix manifests don't work.
assert_eq!(fem(
r#"
---
fn main() {}
"#),
None);
assert_eq!(fem(
"[dependencies]
time = \"0.1.25\"
---
fn main() {}
"),
None);
assert_eq!(fem(
"[dependencies]
time = \"0.1.25\"
fn main() {}
"),
None);
// Make sure we aren't just grabbing the *last* line.
assert_eq!(fem(
"[dependencies]
time = \"0.1.25\"
fn main() {
println!(\"Hi!\");
}
"),
None);
assert_eq!(fem(
"// cargo-deps: time=\"0.1.25\"
fn main() {}
"),
Some((
DepList(" time=\"0.1.25\""),
"// cargo-deps: time=\"0.1.25\"
fn main() {}
"
)));
assert_eq!(fem(
"// cargo-deps: time=\"0.1.25\", libc=\"0.2.5\"
fn main() {}
"),
Some((
DepList(" time=\"0.1.25\", libc=\"0.2.5\""),
"// cargo-deps: time=\"0.1.25\", libc=\"0.2.5\"
fn main() {}
"
)));
assert_eq!(fem(
"
// cargo-deps: time=\"0.1.25\" \n\
fn main() {}
"),
Some((
DepList(" time=\"0.1.25\" "),
"
// cargo-deps: time=\"0.1.25\" \n\
fn main() {}
"
)));
assert_eq!(fem(
"/* cargo-deps: time=\"0.1.25\" */
fn main() {}
"),
None);
assert_eq!(fem(
r#"//! [dependencies]
//! time = "0.1.25"
fn main() {}
"#),
None);
assert_eq!(fem(
r#"//! ```Cargo
//! [dependencies]
//! time = "0.1.25"
//! ```
fn main() {}
"#),
Some((
TomlOwned(r#"[dependencies]
time = "0.1.25"
"#.into()),
r#"//! ```Cargo
//! [dependencies]
//! time = "0.1.25"
//! ```
fn main() {}
"#
)));
assert_eq!(fem(
r#"/*!
[dependencies]
time = "0.1.25"
*/
fn main() {}
"#),
None);
assert_eq!(fem(
r#"/*!
```Cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#),
Some((
TomlOwned(r#"[dependencies]
time = "0.1.25"
"#.into()),
r#"/*!
```Cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#
)));
assert_eq!(fem(
r#"/*!
* [dependencies]
* time = "0.1.25"
*/
fn main() {}
"#),
None);
assert_eq!(fem(
r#"/*!
* ```Cargo
* [dependencies]
* time = "0.1.25"
* ```
*/
fn main() {}
"#),
Some((
TomlOwned(r#"[dependencies]
time = "0.1.25"
"#.into()),
r#"/*!
* ```Cargo
* [dependencies]
* time = "0.1.25"
* ```
*/
fn main() {}
"#
)));
}
/**
Locates a "short comment manifest" in Rust source.
*/
fn find_short_comment_manifest(s: &str) -> Option<(Manifest, &str)> {
/*
This is pretty simple: the only valid syntax for this is for the first, non-blank line to contain a single-line comment whose first token is `cargo-deps:`. That's it.
*/
let re = &*RE_SHORT_MANIFEST;
if let Some(cap) = re.captures(s) {
if let Some((a, b)) = cap.pos(1) {
return Some((Manifest::DepList(&s[a..b]), &s[..]))
}
}
None
}
/**
Locates a "code block manifest" in Rust source.
*/
fn find_code_block_manifest(s: &str) -> Option<(Manifest, &str)> {
/*
This has to happen in a few steps.
First, we will look for and slice out a contiguous, inner doc comment which must be *the very first thing* in the file. `#[doc(...)]` attributes *are not supported*. Multiple single-line comments cannot have any blank lines between them.
Then, we need to strip off the actual comment markers from the content. Including indentation removal, and taking out the (optional) leading line markers for block comments. *sigh*
Then, we need to take the contents of this doc comment and feed it to a Markdown parser. We are looking for *the first* fenced code block with a language token of `cargo`. This is extracted and pasted back together into the manifest.
*/
let start = match RE_CRATE_COMMENT.captures(s) {
Some(cap) => match cap.pos(1) {
Some((a, _)) => a,
None => return None
},
None => return None
};
let comment = match extract_comment(&s[start..]) {
Ok(s) => s,
Err(err) => {
error!("error slicing comment: {}", err);
return None
}
};
scrape_markdown_manifest(&comment)
.unwrap_or(None)
.map(|m| (Manifest::TomlOwned(m), s))
}
/**
Extracts the first `Cargo` fenced code block from a chunk of Markdown.
*/
fn scrape_markdown_manifest(content: &str) -> Result<Option<String>> {
use self::hoedown::{Buffer, Markdown, Render};
// To match librustdoc/html/markdown.rs, HOEDOWN_EXTENSIONS.
let exts
= hoedown::NO_INTRA_EMPHASIS
| hoedown::TABLES
| hoedown::FENCED_CODE
| hoedown::AUTOLINK
| hoedown::STRIKETHROUGH
| hoedown::SUPERSCRIPT
| hoedown::FOOTNOTES;
let md = Markdown::new(&content).extensions(exts);
struct ManifestScraper {
seen_manifest: bool,
}
impl Render for ManifestScraper {
fn code_block(&mut self, output: &mut Buffer, text: &Buffer, lang: &Buffer) {
use std::ascii::AsciiExt;
let lang = lang.to_str().unwrap();
if !self.seen_manifest && lang.eq_ignore_ascii_case("cargo") {
// Pass it through.
info!("found code block manifest");
output.pipe(text);
self.seen_manifest = true;
}
}
}
let mut ms = ManifestScraper { seen_manifest: false };
let mani_buf = ms.render(&md);
if !ms.seen_manifest { return Ok(None) }
mani_buf.to_str().map(|s| Some(s.into()))
.map_err(|_| "error decoding manifest as UTF-8".into())
}
#[test]
fn test_scrape_markdown_manifest() {
macro_rules! smm {
($c:expr) => (scrape_markdown_manifest($c).map_err(|e| e.to_string()));
}
assert_eq!(smm!(
r#"There is no manifest in this comment.
"#
),
Ok(None)
);
assert_eq!(smm!(
r#"There is no manifest in this comment.
```
This is not a manifest.
```
```rust
println!("Nor is this.");
```
Or this.
"#
),
Ok(None)
);
assert_eq!(smm!(
r#"This is a manifest:
```cargo
dependencies = { time = "*" }
```
"#
),
Ok(Some(r#"dependencies = { time = "*" }
"#.into()))
);
assert_eq!(smm!(
r#"This is *not* a manifest:
```
He's lying, I'm *totally* a manifest!
```
This *is*:
```cargo
dependencies = { time = "*" }
```
"#
),
Ok(Some(r#"dependencies = { time = "*" }
"#.into()))
);
assert_eq!(smm!(
r#"This is a manifest:
```cargo
dependencies = { time = "*" }
```
So is this, but it doesn't count:
```cargo
dependencies = { explode = true }
```
"#
),
Ok(Some(r#"dependencies = { time = "*" }
"#.into()))
);
}
/**
Extracts the contents of a Rust doc comment.
*/
fn extract_comment(s: &str) -> Result<String> {
use std::cmp::min;
fn n_leading_spaces(s: &str, n: usize) -> Result<()> {
|
fn extract_block(s: &str) -> Result<String> {
/*
On every line:
- update nesting level and detect end-of-comment
- if margin is None:
- if there appears to be a margin, set margin.
- strip off margin marker
- update the leading space counter
- strip leading space
- append content
*/
let mut r = String::new();
let margin_re = &*RE_MARGIN;
let space_re = &*RE_SPACE;
let nesting_re = &*RE_NESTING;
let mut leading_space = None;
let mut margin = None;
let mut depth: u32 = 1;
for line in s.lines() {
if depth == 0 { break }
// Update nesting and look for end-of-comment.
let mut end_of_comment = None;
for (end, marker) in nesting_re.find_iter(line).map(|(a,b)| (a, &line[a..b])) {
match (marker, depth) {
("/*", _) => depth += 1,
("*/", 1) => {
end_of_comment = Some(end);
depth = 0;
break;
},
("*/", _) => depth -= 1,
_ => panic!("got a comment marker other than /* or */")
}
}
let line = end_of_comment.map(|end| &line[..end]).unwrap_or(line);
// Detect and strip margin.
margin = margin
.or_else(|| margin_re.find(line)
.and_then(|(b, e)| Some(&line[b..e])));
let line = if let Some(margin) = margin {
let end = line.char_indices().take(margin.len())
.map(|(i,c)| i + c.len_utf8()).last().unwrap_or(0);
&line[end..]
} else {
line
};
// Detect and strip leading indentation.
leading_space = leading_space
.or_else(|| space_re.find(line)
.map(|(_,n)| n));
/*
Make sure we have only leading spaces.
If we see a tab, fall over. I *would* expand them, but that gets into the question of how *many* spaces to expand them to, and *where* is the tab, because tabs are tab stops and not just N spaces.
Eurgh.
*/
try!(n_leading_spaces(line, leading_space.unwrap_or(0)));
let strip_len = min(leading_space.unwrap_or(0), line.len());
let line = &line[strip_len..];
// Done.
r.push_str(line);
// `lines` removes newlines. Ideally, it wouldn't do that, but hopefully this shouldn't cause any *real* problems.
r.push_str("\n");
}
Ok(r)
}
fn extract_line(s: &str) -> Result<String> {
let mut r = String::new();
let comment_re = &*RE_COMMENT;
let space_re = &*RE_SPACE;
let mut leading_space = None;
for line in s.lines() {
// Strip leading comment marker.
let content = match comment_re.find(line) {
Some((_, end)) => &line[end..],
None => break
};
// Detect and strip leading indentation.
leading_space = leading_space
.or_else(|| space_re.captures(content)
.and_then(|c| c.pos(1))
.map(|(_,n)| n));
/*
Make sure we have only leading spaces.
If we see a tab, fall over. I *would* expand them, but that gets into the question of how *many* spaces to expand them to, and *where* is the tab, because tabs are tab stops and not just N spaces.
Eurgh.
*/
try!(n_leading_spaces(content, leading_space.unwrap_or(0)));
let strip_len = min(leading_space.unwrap_or(0), content.len());
let content = &content[strip_len..];
// Done.
r.push_str(content);
// `lines` removes newlines. Ideally, it wouldn't do that, but hopefully this shouldn't cause any *real* problems.
r.push_str("\n");
}
Ok(r)
}
if s.starts_with("/*!") {
extract_block(&s[3..])
} else if s.starts_with("//!") {
extract_line(s)
} else {
Err("no doc comment found".into())
}
}
#[test]
fn test_extract_comment() {
macro_rules! ec {
($s:expr) => (extract_comment($s).map_err(|e| e.to_string()))
}
assert_eq!(ec!(
r#"fn main () {}"#
),
Err("no doc comment found".into())
);
assert_eq!(ec!(
r#"/*!
Here is a manifest:
```cargo
[dependencies]
time = "*"
```
*/
fn main() {}
"#
),
Ok(r#"
Here is a manifest:
```cargo
[dependencies]
time = "*"
```
"#.into())
);
assert_eq!(ec!(
r#"/*!
* Here is a manifest:
*
* ```cargo
* [dependencies]
* time = "*"
* ```
*/
fn main() {}
"#
),
Ok(r#"
Here is a manifest:
```cargo
[dependencies]
time = "*"
```
"#.into())
);
assert_eq!(ec!(
r#"//! Here is a manifest:
//!
//! ```cargo
//! [dependencies]
//! time = "*"
//! ```
fn main() {}
"#
),
Ok(r#"Here is a manifest:
```cargo
[dependencies]
time = "*"
```
"#.into())
);
}
/**
Generates a default Cargo manifest for the given input.
*/
fn default_manifest(input: &Input) -> Result<toml::Table> {
let mani_str = consts::DEFAULT_MANIFEST.replace("%n", input.safe_name());
toml::Parser::new(&mani_str).parse()
.ok_or("could not parse default manifest, somehow".into())
}
/**
Generates a partial Cargo manifest containing the specified dependencies.
*/
fn deps_manifest(deps: &[(String, String)]) -> Result<toml::Table> {
let mut mani_str = String::new();
mani_str.push_str("[dependencies]\n");
for &(ref name, ref ver) in deps {
mani_str.push_str(name);
mani_str.push_str("=");
// We only want to quote the version if it *isn't* a table.
let quotes = match ver.starts_with("{") { true => "", false => "\"" };
mani_str.push_str(quotes);
mani_str.push_str(ver);
mani_str.push_str(quotes);
mani_str.push_str("\n");
}
toml::Parser::new(&mani_str).parse()
.ok_or("could not parse dependency manifest".into())
}
/**
Given two Cargo manifests, merges the second *into* the first.
Note that the "merge" in this case is relatively simple: only *top-level* tables are actually merged; everything else is just outright replaced.
*/
fn merge_manifest(mut into_t: toml::Table, from_t: toml::Table) -> Result<toml::Table> {
for (k, v) in from_t {
match v {
toml::Value::Table(from_t) => {
use std::collections::btree_map::Entry::*;
// Merge.
match into_t.entry(k) {
Vacant(e) => {
e.insert(toml::Value::Table(from_t));
},
Occupied(e) => {
let into_t = try!(as_table_mut(e.into_mut())
.ok_or((Blame::Human, "cannot merge manifests: cannot merge \
table and non-table values")));
into_t.extend(from_t);
}
}
},
v => {
// Just replace.
into_t.insert(k, v);
},
}
}
return Ok(into_t);
fn as_table_mut(t: &mut toml::Value) -> Option<&mut toml::Table> {
match *t {
toml::Value::Table(ref mut t) => Some(t),
_ => None
}
}
}
|
if !s.chars().take(n).all(|c| c == ' ') {
return Err(format!("leading {:?} chars aren't all spaces: {:?}", n, s).into())
}
Ok(())
}
|
identifier_body
|
manifest.rs
|
/*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
/*!
This module is concerned with how `cargo-script` extracts the manfiest from a script file.
*/
extern crate hoedown;
extern crate regex;
use self::regex::Regex;
use toml;
use consts;
use error::{Blame, Result};
use Input;
lazy_static! {
static ref RE_SHORT_MANIFEST: Regex = Regex::new(
r"^(?i)\s*//\s*cargo-deps\s*:(.*?)(\r\n|\n)").unwrap();
static ref RE_MARGIN: Regex = Regex::new(r"^\s*\*( |$)").unwrap();
static ref RE_SPACE: Regex = Regex::new(r"^(\s+)").unwrap();
static ref RE_NESTING: Regex = Regex::new(r"/\*|\*/").unwrap();
static ref RE_COMMENT: Regex = Regex::new(r"^\s*//!").unwrap();
static ref RE_HASHBANG: Regex = Regex::new(r"^#![^[].*?(\r\n|\n)").unwrap();
static ref RE_CRATE_COMMENT: Regex = {
Regex::new(
r"(?x)
# We need to find the first `/*!` or `//!` that *isn't* preceeded by something that would make it apply to anything other than the crate itself. Because we can't do this accurately, we'll just require that the doc comment is the *first* thing in the file (after the optional hashbang, which should already have been stripped).
^\s*
(/\*!|//!)
"
).unwrap()
};
}
/**
Splits input into a complete Cargo manifest and unadultered Rust source.
Unless we have prelude items to inject, in which case it will be *slightly* adulterated.
*/
pub fn split_input(input: &Input, deps: &[(String, String)], prelude_items: &[String]) -> Result<(String, String)> {
let (part_mani, source, template, sub_prelude) = match *input {
Input::File(_, _, content, _) => {
assert_eq!(prelude_items.len(), 0);
let content = strip_hashbang(content);
let (manifest, source) = find_embedded_manifest(content)
.unwrap_or((Manifest::Toml(""), content));
(manifest, source, consts::FILE_TEMPLATE, false)
},
Input::Expr(content) => {
(Manifest::Toml(""), content, consts::EXPR_TEMPLATE, true)
},
Input::Loop(content, count) => {
let templ = if count { consts::LOOP_COUNT_TEMPLATE } else { consts::LOOP_TEMPLATE };
(Manifest::Toml(""), content, templ, true)
},
};
let source = template.replace("%b", source);
/*
We are doing it this way because we can guarantee that %p *always* appears before %b, *and* that we don't attempt this when we don't want to allow prelude substitution.
The problem with doing it the other way around is that the user could specify a prelude item that contains `%b` (which would do *weird things*).
Also, don't use `str::replace` because it replaces *all* occurrences, not just the first.
*/
let source = match sub_prelude {
false => source,
true => {
const PRELUDE_PAT: &'static str = "%p";
let offset = source.find(PRELUDE_PAT).expect("template doesn't have %p");
let mut new_source = String::new();
new_source.push_str(&source[..offset]);
for i in prelude_items {
new_source.push_str(i);
new_source.push_str("\n");
}
new_source.push_str(&source[offset + PRELUDE_PAT.len()..]);
new_source
}
};
info!("part_mani: {:?}", part_mani);
info!("source: {:?}", source);
let part_mani = try!(part_mani.into_toml());
info!("part_mani: {:?}", part_mani);
// It's-a mergin' time!
let def_mani = try!(default_manifest(input));
let dep_mani = try!(deps_manifest(deps));
let mani = try!(merge_manifest(def_mani, part_mani));
let mani = try!(merge_manifest(mani, dep_mani));
info!("mani: {:?}", mani);
let mani_str = format!("{}", toml::Value::Table(mani));
info!("mani_str: {}", mani_str);
Ok((mani_str, source))
}
#[test]
fn test_split_input() {
macro_rules! si {
($i:expr) => (split_input(&$i, &[], &[]).ok())
}
let dummy_path: ::std::path::PathBuf = "p".into();
let dummy_path = &dummy_path;
let f = |c| Input::File("n", &dummy_path, c, 0);
macro_rules! r {
($m:expr, $r:expr) => (Some(($m.into(), $r.into())));
}
assert_eq!(si!(f(
r#"fn main() {}"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"fn main() {}"#
)
);
// Ensure removed prefix manifests don't work.
assert_eq!(si!(f(
r#"
---
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
---
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"[dependencies]
time="0.1.25"
---
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"[dependencies]
time="0.1.25"
---
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"
// Cargo-Deps: time="0.1.25"
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
time = "0.1.25"
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
// Cargo-Deps: time="0.1.25"
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"
// Cargo-Deps: time="0.1.25", libc="0.2.5"
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
libc = "0.2.5"
time = "0.1.25"
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
// Cargo-Deps: time="0.1.25", libc="0.2.5"
fn main() {}
"#
)
);
assert_eq!(si!(f(
r#"
/*!
Here is a manifest:
```cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#
)),
r!(
r#"
[[bin]]
name = "n"
path = "n.rs"
[dependencies]
time = "0.1.25"
[package]
authors = ["Anonymous"]
name = "n"
version = "0.1.0"
"#,
r#"
/*!
Here is a manifest:
```cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#
)
|
/**
Returns a slice of the input string with the leading hashbang, if there is one, omitted.
*/
fn strip_hashbang(s: &str) -> &str {
match RE_HASHBANG.find(s) {
Some((_, end)) => &s[end..],
None => s
}
}
#[test]
fn test_strip_hashbang() {
assert_eq!(strip_hashbang("\
#!/usr/bin/env run-cargo-script
and the rest
\
"), "\
and the rest
\
");
assert_eq!(strip_hashbang("\
#![thingy]
and the rest
\
"), "\
#![thingy]
and the rest
\
");
}
/**
Represents the kind, and content of, an embedded manifest.
*/
#[derive(Debug, Eq, PartialEq)]
enum Manifest<'s> {
/// The manifest is a valid TOML fragment.
Toml(&'s str),
/// The manifest is a valid TOML fragment (owned).
// TODO: Change to Cow<'s, str>.
TomlOwned(String),
/// The manifest is a comma-delimited list of dependencies.
DepList(&'s str),
}
impl<'s> Manifest<'s> {
pub fn into_toml(self) -> Result<toml::Table> {
use self::Manifest::*;
match self {
Toml(s) => Ok(try!(toml::Parser::new(s).parse()
.ok_or("could not parse embedded manifest"))),
TomlOwned(ref s) => Ok(try!(toml::Parser::new(s).parse()
.ok_or("could not parse embedded manifest"))),
DepList(s) => Manifest::dep_list_to_toml(s),
}
}
fn dep_list_to_toml(s: &str) -> Result<toml::Table> {
let mut r = String::new();
r.push_str("[dependencies]\n");
for dep in s.trim().split(',') {
// If there's no version specified, add one.
match dep.contains('=') {
true => {
r.push_str(dep);
r.push_str("\n");
},
false => {
r.push_str(dep);
r.push_str("=\"*\"\n");
}
}
}
Ok(try!(toml::Parser::new(&r).parse()
.ok_or("could not parse embedded manifest")))
}
}
/**
Locates a manifest embedded in Rust source.
Returns `Some((manifest, source))` if it finds a manifest, `None` otherwise.
*/
fn find_embedded_manifest(s: &str) -> Option<(Manifest, &str)> {
find_short_comment_manifest(s)
.or_else(|| find_code_block_manifest(s))
}
#[test]
fn test_find_embedded_manifest() {
use self::Manifest::*;
let fem = find_embedded_manifest;
assert_eq!(fem("fn main() {}"), None);
assert_eq!(fem(
"
fn main() {}
"),
None);
// Ensure removed prefix manifests don't work.
assert_eq!(fem(
r#"
---
fn main() {}
"#),
None);
assert_eq!(fem(
"[dependencies]
time = \"0.1.25\"
---
fn main() {}
"),
None);
assert_eq!(fem(
"[dependencies]
time = \"0.1.25\"
fn main() {}
"),
None);
// Make sure we aren't just grabbing the *last* line.
assert_eq!(fem(
"[dependencies]
time = \"0.1.25\"
fn main() {
println!(\"Hi!\");
}
"),
None);
assert_eq!(fem(
"// cargo-deps: time=\"0.1.25\"
fn main() {}
"),
Some((
DepList(" time=\"0.1.25\""),
"// cargo-deps: time=\"0.1.25\"
fn main() {}
"
)));
assert_eq!(fem(
"// cargo-deps: time=\"0.1.25\", libc=\"0.2.5\"
fn main() {}
"),
Some((
DepList(" time=\"0.1.25\", libc=\"0.2.5\""),
"// cargo-deps: time=\"0.1.25\", libc=\"0.2.5\"
fn main() {}
"
)));
assert_eq!(fem(
"
// cargo-deps: time=\"0.1.25\" \n\
fn main() {}
"),
Some((
DepList(" time=\"0.1.25\" "),
"
// cargo-deps: time=\"0.1.25\" \n\
fn main() {}
"
)));
assert_eq!(fem(
"/* cargo-deps: time=\"0.1.25\" */
fn main() {}
"),
None);
assert_eq!(fem(
r#"//! [dependencies]
//! time = "0.1.25"
fn main() {}
"#),
None);
assert_eq!(fem(
r#"//! ```Cargo
//! [dependencies]
//! time = "0.1.25"
//! ```
fn main() {}
"#),
Some((
TomlOwned(r#"[dependencies]
time = "0.1.25"
"#.into()),
r#"//! ```Cargo
//! [dependencies]
//! time = "0.1.25"
//! ```
fn main() {}
"#
)));
assert_eq!(fem(
r#"/*!
[dependencies]
time = "0.1.25"
*/
fn main() {}
"#),
None);
assert_eq!(fem(
r#"/*!
```Cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#),
Some((
TomlOwned(r#"[dependencies]
time = "0.1.25"
"#.into()),
r#"/*!
```Cargo
[dependencies]
time = "0.1.25"
```
*/
fn main() {}
"#
)));
assert_eq!(fem(
r#"/*!
* [dependencies]
* time = "0.1.25"
*/
fn main() {}
"#),
None);
assert_eq!(fem(
r#"/*!
* ```Cargo
* [dependencies]
* time = "0.1.25"
* ```
*/
fn main() {}
"#),
Some((
TomlOwned(r#"[dependencies]
time = "0.1.25"
"#.into()),
r#"/*!
* ```Cargo
* [dependencies]
* time = "0.1.25"
* ```
*/
fn main() {}
"#
)));
}
/**
Locates a "short comment manifest" in Rust source.
*/
fn find_short_comment_manifest(s: &str) -> Option<(Manifest, &str)> {
/*
This is pretty simple: the only valid syntax for this is for the first, non-blank line to contain a single-line comment whose first token is `cargo-deps:`. That's it.
*/
let re = &*RE_SHORT_MANIFEST;
if let Some(cap) = re.captures(s) {
if let Some((a, b)) = cap.pos(1) {
return Some((Manifest::DepList(&s[a..b]), &s[..]))
}
}
None
}
/**
Locates a "code block manifest" in Rust source.
*/
fn find_code_block_manifest(s: &str) -> Option<(Manifest, &str)> {
/*
This has to happen in a few steps.
First, we will look for and slice out a contiguous, inner doc comment which must be *the very first thing* in the file. `#[doc(...)]` attributes *are not supported*. Multiple single-line comments cannot have any blank lines between them.
Then, we need to strip off the actual comment markers from the content. Including indentation removal, and taking out the (optional) leading line markers for block comments. *sigh*
Then, we need to take the contents of this doc comment and feed it to a Markdown parser. We are looking for *the first* fenced code block with a language token of `cargo`. This is extracted and pasted back together into the manifest.
*/
let start = match RE_CRATE_COMMENT.captures(s) {
Some(cap) => match cap.pos(1) {
Some((a, _)) => a,
None => return None
},
None => return None
};
let comment = match extract_comment(&s[start..]) {
Ok(s) => s,
Err(err) => {
error!("error slicing comment: {}", err);
return None
}
};
scrape_markdown_manifest(&comment)
.unwrap_or(None)
.map(|m| (Manifest::TomlOwned(m), s))
}
/**
Extracts the first `Cargo` fenced code block from a chunk of Markdown.
*/
fn scrape_markdown_manifest(content: &str) -> Result<Option<String>> {
use self::hoedown::{Buffer, Markdown, Render};
// To match librustdoc/html/markdown.rs, HOEDOWN_EXTENSIONS.
let exts
= hoedown::NO_INTRA_EMPHASIS
| hoedown::TABLES
| hoedown::FENCED_CODE
| hoedown::AUTOLINK
| hoedown::STRIKETHROUGH
| hoedown::SUPERSCRIPT
| hoedown::FOOTNOTES;
let md = Markdown::new(&content).extensions(exts);
struct ManifestScraper {
seen_manifest: bool,
}
impl Render for ManifestScraper {
fn code_block(&mut self, output: &mut Buffer, text: &Buffer, lang: &Buffer) {
use std::ascii::AsciiExt;
let lang = lang.to_str().unwrap();
if !self.seen_manifest && lang.eq_ignore_ascii_case("cargo") {
// Pass it through.
info!("found code block manifest");
output.pipe(text);
self.seen_manifest = true;
}
}
}
let mut ms = ManifestScraper { seen_manifest: false };
let mani_buf = ms.render(&md);
if !ms.seen_manifest { return Ok(None) }
mani_buf.to_str().map(|s| Some(s.into()))
.map_err(|_| "error decoding manifest as UTF-8".into())
}
#[test]
fn test_scrape_markdown_manifest() {
macro_rules! smm {
($c:expr) => (scrape_markdown_manifest($c).map_err(|e| e.to_string()));
}
assert_eq!(smm!(
r#"There is no manifest in this comment.
"#
),
Ok(None)
);
assert_eq!(smm!(
r#"There is no manifest in this comment.
```
This is not a manifest.
```
```rust
println!("Nor is this.");
```
Or this.
"#
),
Ok(None)
);
assert_eq!(smm!(
r#"This is a manifest:
```cargo
dependencies = { time = "*" }
```
"#
),
Ok(Some(r#"dependencies = { time = "*" }
"#.into()))
);
assert_eq!(smm!(
r#"This is *not* a manifest:
```
He's lying, I'm *totally* a manifest!
```
This *is*:
```cargo
dependencies = { time = "*" }
```
"#
),
Ok(Some(r#"dependencies = { time = "*" }
"#.into()))
);
assert_eq!(smm!(
r#"This is a manifest:
```cargo
dependencies = { time = "*" }
```
So is this, but it doesn't count:
```cargo
dependencies = { explode = true }
```
"#
),
Ok(Some(r#"dependencies = { time = "*" }
"#.into()))
);
}
/**
Extracts the contents of a Rust doc comment.
*/
fn extract_comment(s: &str) -> Result<String> {
use std::cmp::min;
fn n_leading_spaces(s: &str, n: usize) -> Result<()> {
if !s.chars().take(n).all(|c| c == ' ') {
return Err(format!("leading {:?} chars aren't all spaces: {:?}", n, s).into())
}
Ok(())
}
fn extract_block(s: &str) -> Result<String> {
/*
On every line:
- update nesting level and detect end-of-comment
- if margin is None:
- if there appears to be a margin, set margin.
- strip off margin marker
- update the leading space counter
- strip leading space
- append content
*/
let mut r = String::new();
let margin_re = &*RE_MARGIN;
let space_re = &*RE_SPACE;
let nesting_re = &*RE_NESTING;
let mut leading_space = None;
let mut margin = None;
let mut depth: u32 = 1;
for line in s.lines() {
if depth == 0 { break }
// Update nesting and look for end-of-comment.
let mut end_of_comment = None;
for (end, marker) in nesting_re.find_iter(line).map(|(a,b)| (a, &line[a..b])) {
match (marker, depth) {
("/*", _) => depth += 1,
("*/", 1) => {
end_of_comment = Some(end);
depth = 0;
break;
},
("*/", _) => depth -= 1,
_ => panic!("got a comment marker other than /* or */")
}
}
let line = end_of_comment.map(|end| &line[..end]).unwrap_or(line);
// Detect and strip margin.
margin = margin
.or_else(|| margin_re.find(line)
.and_then(|(b, e)| Some(&line[b..e])));
let line = if let Some(margin) = margin {
let end = line.char_indices().take(margin.len())
.map(|(i,c)| i + c.len_utf8()).last().unwrap_or(0);
&line[end..]
} else {
line
};
// Detect and strip leading indentation.
leading_space = leading_space
.or_else(|| space_re.find(line)
.map(|(_,n)| n));
/*
Make sure we have only leading spaces.
If we see a tab, fall over. I *would* expand them, but that gets into the question of how *many* spaces to expand them to, and *where* is the tab, because tabs are tab stops and not just N spaces.
Eurgh.
*/
try!(n_leading_spaces(line, leading_space.unwrap_or(0)));
let strip_len = min(leading_space.unwrap_or(0), line.len());
let line = &line[strip_len..];
// Done.
r.push_str(line);
// `lines` removes newlines. Ideally, it wouldn't do that, but hopefully this shouldn't cause any *real* problems.
r.push_str("\n");
}
Ok(r)
}
fn extract_line(s: &str) -> Result<String> {
let mut r = String::new();
let comment_re = &*RE_COMMENT;
let space_re = &*RE_SPACE;
let mut leading_space = None;
for line in s.lines() {
// Strip leading comment marker.
let content = match comment_re.find(line) {
Some((_, end)) => &line[end..],
None => break
};
// Detect and strip leading indentation.
leading_space = leading_space
.or_else(|| space_re.captures(content)
.and_then(|c| c.pos(1))
.map(|(_,n)| n));
/*
Make sure we have only leading spaces.
If we see a tab, fall over. I *would* expand them, but that gets into the question of how *many* spaces to expand them to, and *where* is the tab, because tabs are tab stops and not just N spaces.
Eurgh.
*/
try!(n_leading_spaces(content, leading_space.unwrap_or(0)));
let strip_len = min(leading_space.unwrap_or(0), content.len());
let content = &content[strip_len..];
// Done.
r.push_str(content);
// `lines` removes newlines. Ideally, it wouldn't do that, but hopefully this shouldn't cause any *real* problems.
r.push_str("\n");
}
Ok(r)
}
if s.starts_with("/*!") {
extract_block(&s[3..])
} else if s.starts_with("//!") {
extract_line(s)
} else {
Err("no doc comment found".into())
}
}
#[test]
fn test_extract_comment() {
macro_rules! ec {
($s:expr) => (extract_comment($s).map_err(|e| e.to_string()))
}
assert_eq!(ec!(
r#"fn main () {}"#
),
Err("no doc comment found".into())
);
assert_eq!(ec!(
r#"/*!
Here is a manifest:
```cargo
[dependencies]
time = "*"
```
*/
fn main() {}
"#
),
Ok(r#"
Here is a manifest:
```cargo
[dependencies]
time = "*"
```
"#.into())
);
assert_eq!(ec!(
r#"/*!
* Here is a manifest:
*
* ```cargo
* [dependencies]
* time = "*"
* ```
*/
fn main() {}
"#
),
Ok(r#"
Here is a manifest:
```cargo
[dependencies]
time = "*"
```
"#.into())
);
assert_eq!(ec!(
r#"//! Here is a manifest:
//!
//! ```cargo
//! [dependencies]
//! time = "*"
//! ```
fn main() {}
"#
),
Ok(r#"Here is a manifest:
```cargo
[dependencies]
time = "*"
```
"#.into())
);
}
/**
Generates a default Cargo manifest for the given input.
*/
fn default_manifest(input: &Input) -> Result<toml::Table> {
let mani_str = consts::DEFAULT_MANIFEST.replace("%n", input.safe_name());
toml::Parser::new(&mani_str).parse()
.ok_or("could not parse default manifest, somehow".into())
}
/**
Generates a partial Cargo manifest containing the specified dependencies.
*/
fn deps_manifest(deps: &[(String, String)]) -> Result<toml::Table> {
let mut mani_str = String::new();
mani_str.push_str("[dependencies]\n");
for &(ref name, ref ver) in deps {
mani_str.push_str(name);
mani_str.push_str("=");
// We only want to quote the version if it *isn't* a table.
let quotes = match ver.starts_with("{") { true => "", false => "\"" };
mani_str.push_str(quotes);
mani_str.push_str(ver);
mani_str.push_str(quotes);
mani_str.push_str("\n");
}
toml::Parser::new(&mani_str).parse()
.ok_or("could not parse dependency manifest".into())
}
/**
Given two Cargo manifests, merges the second *into* the first.
Note that the "merge" in this case is relatively simple: only *top-level* tables are actually merged; everything else is just outright replaced.
*/
fn merge_manifest(mut into_t: toml::Table, from_t: toml::Table) -> Result<toml::Table> {
for (k, v) in from_t {
match v {
toml::Value::Table(from_t) => {
use std::collections::btree_map::Entry::*;
// Merge.
match into_t.entry(k) {
Vacant(e) => {
e.insert(toml::Value::Table(from_t));
},
Occupied(e) => {
let into_t = try!(as_table_mut(e.into_mut())
.ok_or((Blame::Human, "cannot merge manifests: cannot merge \
table and non-table values")));
into_t.extend(from_t);
}
}
},
v => {
// Just replace.
into_t.insert(k, v);
},
}
}
return Ok(into_t);
fn as_table_mut(t: &mut toml::Value) -> Option<&mut toml::Table> {
match *t {
toml::Value::Table(ref mut t) => Some(t),
_ => None
}
}
}
|
);
}
|
random_line_split
|
application.rs
|
//! This module contains the base elements of an OrbTk application (Application, WindowBuilder and Window).
use std::sync::mpsc;
use dces::prelude::Entity;
use crate::{
core::{application::WindowAdapter, localization::*, *},
shell::{Shell, ShellRequest},
};
/// The `Application` represents the entry point of an OrbTk based application.
pub struct Application {
// shells: Vec<Shell<WindowAdapter>>,
request_sender: mpsc::Sender<ShellRequest<WindowAdapter>>,
shell: Shell<WindowAdapter>,
name: Box<str>,
theme: Rc<Theme>,
localization: Option<Rc<RefCell<Box<dyn Localization>>>>,
}
impl Default for Application {
fn default() -> Self {
Application::from_name("orbtk_application")
}
}
impl Application {
/// Creates a new application.
pub fn new() -> Self {
Self::default()
}
/// Sets the default theme for the application. Could be changed per window.
pub fn theme(mut self, theme: Theme) -> Self {
self.theme = Rc::new(theme);
self
}
pub fn localization<L>(mut self, localization: L) -> Self
where
L: Localization + 'static,
|
/// Create a new application with the given name.
pub fn from_name(name: impl Into<Box<str>>) -> Self {
let (sender, receiver) = mpsc::channel();
Application {
request_sender: sender,
name: name.into(),
shell: Shell::new(receiver),
theme: Rc::new(crate::widgets::themes::theme_orbtk::theme_default()),
localization: None,
}
}
/// Creates a new window and add it to the application.
pub fn window<F: Fn(&mut BuildContext) -> Entity + 'static>(mut self, create_fn: F) -> Self {
let (adapter, settings, receiver) = create_window(
self.name.clone(),
&self.theme,
self.request_sender.clone(),
create_fn,
self.localization.clone(),
);
self.shell
.create_window_from_settings(settings, adapter)
.request_receiver(receiver)
.build();
self
}
/// Starts the application and run it until quit is requested.
pub fn run(mut self) {
self.shell.run();
}
}
|
{
self.localization = Some(Rc::new(RefCell::new(Box::new(localization))));
self
}
|
identifier_body
|
application.rs
|
//! This module contains the base elements of an OrbTk application (Application, WindowBuilder and Window).
use std::sync::mpsc;
use dces::prelude::Entity;
use crate::{
core::{application::WindowAdapter, localization::*, *},
shell::{Shell, ShellRequest},
};
/// The `Application` represents the entry point of an OrbTk based application.
pub struct Application {
// shells: Vec<Shell<WindowAdapter>>,
request_sender: mpsc::Sender<ShellRequest<WindowAdapter>>,
shell: Shell<WindowAdapter>,
name: Box<str>,
theme: Rc<Theme>,
|
localization: Option<Rc<RefCell<Box<dyn Localization>>>>,
}
impl Default for Application {
fn default() -> Self {
Application::from_name("orbtk_application")
}
}
impl Application {
/// Creates a new application.
pub fn new() -> Self {
Self::default()
}
/// Sets the default theme for the application. Could be changed per window.
pub fn theme(mut self, theme: Theme) -> Self {
self.theme = Rc::new(theme);
self
}
pub fn localization<L>(mut self, localization: L) -> Self
where
L: Localization + 'static,
{
self.localization = Some(Rc::new(RefCell::new(Box::new(localization))));
self
}
/// Create a new application with the given name.
pub fn from_name(name: impl Into<Box<str>>) -> Self {
let (sender, receiver) = mpsc::channel();
Application {
request_sender: sender,
name: name.into(),
shell: Shell::new(receiver),
theme: Rc::new(crate::widgets::themes::theme_orbtk::theme_default()),
localization: None,
}
}
/// Creates a new window and add it to the application.
pub fn window<F: Fn(&mut BuildContext) -> Entity + 'static>(mut self, create_fn: F) -> Self {
let (adapter, settings, receiver) = create_window(
self.name.clone(),
&self.theme,
self.request_sender.clone(),
create_fn,
self.localization.clone(),
);
self.shell
.create_window_from_settings(settings, adapter)
.request_receiver(receiver)
.build();
self
}
/// Starts the application and run it until quit is requested.
pub fn run(mut self) {
self.shell.run();
}
}
|
random_line_split
|
|
application.rs
|
//! This module contains the base elements of an OrbTk application (Application, WindowBuilder and Window).
use std::sync::mpsc;
use dces::prelude::Entity;
use crate::{
core::{application::WindowAdapter, localization::*, *},
shell::{Shell, ShellRequest},
};
/// The `Application` represents the entry point of an OrbTk based application.
pub struct Application {
// shells: Vec<Shell<WindowAdapter>>,
request_sender: mpsc::Sender<ShellRequest<WindowAdapter>>,
shell: Shell<WindowAdapter>,
name: Box<str>,
theme: Rc<Theme>,
localization: Option<Rc<RefCell<Box<dyn Localization>>>>,
}
impl Default for Application {
fn default() -> Self {
Application::from_name("orbtk_application")
}
}
impl Application {
/// Creates a new application.
pub fn new() -> Self {
Self::default()
}
/// Sets the default theme for the application. Could be changed per window.
pub fn theme(mut self, theme: Theme) -> Self {
self.theme = Rc::new(theme);
self
}
pub fn localization<L>(mut self, localization: L) -> Self
where
L: Localization + 'static,
{
self.localization = Some(Rc::new(RefCell::new(Box::new(localization))));
self
}
/// Create a new application with the given name.
pub fn from_name(name: impl Into<Box<str>>) -> Self {
let (sender, receiver) = mpsc::channel();
Application {
request_sender: sender,
name: name.into(),
shell: Shell::new(receiver),
theme: Rc::new(crate::widgets::themes::theme_orbtk::theme_default()),
localization: None,
}
}
/// Creates a new window and add it to the application.
pub fn window<F: Fn(&mut BuildContext) -> Entity + 'static>(mut self, create_fn: F) -> Self {
let (adapter, settings, receiver) = create_window(
self.name.clone(),
&self.theme,
self.request_sender.clone(),
create_fn,
self.localization.clone(),
);
self.shell
.create_window_from_settings(settings, adapter)
.request_receiver(receiver)
.build();
self
}
/// Starts the application and run it until quit is requested.
pub fn
|
(mut self) {
self.shell.run();
}
}
|
run
|
identifier_name
|
SineWavePointOptimizer.py
|
from neurotune.controllers import SineWaveController
import sys
from neurotune import evaluators
from neurotune import optimizers
from neurotune import utils
if __name__ == "__main__":
showPlots = not ("-nogui" in sys.argv)
verbose = not ("-silent" in sys.argv)
sim_vars = {"amp": 65, "period": 250, "offset": -10}
min_constraints = [60, 150, -20]
max_constraints = [100, 300, 20]
swc = SineWaveController(1000, 0.1)
times, volts = swc.run_individual(sim_vars, showPlots, False)
weights = {"value_200": 1.0, "value_400": 1.0, "value_812": 1.0}
data_analysis = evaluators.PointBasedAnalysis(volts, times)
targets = data_analysis.analyse(weights.keys())
print("Target data: %s" % targets)
# make an evaluator
my_evaluator = evaluators.PointValueEvaluator(
controller=swc, parameters=sim_vars.keys(), weights=weights, targets=targets
)
population_size = 20
max_evaluations = 300
num_selected = 10
num_offspring = 5
mutation_rate = 0.5
num_elites = 1
# make an optimizer
my_optimizer = optimizers.CustomOptimizerA(
max_constraints,
min_constraints,
my_evaluator,
population_size=population_size,
max_evaluations=max_evaluations,
num_selected=num_selected,
num_offspring=num_offspring,
num_elites=num_elites,
mutation_rate=mutation_rate,
seeds=None,
verbose=verbose,
)
# run the optimizer
best_candidate, fitness = my_optimizer.optimize(do_plot=False, seed=1234567)
keys = list(sim_vars.keys())
for i in range(len(best_candidate)):
sim_vars[keys[i]] = best_candidate[i]
fit_times, fit_volts = swc.run_individual(sim_vars, showPlots, False)
if showPlots:
|
utils.plot_generation_evolution(sim_vars.keys(), sim_vars)
|
conditional_block
|
|
SineWavePointOptimizer.py
|
from neurotune.controllers import SineWaveController
import sys
from neurotune import evaluators
from neurotune import optimizers
from neurotune import utils
if __name__ == "__main__":
showPlots = not ("-nogui" in sys.argv)
verbose = not ("-silent" in sys.argv)
sim_vars = {"amp": 65, "period": 250, "offset": -10}
min_constraints = [60, 150, -20]
max_constraints = [100, 300, 20]
swc = SineWaveController(1000, 0.1)
times, volts = swc.run_individual(sim_vars, showPlots, False)
weights = {"value_200": 1.0, "value_400": 1.0, "value_812": 1.0}
data_analysis = evaluators.PointBasedAnalysis(volts, times)
targets = data_analysis.analyse(weights.keys())
print("Target data: %s" % targets)
# make an evaluator
my_evaluator = evaluators.PointValueEvaluator(
controller=swc, parameters=sim_vars.keys(), weights=weights, targets=targets
|
population_size = 20
max_evaluations = 300
num_selected = 10
num_offspring = 5
mutation_rate = 0.5
num_elites = 1
# make an optimizer
my_optimizer = optimizers.CustomOptimizerA(
max_constraints,
min_constraints,
my_evaluator,
population_size=population_size,
max_evaluations=max_evaluations,
num_selected=num_selected,
num_offspring=num_offspring,
num_elites=num_elites,
mutation_rate=mutation_rate,
seeds=None,
verbose=verbose,
)
# run the optimizer
best_candidate, fitness = my_optimizer.optimize(do_plot=False, seed=1234567)
keys = list(sim_vars.keys())
for i in range(len(best_candidate)):
sim_vars[keys[i]] = best_candidate[i]
fit_times, fit_volts = swc.run_individual(sim_vars, showPlots, False)
if showPlots:
utils.plot_generation_evolution(sim_vars.keys(), sim_vars)
|
)
|
random_line_split
|
profile-editor.component.1.ts
|
// #docplaster
// #docregion formgroup, nested-formgroup
import { Component } from '@angular/core';
// #docregion imports
import { FormGroup, FormControl } from '@angular/forms';
// #enddocregion imports
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
// #docregion formgroup-compare
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
// #enddocregion formgroup
address: new FormGroup({
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
// #docregion formgroup
});
// #enddocregion formgroup, nested-formgroup, formgroup-compare
// #docregion patch-value
|
() {
this.profileForm.patchValue({
firstName: 'Nancy',
address: {
street: '123 Drew Street'
}
});
}
// #enddocregion patch-value
// #docregion formgroup, nested-formgroup
}
// #enddocregion formgroup
|
updateProfile
|
identifier_name
|
profile-editor.component.1.ts
|
// #docplaster
// #docregion formgroup, nested-formgroup
import { Component } from '@angular/core';
// #docregion imports
import { FormGroup, FormControl } from '@angular/forms';
// #enddocregion imports
|
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
// #docregion formgroup-compare
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
// #enddocregion formgroup
address: new FormGroup({
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
// #docregion formgroup
});
// #enddocregion formgroup, nested-formgroup, formgroup-compare
// #docregion patch-value
updateProfile() {
this.profileForm.patchValue({
firstName: 'Nancy',
address: {
street: '123 Drew Street'
}
});
}
// #enddocregion patch-value
// #docregion formgroup, nested-formgroup
}
// #enddocregion formgroup
|
@Component({
selector: 'app-profile-editor',
|
random_line_split
|
np.common.js
|
(function () {
'use strict';
var module = angular.module('np.common', []);
module.factory('np.common.requestFactory', [
'$log', '$q', '$http',
function (console, Q, http) {
return function (config) {
return function (method, path, data, params) {
var req = {
method: method,
url: config.endpoint + path,
headers: {Accept: 'application/json'}
//withCredentials: true
};
if (method == 'GET' || method == 'DELETE') {
req.params = data;
} else
|
//if (config.authorization) {
// req.headers.Authorization = 'Bearer ' + SHA1(key + secret + nonce) + nonce
//}
return http(req).then(function (res) {
console.log('***request ', req.method, req.url, 'ok:', res.status);
return res.data;
}, function (res) {
console.log('***request ', req.method, req.url, 'err:', res.status);
var error = (res.data && res.data.status) ? res.data : {
status: res.status,
message: String(res.data)
};
return Q.reject(error);
});
};
};
}
]);
}());
|
{
req.headers['Content-Type'] = 'application/json;charset=utf8';
req.data = data;
req.params = params;
}
|
conditional_block
|
np.common.js
|
(function () {
'use strict';
var module = angular.module('np.common', []);
module.factory('np.common.requestFactory', [
'$log', '$q', '$http',
|
method: method,
url: config.endpoint + path,
headers: {Accept: 'application/json'}
//withCredentials: true
};
if (method == 'GET' || method == 'DELETE') {
req.params = data;
} else {
req.headers['Content-Type'] = 'application/json;charset=utf8';
req.data = data;
req.params = params;
}
//if (config.authorization) {
// req.headers.Authorization = 'Bearer ' + SHA1(key + secret + nonce) + nonce
//}
return http(req).then(function (res) {
console.log('***request ', req.method, req.url, 'ok:', res.status);
return res.data;
}, function (res) {
console.log('***request ', req.method, req.url, 'err:', res.status);
var error = (res.data && res.data.status) ? res.data : {
status: res.status,
message: String(res.data)
};
return Q.reject(error);
});
};
};
}
]);
}());
|
function (console, Q, http) {
return function (config) {
return function (method, path, data, params) {
var req = {
|
random_line_split
|
directory.d.ts
|
/**
* TypeScript definitions for objects returned by the Application Directory.
*
* These structures are defined by the App-Directory FDC3 working group. The definitions here are based on the 1.0.0
* specification which can be found [here](https://fdc3.finos.org/appd-spec).
*
* @module Directory
*/
/**
* Type alias to indicate when an Application Identifier should be passed. Application Identifiers
* are described [here](https://fdc3.finos.org/docs/1.0/appd-discovery#application-identifier).
*
* In the OpenFin implementation of FDC3, we expect this to be the same as the
* [UUID in the manifest](https://developers.openfin.co/docs/application-configuration), but this can be configured
* using [[Application.customConfig]].
*
* This type alias exists to disambiguate the raw string app identity from the [[AppName]].
*/
export declare type AppId = string;
/**
* App Name is the machine-readable name of the app, but it may well be sufficiently
* human-readable that it can be used in user interfaces. If it's not, please use the title.
*
* This type alias exists to disambiguate the raw string app name from the [[AppId]].
*/
export declare type AppName = string;
/**
* An application in the app directory.
*/
export interface Application {
/**
* The Application Identifier. Please see https://fdc3.finos.org/docs/1.0/appd-discovery#application-identifier.
* By convention this should be the same as your [OpenFin UUID](https://developers.openfin.co/docs/application-configuration).
*
* If you can't use your OpenFin UUID as the appId, then instead specify your application's UUID by adding an
* `appUuid` property to the [[customConfig]] field.
*/
appId: AppId;
/**
* The machine-readable app name, used to identify the application in various API calls to the application directory.
* This may well be human-readable, too. If it's not, you can provide a title, and that will be used everywhere
* a name needs to be rendered to a user.
*/
name: AppName;
/**
* An application manifest, used to launch the app. This should be a URL that points to an OpenFin JSON manifest.
*/
manifest: string;
/**
* The manifest type. Always `'openfin'`.
*/
manifestType: string;
/**
* The version of the app. Please use [semantic versioning](https://semver.org/).
*/
version?: string | undefined;
/**
* The human-readable title of the app, typically used by the launcher UI. If not provided, [[name]] is used.
*/
title?: string | undefined;
/**
* A short explanatory text string. For use in tooltips shown by any UIs that display app information.
*/
tooltip?: string | undefined;
/**
* Longer description of the app.
*/
description?: string | undefined;
/**
* Images that can be displayed as part of the app directory entry. Use these for screenshots, previews or similar. These are not the
* application icons - use [[icons]] for that.
*/
images?: AppImage[] | undefined;
/**
* Contact email address.
*/
contactEmail?: string | undefined;
/**
* The email address to send your support requests to.
*/
supportEmail?: string | undefined;
/**
* Name of the publishing company, organization, or individual.
*/
publisher?: string | undefined;
/**
* Icons used in the app directory display. A launcher may be able to use various sizes.
*/
icons?: Icon[] | undefined;
/**
* Additional config.
*
* The OpenFin FDC3 service supports the following configuration values:
* * `appUuid`: Informs the service that the application launched by this [[manifest]] will have this UUID. By
* default, the service will expect the UUID of the application to match the [[appId]]. This configuration value
* can be used to override this.
*
* Any additional fields will still be accessible to applications (via APIs such as [[findIntent]]), but will not
* have any impact on the operation of the service.
*/
customConfig?: NameValuePair[] | undefined;
/**
* The set of intents associated with this application directory entry.
*/
intents?: AppDirIntent[] | undefined;
}
/**
* An image for an app in the app directory.
*/
export interface AppImage {
/**
* A URL that points to an image.
*/
url: string;
/**
* Alt text to be displayed with the image.
*/
tooltip?: string | undefined;
/**
* Additional text description.
*/
description?: string | undefined;
}
/**
* An icon for an app in the app directory.
*/
export interface Icon {
/**
* A URL that points to an icon.
*/
icon: string;
}
/**
* A pair of name and values, that allows extra configuration to be passed in to an application.
*/
export interface NameValuePair {
name: string;
value: string;
}
/**
* A representation of an [FDC3 Intent](https://fdc3.finos.org/docs/1.0/intents-intro) supported by the app in the app directory.
*/
export interface AppDirIntent {
/**
* The intent name.
*/
name: string;
/**
* A short, human-readable description of this intent.
|
displayName?: string | undefined;
/**
* The context types that this intent supports. A context type is a namespaced name;
* examples are given [here](https://fdc3.finos.org/docs/1.0/context-spec).
*/
contexts?: string[] | undefined;
/**
* Custom configuration for the intent. Currently unused, reserved for future use.
*/
customConfig?: any;
}
|
*/
|
random_line_split
|
run.py
|
import os
import sys
import drivecasa
import logging
import shlex
import shutil
import subprocess
import yaml
import glob
casa = drivecasa.Casapy(log2term=True, echo_to_stdout=True, timeout=24*3600*10)
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
with open(CONFIG, "r") as _std:
cab = yaml.safe_load(_std)
junk = cab["junk"]
args = {}
for param in cab['parameters']:
name = param['name']
value = param['value']
if value is None:
|
args[name] = value
script = ['{0}(**{1})'.format(cab['binary'], args)]
def log2term(result):
if result[1]:
err = '\n'.join(result[1] if result[1] else [''])
failed = err.lower().find('an error occurred running task') >= 0
if failed:
raise RuntimeError('CASA Task failed. See error message above')
sys.stdout.write('WARNING:: SEVERE messages from CASA run')
try:
result = casa.run_script(script, raise_on_severe=False)
log2term(result)
finally:
for item in junk:
for dest in [OUTPUT, MSDIR]: # these are the only writable volumes in the container
items = glob.glob("{dest}/{item}".format(**locals()))
for f in items:
if os.path.isfile(f):
os.remove(f)
elif os.path.isdir(f):
shutil.rmtree(f)
|
continue
|
conditional_block
|
run.py
|
import os
import sys
|
import yaml
import glob
casa = drivecasa.Casapy(log2term=True, echo_to_stdout=True, timeout=24*3600*10)
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
with open(CONFIG, "r") as _std:
cab = yaml.safe_load(_std)
junk = cab["junk"]
args = {}
for param in cab['parameters']:
name = param['name']
value = param['value']
if value is None:
continue
args[name] = value
script = ['{0}(**{1})'.format(cab['binary'], args)]
def log2term(result):
if result[1]:
err = '\n'.join(result[1] if result[1] else [''])
failed = err.lower().find('an error occurred running task') >= 0
if failed:
raise RuntimeError('CASA Task failed. See error message above')
sys.stdout.write('WARNING:: SEVERE messages from CASA run')
try:
result = casa.run_script(script, raise_on_severe=False)
log2term(result)
finally:
for item in junk:
for dest in [OUTPUT, MSDIR]: # these are the only writable volumes in the container
items = glob.glob("{dest}/{item}".format(**locals()))
for f in items:
if os.path.isfile(f):
os.remove(f)
elif os.path.isdir(f):
shutil.rmtree(f)
|
import drivecasa
import logging
import shlex
import shutil
import subprocess
|
random_line_split
|
run.py
|
import os
import sys
import drivecasa
import logging
import shlex
import shutil
import subprocess
import yaml
import glob
casa = drivecasa.Casapy(log2term=True, echo_to_stdout=True, timeout=24*3600*10)
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
with open(CONFIG, "r") as _std:
cab = yaml.safe_load(_std)
junk = cab["junk"]
args = {}
for param in cab['parameters']:
name = param['name']
value = param['value']
if value is None:
continue
args[name] = value
script = ['{0}(**{1})'.format(cab['binary'], args)]
def log2term(result):
|
try:
result = casa.run_script(script, raise_on_severe=False)
log2term(result)
finally:
for item in junk:
for dest in [OUTPUT, MSDIR]: # these are the only writable volumes in the container
items = glob.glob("{dest}/{item}".format(**locals()))
for f in items:
if os.path.isfile(f):
os.remove(f)
elif os.path.isdir(f):
shutil.rmtree(f)
|
if result[1]:
err = '\n'.join(result[1] if result[1] else [''])
failed = err.lower().find('an error occurred running task') >= 0
if failed:
raise RuntimeError('CASA Task failed. See error message above')
sys.stdout.write('WARNING:: SEVERE messages from CASA run')
|
identifier_body
|
run.py
|
import os
import sys
import drivecasa
import logging
import shlex
import shutil
import subprocess
import yaml
import glob
casa = drivecasa.Casapy(log2term=True, echo_to_stdout=True, timeout=24*3600*10)
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
with open(CONFIG, "r") as _std:
cab = yaml.safe_load(_std)
junk = cab["junk"]
args = {}
for param in cab['parameters']:
name = param['name']
value = param['value']
if value is None:
continue
args[name] = value
script = ['{0}(**{1})'.format(cab['binary'], args)]
def
|
(result):
if result[1]:
err = '\n'.join(result[1] if result[1] else [''])
failed = err.lower().find('an error occurred running task') >= 0
if failed:
raise RuntimeError('CASA Task failed. See error message above')
sys.stdout.write('WARNING:: SEVERE messages from CASA run')
try:
result = casa.run_script(script, raise_on_severe=False)
log2term(result)
finally:
for item in junk:
for dest in [OUTPUT, MSDIR]: # these are the only writable volumes in the container
items = glob.glob("{dest}/{item}".format(**locals()))
for f in items:
if os.path.isfile(f):
os.remove(f)
elif os.path.isdir(f):
shutil.rmtree(f)
|
log2term
|
identifier_name
|
index.js
|
var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');
var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.length == 0) {
throw "Error: please, provide your userkey as first parameter!";
}
var userKey = argv[0];
function registerMachine(callback) {
var data = {
'UserKey': userKey,
'ComputerName': os.hostname(),
'OS': os.type() + ' ' + os.release()
};
sendPOST(data, '/machine', callback);
}
function sendHealthcheck(hc, callback)
|
function sendPOST(postData, path, callback) {
var data = JSON.stringify(postData);
var options = getOpts(config.get('api.url'), 'POST', path, data);
var req = http.request(options, function (res) {
var resData = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
resData += chunk;
});
res.on('end', function () {
callback(res.statusCode != 200 ? res.statusCode : null, resData);
});
});
req.on('error', function (err) {
callback(err);
});
req.write(data);
req.end();
}
function getOpts(apiUrl, method, path, data) {
var options = url.parse(apiUrl + '/v'+config.get('api.v')+path);
options.method = method;
options.headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
return options;
}
attempt(
{
retries: 5,
interval: 3000
},
function() {
registerMachine(this);
},
function(err, res) {
if (err) {
logger.error(err);
throw err;
}
logger.debug(res);
var machineContainer = JSON.parse(res);
(function gatherHealthCheck(timeout) {
logger.debug('Getting healthcheck...')
healthcheck.getHealthcheck(machineContainer.Key, userKey, function (err, res) {
if (err) throw err;
logger.debug('Healthcheck: ' + JSON.stringify(res));
logger.debug('Sending data to API...');
sendHealthcheck(res, function (err, data) {
if (err) {
logger.error(err);
}
else {
var json = JSON.parse(data);
logger.debug('Got response: ' + data);
var newInterval = json.Interval * 1000;
if (newInterval != timeout) {
logger.debug('Changing data collection interval: ');
timeout = newInterval;
}
}
});
});
setTimeout(function () {
gatherHealthCheck(timeout);
}, timeout);
})(machineContainer.Settings.Interval * 1000);
});
|
{
sendPOST(hc, '/', callback);
}
|
identifier_body
|
index.js
|
var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');
var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.length == 0) {
throw "Error: please, provide your userkey as first parameter!";
}
var userKey = argv[0];
function registerMachine(callback) {
var data = {
'UserKey': userKey,
'ComputerName': os.hostname(),
'OS': os.type() + ' ' + os.release()
};
sendPOST(data, '/machine', callback);
}
function
|
(hc, callback) {
sendPOST(hc, '/', callback);
}
function sendPOST(postData, path, callback) {
var data = JSON.stringify(postData);
var options = getOpts(config.get('api.url'), 'POST', path, data);
var req = http.request(options, function (res) {
var resData = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
resData += chunk;
});
res.on('end', function () {
callback(res.statusCode != 200 ? res.statusCode : null, resData);
});
});
req.on('error', function (err) {
callback(err);
});
req.write(data);
req.end();
}
function getOpts(apiUrl, method, path, data) {
var options = url.parse(apiUrl + '/v'+config.get('api.v')+path);
options.method = method;
options.headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
return options;
}
attempt(
{
retries: 5,
interval: 3000
},
function() {
registerMachine(this);
},
function(err, res) {
if (err) {
logger.error(err);
throw err;
}
logger.debug(res);
var machineContainer = JSON.parse(res);
(function gatherHealthCheck(timeout) {
logger.debug('Getting healthcheck...')
healthcheck.getHealthcheck(machineContainer.Key, userKey, function (err, res) {
if (err) throw err;
logger.debug('Healthcheck: ' + JSON.stringify(res));
logger.debug('Sending data to API...');
sendHealthcheck(res, function (err, data) {
if (err) {
logger.error(err);
}
else {
var json = JSON.parse(data);
logger.debug('Got response: ' + data);
var newInterval = json.Interval * 1000;
if (newInterval != timeout) {
logger.debug('Changing data collection interval: ');
timeout = newInterval;
}
}
});
});
setTimeout(function () {
gatherHealthCheck(timeout);
}, timeout);
})(machineContainer.Settings.Interval * 1000);
});
|
sendHealthcheck
|
identifier_name
|
index.js
|
var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');
var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.length == 0) {
throw "Error: please, provide your userkey as first parameter!";
}
var userKey = argv[0];
function registerMachine(callback) {
var data = {
'UserKey': userKey,
'ComputerName': os.hostname(),
'OS': os.type() + ' ' + os.release()
};
sendPOST(data, '/machine', callback);
}
function sendHealthcheck(hc, callback) {
sendPOST(hc, '/', callback);
}
function sendPOST(postData, path, callback) {
var data = JSON.stringify(postData);
var options = getOpts(config.get('api.url'), 'POST', path, data);
var req = http.request(options, function (res) {
var resData = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
resData += chunk;
});
res.on('end', function () {
callback(res.statusCode != 200 ? res.statusCode : null, resData);
});
});
req.on('error', function (err) {
callback(err);
});
req.write(data);
req.end();
}
function getOpts(apiUrl, method, path, data) {
var options = url.parse(apiUrl + '/v'+config.get('api.v')+path);
options.method = method;
options.headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
return options;
}
attempt(
{
retries: 5,
interval: 3000
},
function() {
registerMachine(this);
},
function(err, res) {
if (err) {
logger.error(err);
throw err;
}
logger.debug(res);
var machineContainer = JSON.parse(res);
(function gatherHealthCheck(timeout) {
logger.debug('Getting healthcheck...')
healthcheck.getHealthcheck(machineContainer.Key, userKey, function (err, res) {
if (err) throw err;
logger.debug('Healthcheck: ' + JSON.stringify(res));
logger.debug('Sending data to API...');
sendHealthcheck(res, function (err, data) {
if (err)
|
else {
var json = JSON.parse(data);
logger.debug('Got response: ' + data);
var newInterval = json.Interval * 1000;
if (newInterval != timeout) {
logger.debug('Changing data collection interval: ');
timeout = newInterval;
}
}
});
});
setTimeout(function () {
gatherHealthCheck(timeout);
}, timeout);
})(machineContainer.Settings.Interval * 1000);
});
|
{
logger.error(err);
}
|
conditional_block
|
index.js
|
var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');
var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.length == 0) {
throw "Error: please, provide your userkey as first parameter!";
}
var userKey = argv[0];
function registerMachine(callback) {
var data = {
'UserKey': userKey,
'ComputerName': os.hostname(),
'OS': os.type() + ' ' + os.release()
};
sendPOST(data, '/machine', callback);
}
function sendHealthcheck(hc, callback) {
sendPOST(hc, '/', callback);
}
function sendPOST(postData, path, callback) {
var data = JSON.stringify(postData);
var options = getOpts(config.get('api.url'), 'POST', path, data);
var req = http.request(options, function (res) {
var resData = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
resData += chunk;
});
res.on('end', function () {
callback(res.statusCode != 200 ? res.statusCode : null, resData);
});
});
req.on('error', function (err) {
callback(err);
});
req.write(data);
req.end();
}
function getOpts(apiUrl, method, path, data) {
var options = url.parse(apiUrl + '/v'+config.get('api.v')+path);
options.method = method;
options.headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
return options;
}
attempt(
{
retries: 5,
interval: 3000
},
function() {
registerMachine(this);
},
function(err, res) {
if (err) {
logger.error(err);
throw err;
}
logger.debug(res);
|
healthcheck.getHealthcheck(machineContainer.Key, userKey, function (err, res) {
if (err) throw err;
logger.debug('Healthcheck: ' + JSON.stringify(res));
logger.debug('Sending data to API...');
sendHealthcheck(res, function (err, data) {
if (err) {
logger.error(err);
}
else {
var json = JSON.parse(data);
logger.debug('Got response: ' + data);
var newInterval = json.Interval * 1000;
if (newInterval != timeout) {
logger.debug('Changing data collection interval: ');
timeout = newInterval;
}
}
});
});
setTimeout(function () {
gatherHealthCheck(timeout);
}, timeout);
})(machineContainer.Settings.Interval * 1000);
});
|
var machineContainer = JSON.parse(res);
(function gatherHealthCheck(timeout) {
logger.debug('Getting healthcheck...')
|
random_line_split
|
mobile_v2_message.js
|
/**
* zepto插件:向左滑动删除动效
* 使用方法:$('.itemWipe').touchWipe({itemDelete: '.item-delete'});
* 参数:itemDelete 删除按钮的样式名
*/
(function($) {
$.fn.touchWipe = function(option) {
var isMove = 0;
var defaults = {
itemDelete: '.item-delete', //删除元素
};
var isMoveAdd = function(){
isMove += 1;
}
var isMoveZero = function(){
isMove = 0;
}
/* var abc = function(){
return isMove
}
console.log(abc());*/
var opts = $.extend({}, defaults, option); //配置选项
var delWidth = $(opts.itemDelete).width();
var initX; //触摸位置
var moveX; //滑动时的位置
var X = 0; //移动距离
var objX = 0; //目标对象位置
$(this).on('touchstart', function(event) {
//event.preventDefault();
var obj = this;
initX = event.targetTouches[0].pageX;
objX = (obj.style.WebkitTransform.replace(/translateX\(/g, "").replace(/px\)/g, "")) * 1;
if (objX == 0) {
$(this).on('touchmove', function(event) {
//event.preventDefault();
var obj = this;
moveX = event.targetTouches[0].pageX;
X = moveX - initX;
if (X >= 0) {
var abc = function(){
isMoveAdd();
}
abc();
obj.style.WebkitTransform = "translateX(" + 0 + "px)";
} else if (X < 0) {
var l = Math.abs(X);
obj.style.WebkitTransform = "translateX(" + -l + "px)";
if (l > delWidth) {
l = delWidth;
obj.style.WebkitTransform = "translateX(" + -l + "px)";
}
}
});
} else if (objX < 0) {
$(this).on('touchmove', function(event) {
var abc = function(){
isMoveAdd();
}
abc();
//event.preventDefault();
var obj = this;
moveX = event.targetTouches[0].pageX;
X = moveX - initX;
if (X >= 0) {
var r = -delWidth + Math.abs(X);
obj.style.WebkitTransform = "translateX(" + r + "px)";
if (r > 0) {
r = 0;
obj.style.WebkitTransform = "translateX(" + r + "px)";
}
} else { //向左滑动
obj.style.WebkitTransform = "translateX(" + -delWidth + "px)";
}
});
}
})
$(this).on('touchend', function(event) {
|
return isMove
}
/* var num = abc();
if(num>0){
var zero = function(){
isMoveZero();
}
zero();
}else{
} */
if (objX > -delWidth / 2) {
obj.style.transition = "all 0.2s";
obj.style.WebkitTransform = "translateX(" + 0 + "px)";
obj.style.transition = "all 0";
objX = 0;
} else {
obj.style.transition = "all 0.2s";
obj.style.WebkitTransform = "translateX(" + -delWidth + "px)";
obj.style.transition = "all 0";
objX = -delWidth;
}
})
//链式返回
return this;
};
})(Zepto);
$(function() {
function deleteMessage(id) {
var rawID = id.replace('del', ''),
$loading = document.getElementById("loading"),
host = "123.56.91.131:8090",
host1 = "localhost:4567";
$loading.style.display = "block";
$.ajax({
type: "DELETE",
url: "http://" + host + "/mobile/v2/message",
data: {id: rawID},
success: function(response, status, xhr) {
$('.'+id).remove();
$loading.style.display = "none";
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
$loading.style.display = "none";
alert(errorThrown);
}
});
}
// $('.list-li').touchWipe({itemDelete: '.btn'});
$('.detail').on('click', function(event) {
//event.preventDefault();
$('.content-detail').hide();
$('.detail').hide();
})
$('.list-li').on('click',function(event) {
var content = $(this).attr('_val');
$('.content-detail').html(content);
$('.content-detail').show();
$('.detail').show();
//alert()
})
$('.item-delete').on('click', function(event) {
event.preventDefault();
var r=confirm("确认删除?")
var id = $(this).attr('_val');
if(r){
deleteMessage(id);
}
return false;
})
});
|
//event.preventDefault();
var obj = this;
objX = (obj.style.WebkitTransform.replace(/translateX\(/g, "").replace(/px\)/g, "")) * 1;
var abc = function(){
|
random_line_split
|
mobile_v2_message.js
|
/**
* zepto插件:向左滑动删除动效
* 使用方法:$('.itemWipe').touchWipe({itemDelete: '.item-delete'});
* 参数:itemDelete 删除按钮的样式名
*/
(function($) {
$.fn.touchWipe = function(option) {
var isMove = 0;
var defaults = {
itemDelete: '.item-delete', //删除元素
};
var isMoveAdd = function(){
isMove += 1;
}
var isMoveZero = function(){
isMove = 0;
}
/* var abc = function(){
return isMove
}
console.log(abc());*/
var opts = $.extend({}, defaults, option); //配置选项
var delWidth = $(opts.itemDelete).width();
var initX; //触摸位置
var moveX; //滑动时的位置
var X = 0; //移动距离
var objX = 0; //目标对象位置
$(this).on('touchstart', function(event) {
//event.preventDefault();
var obj = this;
initX = event.targetTouches[0].pageX;
objX = (obj.style.WebkitTransform.replace(/translateX\(/g, "").replace(/px\)/g, "")) * 1;
if (objX == 0) {
$(this).on('touchmove', function(event) {
//event.preventDefault();
var obj = this;
moveX = event.targetTouches[0].pageX;
X = moveX - initX;
if (X >= 0) {
var abc = function(){
isMoveAdd();
}
abc();
obj.style.WebkitTransform = "translateX(" + 0 + "px)";
} else if (X < 0) {
var l = Math.abs(X);
obj.style.WebkitTransform = "translateX(" + -l + "px)";
if (l > delWidth) {
l = delWidth;
obj.style.WebkitTransform = "translateX(" + -l + "px)";
}
}
});
} else if (objX < 0) {
$(this).on('touchmove', function(event) {
var abc = function(){
isMoveAdd();
}
abc();
//event.preventDefault();
var obj = this;
moveX = event.targetTouches[0].pageX;
X = moveX - initX;
if (X >= 0) {
var r = -delWidth + Math.abs(X);
obj.style.WebkitTransform = "translateX(" + r + "px)";
if (r > 0) {
r = 0;
obj.style.WebkitTransform = "translateX(" + r + "px)";
}
} else { //向左滑动
obj.style.WebkitTransform = "translateX(" + -delWidth + "px)";
}
});
}
})
$(this).on('touchend', function(event) {
//event.preventDefault();
var obj = this;
objX = (obj.style.WebkitTransform.replace(/translateX\(/g, "").replace(/px\)/g, "")) * 1;
var abc = function(){
return isMove
}
/* var num = abc();
if(num>0){
var zero = function(){
isMoveZero();
}
zero();
}else{
} */
if (objX > -delWidth / 2) {
obj.style.transition = "all 0.2s";
obj.style.WebkitTransform = "translateX(" + 0 + "px)";
obj.style.transition = "all 0";
objX = 0;
} else {
obj.style.transition = "all 0.2s";
obj.style.WebkitTransform = "translateX(" + -delWidth + "px)";
obj.style.transition = "all 0";
objX = -delWidth;
}
})
//链式返回
return this;
};
})(Zepto);
$(function() {
function deleteMessage(id) {
var rawID = id.replace('del', ''),
$loading = document.getElementById("loading"),
host = "123.56.91.1
|
);
$('.content-detail').hide();
$('.detail').hide();
})
$('.list-li').on('click',function(event) {
var content = $(this).attr('_val');
$('.content-detail').html(content);
$('.content-detail').show();
$('.detail').show();
//alert()
})
$('.item-delete').on('click', function(event) {
event.preventDefault();
var r=confirm("确认删除?")
var id = $(this).attr('_val');
if(r){
deleteMessage(id);
}
return false;
})
});
|
31:8090",
host1 = "localhost:4567";
$loading.style.display = "block";
$.ajax({
type: "DELETE",
url: "http://" + host + "/mobile/v2/message",
data: {id: rawID},
success: function(response, status, xhr) {
$('.'+id).remove();
$loading.style.display = "none";
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
$loading.style.display = "none";
alert(errorThrown);
}
});
}
// $('.list-li').touchWipe({itemDelete: '.btn'});
$('.detail').on('click', function(event) {
//event.preventDefault(
|
identifier_body
|
mobile_v2_message.js
|
/**
* zepto插件:向左滑动删除动效
* 使用方法:$('.itemWipe').touchWipe({itemDelete: '.item-delete'});
* 参数:itemDelete 删除按钮的样式名
*/
(function($) {
$.fn.touchWipe = function(option) {
var isMove = 0;
var defaults = {
itemDelete: '.item-delete', //删除元素
};
var isMoveAdd = function(){
isMove += 1;
}
var isMoveZero = function(){
isMove = 0;
}
/* var abc = function(){
return isMove
}
console.log(abc());*/
var opts = $.extend({}, defaults, option); //配置选项
var delWidth = $(opts.itemDelete).width();
var initX; //触摸位置
var moveX; //滑动时的位置
var X = 0; //移动距离
var objX = 0; //目标对象位置
$(this).on('touchstart', function(event) {
//event.preventDefault();
var obj = this;
initX = event.targetTouches[0].pageX;
objX = (obj.style.WebkitTransform.replace(/translateX\(/g, "").replace(/px\)/g, "")) * 1;
if (objX == 0) {
$(this).on('touchmove', function(event) {
//event.preventDefault();
var obj = this;
moveX = event.targetTouches[0].pageX;
X = moveX - initX;
if (X >= 0) {
var abc = function(){
isMoveAdd();
}
abc();
obj.style.WebkitTransform = "translateX(" + 0 + "px)";
} else if (X < 0) {
var l = Math.abs(X);
obj.style.WebkitTransform = "translateX(" + -l + "px)";
if (l > delWidth) {
l = delWidth;
obj.style.WebkitTransform = "translateX(" + -l + "px)";
}
}
});
} else if (objX < 0) {
$(this).on('touchmove', function(event) {
var abc = function(){
isMoveAdd();
}
abc();
//event.preventDefault();
var obj = this;
moveX = event.targetTouches[0].pageX;
X = moveX - initX;
if (X >= 0) {
var r = -delWidth + Math.abs(X);
obj.style.WebkitTransform = "translateX(" + r + "px)";
if (r > 0) {
r = 0;
obj.style.WebkitTransform = "translateX(" + r + "px)";
}
} else { //向左滑动
obj.style.WebkitTransform = "translateX(" + -delWidth + "px)";
}
});
}
})
$(this).on('touchend', function(event) {
//event.preventDefault();
var obj = this;
objX = (obj.style.WebkitTransform.replace(/translateX\(/g, "").replace(/px\)/g, "")) * 1;
var abc = function(){
return isMove
}
/* var num = abc();
if(num>0){
var zero = function(){
isMoveZero();
}
zero();
}else{
} */
if (objX > -delWidth / 2) {
obj.style.transition = "all 0.2s";
obj.style.WebkitTransform = "translateX(" + 0 + "px)";
obj.style.transition = "all 0";
objX = 0;
} else {
obj.style.transition = "all 0.2s";
obj.style.WebkitTransform = "translateX(" + -delWidth + "px)";
obj.style.transition = "all 0";
objX = -delWidth;
}
})
//链式返回
return this;
};
})(Zepto);
$(function() {
function deleteMessage(id) {
var rawID = id.replace('del', ''),
$loading = document.getElementById("loading"),
h
|
.91.131:8090",
host1 = "localhost:4567";
$loading.style.display = "block";
$.ajax({
type: "DELETE",
url: "http://" + host + "/mobile/v2/message",
data: {id: rawID},
success: function(response, status, xhr) {
$('.'+id).remove();
$loading.style.display = "none";
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
$loading.style.display = "none";
alert(errorThrown);
}
});
}
// $('.list-li').touchWipe({itemDelete: '.btn'});
$('.detail').on('click', function(event) {
//event.preventDefault();
$('.content-detail').hide();
$('.detail').hide();
})
$('.list-li').on('click',function(event) {
var content = $(this).attr('_val');
$('.content-detail').html(content);
$('.content-detail').show();
$('.detail').show();
//alert()
})
$('.item-delete').on('click', function(event) {
event.preventDefault();
var r=confirm("确认删除?")
var id = $(this).attr('_val');
if(r){
deleteMessage(id);
}
return false;
})
});
|
ost = "123.56
|
identifier_name
|
modal.component.ts
|
import { animate, keyframes, state, style, transition, trigger } from '@angular/animations';
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { ModalService } from 'service/modal.service';
@Component({
selector: 'modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css'],
animations: [
trigger('flyInOut', [
transition('void => *', [
animate('100ms ease-out', keyframes([
style({ transform: 'scale(0.8, 0.8)', opacity: '0', offset: 0 }),
style({ transform: 'scale(1.0, 1.0)', opacity: '1.0', offset: 1.0 })
]))
]),
transition('* => void', [
animate(100, style({ transform: 'scale(0, 0)' }))
])
]),
|
state('in', style({ 'background-color': 'rgba(30, 30, 30, 0.4)' })),
transition('void => *', [
style({ 'background-color': 'rgba(30, 30, 30, 0.0)' }), animate(200)
]),
transition('* => void', [
animate(200, style({ 'background-color': 'rgba(30, 30, 30, 0.0)' }))
])
]),
]
})
export class ModalComponent {
@ViewChild('content', { read: ViewContainerRef, static: true }) content: ViewContainerRef;
constructor(
public modalService: ModalService) { }
clickBackground(event: MouseEvent) {
if (event.target === event.currentTarget) this.resolve();
}
resolve() {
this.modalService.resolve(null);
}
reject() {
this.modalService.reject();
}
}
|
trigger('bgInOut', [
|
random_line_split
|
modal.component.ts
|
import { animate, keyframes, state, style, transition, trigger } from '@angular/animations';
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { ModalService } from 'service/modal.service';
@Component({
selector: 'modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css'],
animations: [
trigger('flyInOut', [
transition('void => *', [
animate('100ms ease-out', keyframes([
style({ transform: 'scale(0.8, 0.8)', opacity: '0', offset: 0 }),
style({ transform: 'scale(1.0, 1.0)', opacity: '1.0', offset: 1.0 })
]))
]),
transition('* => void', [
animate(100, style({ transform: 'scale(0, 0)' }))
])
]),
trigger('bgInOut', [
state('in', style({ 'background-color': 'rgba(30, 30, 30, 0.4)' })),
transition('void => *', [
style({ 'background-color': 'rgba(30, 30, 30, 0.0)' }), animate(200)
]),
transition('* => void', [
animate(200, style({ 'background-color': 'rgba(30, 30, 30, 0.0)' }))
])
]),
]
})
export class
|
{
@ViewChild('content', { read: ViewContainerRef, static: true }) content: ViewContainerRef;
constructor(
public modalService: ModalService) { }
clickBackground(event: MouseEvent) {
if (event.target === event.currentTarget) this.resolve();
}
resolve() {
this.modalService.resolve(null);
}
reject() {
this.modalService.reject();
}
}
|
ModalComponent
|
identifier_name
|
modal.component.ts
|
import { animate, keyframes, state, style, transition, trigger } from '@angular/animations';
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { ModalService } from 'service/modal.service';
@Component({
selector: 'modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css'],
animations: [
trigger('flyInOut', [
transition('void => *', [
animate('100ms ease-out', keyframes([
style({ transform: 'scale(0.8, 0.8)', opacity: '0', offset: 0 }),
style({ transform: 'scale(1.0, 1.0)', opacity: '1.0', offset: 1.0 })
]))
]),
transition('* => void', [
animate(100, style({ transform: 'scale(0, 0)' }))
])
]),
trigger('bgInOut', [
state('in', style({ 'background-color': 'rgba(30, 30, 30, 0.4)' })),
transition('void => *', [
style({ 'background-color': 'rgba(30, 30, 30, 0.0)' }), animate(200)
]),
transition('* => void', [
animate(200, style({ 'background-color': 'rgba(30, 30, 30, 0.0)' }))
])
]),
]
})
export class ModalComponent {
@ViewChild('content', { read: ViewContainerRef, static: true }) content: ViewContainerRef;
constructor(
public modalService: ModalService)
|
clickBackground(event: MouseEvent) {
if (event.target === event.currentTarget) this.resolve();
}
resolve() {
this.modalService.resolve(null);
}
reject() {
this.modalService.reject();
}
}
|
{ }
|
identifier_body
|
DsReplicaObjMetaData2Ctr.py
|
# encoding: utf-8
# module samba.dcerpc.drsuapi
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so
# by generator 1.135
""" drsuapi DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class DsReplicaObjMetaData2Ctr(__talloc.Object):
# no doc
def
|
(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
array = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
enumeration_context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
|
__init__
|
identifier_name
|
DsReplicaObjMetaData2Ctr.py
|
# encoding: utf-8
# module samba.dcerpc.drsuapi
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so
# by generator 1.135
""" drsuapi DCE/RPC """
# imports
import dcerpc as __dcerpc
|
class DsReplicaObjMetaData2Ctr(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
array = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
enumeration_context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
|
import talloc as __talloc
|
random_line_split
|
DsReplicaObjMetaData2Ctr.py
|
# encoding: utf-8
# module samba.dcerpc.drsuapi
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so
# by generator 1.135
""" drsuapi DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class DsReplicaObjMetaData2Ctr(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
|
array = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
enumeration_context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
|
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
|
identifier_body
|
main.rs
|
use std::env::args;
use std::collections::HashMap;
trait Validator {
fn increment(&mut self) -> bool;
fn has_sequence(&self) -> bool;
fn no_forbidden_chars(&self) -> bool;
fn has_two_doubles(&self) -> bool;
}
impl Validator for Vec<u8> {
fn increment(&mut self) -> bool {
*(self.last_mut().unwrap()) += 1;
let mut carry: u8 = 0;
for pos in (0..self.len()).rev() {
if carry > 0 {
self[pos] += 1;
carry = 0;
}
if self[pos] >= 26 {
carry = self[pos] / 26;
self[pos] = 0;
}
}
carry != 0
}
fn has_sequence(&self) -> bool {
for win in self.windows(3) {
if win[0] + 2 == win[1] + 1 && win[1] + 1 == win[2] {
return true;
}
}
false
}
fn no_forbidden_chars(&self) -> bool
|
fn has_two_doubles(&self) -> bool {
let mut double_count = 0;
let mut pos = 0;
while pos < (self.len() - 1) {
if self[pos] == self[pos + 1] {
double_count += 1;
pos += 1;
if double_count >= 2 {
return true;
}
}
pos += 1;
}
false
}
}
fn main() {
let mut a = args();
a.next(); // The first argument is the binary name/path
let start = a.next().unwrap(); // The puzzle input
let mut char_to_num = HashMap::new();
let mut num_to_char = HashMap::new();
for i in 0..26 {
let ch = (('a' as u8) + i) as char;
char_to_num.insert(ch, i);
num_to_char.insert(i, ch);
}
let mut passwd_vec = start.chars().map(|ch| char_to_num[&ch]).collect::<Vec<u8>>();
loop {
if passwd_vec.increment() {
panic!("All password combinations exhausted and no password found.");
}
if !passwd_vec.has_sequence() {
continue;
}
if !passwd_vec.no_forbidden_chars() {
continue;
}
if !passwd_vec.has_two_doubles() {
continue;
}
break;
}
let readable_passwd = passwd_vec.iter().map(|ch_num| num_to_char[ch_num]).collect::<String>();
println!("The next password is: {:?}", passwd_vec);
println!("Readable password: {:?}", readable_passwd);
}
|
{
let i = ('i' as u8) - ('a' as u8);
let o = ('o' as u8) - ('a' as u8);
let l = ('l' as u8) - ('a' as u8);
!(self.contains(&i) || self.contains(&o) || self.contains(&l))
}
|
identifier_body
|
main.rs
|
use std::env::args;
use std::collections::HashMap;
trait Validator {
fn increment(&mut self) -> bool;
fn has_sequence(&self) -> bool;
fn no_forbidden_chars(&self) -> bool;
fn has_two_doubles(&self) -> bool;
}
impl Validator for Vec<u8> {
fn increment(&mut self) -> bool {
*(self.last_mut().unwrap()) += 1;
let mut carry: u8 = 0;
for pos in (0..self.len()).rev() {
if carry > 0 {
self[pos] += 1;
carry = 0;
}
if self[pos] >= 26 {
carry = self[pos] / 26;
self[pos] = 0;
}
}
carry != 0
}
fn has_sequence(&self) -> bool {
for win in self.windows(3) {
if win[0] + 2 == win[1] + 1 && win[1] + 1 == win[2] {
return true;
}
}
false
}
fn no_forbidden_chars(&self) -> bool {
let i = ('i' as u8) - ('a' as u8);
let o = ('o' as u8) - ('a' as u8);
let l = ('l' as u8) - ('a' as u8);
!(self.contains(&i) || self.contains(&o) || self.contains(&l))
}
fn
|
(&self) -> bool {
let mut double_count = 0;
let mut pos = 0;
while pos < (self.len() - 1) {
if self[pos] == self[pos + 1] {
double_count += 1;
pos += 1;
if double_count >= 2 {
return true;
}
}
pos += 1;
}
false
}
}
fn main() {
let mut a = args();
a.next(); // The first argument is the binary name/path
let start = a.next().unwrap(); // The puzzle input
let mut char_to_num = HashMap::new();
let mut num_to_char = HashMap::new();
for i in 0..26 {
let ch = (('a' as u8) + i) as char;
char_to_num.insert(ch, i);
num_to_char.insert(i, ch);
}
let mut passwd_vec = start.chars().map(|ch| char_to_num[&ch]).collect::<Vec<u8>>();
loop {
if passwd_vec.increment() {
panic!("All password combinations exhausted and no password found.");
}
if !passwd_vec.has_sequence() {
continue;
}
if !passwd_vec.no_forbidden_chars() {
continue;
}
if !passwd_vec.has_two_doubles() {
continue;
}
break;
}
let readable_passwd = passwd_vec.iter().map(|ch_num| num_to_char[ch_num]).collect::<String>();
println!("The next password is: {:?}", passwd_vec);
println!("Readable password: {:?}", readable_passwd);
}
|
has_two_doubles
|
identifier_name
|
main.rs
|
use std::env::args;
use std::collections::HashMap;
trait Validator {
fn increment(&mut self) -> bool;
fn has_sequence(&self) -> bool;
fn no_forbidden_chars(&self) -> bool;
fn has_two_doubles(&self) -> bool;
}
impl Validator for Vec<u8> {
fn increment(&mut self) -> bool {
*(self.last_mut().unwrap()) += 1;
let mut carry: u8 = 0;
for pos in (0..self.len()).rev() {
if carry > 0 {
self[pos] += 1;
carry = 0;
}
if self[pos] >= 26 {
carry = self[pos] / 26;
self[pos] = 0;
}
}
carry != 0
}
fn has_sequence(&self) -> bool {
for win in self.windows(3) {
if win[0] + 2 == win[1] + 1 && win[1] + 1 == win[2] {
return true;
}
}
false
}
fn no_forbidden_chars(&self) -> bool {
let i = ('i' as u8) - ('a' as u8);
let o = ('o' as u8) - ('a' as u8);
let l = ('l' as u8) - ('a' as u8);
!(self.contains(&i) || self.contains(&o) || self.contains(&l))
}
fn has_two_doubles(&self) -> bool {
let mut double_count = 0;
let mut pos = 0;
while pos < (self.len() - 1) {
if self[pos] == self[pos + 1]
|
pos += 1;
}
false
}
}
fn main() {
let mut a = args();
a.next(); // The first argument is the binary name/path
let start = a.next().unwrap(); // The puzzle input
let mut char_to_num = HashMap::new();
let mut num_to_char = HashMap::new();
for i in 0..26 {
let ch = (('a' as u8) + i) as char;
char_to_num.insert(ch, i);
num_to_char.insert(i, ch);
}
let mut passwd_vec = start.chars().map(|ch| char_to_num[&ch]).collect::<Vec<u8>>();
loop {
if passwd_vec.increment() {
panic!("All password combinations exhausted and no password found.");
}
if !passwd_vec.has_sequence() {
continue;
}
if !passwd_vec.no_forbidden_chars() {
continue;
}
if !passwd_vec.has_two_doubles() {
continue;
}
break;
}
let readable_passwd = passwd_vec.iter().map(|ch_num| num_to_char[ch_num]).collect::<String>();
println!("The next password is: {:?}", passwd_vec);
println!("Readable password: {:?}", readable_passwd);
}
|
{
double_count += 1;
pos += 1;
if double_count >= 2 {
return true;
}
}
|
conditional_block
|
main.rs
|
use std::env::args;
use std::collections::HashMap;
trait Validator {
fn increment(&mut self) -> bool;
fn has_sequence(&self) -> bool;
fn no_forbidden_chars(&self) -> bool;
fn has_two_doubles(&self) -> bool;
}
impl Validator for Vec<u8> {
fn increment(&mut self) -> bool {
*(self.last_mut().unwrap()) += 1;
let mut carry: u8 = 0;
for pos in (0..self.len()).rev() {
if carry > 0 {
self[pos] += 1;
carry = 0;
}
if self[pos] >= 26 {
carry = self[pos] / 26;
self[pos] = 0;
}
}
carry != 0
}
fn has_sequence(&self) -> bool {
for win in self.windows(3) {
if win[0] + 2 == win[1] + 1 && win[1] + 1 == win[2] {
return true;
}
}
false
}
fn no_forbidden_chars(&self) -> bool {
let i = ('i' as u8) - ('a' as u8);
let o = ('o' as u8) - ('a' as u8);
let l = ('l' as u8) - ('a' as u8);
!(self.contains(&i) || self.contains(&o) || self.contains(&l))
}
fn has_two_doubles(&self) -> bool {
let mut double_count = 0;
let mut pos = 0;
while pos < (self.len() - 1) {
if self[pos] == self[pos + 1] {
double_count += 1;
pos += 1;
if double_count >= 2 {
return true;
}
}
pos += 1;
}
false
}
}
fn main() {
let mut a = args();
a.next(); // The first argument is the binary name/path
let start = a.next().unwrap(); // The puzzle input
let mut char_to_num = HashMap::new();
let mut num_to_char = HashMap::new();
for i in 0..26 {
let ch = (('a' as u8) + i) as char;
char_to_num.insert(ch, i);
num_to_char.insert(i, ch);
}
let mut passwd_vec = start.chars().map(|ch| char_to_num[&ch]).collect::<Vec<u8>>();
loop {
if passwd_vec.increment() {
panic!("All password combinations exhausted and no password found.");
}
if !passwd_vec.has_sequence() {
continue;
|
}
if !passwd_vec.no_forbidden_chars() {
continue;
}
if !passwd_vec.has_two_doubles() {
continue;
}
break;
}
let readable_passwd = passwd_vec.iter().map(|ch_num| num_to_char[ch_num]).collect::<String>();
println!("The next password is: {:?}", passwd_vec);
println!("Readable password: {:?}", readable_passwd);
}
|
random_line_split
|
|
main.rs
|
use std::thread;
use std::time::Duration;
use std::collections::HashMap;
fn main() {
let simulated_user_specified_value = 10;
let simulated_random_number = 7;
generate_workout(simulated_user_specified_value, simulated_random_number);
}
struct Cacher<T, K, V>
where T: Fn(K) -> V,
K: Eq + std::hash::Hash + Clone,
V: Clone
{
calculation: T,
value: HashMap<K, V>,
}
impl<T, K, V> Cacher<T, K, V>
where T: Fn(K) -> V,
K: Eq + std::hash::Hash + Clone,
V: Clone
{
fn new(calculation: T) -> Cacher<T, K, V> {
Cacher {
calculation,
value: HashMap::new(),
}
}
fn
|
(&mut self, arg: K) -> V {
let closure = &self.calculation;
let v = self.value
.entry(arg.clone())
.or_insert_with(|| (closure)(arg));
(*v).clone()
}
}
fn generate_workout(intensity: i32, random_number: i32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!("Today, do {} pushups!", expensive_result.value(intensity));
println!("Next, do {} situps!", expensive_result.value(intensity));
} else if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!("Today, run for {} minutes!",
expensive_result.value(intensity));
}
}
#[test]
#[allow(unused_variables)]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
let v2 = c.value(2);
assert_eq!(v2, 2);
}
|
value
|
identifier_name
|
main.rs
|
use std::thread;
use std::time::Duration;
use std::collections::HashMap;
fn main() {
let simulated_user_specified_value = 10;
let simulated_random_number = 7;
generate_workout(simulated_user_specified_value, simulated_random_number);
}
struct Cacher<T, K, V>
where T: Fn(K) -> V,
K: Eq + std::hash::Hash + Clone,
V: Clone
{
calculation: T,
value: HashMap<K, V>,
}
impl<T, K, V> Cacher<T, K, V>
where T: Fn(K) -> V,
K: Eq + std::hash::Hash + Clone,
V: Clone
{
fn new(calculation: T) -> Cacher<T, K, V> {
Cacher {
calculation,
value: HashMap::new(),
}
}
fn value(&mut self, arg: K) -> V
|
}
fn generate_workout(intensity: i32, random_number: i32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!("Today, do {} pushups!", expensive_result.value(intensity));
println!("Next, do {} situps!", expensive_result.value(intensity));
} else if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!("Today, run for {} minutes!",
expensive_result.value(intensity));
}
}
#[test]
#[allow(unused_variables)]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
let v2 = c.value(2);
assert_eq!(v2, 2);
}
|
{
let closure = &self.calculation;
let v = self.value
.entry(arg.clone())
.or_insert_with(|| (closure)(arg));
(*v).clone()
}
|
identifier_body
|
main.rs
|
use std::thread;
use std::time::Duration;
use std::collections::HashMap;
fn main() {
let simulated_user_specified_value = 10;
let simulated_random_number = 7;
generate_workout(simulated_user_specified_value, simulated_random_number);
}
struct Cacher<T, K, V>
where T: Fn(K) -> V,
K: Eq + std::hash::Hash + Clone,
V: Clone
{
calculation: T,
value: HashMap<K, V>,
}
impl<T, K, V> Cacher<T, K, V>
where T: Fn(K) -> V,
K: Eq + std::hash::Hash + Clone,
V: Clone
{
fn new(calculation: T) -> Cacher<T, K, V> {
Cacher {
calculation,
value: HashMap::new(),
}
}
fn value(&mut self, arg: K) -> V {
let closure = &self.calculation;
let v = self.value
.entry(arg.clone())
.or_insert_with(|| (closure)(arg));
(*v).clone()
|
fn generate_workout(intensity: i32, random_number: i32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!("Today, do {} pushups!", expensive_result.value(intensity));
println!("Next, do {} situps!", expensive_result.value(intensity));
} else if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!("Today, run for {} minutes!",
expensive_result.value(intensity));
}
}
#[test]
#[allow(unused_variables)]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
let v2 = c.value(2);
assert_eq!(v2, 2);
}
|
}
}
|
random_line_split
|
controls.ts
|
// Copyright 2016 David Li, Michael Mauer, Andy Jiang
// This file is part of Tell Me to Survive.
// Tell Me to Survive is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tell Me to Survive is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with Tell Me to Survive. If not, see <http://www.gnu.org/licenses/>.
import PubSub = require("pubsub");
import {EditorContext, MAIN} from "model/editorcontext";
interface ControlsController extends _mithril.MithrilController {
}
export const Component: _mithril.MithrilComponent<ControlsController> = <any> {
controller: function(): ControlsController {
return {};
},
view: function(controller: ControlsController, args: {
executing: _mithril.MithrilProperty<boolean>,
doneExecuting: _mithril.MithrilProperty<boolean>,
paused: _mithril.MithrilProperty<boolean>,
speed: _mithril.MithrilProperty<number>,
valid: boolean,
memoryUsage: EditorContext,
onrun?: () => void,
onruninvalid?: () => void,
onrunmemory?: () => void,
onreset?: () => void,
onabort?: () => void,
onpause?: () => void,
onstep?: () => void,
}): _mithril.MithrilVirtualElement<ControlsController> {
let buttons: _mithril.MithrilVirtualElement<ControlsController>[] = [];
if (args.doneExecuting()) {
buttons.push(m(<any> "button.reset", {
onclick: function() {
if (args.onreset) {
args.onreset();
}
},
}, "Reset"));
}
else if (!args.executing()) {
let cssClass = args.valid ? ".run" : ".runInvalid";
let text = args.valid ? "Run" : "Invalid Code";
if (args.memoryUsage !== null) {
cssClass = ".runMemory";
let overLimit = args.memoryUsage.className + "." + args.memoryUsage.method;
if (args.memoryUsage.className === MAIN)
|
text = "Over Memory Limit: " + overLimit;
}
buttons.push(m(<any> ("button" + cssClass), {
onclick: function() {
if (!args.valid) {
if (args.onruninvalid) {
args.onruninvalid();
}
}
else if (args.memoryUsage !== null) {
if (args.onrunmemory) {
args.onrunmemory();
}
}
else if (args.onrun) {
args.onrun();
}
},
}, text));
}
else {
buttons.push(m(<any> "button.abort", {
onclick: function() {
if (args.onabort) {
args.onabort();
}
},
}, "Abort"));
buttons.push(m(".speed-control", [
"Slow",
m("input[type=range][min=0.5][max=2.0][step=0.1]", {
value: args.speed(),
onchange: function(event: any) {
let value = parseFloat(event.target.value);
args.speed(value);
},
}),
"Fast"
]));
}
return m("nav#gameControls", buttons);
}
}
|
{
overLimit = "main";
}
|
conditional_block
|
controls.ts
|
// Copyright 2016 David Li, Michael Mauer, Andy Jiang
// This file is part of Tell Me to Survive.
// Tell Me to Survive is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tell Me to Survive is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with Tell Me to Survive. If not, see <http://www.gnu.org/licenses/>.
import PubSub = require("pubsub");
import {EditorContext, MAIN} from "model/editorcontext";
interface ControlsController extends _mithril.MithrilController {
}
export const Component: _mithril.MithrilComponent<ControlsController> = <any> {
controller: function(): ControlsController {
return {};
},
view: function(controller: ControlsController, args: {
executing: _mithril.MithrilProperty<boolean>,
doneExecuting: _mithril.MithrilProperty<boolean>,
paused: _mithril.MithrilProperty<boolean>,
speed: _mithril.MithrilProperty<number>,
valid: boolean,
memoryUsage: EditorContext,
onrun?: () => void,
onruninvalid?: () => void,
onrunmemory?: () => void,
onreset?: () => void,
onabort?: () => void,
onpause?: () => void,
onstep?: () => void,
}): _mithril.MithrilVirtualElement<ControlsController> {
let buttons: _mithril.MithrilVirtualElement<ControlsController>[] = [];
if (args.doneExecuting()) {
buttons.push(m(<any> "button.reset", {
onclick: function() {
|
args.onreset();
}
},
}, "Reset"));
}
else if (!args.executing()) {
let cssClass = args.valid ? ".run" : ".runInvalid";
let text = args.valid ? "Run" : "Invalid Code";
if (args.memoryUsage !== null) {
cssClass = ".runMemory";
let overLimit = args.memoryUsage.className + "." + args.memoryUsage.method;
if (args.memoryUsage.className === MAIN) {
overLimit = "main";
}
text = "Over Memory Limit: " + overLimit;
}
buttons.push(m(<any> ("button" + cssClass), {
onclick: function() {
if (!args.valid) {
if (args.onruninvalid) {
args.onruninvalid();
}
}
else if (args.memoryUsage !== null) {
if (args.onrunmemory) {
args.onrunmemory();
}
}
else if (args.onrun) {
args.onrun();
}
},
}, text));
}
else {
buttons.push(m(<any> "button.abort", {
onclick: function() {
if (args.onabort) {
args.onabort();
}
},
}, "Abort"));
buttons.push(m(".speed-control", [
"Slow",
m("input[type=range][min=0.5][max=2.0][step=0.1]", {
value: args.speed(),
onchange: function(event: any) {
let value = parseFloat(event.target.value);
args.speed(value);
},
}),
"Fast"
]));
}
return m("nav#gameControls", buttons);
}
}
|
if (args.onreset) {
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.