file_name
large_stringlengths 4
140
| prefix
large_stringlengths 0
12.1k
| suffix
large_stringlengths 0
12k
| middle
large_stringlengths 0
7.51k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
decode.rs | use std::{iter, fs, path};
use image::ImageFormat;
use criterion::{Criterion, criterion_group, criterion_main};
#[derive(Clone, Copy)]
struct BenchDef {
dir: &'static [&'static str],
files: &'static [&'static str],
format: ImageFormat,
}
fn load_all(c: &mut Criterion) {
const BENCH_DEFS: &'static [BenchDef] = &[
BenchDef {
dir: &["bmp", "images"],
files: &[
"Core_1_Bit.bmp",
"Core_4_Bit.bmp",
"Core_8_Bit.bmp",
"rgb16.bmp",
"rgb24.bmp",
"rgb32.bmp",
"pal4rle.bmp",
"pal8rle.bmp",
"rgb16-565.bmp",
"rgb32bf.bmp",
],
format: ImageFormat::Bmp,
},
BenchDef {
dir: &["gif", "simple"],
files: &[
"alpha_gif_a.gif",
"sample_1.gif",
],
format: ImageFormat::Gif,
},
BenchDef {
dir: &["hdr", "images"],
files: &[
"image1.hdr",
"rgbr4x4.hdr",
],
format: ImageFormat::Hdr,
},
BenchDef {
dir: &["ico", "images"],
files: &[
"bmp-24bpp-mask.ico",
"bmp-32bpp-alpha.ico",
"png-32bpp-alpha.ico",
"smile.ico",
], | format: ImageFormat::Ico,
},
BenchDef {
dir: &["jpg", "progressive"],
files: &[
"3.jpg",
"cat.jpg",
"test.jpg",
],
format: ImageFormat::Jpeg,
},
// TODO: pnm
// TODO: png
BenchDef {
dir: &["tga", "testsuite"],
files: &[
"cbw8.tga",
"ctc24.tga",
"ubw8.tga",
"utc24.tga",
],
format: ImageFormat::Tga,
},
BenchDef {
dir: &["tiff", "testsuite"],
files: &[
"hpredict.tiff",
"hpredict_packbits.tiff",
"mandrill.tiff",
"rgb-3c-16b.tiff",
],
format: ImageFormat::Tiff,
},
BenchDef {
dir: &["webp", "images"],
files: &[
"simple-gray.webp",
"simple-rgb.webp",
"vp8x-gray.webp",
"vp8x-rgb.webp",
],
format: ImageFormat::WebP,
},
];
for bench in BENCH_DEFS {
bench_load(c, bench);
}
}
criterion_group!(benches, load_all);
criterion_main!(benches);
fn bench_load(c: &mut Criterion, def: &BenchDef) {
let group_name = format!("load-{:?}", def.format);
let mut group = c.benchmark_group(&group_name);
let paths = IMAGE_DIR.iter().chain(def.dir);
for file_name in def.files {
let path: path::PathBuf = paths.clone().chain(iter::once(file_name)).collect();
let buf = fs::read(path).unwrap();
group.bench_function(file_name.to_owned(), |b| b.iter(|| {
image::load_from_memory_with_format(&buf, def.format).unwrap();
}));
}
}
const IMAGE_DIR: [&'static str; 3] = [".", "tests", "images"]; | random_line_split |
|
FixtureSearchHeader.tsx | import React from 'react';
import styled from 'styled-components';
import { IconButton32 } from '../../shared/buttons';
import { blue, grey160, grey32, white10 } from '../../shared/colors';
import { ChevronLeftIcon, SearchIcon } from '../../shared/icons';
import { KeyBox } from '../../shared/KeyBox';
type Props = {
validFixtureSelected: boolean;
onOpen: () => unknown;
onCloseNav: () => unknown;
};
export function FixtureSearchHeader({
validFixtureSelected,
onOpen,
onCloseNav,
}: Props) | </Container>
);
}
const Container = styled.div`
display: flex;
flex-direction: row;
align-items: center;
height: 40px;
margin: 0 1px 0 0;
background: ${grey32};
`;
const SearchButton = styled.button`
flex: 1;
height: 32px;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
border: none;
background: transparent;
color: ${grey160};
padding: 0 0 0 16px;
overflow: hidden;
cursor: text;
:focus {
outline: none;
box-shadow: inset 2px 0px 0 0 ${blue};
}
::-moz-focus-inner {
border: 0;
}
`;
const SearchIconContainer = styled.span`
flex-shrink: 0;
width: 16px;
height: 16px;
margin: 1px 8px 0 6px;
opacity: 0.64;
`;
const SearchLabel = styled.span`
padding: 0 3px 0 0;
line-height: 24px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: left;
`;
const NavButtonContainer = styled.div`
padding: 0 4px;
`;
| {
return (
<Container>
<SearchButton onClick={onOpen}>
<SearchIconContainer>
<SearchIcon />
</SearchIconContainer>
<SearchLabel>Search fixtures</SearchLabel>
<KeyBox value={'⌘'} bgColor={white10} textColor={grey160} size={20} />
<KeyBox value={'P'} bgColor={white10} textColor={grey160} size={20} />
</SearchButton>
<NavButtonContainer>
<IconButton32
icon={<ChevronLeftIcon />}
title="Hide fixture list"
disabled={!validFixtureSelected}
selected={false}
onClick={onCloseNav}
/>
</NavButtonContainer> | identifier_body |
FixtureSearchHeader.tsx | import React from 'react';
import styled from 'styled-components';
import { IconButton32 } from '../../shared/buttons';
import { blue, grey160, grey32, white10 } from '../../shared/colors';
import { ChevronLeftIcon, SearchIcon } from '../../shared/icons';
import { KeyBox } from '../../shared/KeyBox';
type Props = {
validFixtureSelected: boolean;
onOpen: () => unknown;
onCloseNav: () => unknown;
};
export function | ({
validFixtureSelected,
onOpen,
onCloseNav,
}: Props) {
return (
<Container>
<SearchButton onClick={onOpen}>
<SearchIconContainer>
<SearchIcon />
</SearchIconContainer>
<SearchLabel>Search fixtures</SearchLabel>
<KeyBox value={'⌘'} bgColor={white10} textColor={grey160} size={20} />
<KeyBox value={'P'} bgColor={white10} textColor={grey160} size={20} />
</SearchButton>
<NavButtonContainer>
<IconButton32
icon={<ChevronLeftIcon />}
title="Hide fixture list"
disabled={!validFixtureSelected}
selected={false}
onClick={onCloseNav}
/>
</NavButtonContainer>
</Container>
);
}
const Container = styled.div`
display: flex;
flex-direction: row;
align-items: center;
height: 40px;
margin: 0 1px 0 0;
background: ${grey32};
`;
const SearchButton = styled.button`
flex: 1;
height: 32px;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
border: none;
background: transparent;
color: ${grey160};
padding: 0 0 0 16px;
overflow: hidden;
cursor: text;
:focus {
outline: none;
box-shadow: inset 2px 0px 0 0 ${blue};
}
::-moz-focus-inner {
border: 0;
}
`;
const SearchIconContainer = styled.span`
flex-shrink: 0;
width: 16px;
height: 16px;
margin: 1px 8px 0 6px;
opacity: 0.64;
`;
const SearchLabel = styled.span`
padding: 0 3px 0 0;
line-height: 24px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: left;
`;
const NavButtonContainer = styled.div`
padding: 0 4px;
`;
| FixtureSearchHeader | identifier_name |
FixtureSearchHeader.tsx | import React from 'react';
import styled from 'styled-components';
import { IconButton32 } from '../../shared/buttons';
import { blue, grey160, grey32, white10 } from '../../shared/colors';
import { ChevronLeftIcon, SearchIcon } from '../../shared/icons';
import { KeyBox } from '../../shared/KeyBox';
type Props = {
validFixtureSelected: boolean;
onOpen: () => unknown;
onCloseNav: () => unknown;
};
export function FixtureSearchHeader({
validFixtureSelected,
onOpen,
onCloseNav,
}: Props) {
return (
<Container>
<SearchButton onClick={onOpen}>
<SearchIconContainer>
<SearchIcon />
</SearchIconContainer>
<SearchLabel>Search fixtures</SearchLabel>
<KeyBox value={'⌘'} bgColor={white10} textColor={grey160} size={20} />
<KeyBox value={'P'} bgColor={white10} textColor={grey160} size={20} />
</SearchButton>
<NavButtonContainer>
<IconButton32
icon={<ChevronLeftIcon />}
title="Hide fixture list"
disabled={!validFixtureSelected}
selected={false}
onClick={onCloseNav}
/>
</NavButtonContainer>
</Container>
);
}
const Container = styled.div`
display: flex;
flex-direction: row;
align-items: center;
height: 40px;
margin: 0 1px 0 0;
background: ${grey32};
`;
const SearchButton = styled.button`
flex: 1;
height: 32px;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
border: none;
background: transparent;
color: ${grey160};
padding: 0 0 0 16px;
overflow: hidden;
cursor: text;
:focus {
outline: none;
box-shadow: inset 2px 0px 0 0 ${blue};
}
::-moz-focus-inner {
border: 0;
}
`;
const SearchIconContainer = styled.span`
flex-shrink: 0;
width: 16px;
height: 16px;
margin: 1px 8px 0 6px;
opacity: 0.64;
`;
const SearchLabel = styled.span`
padding: 0 3px 0 0;
line-height: 24px;
white-space: nowrap;
overflow: hidden; | padding: 0 4px;
`; | text-overflow: ellipsis;
text-align: left;
`;
const NavButtonContainer = styled.div` | random_line_split |
index.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license | * @description
* This module provides a set of common Pipes.
*/
import { AsyncPipe } from './async_pipe';
import { LowerCasePipe, TitleCasePipe, UpperCasePipe } from './case_conversion_pipes';
import { DatePipe } from './date_pipe';
import { I18nPluralPipe } from './i18n_plural_pipe';
import { I18nSelectPipe } from './i18n_select_pipe';
import { JsonPipe } from './json_pipe';
import { CurrencyPipe, DecimalPipe, PercentPipe } from './number_pipe';
import { SlicePipe } from './slice_pipe';
export { AsyncPipe, CurrencyPipe, DatePipe, DecimalPipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, LowerCasePipe, PercentPipe, SlicePipe, TitleCasePipe, UpperCasePipe };
/**
* A collection of Angular pipes that are likely to be used in each and every application.
*/
export declare const COMMON_PIPES: (typeof AsyncPipe | typeof DecimalPipe | typeof PercentPipe | typeof CurrencyPipe | typeof DatePipe | typeof I18nPluralPipe | typeof I18nSelectPipe | typeof SlicePipe)[]; | */
/**
* @module | random_line_split |
walker.js | 'use strict';
const fs = require('fs'),
Emitter = require('events').EventEmitter,
emitter = new Emitter(),
eventState = require('event-state'),
dirTree = (path, cb) => {
const buildBranch = (path, branch) => {
fs.readdir(path, (err, files) => {
if (err) {
//Errors result in a false value in the tree.
branch[path] = false;
cb(err);
} else {
const newEvents = files.map(file => {
return path + '/' + file;
});
if (!state) {
// If this is the first iteration,
// initialize the dynamic state machine (DSM).
state = emitter.required(newEvents, () => {
// Allow for multiple paradigms vis-a-vis callback and promises.
// resolve the promise with the completed tree..
cb(null, tree); | state.add(newEvents);
}
// Check each file descriptor to see if it's a directory.
files.forEach(file => {
const filePath = path + '/' + file;
fs.stat(filePath, (err, stats) => {
if (err) {
// Errors result in a false value in the tree
branch[file] = false;
emitter.emit(filePath, true);
} else if (stats.isDirectory() && file[0] !== '.' && file !== 'node_modules') {
// Directories are object properties on the tree.
branch[file] = {};
//console.log('cur dir name', file);
// Recurse into the directory.
buildBranch(filePath, branch[file]);
} else {
const fp = filePath.replace(process.cwd(), '');
//console.log(dir, file);
// If it's not a directory, it's a file.
// Files get a true value in the tree.
branch[file] = fp;
emitter.emit(filePath, true);
}
});
});
}
//Once we've read the directory, we can raise the event for the parent
// directory and let it's children take care of themselves.
emitter.emit(path, true);
});
};
let tree = {},
state;
return buildBranch(path, tree);
};
emitter.required = eventState;
module.exports = dirTree; | });
} else {
// Add events to the DSM for the directory's children | random_line_split |
walker.js | 'use strict';
const fs = require('fs'),
Emitter = require('events').EventEmitter,
emitter = new Emitter(),
eventState = require('event-state'),
dirTree = (path, cb) => {
const buildBranch = (path, branch) => {
fs.readdir(path, (err, files) => {
if (err) {
//Errors result in a false value in the tree.
branch[path] = false;
cb(err);
} else | files.forEach(file => {
const filePath = path + '/' + file;
fs.stat(filePath, (err, stats) => {
if (err) {
// Errors result in a false value in the tree
branch[file] = false;
emitter.emit(filePath, true);
} else if (stats.isDirectory() && file[0] !== '.' && file !== 'node_modules') {
// Directories are object properties on the tree.
branch[file] = {};
//console.log('cur dir name', file);
// Recurse into the directory.
buildBranch(filePath, branch[file]);
} else {
const fp = filePath.replace(process.cwd(), '');
//console.log(dir, file);
// If it's not a directory, it's a file.
// Files get a true value in the tree.
branch[file] = fp;
emitter.emit(filePath, true);
}
});
});
}
//Once we've read the directory, we can raise the event for the parent
// directory and let it's children take care of themselves.
emitter.emit(path, true);
});
};
let tree = {},
state;
return buildBranch(path, tree);
};
emitter.required = eventState;
module.exports = dirTree;
| {
const newEvents = files.map(file => {
return path + '/' + file;
});
if (!state) {
// If this is the first iteration,
// initialize the dynamic state machine (DSM).
state = emitter.required(newEvents, () => {
// Allow for multiple paradigms vis-a-vis callback and promises.
// resolve the promise with the completed tree..
cb(null, tree);
});
} else {
// Add events to the DSM for the directory's children
state.add(newEvents);
}
// Check each file descriptor to see if it's a directory. | conditional_block |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::global::global_root_from_object;
use dom::bindings::reflector::Reflectable;
use js::jsapi::GetGlobalForObjectCrossCompartment;
use js::jsapi::JSAutoCompartment;
use js::jsapi::{Heap, MutableHandleObject, RootedObject, RootedValue};
use js::jsapi::{IsCallable, JSContext, JSObject, JS_WrapObject};
use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment};
use js::jsapi::{JS_BeginRequest, JS_EndRequest};
use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException};
use js::jsapi::{JS_RestoreFrameChain, JS_SaveFrameChain};
use js::jsval::{JSVal, UndefinedValue};
use std::default::Default;
use std::ffi::CString;
use std::intrinsics::return_address;
use std::ptr;
use std::rc::Rc;
/// The exception handling used for a call.
#[derive(Copy, Clone, PartialEq)]
pub enum ExceptionHandling {
/// Report any exception and don't throw it to the caller code.
Report,
/// Throw any exception to the caller code.
Rethrow,
}
/// A common base class for representing IDL callback function types.
#[derive(JSTraceable, PartialEq)]
pub struct CallbackFunction {
object: CallbackObject,
}
impl CallbackFunction {
/// Create a new `CallbackFunction` for this object.
pub fn new() -> CallbackFunction {
CallbackFunction {
object: CallbackObject {
callback: Heap::default(),
},
}
}
/// Initialize the callback function with a value.
/// Should be called once this object is done moving.
pub fn init(&mut self, callback: *mut JSObject) {
self.object.callback.set(callback);
}
}
/// A common base class for representing IDL callback interface types.
#[derive(JSTraceable, PartialEq)]
pub struct CallbackInterface {
object: CallbackObject,
}
/// A common base class for representing IDL callback function and
/// callback interface types.
#[allow(raw_pointer_derive)]
#[derive(JSTraceable)]
struct CallbackObject {
/// The underlying `JSObject`.
callback: Heap<*mut JSObject>,
}
impl PartialEq for CallbackObject {
fn eq(&self, other: &CallbackObject) -> bool {
self.callback.get() == other.callback.get()
}
}
/// A trait to be implemented by concrete IDL callback function and
/// callback interface types.
pub trait CallbackContainer {
/// Create a new CallbackContainer object for the given `JSObject`.
fn new(callback: *mut JSObject) -> Rc<Self>;
/// Returns the underlying `JSObject`.
fn callback(&self) -> *mut JSObject;
}
impl CallbackInterface {
/// Returns the underlying `JSObject`.
pub fn callback(&self) -> *mut JSObject {
self.object.callback.get()
}
}
impl CallbackFunction {
/// Returns the underlying `JSObject`.
pub fn callback(&self) -> *mut JSObject {
self.object.callback.get()
}
}
impl CallbackInterface {
/// Create a new CallbackInterface object for the given `JSObject`.
pub fn new() -> CallbackInterface {
CallbackInterface {
object: CallbackObject {
callback: Heap::default(),
},
}
}
/// Initialize the callback function with a value.
/// Should be called once this object is done moving.
pub fn init(&mut self, callback: *mut JSObject) {
self.object.callback.set(callback);
}
/// Returns the property with the given `name`, if it is a callable object,
/// or an error otherwise.
pub fn get_callable_property(&self, cx: *mut JSContext, name: &str) -> Fallible<JSVal> {
let mut callable = RootedValue::new(cx, UndefinedValue());
let obj = RootedObject::new(cx, self.callback());
unsafe {
let c_name = CString::new(name).unwrap();
if !JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) {
return Err(Error::JSFailed);
}
if !callable.ptr.is_object() || !IsCallable(callable.ptr.to_object()) |
}
Ok(callable.ptr)
}
}
/// Wraps the reflector for `p` into the compartment of `cx`.
pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext,
p: &T,
rval: MutableHandleObject) {
rval.set(p.reflector().get_jsobject().get());
assert!(!rval.get().is_null());
unsafe {
if !JS_WrapObject(cx, rval) {
rval.set(ptr::null_mut());
}
}
}
/// A class that performs whatever setup we need to safely make a call while
/// this class is on the stack. After `new` returns, the call is safe to make.
pub struct CallSetup {
/// The compartment for reporting exceptions.
/// As a RootedObject, this must be the first field in order to
/// determine the final address on the stack correctly.
exception_compartment: RootedObject,
/// The `JSContext` used for the call.
cx: *mut JSContext,
/// The compartment we were in before the call.
old_compartment: *mut JSCompartment,
/// The exception handling used for the call.
handling: ExceptionHandling,
}
impl CallSetup {
/// Performs the setup needed to make a call.
#[allow(unrooted_must_root)]
pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
let global = global_root_from_object(callback.callback());
let cx = global.r().get_cx();
unsafe {
JS_BeginRequest(cx);
}
let exception_compartment = unsafe {
GetGlobalForObjectCrossCompartment(callback.callback())
};
CallSetup {
exception_compartment: RootedObject::new_with_addr(cx,
exception_compartment,
unsafe { return_address() }),
cx: cx,
old_compartment: unsafe { JS_EnterCompartment(cx, callback.callback()) },
handling: handling,
}
}
/// Returns the `JSContext` used for the call.
pub fn get_context(&self) -> *mut JSContext {
self.cx
}
}
impl Drop for CallSetup {
fn drop(&mut self) {
unsafe {
JS_LeaveCompartment(self.cx, self.old_compartment);
}
let need_to_deal_with_exception = self.handling == ExceptionHandling::Report &&
unsafe { JS_IsExceptionPending(self.cx) };
if need_to_deal_with_exception {
unsafe {
let old_global = RootedObject::new(self.cx, self.exception_compartment.ptr);
let saved = JS_SaveFrameChain(self.cx);
{
let _ac = JSAutoCompartment::new(self.cx, old_global.ptr);
JS_ReportPendingException(self.cx);
}
if saved {
JS_RestoreFrameChain(self.cx);
}
}
}
unsafe {
JS_EndRequest(self.cx);
}
}
}
| {
return Err(Error::Type(format!("The value of the {} property is not callable",
name)));
} | conditional_block |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::global::global_root_from_object;
use dom::bindings::reflector::Reflectable;
use js::jsapi::GetGlobalForObjectCrossCompartment;
use js::jsapi::JSAutoCompartment;
use js::jsapi::{Heap, MutableHandleObject, RootedObject, RootedValue};
use js::jsapi::{IsCallable, JSContext, JSObject, JS_WrapObject};
use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment};
use js::jsapi::{JS_BeginRequest, JS_EndRequest};
use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException};
use js::jsapi::{JS_RestoreFrameChain, JS_SaveFrameChain};
use js::jsval::{JSVal, UndefinedValue};
use std::default::Default;
use std::ffi::CString;
use std::intrinsics::return_address;
use std::ptr;
use std::rc::Rc;
/// The exception handling used for a call.
#[derive(Copy, Clone, PartialEq)]
pub enum ExceptionHandling {
/// Report any exception and don't throw it to the caller code.
Report,
/// Throw any exception to the caller code.
Rethrow,
}
/// A common base class for representing IDL callback function types.
#[derive(JSTraceable, PartialEq)]
pub struct CallbackFunction {
object: CallbackObject,
}
impl CallbackFunction {
/// Create a new `CallbackFunction` for this object.
pub fn new() -> CallbackFunction {
CallbackFunction {
object: CallbackObject {
callback: Heap::default(),
},
}
}
/// Initialize the callback function with a value.
/// Should be called once this object is done moving.
pub fn init(&mut self, callback: *mut JSObject) {
self.object.callback.set(callback);
}
}
/// A common base class for representing IDL callback interface types.
#[derive(JSTraceable, PartialEq)]
pub struct CallbackInterface {
object: CallbackObject,
}
/// A common base class for representing IDL callback function and
/// callback interface types.
#[allow(raw_pointer_derive)]
#[derive(JSTraceable)]
struct CallbackObject {
/// The underlying `JSObject`.
callback: Heap<*mut JSObject>,
}
impl PartialEq for CallbackObject {
fn eq(&self, other: &CallbackObject) -> bool {
self.callback.get() == other.callback.get()
}
}
/// A trait to be implemented by concrete IDL callback function and
/// callback interface types.
pub trait CallbackContainer {
/// Create a new CallbackContainer object for the given `JSObject`.
fn new(callback: *mut JSObject) -> Rc<Self>;
/// Returns the underlying `JSObject`.
fn callback(&self) -> *mut JSObject;
}
impl CallbackInterface {
/// Returns the underlying `JSObject`.
pub fn callback(&self) -> *mut JSObject {
self.object.callback.get()
}
}
impl CallbackFunction {
/// Returns the underlying `JSObject`.
pub fn callback(&self) -> *mut JSObject {
self.object.callback.get()
}
}
impl CallbackInterface {
/// Create a new CallbackInterface object for the given `JSObject`.
pub fn new() -> CallbackInterface {
CallbackInterface {
object: CallbackObject {
callback: Heap::default(),
},
}
}
/// Initialize the callback function with a value.
/// Should be called once this object is done moving.
pub fn init(&mut self, callback: *mut JSObject) {
self.object.callback.set(callback);
}
/// Returns the property with the given `name`, if it is a callable object,
/// or an error otherwise.
pub fn get_callable_property(&self, cx: *mut JSContext, name: &str) -> Fallible<JSVal> {
let mut callable = RootedValue::new(cx, UndefinedValue());
let obj = RootedObject::new(cx, self.callback());
unsafe {
let c_name = CString::new(name).unwrap();
if !JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) {
return Err(Error::JSFailed);
}
if !callable.ptr.is_object() || !IsCallable(callable.ptr.to_object()) {
return Err(Error::Type(format!("The value of the {} property is not callable",
name)));
}
}
Ok(callable.ptr)
}
}
/// Wraps the reflector for `p` into the compartment of `cx`.
pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext,
p: &T,
rval: MutableHandleObject) {
rval.set(p.reflector().get_jsobject().get());
assert!(!rval.get().is_null());
unsafe {
if !JS_WrapObject(cx, rval) {
rval.set(ptr::null_mut());
}
}
}
/// A class that performs whatever setup we need to safely make a call while
/// this class is on the stack. After `new` returns, the call is safe to make.
pub struct CallSetup {
/// The compartment for reporting exceptions.
/// As a RootedObject, this must be the first field in order to
/// determine the final address on the stack correctly.
exception_compartment: RootedObject,
/// The `JSContext` used for the call.
cx: *mut JSContext,
/// The compartment we were in before the call.
old_compartment: *mut JSCompartment,
/// The exception handling used for the call.
handling: ExceptionHandling,
}
impl CallSetup {
/// Performs the setup needed to make a call.
#[allow(unrooted_must_root)] | let cx = global.r().get_cx();
unsafe {
JS_BeginRequest(cx);
}
let exception_compartment = unsafe {
GetGlobalForObjectCrossCompartment(callback.callback())
};
CallSetup {
exception_compartment: RootedObject::new_with_addr(cx,
exception_compartment,
unsafe { return_address() }),
cx: cx,
old_compartment: unsafe { JS_EnterCompartment(cx, callback.callback()) },
handling: handling,
}
}
/// Returns the `JSContext` used for the call.
pub fn get_context(&self) -> *mut JSContext {
self.cx
}
}
impl Drop for CallSetup {
fn drop(&mut self) {
unsafe {
JS_LeaveCompartment(self.cx, self.old_compartment);
}
let need_to_deal_with_exception = self.handling == ExceptionHandling::Report &&
unsafe { JS_IsExceptionPending(self.cx) };
if need_to_deal_with_exception {
unsafe {
let old_global = RootedObject::new(self.cx, self.exception_compartment.ptr);
let saved = JS_SaveFrameChain(self.cx);
{
let _ac = JSAutoCompartment::new(self.cx, old_global.ptr);
JS_ReportPendingException(self.cx);
}
if saved {
JS_RestoreFrameChain(self.cx);
}
}
}
unsafe {
JS_EndRequest(self.cx);
}
}
} | pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
let global = global_root_from_object(callback.callback()); | random_line_split |
callback.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/. */
//! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible};
use dom::bindings::global::global_root_from_object;
use dom::bindings::reflector::Reflectable;
use js::jsapi::GetGlobalForObjectCrossCompartment;
use js::jsapi::JSAutoCompartment;
use js::jsapi::{Heap, MutableHandleObject, RootedObject, RootedValue};
use js::jsapi::{IsCallable, JSContext, JSObject, JS_WrapObject};
use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment};
use js::jsapi::{JS_BeginRequest, JS_EndRequest};
use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException};
use js::jsapi::{JS_RestoreFrameChain, JS_SaveFrameChain};
use js::jsval::{JSVal, UndefinedValue};
use std::default::Default;
use std::ffi::CString;
use std::intrinsics::return_address;
use std::ptr;
use std::rc::Rc;
/// The exception handling used for a call.
#[derive(Copy, Clone, PartialEq)]
pub enum ExceptionHandling {
/// Report any exception and don't throw it to the caller code.
Report,
/// Throw any exception to the caller code.
Rethrow,
}
/// A common base class for representing IDL callback function types.
#[derive(JSTraceable, PartialEq)]
pub struct CallbackFunction {
object: CallbackObject,
}
impl CallbackFunction {
/// Create a new `CallbackFunction` for this object.
pub fn new() -> CallbackFunction {
CallbackFunction {
object: CallbackObject {
callback: Heap::default(),
},
}
}
/// Initialize the callback function with a value.
/// Should be called once this object is done moving.
pub fn init(&mut self, callback: *mut JSObject) {
self.object.callback.set(callback);
}
}
/// A common base class for representing IDL callback interface types.
#[derive(JSTraceable, PartialEq)]
pub struct CallbackInterface {
object: CallbackObject,
}
/// A common base class for representing IDL callback function and
/// callback interface types.
#[allow(raw_pointer_derive)]
#[derive(JSTraceable)]
struct CallbackObject {
/// The underlying `JSObject`.
callback: Heap<*mut JSObject>,
}
impl PartialEq for CallbackObject {
fn eq(&self, other: &CallbackObject) -> bool {
self.callback.get() == other.callback.get()
}
}
/// A trait to be implemented by concrete IDL callback function and
/// callback interface types.
pub trait CallbackContainer {
/// Create a new CallbackContainer object for the given `JSObject`.
fn new(callback: *mut JSObject) -> Rc<Self>;
/// Returns the underlying `JSObject`.
fn callback(&self) -> *mut JSObject;
}
impl CallbackInterface {
/// Returns the underlying `JSObject`.
pub fn callback(&self) -> *mut JSObject {
self.object.callback.get()
}
}
impl CallbackFunction {
/// Returns the underlying `JSObject`.
pub fn callback(&self) -> *mut JSObject {
self.object.callback.get()
}
}
impl CallbackInterface {
/// Create a new CallbackInterface object for the given `JSObject`.
pub fn new() -> CallbackInterface {
CallbackInterface {
object: CallbackObject {
callback: Heap::default(),
},
}
}
/// Initialize the callback function with a value.
/// Should be called once this object is done moving.
pub fn init(&mut self, callback: *mut JSObject) {
self.object.callback.set(callback);
}
/// Returns the property with the given `name`, if it is a callable object,
/// or an error otherwise.
pub fn get_callable_property(&self, cx: *mut JSContext, name: &str) -> Fallible<JSVal> {
let mut callable = RootedValue::new(cx, UndefinedValue());
let obj = RootedObject::new(cx, self.callback());
unsafe {
let c_name = CString::new(name).unwrap();
if !JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) {
return Err(Error::JSFailed);
}
if !callable.ptr.is_object() || !IsCallable(callable.ptr.to_object()) {
return Err(Error::Type(format!("The value of the {} property is not callable",
name)));
}
}
Ok(callable.ptr)
}
}
/// Wraps the reflector for `p` into the compartment of `cx`.
pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext,
p: &T,
rval: MutableHandleObject) {
rval.set(p.reflector().get_jsobject().get());
assert!(!rval.get().is_null());
unsafe {
if !JS_WrapObject(cx, rval) {
rval.set(ptr::null_mut());
}
}
}
/// A class that performs whatever setup we need to safely make a call while
/// this class is on the stack. After `new` returns, the call is safe to make.
pub struct CallSetup {
/// The compartment for reporting exceptions.
/// As a RootedObject, this must be the first field in order to
/// determine the final address on the stack correctly.
exception_compartment: RootedObject,
/// The `JSContext` used for the call.
cx: *mut JSContext,
/// The compartment we were in before the call.
old_compartment: *mut JSCompartment,
/// The exception handling used for the call.
handling: ExceptionHandling,
}
impl CallSetup {
/// Performs the setup needed to make a call.
#[allow(unrooted_must_root)]
pub fn | <T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
let global = global_root_from_object(callback.callback());
let cx = global.r().get_cx();
unsafe {
JS_BeginRequest(cx);
}
let exception_compartment = unsafe {
GetGlobalForObjectCrossCompartment(callback.callback())
};
CallSetup {
exception_compartment: RootedObject::new_with_addr(cx,
exception_compartment,
unsafe { return_address() }),
cx: cx,
old_compartment: unsafe { JS_EnterCompartment(cx, callback.callback()) },
handling: handling,
}
}
/// Returns the `JSContext` used for the call.
pub fn get_context(&self) -> *mut JSContext {
self.cx
}
}
impl Drop for CallSetup {
fn drop(&mut self) {
unsafe {
JS_LeaveCompartment(self.cx, self.old_compartment);
}
let need_to_deal_with_exception = self.handling == ExceptionHandling::Report &&
unsafe { JS_IsExceptionPending(self.cx) };
if need_to_deal_with_exception {
unsafe {
let old_global = RootedObject::new(self.cx, self.exception_compartment.ptr);
let saved = JS_SaveFrameChain(self.cx);
{
let _ac = JSAutoCompartment::new(self.cx, old_global.ptr);
JS_ReportPendingException(self.cx);
}
if saved {
JS_RestoreFrameChain(self.cx);
}
}
}
unsafe {
JS_EndRequest(self.cx);
}
}
}
| new | identifier_name |
badfiles.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Use command-line tools to check for audio file corruption.
"""
from __future__ import division, absolute_import, print_function
from beets.plugins import BeetsPlugin
from beets.ui import Subcommand
from beets.util import displayable_path, confit
from beets import ui
from subprocess import check_output, CalledProcessError, list2cmdline, STDOUT
import shlex
import os
import errno
import sys
class BadFiles(BeetsPlugin):
def run_command(self, cmd):
self._log.debug(u"running command: {}",
displayable_path(list2cmdline(cmd)))
try:
output = check_output(cmd, stderr=STDOUT)
errors = 0
status = 0
except CalledProcessError as e:
output = e.output
errors = 1
status = e.returncode
except OSError as e:
if e.errno == errno.ENOENT:
ui.print_(u"command not found: {}".format(cmd[0]))
sys.exit(1)
else:
raise
output = output.decode(sys.getfilesystemencoding())
return status, errors, [line for line in output.split("\n") if line]
def check_mp3val(self, path):
status, errors, output = self.run_command(["mp3val", path])
if status == 0:
output = [line for line in output if line.startswith("WARNING:")]
errors = len(output)
return status, errors, output
def check_flac(self, path):
return self.run_command(["flac", "-wst", path])
def check_custom(self, command):
def checker(path):
cmd = shlex.split(command)
cmd.append(path)
return self.run_command(cmd)
return checker
def get_checker(self, ext):
ext = ext.lower()
try:
command = self.config['commands'].get(dict).get(ext)
except confit.NotFoundError:
command = None
if command:
return self.check_custom(command)
elif ext == "mp3":
return self.check_mp3val
elif ext == "flac":
return self.check_flac
def check_bad(self, lib, opts, args):
for item in lib.items(ui.decargs(args)):
# First, check whether the path exists. If not, the user
# should probably run `beet update` to cleanup your library.
dpath = displayable_path(item.path)
self._log.debug(u"checking path: {}", dpath)
if not os.path.exists(item.path):
ui.print_(u"{}: file does not exist".format(
ui.colorize('text_error', dpath)))
# Run the checker against the file if one is found
ext = os.path.splitext(item.path)[1][1:]
checker = self.get_checker(ext)
if not checker:
continue
path = item.path
if not isinstance(path, unicode):
path = item.path.decode(sys.getfilesystemencoding())
status, errors, output = checker(path)
if status > 0:
ui.print_(u"{}: checker exited withs status {}"
.format(ui.colorize('text_error', dpath), status))
for line in output:
ui.print_(" {}".format(displayable_path(line)))
elif errors > 0:
ui.print_(u"{}: checker found {} errors or warnings"
.format(ui.colorize('text_warning', dpath), errors))
for line in output:
ui.print_(u" {}".format(displayable_path(line)))
else: |
def commands(self):
bad_command = Subcommand('bad',
help=u'check for corrupt or missing files')
bad_command.func = self.check_bad
return [bad_command] | ui.print_(u"{}: ok".format(ui.colorize('text_success', dpath))) | random_line_split |
badfiles.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Use command-line tools to check for audio file corruption.
"""
from __future__ import division, absolute_import, print_function
from beets.plugins import BeetsPlugin
from beets.ui import Subcommand
from beets.util import displayable_path, confit
from beets import ui
from subprocess import check_output, CalledProcessError, list2cmdline, STDOUT
import shlex
import os
import errno
import sys
class B | BeetsPlugin):
def run_command(self, cmd):
self._log.debug(u"running command: {}",
displayable_path(list2cmdline(cmd)))
try:
output = check_output(cmd, stderr=STDOUT)
errors = 0
status = 0
except CalledProcessError as e:
output = e.output
errors = 1
status = e.returncode
except OSError as e:
if e.errno == errno.ENOENT:
ui.print_(u"command not found: {}".format(cmd[0]))
sys.exit(1)
else:
raise
output = output.decode(sys.getfilesystemencoding())
return status, errors, [line for line in output.split("\n") if line]
def check_mp3val(self, path):
status, errors, output = self.run_command(["mp3val", path])
if status == 0:
output = [line for line in output if line.startswith("WARNING:")]
errors = len(output)
return status, errors, output
def check_flac(self, path):
return self.run_command(["flac", "-wst", path])
def check_custom(self, command):
def checker(path):
cmd = shlex.split(command)
cmd.append(path)
return self.run_command(cmd)
return checker
def get_checker(self, ext):
ext = ext.lower()
try:
command = self.config['commands'].get(dict).get(ext)
except confit.NotFoundError:
command = None
if command:
return self.check_custom(command)
elif ext == "mp3":
return self.check_mp3val
elif ext == "flac":
return self.check_flac
def check_bad(self, lib, opts, args):
for item in lib.items(ui.decargs(args)):
# First, check whether the path exists. If not, the user
# should probably run `beet update` to cleanup your library.
dpath = displayable_path(item.path)
self._log.debug(u"checking path: {}", dpath)
if not os.path.exists(item.path):
ui.print_(u"{}: file does not exist".format(
ui.colorize('text_error', dpath)))
# Run the checker against the file if one is found
ext = os.path.splitext(item.path)[1][1:]
checker = self.get_checker(ext)
if not checker:
continue
path = item.path
if not isinstance(path, unicode):
path = item.path.decode(sys.getfilesystemencoding())
status, errors, output = checker(path)
if status > 0:
ui.print_(u"{}: checker exited withs status {}"
.format(ui.colorize('text_error', dpath), status))
for line in output:
ui.print_(" {}".format(displayable_path(line)))
elif errors > 0:
ui.print_(u"{}: checker found {} errors or warnings"
.format(ui.colorize('text_warning', dpath), errors))
for line in output:
ui.print_(u" {}".format(displayable_path(line)))
else:
ui.print_(u"{}: ok".format(ui.colorize('text_success', dpath)))
def commands(self):
bad_command = Subcommand('bad',
help=u'check for corrupt or missing files')
bad_command.func = self.check_bad
return [bad_command]
| adFiles( | identifier_name |
badfiles.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Use command-line tools to check for audio file corruption.
"""
from __future__ import division, absolute_import, print_function
from beets.plugins import BeetsPlugin
from beets.ui import Subcommand
from beets.util import displayable_path, confit
from beets import ui
from subprocess import check_output, CalledProcessError, list2cmdline, STDOUT
import shlex
import os
import errno
import sys
class BadFiles(BeetsPlugin):
def run_command(self, cmd):
s |
def check_mp3val(self, path):
status, errors, output = self.run_command(["mp3val", path])
if status == 0:
output = [line for line in output if line.startswith("WARNING:")]
errors = len(output)
return status, errors, output
def check_flac(self, path):
return self.run_command(["flac", "-wst", path])
def check_custom(self, command):
def checker(path):
cmd = shlex.split(command)
cmd.append(path)
return self.run_command(cmd)
return checker
def get_checker(self, ext):
ext = ext.lower()
try:
command = self.config['commands'].get(dict).get(ext)
except confit.NotFoundError:
command = None
if command:
return self.check_custom(command)
elif ext == "mp3":
return self.check_mp3val
elif ext == "flac":
return self.check_flac
def check_bad(self, lib, opts, args):
for item in lib.items(ui.decargs(args)):
# First, check whether the path exists. If not, the user
# should probably run `beet update` to cleanup your library.
dpath = displayable_path(item.path)
self._log.debug(u"checking path: {}", dpath)
if not os.path.exists(item.path):
ui.print_(u"{}: file does not exist".format(
ui.colorize('text_error', dpath)))
# Run the checker against the file if one is found
ext = os.path.splitext(item.path)[1][1:]
checker = self.get_checker(ext)
if not checker:
continue
path = item.path
if not isinstance(path, unicode):
path = item.path.decode(sys.getfilesystemencoding())
status, errors, output = checker(path)
if status > 0:
ui.print_(u"{}: checker exited withs status {}"
.format(ui.colorize('text_error', dpath), status))
for line in output:
ui.print_(" {}".format(displayable_path(line)))
elif errors > 0:
ui.print_(u"{}: checker found {} errors or warnings"
.format(ui.colorize('text_warning', dpath), errors))
for line in output:
ui.print_(u" {}".format(displayable_path(line)))
else:
ui.print_(u"{}: ok".format(ui.colorize('text_success', dpath)))
def commands(self):
bad_command = Subcommand('bad',
help=u'check for corrupt or missing files')
bad_command.func = self.check_bad
return [bad_command]
| elf._log.debug(u"running command: {}",
displayable_path(list2cmdline(cmd)))
try:
output = check_output(cmd, stderr=STDOUT)
errors = 0
status = 0
except CalledProcessError as e:
output = e.output
errors = 1
status = e.returncode
except OSError as e:
if e.errno == errno.ENOENT:
ui.print_(u"command not found: {}".format(cmd[0]))
sys.exit(1)
else:
raise
output = output.decode(sys.getfilesystemencoding())
return status, errors, [line for line in output.split("\n") if line]
| identifier_body |
badfiles.py | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Use command-line tools to check for audio file corruption.
"""
from __future__ import division, absolute_import, print_function
from beets.plugins import BeetsPlugin
from beets.ui import Subcommand
from beets.util import displayable_path, confit
from beets import ui
from subprocess import check_output, CalledProcessError, list2cmdline, STDOUT
import shlex
import os
import errno
import sys
class BadFiles(BeetsPlugin):
def run_command(self, cmd):
self._log.debug(u"running command: {}",
displayable_path(list2cmdline(cmd)))
try:
output = check_output(cmd, stderr=STDOUT)
errors = 0
status = 0
except CalledProcessError as e:
output = e.output
errors = 1
status = e.returncode
except OSError as e:
if e.errno == errno.ENOENT:
ui.print_(u"command not found: {}".format(cmd[0]))
sys.exit(1)
else:
raise
output = output.decode(sys.getfilesystemencoding())
return status, errors, [line for line in output.split("\n") if line]
def check_mp3val(self, path):
status, errors, output = self.run_command(["mp3val", path])
if status == 0:
output = [line for line in output if line.startswith("WARNING:")]
errors = len(output)
return status, errors, output
def check_flac(self, path):
return self.run_command(["flac", "-wst", path])
def check_custom(self, command):
def checker(path):
cmd = shlex.split(command)
cmd.append(path)
return self.run_command(cmd)
return checker
def get_checker(self, ext):
ext = ext.lower()
try:
command = self.config['commands'].get(dict).get(ext)
except confit.NotFoundError:
command = None
if command:
return self.check_custom(command)
elif ext == "mp3":
return self.check_mp3val
elif ext == "flac":
return self.check_flac
def check_bad(self, lib, opts, args):
for item in lib.items(ui.decargs(args)):
# First, check whether the path exists. If not, the user
# should probably run `beet update` to cleanup your library.
dpath = displayable_path(item.path)
self._log.debug(u"checking path: {}", dpath)
if not os.path.exists(item.path):
ui.print_(u"{}: file does not exist".format(
ui.colorize('text_error', dpath)))
# Run the checker against the file if one is found
ext = os.path.splitext(item.path)[1][1:]
checker = self.get_checker(ext)
if not checker:
continue
path = item.path
if not isinstance(path, unicode):
path = item.path.decode(sys.getfilesystemencoding())
status, errors, output = checker(path)
if status > 0:
ui.print_(u"{}: checker exited withs status {}"
.format(ui.colorize('text_error', dpath), status))
for line in output:
u | elif errors > 0:
ui.print_(u"{}: checker found {} errors or warnings"
.format(ui.colorize('text_warning', dpath), errors))
for line in output:
ui.print_(u" {}".format(displayable_path(line)))
else:
ui.print_(u"{}: ok".format(ui.colorize('text_success', dpath)))
def commands(self):
bad_command = Subcommand('bad',
help=u'check for corrupt or missing files')
bad_command.func = self.check_bad
return [bad_command]
| i.print_(" {}".format(displayable_path(line)))
| conditional_block |
TypeaheadInputMulti.stories.tsx | /* eslint-disable sort-keys,import/no-extraneous-dependencies */
import React, { ChangeEvent, useState } from 'react';
import { Story, Meta } from '@storybook/react';
import Token from '../Token';
import TypeaheadInputMulti, {
TypeaheadInputMultiProps,
} from './TypeaheadInputMulti';
import options from '../../tests/data';
import { HintProvider, noop } from '../../tests/helpers';
import type { Size } from '../../types';
export default {
title: 'Components/TypeaheadInputMulti',
component: TypeaheadInputMulti,
} as Meta;
const selected = options.slice(1, 4);
const defaultProps = {
children: selected.map((option) => (
<Token key={option.name} option={option} onRemove={noop}>
{option.name}
</Token>
)),
selected,
};
interface Args extends TypeaheadInputMultiProps {
hintText?: string;
isValid?: boolean;
isInvalid?: boolean;
size?: Size;
}
const Template: Story<Args> = ({ hintText = '', ...args }) => {
const [value, setValue] = useState(args.value);
const [inputNode, setInputNode] = useState<HTMLInputElement | null>(null);
return (
<HintProvider hintText={hintText} inputNode={inputNode}>
<TypeaheadInputMulti
{...args}
inputRef={setInputNode}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setValue(e.target.value)
}
referenceElementRef={noop}
value={value}
/>
</HintProvider>
);
};
export const Default = Template.bind({});
Default.args = {
...defaultProps,
};
export const FocusState = Template.bind({});
FocusState.args = {
...defaultProps,
className: 'focus',
};
export const Disabled = Template.bind({});
Disabled.args = {
...defaultProps,
children: selected.map((option) => (
<Token disabled key={option.name} option={option} onRemove={noop}>
{option.name}
</Token>
)),
disabled: true,
};
export const Small = Template.bind({});
Small.args = {
...defaultProps,
size: 'sm',
};
export const Large = Template.bind({});
Large.args = {
...defaultProps,
size: 'lg', | Valid.args = {
...defaultProps,
className: 'focus',
isValid: true,
};
export const Invalid = Template.bind({});
Invalid.args = {
...defaultProps,
className: 'focus',
isInvalid: true,
};
export const WithHint = Template.bind({});
WithHint.args = {
...defaultProps,
hintText: 'california',
value: 'cali',
}; | };
export const Valid = Template.bind({}); | random_line_split |
vec.rs | use super::{AssertionFailure, Spec};
pub trait VecAssertions {
fn has_length(&mut self, expected: usize);
fn is_empty(&mut self);
}
impl<'s, T> VecAssertions for Spec<'s, Vec<T>> {
/// Asserts that the length of the subject vector is equal to the provided length. The subject
/// type must be of `Vec`.
///
/// ```rust,ignore
/// assert_that(&vec![1, 2, 3, 4]).has_length(4);
/// ```
fn has_length(&mut self, expected: usize) {
let length = self.subject.len();
if length != expected {
AssertionFailure::from_spec(self)
.with_expected(format!("vec to have length <{}>", expected))
.with_actual(format!("<{}>", length))
.fail();
}
}
/// Asserts that the subject vector is empty. The subject type must be of `Vec`.
///
/// ```rust,ignore
/// let test_vec: Vec<u8> = vec![];
/// assert_that(&test_vec).is_empty();
/// ```
fn is_empty(&mut self) {
let subject = self.subject;
if !subject.is_empty() |
}
}
#[cfg(test)]
mod tests {
use super::super::prelude::*;
#[test]
fn should_not_panic_if_vec_length_matches_expected() {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(3);
}
#[test]
#[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but was: <3>")]
fn should_panic_if_vec_length_does_not_match_expected() {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(1);
}
#[test]
fn should_not_panic_if_vec_was_expected_to_be_empty_and_is() {
let test_vec: Vec<u8> = vec![];
assert_that(&test_vec).is_empty();
}
#[test]
#[should_panic(expected = "\n\texpected: an empty vec\
\n\t but was: a vec with length <1>")]
fn should_panic_if_vec_was_expected_to_be_empty_and_is_not() {
assert_that(&vec![1]).is_empty();
}
}
| {
AssertionFailure::from_spec(self)
.with_expected(format!("an empty vec"))
.with_actual(format!("a vec with length <{:?}>", subject.len()))
.fail();
} | conditional_block |
vec.rs | use super::{AssertionFailure, Spec};
pub trait VecAssertions {
fn has_length(&mut self, expected: usize);
fn is_empty(&mut self);
}
impl<'s, T> VecAssertions for Spec<'s, Vec<T>> {
/// Asserts that the length of the subject vector is equal to the provided length. The subject
/// type must be of `Vec`.
///
/// ```rust,ignore
/// assert_that(&vec![1, 2, 3, 4]).has_length(4);
/// ``` | fn has_length(&mut self, expected: usize) {
let length = self.subject.len();
if length != expected {
AssertionFailure::from_spec(self)
.with_expected(format!("vec to have length <{}>", expected))
.with_actual(format!("<{}>", length))
.fail();
}
}
/// Asserts that the subject vector is empty. The subject type must be of `Vec`.
///
/// ```rust,ignore
/// let test_vec: Vec<u8> = vec![];
/// assert_that(&test_vec).is_empty();
/// ```
fn is_empty(&mut self) {
let subject = self.subject;
if !subject.is_empty() {
AssertionFailure::from_spec(self)
.with_expected(format!("an empty vec"))
.with_actual(format!("a vec with length <{:?}>", subject.len()))
.fail();
}
}
}
#[cfg(test)]
mod tests {
use super::super::prelude::*;
#[test]
fn should_not_panic_if_vec_length_matches_expected() {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(3);
}
#[test]
#[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but was: <3>")]
fn should_panic_if_vec_length_does_not_match_expected() {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(1);
}
#[test]
fn should_not_panic_if_vec_was_expected_to_be_empty_and_is() {
let test_vec: Vec<u8> = vec![];
assert_that(&test_vec).is_empty();
}
#[test]
#[should_panic(expected = "\n\texpected: an empty vec\
\n\t but was: a vec with length <1>")]
fn should_panic_if_vec_was_expected_to_be_empty_and_is_not() {
assert_that(&vec![1]).is_empty();
}
} | random_line_split |
|
vec.rs | use super::{AssertionFailure, Spec};
pub trait VecAssertions {
fn has_length(&mut self, expected: usize);
fn is_empty(&mut self);
}
impl<'s, T> VecAssertions for Spec<'s, Vec<T>> {
/// Asserts that the length of the subject vector is equal to the provided length. The subject
/// type must be of `Vec`.
///
/// ```rust,ignore
/// assert_that(&vec![1, 2, 3, 4]).has_length(4);
/// ```
fn has_length(&mut self, expected: usize) {
let length = self.subject.len();
if length != expected {
AssertionFailure::from_spec(self)
.with_expected(format!("vec to have length <{}>", expected))
.with_actual(format!("<{}>", length))
.fail();
}
}
/// Asserts that the subject vector is empty. The subject type must be of `Vec`.
///
/// ```rust,ignore
/// let test_vec: Vec<u8> = vec![];
/// assert_that(&test_vec).is_empty();
/// ```
fn is_empty(&mut self) {
let subject = self.subject;
if !subject.is_empty() {
AssertionFailure::from_spec(self)
.with_expected(format!("an empty vec"))
.with_actual(format!("a vec with length <{:?}>", subject.len()))
.fail();
}
}
}
#[cfg(test)]
mod tests {
use super::super::prelude::*;
#[test]
fn should_not_panic_if_vec_length_matches_expected() {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(3);
}
#[test]
#[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but was: <3>")]
fn should_panic_if_vec_length_does_not_match_expected() |
#[test]
fn should_not_panic_if_vec_was_expected_to_be_empty_and_is() {
let test_vec: Vec<u8> = vec![];
assert_that(&test_vec).is_empty();
}
#[test]
#[should_panic(expected = "\n\texpected: an empty vec\
\n\t but was: a vec with length <1>")]
fn should_panic_if_vec_was_expected_to_be_empty_and_is_not() {
assert_that(&vec![1]).is_empty();
}
}
| {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(1);
} | identifier_body |
vec.rs | use super::{AssertionFailure, Spec};
pub trait VecAssertions {
fn has_length(&mut self, expected: usize);
fn is_empty(&mut self);
}
impl<'s, T> VecAssertions for Spec<'s, Vec<T>> {
/// Asserts that the length of the subject vector is equal to the provided length. The subject
/// type must be of `Vec`.
///
/// ```rust,ignore
/// assert_that(&vec![1, 2, 3, 4]).has_length(4);
/// ```
fn has_length(&mut self, expected: usize) {
let length = self.subject.len();
if length != expected {
AssertionFailure::from_spec(self)
.with_expected(format!("vec to have length <{}>", expected))
.with_actual(format!("<{}>", length))
.fail();
}
}
/// Asserts that the subject vector is empty. The subject type must be of `Vec`.
///
/// ```rust,ignore
/// let test_vec: Vec<u8> = vec![];
/// assert_that(&test_vec).is_empty();
/// ```
fn is_empty(&mut self) {
let subject = self.subject;
if !subject.is_empty() {
AssertionFailure::from_spec(self)
.with_expected(format!("an empty vec"))
.with_actual(format!("a vec with length <{:?}>", subject.len()))
.fail();
}
}
}
#[cfg(test)]
mod tests {
use super::super::prelude::*;
#[test]
fn | () {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(3);
}
#[test]
#[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but was: <3>")]
fn should_panic_if_vec_length_does_not_match_expected() {
let test_vec = vec![1, 2, 3];
assert_that(&test_vec).has_length(1);
}
#[test]
fn should_not_panic_if_vec_was_expected_to_be_empty_and_is() {
let test_vec: Vec<u8> = vec![];
assert_that(&test_vec).is_empty();
}
#[test]
#[should_panic(expected = "\n\texpected: an empty vec\
\n\t but was: a vec with length <1>")]
fn should_panic_if_vec_was_expected_to_be_empty_and_is_not() {
assert_that(&vec![1]).is_empty();
}
}
| should_not_panic_if_vec_length_matches_expected | identifier_name |
parser.js | const pug = require("pug");
const pugRuntimeWrap = require("pug-runtime/wrap");
const path = require("path");
const YAML = require("js-yaml");
const getCodeBlock = require("pug-code-block");
const detectIndent = require("detect-indent");
const rebaseIndent = require("rebase-indent");
const pugdocArguments = require("./arguments");
const MIXIN_NAME_REGEX = /^mixin +([-\w]+)?/;
const DOC_REGEX = /^\s*\/\/-\s+?\@pugdoc\s*$/;
const DOC_STRING = "//- @pugdoc";
const CAPTURE_ALL = "all";
const CAPTURE_SECTION = "section";
const EXAMPLE_BLOCK = "block";
/**
* Returns all pugdoc comment and code blocks for the given code
*
* @param templateSrc {string}
* @return {{lineNumber: number, comment: string, code: string}[]}
*/
function extractPugdocBlocks(templateSrc) {
return (
templateSrc
.split("\n")
// Walk through every line and look for a pugdoc comment
.map(function (line, lineIndex) {
// If the line does not contain a pugdoc comment skip it
if (!line.match(DOC_REGEX)) {
return undefined;
}
// If the line contains a pugdoc comment return
// the comment block and the next code block
const comment = getCodeBlock.byLine(templateSrc, lineIndex + 1);
const meta = parsePugdocComment(comment);
// add number of captured blocks
if (meta.capture <= 0) {
return undefined;
}
let capture = 2;
if (meta.capture) {
if (meta.capture === CAPTURE_ALL) {
capture = Infinity;
} else if (meta.capture === CAPTURE_SECTION) {
capture = Infinity;
} else {
capture = meta.capture + 1;
}
}
// get all code blocks
let code = getCodeBlock.byLine(templateSrc, lineIndex + 1, capture);
// make string
if (Array.isArray(code)) {
// remove comment
code.shift();
// join all code
code = code.join("\n");
} else {
return undefined;
}
// filter out all but current pugdoc section
if (meta.capture === CAPTURE_SECTION) {
const nextPugDocIndex = code.indexOf(DOC_STRING);
if (nextPugDocIndex > -1) {
code = code.substr(0, nextPugDocIndex);
}
}
// if no code and no comment, skip
if (comment.match(DOC_REGEX) && code === "") {
return undefined;
}
return {
lineNumber: lineIndex + 1,
comment: comment,
code: code,
};
})
// Remove skiped lines
.filter(function (result) {
return result !== undefined;
})
);
}
/**
* Returns all pugdocDocuments for the given code
*
* @param templateSrc {string}
* @param filename {string}
*/
function getPugdocDocuments(templateSrc, filename, locals) {
return extractPugdocBlocks(templateSrc).map(function (pugdocBlock) {
const meta = parsePugdocComment(pugdocBlock.comment);
const fragments = [];
// parse jsdoc style arguments list
if (meta.arguments) {
meta.arguments = meta.arguments.map(function (arg) {
return pugdocArguments.parse(arg, true);
});
}
// parse jsdoc style attributes list
if (meta.attributes) {
meta.attributes = meta.attributes.map(function (arg) {
return pugdocArguments.parse(arg, true);
});
}
let source = pugdocBlock.code;
source = source.replace(/\u2028|\u200B/g, "");
if (meta.example && meta.example !== false) {
if (meta.beforeEach) {
meta.example = `${meta.beforeEach}\n${meta.example}`;
}
if (meta.afterEach) {
meta.example = `${meta.example}\n${meta.afterEach}`;
}
}
// get example objects and add them to parent example
// also return them as separate pugdoc blocks
if (meta.examples) {
for (let i = 0, l = meta.examples.length; i < l; ++i) {
let x = meta.examples[i];
// do nothing for simple examples
if (typeof x === "string") {
if (meta.beforeEach) {
meta.examples[i] = `${meta.beforeEach}\n${x}`;
}
if (meta.afterEach) {
meta.examples[i] = `${x}\n${meta.afterEach}`;
}
continue;
}
if (meta.beforeEach && typeof x.beforeEach === "undefined") |
if (meta.afterEach && typeof x.afterEach === "undefined") {
x.example = `${x.example}\n${meta.afterEach}`;
}
// merge example/examples with parent examples
meta.examples[i] = getExamples(x).reduce(
(acc, val) => acc.concat(val),
[]
);
// add fragments
fragments.push(x);
}
meta.examples = meta.examples.reduce((acc, val) => acc.concat(val), []);
}
// fix pug compilation for boolean use of example
const exampleClone = meta.example;
if (typeof meta.example === "boolean") {
meta.example = "";
}
const obj = {
// get meta
meta: meta,
// add file path
file: path.relative(".", filename),
// get pug code block matching the comments indent
source: source,
// get html output
output: compilePug(source, meta, filename, locals),
};
// remove output if example = false
if (exampleClone === false) {
obj.output = null;
}
// add fragments
if (fragments && fragments.length) {
obj.fragments = fragments.map((subexample) => {
return {
// get meta
meta: subexample,
// get html output
output: compilePug(source, subexample, filename, locals),
};
});
}
if (obj.output || obj.fragments) {
return obj;
}
return null;
});
}
/**
* Extract pug attributes from comment block
*/
function parsePugdocComment(comment) {
// remove first line (@pugdoc)
if (comment.indexOf("\n") === -1) {
return {};
}
comment = comment.substr(comment.indexOf("\n"));
comment = pugdocArguments.escapeArgumentsYAML(comment, "arguments");
comment = pugdocArguments.escapeArgumentsYAML(comment, "attributes");
// parse YAML
return YAML.safeLoad(comment) || {};
}
/**
* get all examples from the meta object
* either one or both of meta.example and meta.examples can be given
*/
function getExamples(meta) {
let examples = [];
if (meta.example) {
examples = examples.concat(meta.example);
}
if (meta.examples) {
examples = examples.concat(meta.examples);
}
return examples;
}
/**
* Compile Pug
*/
function compilePug(src, meta, filename, locals) {
let newSrc = [src];
// add example calls
getExamples(meta).forEach(function (example, i) {
// append to pug if it's a mixin example
if (MIXIN_NAME_REGEX.test(src)) {
newSrc.push(example);
// replace example block with src
} else {
if (i === 0) {
newSrc = [];
}
const lines = example.split("\n");
lines.forEach(function (line) {
if (line.trim() === EXAMPLE_BLOCK) {
const indent = detectIndent(line).indent.length;
line = rebaseIndent(src.split("\n"), indent).join("\n");
}
newSrc.push(line);
});
}
});
newSrc = newSrc.join("\n");
locals = Object.assign({}, locals, meta.locals);
// compile pug
const compiled = pug.compileClient(newSrc, {
name: "tmp",
externalRuntime: true,
filename: filename,
});
try {
const templateFunc = pugRuntimeWrap(compiled, "tmp");
return templateFunc(locals || {});
} catch (err) {
try {
const compiledDebug = pug.compileClient(newSrc, {
name: "tmp",
externalRuntime: true,
filename: filename,
compileDebug: true,
});
const templateFuncDebug = pugRuntimeWrap(compiledDebug, "tmp");
templateFuncDebug(locals || {});
} catch (debugErr) {
process.stderr.write(
`\n\nPug-doc error: ${JSON.stringify(meta, null, 2)}`
);
process.stderr.write(`\n\n${debugErr.toString()}`);
return null;
}
}
}
// Exports
module.exports = {
extractPugdocBlocks: extractPugdocBlocks,
getPugdocDocuments: getPugdocDocuments,
parsePugdocComment: parsePugdocComment,
getExamples: getExamples,
};
| {
x.example = `${meta.beforeEach}\n${x.example}`;
} | conditional_block |
parser.js | const pug = require("pug");
const pugRuntimeWrap = require("pug-runtime/wrap");
const path = require("path");
const YAML = require("js-yaml");
const getCodeBlock = require("pug-code-block");
const detectIndent = require("detect-indent");
const rebaseIndent = require("rebase-indent");
const pugdocArguments = require("./arguments");
const MIXIN_NAME_REGEX = /^mixin +([-\w]+)?/;
const DOC_REGEX = /^\s*\/\/-\s+?\@pugdoc\s*$/;
const DOC_STRING = "//- @pugdoc";
const CAPTURE_ALL = "all";
const CAPTURE_SECTION = "section";
const EXAMPLE_BLOCK = "block";
/**
* Returns all pugdoc comment and code blocks for the given code
*
* @param templateSrc {string}
* @return {{lineNumber: number, comment: string, code: string}[]}
*/
function extractPugdocBlocks(templateSrc) {
return (
templateSrc
.split("\n")
// Walk through every line and look for a pugdoc comment
.map(function (line, lineIndex) {
// If the line does not contain a pugdoc comment skip it
if (!line.match(DOC_REGEX)) {
return undefined;
}
// If the line contains a pugdoc comment return
// the comment block and the next code block
const comment = getCodeBlock.byLine(templateSrc, lineIndex + 1);
const meta = parsePugdocComment(comment);
// add number of captured blocks
if (meta.capture <= 0) {
return undefined;
}
let capture = 2;
if (meta.capture) {
if (meta.capture === CAPTURE_ALL) {
capture = Infinity;
} else if (meta.capture === CAPTURE_SECTION) {
capture = Infinity;
} else {
capture = meta.capture + 1;
}
}
// get all code blocks
let code = getCodeBlock.byLine(templateSrc, lineIndex + 1, capture);
// make string
if (Array.isArray(code)) {
// remove comment
code.shift();
// join all code
code = code.join("\n");
} else {
return undefined;
}
// filter out all but current pugdoc section
if (meta.capture === CAPTURE_SECTION) {
const nextPugDocIndex = code.indexOf(DOC_STRING);
if (nextPugDocIndex > -1) {
code = code.substr(0, nextPugDocIndex);
}
}
// if no code and no comment, skip
if (comment.match(DOC_REGEX) && code === "") {
return undefined;
}
return {
lineNumber: lineIndex + 1,
comment: comment,
code: code,
};
})
// Remove skiped lines
.filter(function (result) {
return result !== undefined;
})
);
}
/**
* Returns all pugdocDocuments for the given code
*
* @param templateSrc {string}
* @param filename {string}
*/
function getPugdocDocuments(templateSrc, filename, locals) {
return extractPugdocBlocks(templateSrc).map(function (pugdocBlock) {
const meta = parsePugdocComment(pugdocBlock.comment);
const fragments = [];
// parse jsdoc style arguments list
if (meta.arguments) {
meta.arguments = meta.arguments.map(function (arg) {
return pugdocArguments.parse(arg, true);
});
}
// parse jsdoc style attributes list
if (meta.attributes) {
meta.attributes = meta.attributes.map(function (arg) {
return pugdocArguments.parse(arg, true);
});
}
let source = pugdocBlock.code;
source = source.replace(/\u2028|\u200B/g, "");
if (meta.example && meta.example !== false) {
if (meta.beforeEach) {
meta.example = `${meta.beforeEach}\n${meta.example}`;
}
if (meta.afterEach) {
meta.example = `${meta.example}\n${meta.afterEach}`;
}
}
// get example objects and add them to parent example
// also return them as separate pugdoc blocks
if (meta.examples) {
for (let i = 0, l = meta.examples.length; i < l; ++i) {
let x = meta.examples[i];
// do nothing for simple examples
if (typeof x === "string") {
if (meta.beforeEach) {
meta.examples[i] = `${meta.beforeEach}\n${x}`;
}
if (meta.afterEach) {
meta.examples[i] = `${x}\n${meta.afterEach}`;
}
continue;
}
if (meta.beforeEach && typeof x.beforeEach === "undefined") {
x.example = `${meta.beforeEach}\n${x.example}`;
}
if (meta.afterEach && typeof x.afterEach === "undefined") {
x.example = `${x.example}\n${meta.afterEach}`;
}
// merge example/examples with parent examples
meta.examples[i] = getExamples(x).reduce(
(acc, val) => acc.concat(val),
[]
);
// add fragments
fragments.push(x);
}
meta.examples = meta.examples.reduce((acc, val) => acc.concat(val), []);
}
// fix pug compilation for boolean use of example
const exampleClone = meta.example;
if (typeof meta.example === "boolean") {
meta.example = "";
}
const obj = {
// get meta
meta: meta,
// add file path
file: path.relative(".", filename),
// get pug code block matching the comments indent
source: source,
// get html output
output: compilePug(source, meta, filename, locals),
};
// remove output if example = false
if (exampleClone === false) {
obj.output = null;
}
// add fragments
if (fragments && fragments.length) {
obj.fragments = fragments.map((subexample) => {
return {
// get meta
meta: subexample,
// get html output
output: compilePug(source, subexample, filename, locals),
};
});
}
if (obj.output || obj.fragments) {
return obj;
}
return null;
});
}
/**
* Extract pug attributes from comment block
*/
function parsePugdocComment(comment) {
// remove first line (@pugdoc)
if (comment.indexOf("\n") === -1) {
return {};
}
comment = comment.substr(comment.indexOf("\n"));
comment = pugdocArguments.escapeArgumentsYAML(comment, "arguments");
comment = pugdocArguments.escapeArgumentsYAML(comment, "attributes");
// parse YAML
return YAML.safeLoad(comment) || {};
}
/**
* get all examples from the meta object
* either one or both of meta.example and meta.examples can be given
*/
function | (meta) {
let examples = [];
if (meta.example) {
examples = examples.concat(meta.example);
}
if (meta.examples) {
examples = examples.concat(meta.examples);
}
return examples;
}
/**
* Compile Pug
*/
function compilePug(src, meta, filename, locals) {
let newSrc = [src];
// add example calls
getExamples(meta).forEach(function (example, i) {
// append to pug if it's a mixin example
if (MIXIN_NAME_REGEX.test(src)) {
newSrc.push(example);
// replace example block with src
} else {
if (i === 0) {
newSrc = [];
}
const lines = example.split("\n");
lines.forEach(function (line) {
if (line.trim() === EXAMPLE_BLOCK) {
const indent = detectIndent(line).indent.length;
line = rebaseIndent(src.split("\n"), indent).join("\n");
}
newSrc.push(line);
});
}
});
newSrc = newSrc.join("\n");
locals = Object.assign({}, locals, meta.locals);
// compile pug
const compiled = pug.compileClient(newSrc, {
name: "tmp",
externalRuntime: true,
filename: filename,
});
try {
const templateFunc = pugRuntimeWrap(compiled, "tmp");
return templateFunc(locals || {});
} catch (err) {
try {
const compiledDebug = pug.compileClient(newSrc, {
name: "tmp",
externalRuntime: true,
filename: filename,
compileDebug: true,
});
const templateFuncDebug = pugRuntimeWrap(compiledDebug, "tmp");
templateFuncDebug(locals || {});
} catch (debugErr) {
process.stderr.write(
`\n\nPug-doc error: ${JSON.stringify(meta, null, 2)}`
);
process.stderr.write(`\n\n${debugErr.toString()}`);
return null;
}
}
}
// Exports
module.exports = {
extractPugdocBlocks: extractPugdocBlocks,
getPugdocDocuments: getPugdocDocuments,
parsePugdocComment: parsePugdocComment,
getExamples: getExamples,
};
| getExamples | identifier_name |
parser.js | const pug = require("pug");
const pugRuntimeWrap = require("pug-runtime/wrap");
const path = require("path");
const YAML = require("js-yaml");
const getCodeBlock = require("pug-code-block");
const detectIndent = require("detect-indent");
const rebaseIndent = require("rebase-indent");
const pugdocArguments = require("./arguments");
const MIXIN_NAME_REGEX = /^mixin +([-\w]+)?/;
const DOC_REGEX = /^\s*\/\/-\s+?\@pugdoc\s*$/;
const DOC_STRING = "//- @pugdoc";
const CAPTURE_ALL = "all";
const CAPTURE_SECTION = "section";
const EXAMPLE_BLOCK = "block";
/**
* Returns all pugdoc comment and code blocks for the given code
*
* @param templateSrc {string}
* @return {{lineNumber: number, comment: string, code: string}[]}
*/
function extractPugdocBlocks(templateSrc) |
let capture = 2;
if (meta.capture) {
if (meta.capture === CAPTURE_ALL) {
capture = Infinity;
} else if (meta.capture === CAPTURE_SECTION) {
capture = Infinity;
} else {
capture = meta.capture + 1;
}
}
// get all code blocks
let code = getCodeBlock.byLine(templateSrc, lineIndex + 1, capture);
// make string
if (Array.isArray(code)) {
// remove comment
code.shift();
// join all code
code = code.join("\n");
} else {
return undefined;
}
// filter out all but current pugdoc section
if (meta.capture === CAPTURE_SECTION) {
const nextPugDocIndex = code.indexOf(DOC_STRING);
if (nextPugDocIndex > -1) {
code = code.substr(0, nextPugDocIndex);
}
}
// if no code and no comment, skip
if (comment.match(DOC_REGEX) && code === "") {
return undefined;
}
return {
lineNumber: lineIndex + 1,
comment: comment,
code: code,
};
})
// Remove skiped lines
.filter(function (result) {
return result !== undefined;
})
);
}
/**
* Returns all pugdocDocuments for the given code
*
* @param templateSrc {string}
* @param filename {string}
*/
function getPugdocDocuments(templateSrc, filename, locals) {
return extractPugdocBlocks(templateSrc).map(function (pugdocBlock) {
const meta = parsePugdocComment(pugdocBlock.comment);
const fragments = [];
// parse jsdoc style arguments list
if (meta.arguments) {
meta.arguments = meta.arguments.map(function (arg) {
return pugdocArguments.parse(arg, true);
});
}
// parse jsdoc style attributes list
if (meta.attributes) {
meta.attributes = meta.attributes.map(function (arg) {
return pugdocArguments.parse(arg, true);
});
}
let source = pugdocBlock.code;
source = source.replace(/\u2028|\u200B/g, "");
if (meta.example && meta.example !== false) {
if (meta.beforeEach) {
meta.example = `${meta.beforeEach}\n${meta.example}`;
}
if (meta.afterEach) {
meta.example = `${meta.example}\n${meta.afterEach}`;
}
}
// get example objects and add them to parent example
// also return them as separate pugdoc blocks
if (meta.examples) {
for (let i = 0, l = meta.examples.length; i < l; ++i) {
let x = meta.examples[i];
// do nothing for simple examples
if (typeof x === "string") {
if (meta.beforeEach) {
meta.examples[i] = `${meta.beforeEach}\n${x}`;
}
if (meta.afterEach) {
meta.examples[i] = `${x}\n${meta.afterEach}`;
}
continue;
}
if (meta.beforeEach && typeof x.beforeEach === "undefined") {
x.example = `${meta.beforeEach}\n${x.example}`;
}
if (meta.afterEach && typeof x.afterEach === "undefined") {
x.example = `${x.example}\n${meta.afterEach}`;
}
// merge example/examples with parent examples
meta.examples[i] = getExamples(x).reduce(
(acc, val) => acc.concat(val),
[]
);
// add fragments
fragments.push(x);
}
meta.examples = meta.examples.reduce((acc, val) => acc.concat(val), []);
}
// fix pug compilation for boolean use of example
const exampleClone = meta.example;
if (typeof meta.example === "boolean") {
meta.example = "";
}
const obj = {
// get meta
meta: meta,
// add file path
file: path.relative(".", filename),
// get pug code block matching the comments indent
source: source,
// get html output
output: compilePug(source, meta, filename, locals),
};
// remove output if example = false
if (exampleClone === false) {
obj.output = null;
}
// add fragments
if (fragments && fragments.length) {
obj.fragments = fragments.map((subexample) => {
return {
// get meta
meta: subexample,
// get html output
output: compilePug(source, subexample, filename, locals),
};
});
}
if (obj.output || obj.fragments) {
return obj;
}
return null;
});
}
/**
* Extract pug attributes from comment block
*/
function parsePugdocComment(comment) {
// remove first line (@pugdoc)
if (comment.indexOf("\n") === -1) {
return {};
}
comment = comment.substr(comment.indexOf("\n"));
comment = pugdocArguments.escapeArgumentsYAML(comment, "arguments");
comment = pugdocArguments.escapeArgumentsYAML(comment, "attributes");
// parse YAML
return YAML.safeLoad(comment) || {};
}
/**
* get all examples from the meta object
* either one or both of meta.example and meta.examples can be given
*/
function getExamples(meta) {
let examples = [];
if (meta.example) {
examples = examples.concat(meta.example);
}
if (meta.examples) {
examples = examples.concat(meta.examples);
}
return examples;
}
/**
* Compile Pug
*/
function compilePug(src, meta, filename, locals) {
let newSrc = [src];
// add example calls
getExamples(meta).forEach(function (example, i) {
// append to pug if it's a mixin example
if (MIXIN_NAME_REGEX.test(src)) {
newSrc.push(example);
// replace example block with src
} else {
if (i === 0) {
newSrc = [];
}
const lines = example.split("\n");
lines.forEach(function (line) {
if (line.trim() === EXAMPLE_BLOCK) {
const indent = detectIndent(line).indent.length;
line = rebaseIndent(src.split("\n"), indent).join("\n");
}
newSrc.push(line);
});
}
});
newSrc = newSrc.join("\n");
locals = Object.assign({}, locals, meta.locals);
// compile pug
const compiled = pug.compileClient(newSrc, {
name: "tmp",
externalRuntime: true,
filename: filename,
});
try {
const templateFunc = pugRuntimeWrap(compiled, "tmp");
return templateFunc(locals || {});
} catch (err) {
try {
const compiledDebug = pug.compileClient(newSrc, {
name: "tmp",
externalRuntime: true,
filename: filename,
compileDebug: true,
});
const templateFuncDebug = pugRuntimeWrap(compiledDebug, "tmp");
templateFuncDebug(locals || {});
} catch (debugErr) {
process.stderr.write(
`\n\nPug-doc error: ${JSON.stringify(meta, null, 2)}`
);
process.stderr.write(`\n\n${debugErr.toString()}`);
return null;
}
}
}
// Exports
module.exports = {
extractPugdocBlocks: extractPugdocBlocks,
getPugdocDocuments: getPugdocDocuments,
parsePugdocComment: parsePugdocComment,
getExamples: getExamples,
};
| {
return (
templateSrc
.split("\n")
// Walk through every line and look for a pugdoc comment
.map(function (line, lineIndex) {
// If the line does not contain a pugdoc comment skip it
if (!line.match(DOC_REGEX)) {
return undefined;
}
// If the line contains a pugdoc comment return
// the comment block and the next code block
const comment = getCodeBlock.byLine(templateSrc, lineIndex + 1);
const meta = parsePugdocComment(comment);
// add number of captured blocks
if (meta.capture <= 0) {
return undefined;
} | identifier_body |
parser.js | const pug = require("pug");
const pugRuntimeWrap = require("pug-runtime/wrap");
const path = require("path");
const YAML = require("js-yaml");
const getCodeBlock = require("pug-code-block");
const detectIndent = require("detect-indent");
const rebaseIndent = require("rebase-indent");
const pugdocArguments = require("./arguments");
const MIXIN_NAME_REGEX = /^mixin +([-\w]+)?/;
const DOC_REGEX = /^\s*\/\/-\s+?\@pugdoc\s*$/;
const DOC_STRING = "//- @pugdoc";
const CAPTURE_ALL = "all";
const CAPTURE_SECTION = "section";
const EXAMPLE_BLOCK = "block";
/**
* Returns all pugdoc comment and code blocks for the given code
*
* @param templateSrc {string}
* @return {{lineNumber: number, comment: string, code: string}[]}
*/
function extractPugdocBlocks(templateSrc) {
return (
templateSrc
.split("\n")
// Walk through every line and look for a pugdoc comment
.map(function (line, lineIndex) {
// If the line does not contain a pugdoc comment skip it
if (!line.match(DOC_REGEX)) {
return undefined;
}
// If the line contains a pugdoc comment return
// the comment block and the next code block
const comment = getCodeBlock.byLine(templateSrc, lineIndex + 1);
const meta = parsePugdocComment(comment);
// add number of captured blocks
if (meta.capture <= 0) {
return undefined;
}
let capture = 2;
if (meta.capture) {
if (meta.capture === CAPTURE_ALL) {
capture = Infinity;
} else if (meta.capture === CAPTURE_SECTION) {
capture = Infinity;
} else {
capture = meta.capture + 1;
}
}
// get all code blocks
let code = getCodeBlock.byLine(templateSrc, lineIndex + 1, capture);
// make string
if (Array.isArray(code)) {
// remove comment
code.shift();
// join all code
code = code.join("\n");
} else {
return undefined;
}
// filter out all but current pugdoc section
if (meta.capture === CAPTURE_SECTION) {
const nextPugDocIndex = code.indexOf(DOC_STRING);
if (nextPugDocIndex > -1) {
code = code.substr(0, nextPugDocIndex);
}
}
// if no code and no comment, skip
if (comment.match(DOC_REGEX) && code === "") {
return undefined;
}
return {
lineNumber: lineIndex + 1,
comment: comment,
code: code,
};
})
// Remove skiped lines
.filter(function (result) {
return result !== undefined;
})
);
}
/**
* Returns all pugdocDocuments for the given code
*
* @param templateSrc {string}
* @param filename {string}
*/
function getPugdocDocuments(templateSrc, filename, locals) {
return extractPugdocBlocks(templateSrc).map(function (pugdocBlock) {
const meta = parsePugdocComment(pugdocBlock.comment);
const fragments = [];
// parse jsdoc style arguments list
if (meta.arguments) {
meta.arguments = meta.arguments.map(function (arg) {
return pugdocArguments.parse(arg, true);
});
}
// parse jsdoc style attributes list
if (meta.attributes) {
meta.attributes = meta.attributes.map(function (arg) {
return pugdocArguments.parse(arg, true);
});
}
let source = pugdocBlock.code;
source = source.replace(/\u2028|\u200B/g, "");
if (meta.example && meta.example !== false) {
if (meta.beforeEach) {
meta.example = `${meta.beforeEach}\n${meta.example}`;
}
if (meta.afterEach) {
meta.example = `${meta.example}\n${meta.afterEach}`;
}
}
// get example objects and add them to parent example
// also return them as separate pugdoc blocks
if (meta.examples) {
for (let i = 0, l = meta.examples.length; i < l; ++i) {
let x = meta.examples[i];
// do nothing for simple examples
if (typeof x === "string") {
if (meta.beforeEach) {
meta.examples[i] = `${meta.beforeEach}\n${x}`;
}
if (meta.afterEach) {
meta.examples[i] = `${x}\n${meta.afterEach}`;
}
continue;
}
if (meta.beforeEach && typeof x.beforeEach === "undefined") {
x.example = `${meta.beforeEach}\n${x.example}`;
}
if (meta.afterEach && typeof x.afterEach === "undefined") {
x.example = `${x.example}\n${meta.afterEach}`;
}
// merge example/examples with parent examples
meta.examples[i] = getExamples(x).reduce(
(acc, val) => acc.concat(val),
[]
);
// add fragments
fragments.push(x);
}
meta.examples = meta.examples.reduce((acc, val) => acc.concat(val), []);
}
// fix pug compilation for boolean use of example
const exampleClone = meta.example;
if (typeof meta.example === "boolean") {
meta.example = "";
}
const obj = {
// get meta
meta: meta,
// add file path
file: path.relative(".", filename),
// get pug code block matching the comments indent
source: source,
// get html output
output: compilePug(source, meta, filename, locals),
};
// remove output if example = false
if (exampleClone === false) {
obj.output = null;
}
// add fragments
if (fragments && fragments.length) {
obj.fragments = fragments.map((subexample) => {
return {
// get meta
meta: subexample,
// get html output
output: compilePug(source, subexample, filename, locals),
};
});
}
if (obj.output || obj.fragments) {
return obj;
}
return null; | /**
* Extract pug attributes from comment block
*/
function parsePugdocComment(comment) {
// remove first line (@pugdoc)
if (comment.indexOf("\n") === -1) {
return {};
}
comment = comment.substr(comment.indexOf("\n"));
comment = pugdocArguments.escapeArgumentsYAML(comment, "arguments");
comment = pugdocArguments.escapeArgumentsYAML(comment, "attributes");
// parse YAML
return YAML.safeLoad(comment) || {};
}
/**
* get all examples from the meta object
* either one or both of meta.example and meta.examples can be given
*/
function getExamples(meta) {
let examples = [];
if (meta.example) {
examples = examples.concat(meta.example);
}
if (meta.examples) {
examples = examples.concat(meta.examples);
}
return examples;
}
/**
* Compile Pug
*/
function compilePug(src, meta, filename, locals) {
let newSrc = [src];
// add example calls
getExamples(meta).forEach(function (example, i) {
// append to pug if it's a mixin example
if (MIXIN_NAME_REGEX.test(src)) {
newSrc.push(example);
// replace example block with src
} else {
if (i === 0) {
newSrc = [];
}
const lines = example.split("\n");
lines.forEach(function (line) {
if (line.trim() === EXAMPLE_BLOCK) {
const indent = detectIndent(line).indent.length;
line = rebaseIndent(src.split("\n"), indent).join("\n");
}
newSrc.push(line);
});
}
});
newSrc = newSrc.join("\n");
locals = Object.assign({}, locals, meta.locals);
// compile pug
const compiled = pug.compileClient(newSrc, {
name: "tmp",
externalRuntime: true,
filename: filename,
});
try {
const templateFunc = pugRuntimeWrap(compiled, "tmp");
return templateFunc(locals || {});
} catch (err) {
try {
const compiledDebug = pug.compileClient(newSrc, {
name: "tmp",
externalRuntime: true,
filename: filename,
compileDebug: true,
});
const templateFuncDebug = pugRuntimeWrap(compiledDebug, "tmp");
templateFuncDebug(locals || {});
} catch (debugErr) {
process.stderr.write(
`\n\nPug-doc error: ${JSON.stringify(meta, null, 2)}`
);
process.stderr.write(`\n\n${debugErr.toString()}`);
return null;
}
}
}
// Exports
module.exports = {
extractPugdocBlocks: extractPugdocBlocks,
getPugdocDocuments: getPugdocDocuments,
parsePugdocComment: parsePugdocComment,
getExamples: getExamples,
}; | });
}
| random_line_split |
theodolite.module.ts | import { NgModule } from '@angular/core';
import { TheodoliteComponent } from './theodolite/theodolite.component';
import { MarkdownSlideComponent } from './slide/markdown/markdownSlide.component';
import { CodeSlideComponent } from './slide/code/codeSlide.component';
import { PresentationComponent } from './presentation/presentation.component';
import { MarkdownService } from './markdown/markdown.service';
import { ParseService } from './parse/parse.service';
import { BrowserModule } from '@angular/platform-browser';
import { ControlsComponent } from './controls/controls.component';
import { AboutComponent } from './about/about.component';
import { ModalComponent } from './modal/modal.component';
import { SlideComponent } from './slide/slide.component';
import { DefaultValuePipe } from './common/default.pipe';
import { HighlightService } from './highlight/highlight.service';
import { EventsService } from './events/events.service';
import { ProgressComponent } from './progress/progress.component';
import { HmsPipe } from "./common/hms.pipe";
import {TimerComponent} from "./timer/timer.component";
import {PugSlideComponent} from "./slide/pug/pugSlide.component";
@NgModule({
imports: [ BrowserModule ],
declarations: [ TheodoliteComponent, PresentationComponent, SlideComponent, MarkdownSlideComponent,
CodeSlideComponent, ControlsComponent, AboutComponent, ModalComponent, DefaultValuePipe,
ProgressComponent, HmsPipe, TimerComponent, PugSlideComponent ],
bootstrap: [ TheodoliteComponent ],
providers: [ EventsService, HighlightService, MarkdownService, ParseService ]
})
export class TheodoliteModule {
| () {
}
} | constructor | identifier_name |
theodolite.module.ts | import { NgModule } from '@angular/core';
import { TheodoliteComponent } from './theodolite/theodolite.component';
import { MarkdownSlideComponent } from './slide/markdown/markdownSlide.component';
import { CodeSlideComponent } from './slide/code/codeSlide.component';
import { PresentationComponent } from './presentation/presentation.component';
import { MarkdownService } from './markdown/markdown.service';
import { ParseService } from './parse/parse.service';
import { BrowserModule } from '@angular/platform-browser';
import { ControlsComponent } from './controls/controls.component';
import { AboutComponent } from './about/about.component';
import { ModalComponent } from './modal/modal.component';
import { SlideComponent } from './slide/slide.component';
import { DefaultValuePipe } from './common/default.pipe';
import { HighlightService } from './highlight/highlight.service';
import { EventsService } from './events/events.service';
import { ProgressComponent } from './progress/progress.component';
import { HmsPipe } from "./common/hms.pipe";
import {TimerComponent} from "./timer/timer.component";
import {PugSlideComponent} from "./slide/pug/pugSlide.component";
@NgModule({
imports: [ BrowserModule ],
declarations: [ TheodoliteComponent, PresentationComponent, SlideComponent, MarkdownSlideComponent,
CodeSlideComponent, ControlsComponent, AboutComponent, ModalComponent, DefaultValuePipe,
ProgressComponent, HmsPipe, TimerComponent, PugSlideComponent ],
bootstrap: [ TheodoliteComponent ],
providers: [ EventsService, HighlightService, MarkdownService, ParseService ]
})
export class TheodoliteModule {
constructor() |
} | {
} | identifier_body |
theodolite.module.ts | import { NgModule } from '@angular/core';
import { TheodoliteComponent } from './theodolite/theodolite.component'; | import { BrowserModule } from '@angular/platform-browser';
import { ControlsComponent } from './controls/controls.component';
import { AboutComponent } from './about/about.component';
import { ModalComponent } from './modal/modal.component';
import { SlideComponent } from './slide/slide.component';
import { DefaultValuePipe } from './common/default.pipe';
import { HighlightService } from './highlight/highlight.service';
import { EventsService } from './events/events.service';
import { ProgressComponent } from './progress/progress.component';
import { HmsPipe } from "./common/hms.pipe";
import {TimerComponent} from "./timer/timer.component";
import {PugSlideComponent} from "./slide/pug/pugSlide.component";
@NgModule({
imports: [ BrowserModule ],
declarations: [ TheodoliteComponent, PresentationComponent, SlideComponent, MarkdownSlideComponent,
CodeSlideComponent, ControlsComponent, AboutComponent, ModalComponent, DefaultValuePipe,
ProgressComponent, HmsPipe, TimerComponent, PugSlideComponent ],
bootstrap: [ TheodoliteComponent ],
providers: [ EventsService, HighlightService, MarkdownService, ParseService ]
})
export class TheodoliteModule {
constructor() {
}
} | import { MarkdownSlideComponent } from './slide/markdown/markdownSlide.component';
import { CodeSlideComponent } from './slide/code/codeSlide.component';
import { PresentationComponent } from './presentation/presentation.component';
import { MarkdownService } from './markdown/markdown.service';
import { ParseService } from './parse/parse.service'; | random_line_split |
Problem_37.py | __author__ = 'Meemaw'
import math
def | (stevilo):
if stevilo == 1:
return 0
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[i:]))) != 1:
return False
return True
def izDesne(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[0:len(stevilo)-i]))) != 1:
return False
return True
numOfPrimes = 0
vsota = 0
poglej = 11
while numOfPrimes != 11:
string = str(poglej)
if izDesne(string) and izLeve(string):
numOfPrimes+=1
vsota+=poglej
poglej+=1
print("Sum of the only eleven primes that are trunctable from left to right and right to left is:")
print(vsota) | isPrime | identifier_name |
Problem_37.py | __author__ = 'Meemaw'
import math
def isPrime(stevilo):
if stevilo == 1:
|
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[i:]))) != 1:
return False
return True
def izDesne(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[0:len(stevilo)-i]))) != 1:
return False
return True
numOfPrimes = 0
vsota = 0
poglej = 11
while numOfPrimes != 11:
string = str(poglej)
if izDesne(string) and izLeve(string):
numOfPrimes+=1
vsota+=poglej
poglej+=1
print("Sum of the only eleven primes that are trunctable from left to right and right to left is:")
print(vsota) | return 0 | conditional_block |
Problem_37.py | __author__ = 'Meemaw'
import math
def isPrime(stevilo):
|
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[i:]))) != 1:
return False
return True
def izDesne(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[0:len(stevilo)-i]))) != 1:
return False
return True
numOfPrimes = 0
vsota = 0
poglej = 11
while numOfPrimes != 11:
string = str(poglej)
if izDesne(string) and izLeve(string):
numOfPrimes+=1
vsota+=poglej
poglej+=1
print("Sum of the only eleven primes that are trunctable from left to right and right to left is:")
print(vsota) | if stevilo == 1:
return 0
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1 | identifier_body |
Problem_37.py | __author__ = 'Meemaw'
import math
def isPrime(stevilo):
if stevilo == 1:
return 0 | if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[i:]))) != 1:
return False
return True
def izDesne(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[0:len(stevilo)-i]))) != 1:
return False
return True
numOfPrimes = 0
vsota = 0
poglej = 11
while numOfPrimes != 11:
string = str(poglej)
if izDesne(string) and izLeve(string):
numOfPrimes+=1
vsota+=poglej
poglej+=1
print("Sum of the only eleven primes that are trunctable from left to right and right to left is:")
print(vsota) | meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2): | random_line_split |
make_single_pages.py | import os
import internetarchive
folder = 'pages'
def | (book, item, filepattern, start, steps, finish):
if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book):
os.makedirs(os.getcwd() + os.sep + folder + os.sep + book)
session = internetarchive.ArchiveSession()
re_item = session.get_item(item)
list_of_pages = range(start, finish + steps, steps)
for idx, i in enumerate(list_of_pages):
print('Band: {}, Seite:{}/{}, {}'.format(book, idx, len(list_of_pages), filepattern.format(i)))
file_on_harddisk = os.getcwd() + os.sep + folder + os.sep + book + os.sep + '{0:04d}.png'.format(i)
if not os.path.isfile(file_on_harddisk):
try:
re_file = re_item.get_file(filepattern.format(i))
re_file.download(file_on_harddisk, silent=True)
except:
print('{} is not an item'.format(filepattern.format(i)))
def make_single_pages():
if not os.path.exists(os.getcwd() + os.sep + folder):
os.makedirs(os.getcwd() + os.sep + folder)
from_IA(book='I,1', item='PWRE01-02', filepattern='Pauly-Wissowa_I1_{0:04d}.png', start=1, steps=2, finish=1439)
from_IA(book='I,2', item='PWRE01-02', filepattern='Pauly-Wissowa_I2_{0:04d}.png', start=1441, steps=2, finish=2901)
if __name__ == "__main__":
make_single_pages()
| from_IA | identifier_name |
make_single_pages.py | import os
import internetarchive
folder = 'pages'
def from_IA(book, item, filepattern, start, steps, finish):
if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book):
os.makedirs(os.getcwd() + os.sep + folder + os.sep + book)
session = internetarchive.ArchiveSession()
re_item = session.get_item(item)
list_of_pages = range(start, finish + steps, steps)
for idx, i in enumerate(list_of_pages):
print('Band: {}, Seite:{}/{}, {}'.format(book, idx, len(list_of_pages), filepattern.format(i)))
file_on_harddisk = os.getcwd() + os.sep + folder + os.sep + book + os.sep + '{0:04d}.png'.format(i)
if not os.path.isfile(file_on_harddisk):
try:
re_file = re_item.get_file(filepattern.format(i))
re_file.download(file_on_harddisk, silent=True)
except:
print('{} is not an item'.format(filepattern.format(i)))
def make_single_pages():
if not os.path.exists(os.getcwd() + os.sep + folder):
os.makedirs(os.getcwd() + os.sep + folder)
from_IA(book='I,1', item='PWRE01-02', filepattern='Pauly-Wissowa_I1_{0:04d}.png', start=1, steps=2, finish=1439)
from_IA(book='I,2', item='PWRE01-02', filepattern='Pauly-Wissowa_I2_{0:04d}.png', start=1441, steps=2, finish=2901)
if __name__ == "__main__":
| make_single_pages() | conditional_block |
|
make_single_pages.py | import os
import internetarchive
folder = 'pages'
def from_IA(book, item, filepattern, start, steps, finish):
|
def make_single_pages():
if not os.path.exists(os.getcwd() + os.sep + folder):
os.makedirs(os.getcwd() + os.sep + folder)
from_IA(book='I,1', item='PWRE01-02', filepattern='Pauly-Wissowa_I1_{0:04d}.png', start=1, steps=2, finish=1439)
from_IA(book='I,2', item='PWRE01-02', filepattern='Pauly-Wissowa_I2_{0:04d}.png', start=1441, steps=2, finish=2901)
if __name__ == "__main__":
make_single_pages()
| if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book):
os.makedirs(os.getcwd() + os.sep + folder + os.sep + book)
session = internetarchive.ArchiveSession()
re_item = session.get_item(item)
list_of_pages = range(start, finish + steps, steps)
for idx, i in enumerate(list_of_pages):
print('Band: {}, Seite:{}/{}, {}'.format(book, idx, len(list_of_pages), filepattern.format(i)))
file_on_harddisk = os.getcwd() + os.sep + folder + os.sep + book + os.sep + '{0:04d}.png'.format(i)
if not os.path.isfile(file_on_harddisk):
try:
re_file = re_item.get_file(filepattern.format(i))
re_file.download(file_on_harddisk, silent=True)
except:
print('{} is not an item'.format(filepattern.format(i))) | identifier_body |
make_single_pages.py | import os
import internetarchive
folder = 'pages'
def from_IA(book, item, filepattern, start, steps, finish):
if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book):
os.makedirs(os.getcwd() + os.sep + folder + os.sep + book)
session = internetarchive.ArchiveSession()
re_item = session.get_item(item)
list_of_pages = range(start, finish + steps, steps)
for idx, i in enumerate(list_of_pages):
print('Band: {}, Seite:{}/{}, {}'.format(book, idx, len(list_of_pages), filepattern.format(i)))
file_on_harddisk = os.getcwd() + os.sep + folder + os.sep + book + os.sep + '{0:04d}.png'.format(i)
if not os.path.isfile(file_on_harddisk): | except:
print('{} is not an item'.format(filepattern.format(i)))
def make_single_pages():
if not os.path.exists(os.getcwd() + os.sep + folder):
os.makedirs(os.getcwd() + os.sep + folder)
from_IA(book='I,1', item='PWRE01-02', filepattern='Pauly-Wissowa_I1_{0:04d}.png', start=1, steps=2, finish=1439)
from_IA(book='I,2', item='PWRE01-02', filepattern='Pauly-Wissowa_I2_{0:04d}.png', start=1441, steps=2, finish=2901)
if __name__ == "__main__":
make_single_pages() | try:
re_file = re_item.get_file(filepattern.format(i))
re_file.download(file_on_harddisk, silent=True) | random_line_split |
dragon.rs | , /*exp*/ i16) {
// the number `v` to format is known to be:
// - equal to `mant * 2^exp`;
// - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and
// - followed by `(mant + 2 * plus) * 2^exp` in the original type.
//
// obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.)
// also we assume that at least one digit is generated, i.e. `mant` cannot be zero too.
//
// this also means that any number between `low = (mant - minus) * 2^exp` and
// `high = (mant + plus) * 2^exp` will map to this exact floating point number,
// with bounds included when the original mantissa was even (i.e. `!mant_was_odd`).
assert!(d.mant > 0);
assert!(d.minus > 0);
assert!(d.plus > 0);
assert!(d.mant.checked_add(d.plus).is_some());
assert!(d.mant.checked_sub(d.minus).is_some());
assert!(buf.len() >= MAX_SIG_DIGITS);
// `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}`
let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal};
// estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`.
// the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later.
let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp);
// convert `{mant, plus, minus} * 2^exp` into the fractional form so that:
// - `v = mant / scale`
// - `low = (mant - minus) / scale`
// - `high = (mant + plus) / scale`
let mut mant = Big::from_u64(d.mant);
let mut minus = Big::from_u64(d.minus);
let mut plus = Big::from_u64(d.plus);
let mut scale = Big::from_small(1);
if d.exp < 0 {
scale.mul_pow2(-d.exp as usize);
} else {
mant.mul_pow2(d.exp as usize);
minus.mul_pow2(d.exp as usize);
plus.mul_pow2(d.exp as usize);
}
// divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
if k >= 0 {
mul_pow10(&mut scale, k as usize);
} else {
mul_pow10(&mut mant, -k as usize);
mul_pow10(&mut minus, -k as usize);
mul_pow10(&mut plus, -k as usize);
}
// fixup when `mant + plus > scale` (or `>=`).
// we are not actually modifying `scale`, since we can skip the initial multiplication instead.
// now `scale < mant + plus <= scale * 10` and we are ready to generate digits.
//
// note that `d[0]` *can* be zero, when `scale - plus < mant < scale`.
// in this case rounding-up condition (`up` below) will be triggered immediately.
if scale.cmp(mant.clone().add(&plus)) < rounding {
// equivalent to scaling `scale` by 10
k += 1;
} else {
mant.mul_small(10);
minus.mul_small(10);
plus.mul_small(10);
}
// cache `(2, 4, 8) * scale` for digit generation.
let mut scale2 = scale.clone(); scale2.mul_pow2(1);
let mut scale4 = scale.clone(); scale4.mul_pow2(2);
let mut scale8 = scale.clone(); scale8.mul_pow2(3);
let mut down;
let mut up;
let mut i = 0;
loop {
// invariants, where `d[0..n-1]` are digits generated so far:
// - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)`
// - `v - low = minus / scale * 10^(k-n-1)`
// - `high - v = plus / scale * 10^(k-n-1)`
// - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`)
// where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) + ... + d[j-1] * 10 + d[j]`.
// generate one digit: `d[n] = floor(mant / scale) < 10`.
let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8);
debug_assert!(d < 10);
buf[i] = b'0' + d;
i += 1;
// this is a simplified description of the modified Dragon algorithm.
// many intermediate derivations and completeness arguments are omitted for convenience.
//
// start with modified invariants, as we've updated `n`:
// - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)`
// - `v - low = minus / scale * 10^(k-n)`
// - `high - v = plus / scale * 10^(k-n)`
//
// assume that `d[0..n-1]` is the shortest representation between `low` and `high`,
// i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't:
// - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and
// - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct).
//
// the second condition simplifies to `2 * mant <= scale`.
// solving invariants in terms of `mant`, `low` and `high` yields
// a simpler version of the first condition: `-plus < mant < minus`.
// since `-plus < 0 <= mant`, we have the correct shortest representation
// when `mant < minus` and `2 * mant <= scale`.
// (the former becomes `mant <= minus` when the original mantissa is even.)
//
// when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit.
// this is enough for restoring that condition: we already know that
// the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`.
// in this case, the first condition becomes `-plus < mant - scale < minus`.
// since `mant < scale` after the generation, we have `scale < mant + plus`.
// (again, this becomes `scale <= mant + plus` when the original mantissa is even.)
//
// in short:
// - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`).
// - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`).
// - keep generating otherwise.
down = mant.cmp(&minus) < rounding;
up = scale.cmp(mant.clone().add(&plus)) < rounding;
if down || up { break; } // we have the shortest representation, proceed to the rounding
// restore the invariants.
// this makes the algorithm always terminating: `minus` and `plus` always increases,
// but `mant` is clipped modulo `scale` and `scale` is fixed.
mant.mul_small(10);
minus.mul_small(10);
plus.mul_small(10);
}
// rounding up happens when
// i) only the rounding-up condition was triggered, or
// ii) both conditions were triggered and tie breaking prefers rounding up.
if up && (!down || *mant.mul_pow2(1) >= scale) {
// if rounding up changes the length, the exponent should also change.
// it seems that this condition is very hard to satisfy (possibly impossible),
// but we are just being safe and consistent here.
if let Some(c) = round_up(buf, i) {
buf[i] = c;
i += 1;
k += 1;
}
}
(i, k)
}
/// The exact and fixed mode implementation for Dragon.
pub fn | format_exact | identifier_name |
|
dragon.rs | static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03];
static POW10TO128: [Digit; 14] =
[0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08,
0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e];
static POW10TO256: [Digit; 27] =
[0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6,
0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e,
0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7];
#[doc(hidden)]
pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big {
debug_assert!(n < 512);
if n & 7 != 0 { x.mul_small(POW10[n & 7]); }
if n & 8 != 0 { x.mul_small(POW10[8]); }
if n & 16 != 0 { x.mul_digits(&POW10TO16); }
if n & 32 != 0 { x.mul_digits(&POW10TO32); }
if n & 64 != 0 { x.mul_digits(&POW10TO64); }
if n & 128 != 0 { x.mul_digits(&POW10TO128); }
if n & 256 != 0 { x.mul_digits(&POW10TO256); }
x
}
fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big {
let largest = POW10.len() - 1;
while n > largest {
x.div_rem_small(POW10[largest]);
n -= largest;
}
x.div_rem_small(TWOPOW10[n]);
x
}
// only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)`
fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big,
scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) {
let mut d = 0;
if *x >= *scale8 { x.sub(scale8); d += 8; }
if *x >= *scale4 { x.sub(scale4); d += 4; }
if *x >= *scale2 { x.sub(scale2); d += 2; }
if *x >= *scale { x.sub(scale); d += 1; }
debug_assert!(*x < *scale);
(d, x)
}
/// The shortest mode implementation for Dragon.
pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) {
// the number `v` to format is known to be:
// - equal to `mant * 2^exp`;
// - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and
// - followed by `(mant + 2 * plus) * 2^exp` in the original type.
//
// obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.)
// also we assume that at least one digit is generated, i.e. `mant` cannot be zero too.
//
// this also means that any number between `low = (mant - minus) * 2^exp` and
// `high = (mant + plus) * 2^exp` will map to this exact floating point number,
// with bounds included when the original mantissa was even (i.e. `!mant_was_odd`).
assert!(d.mant > 0);
assert!(d.minus > 0);
assert!(d.plus > 0);
assert!(d.mant.checked_add(d.plus).is_some());
assert!(d.mant.checked_sub(d.minus).is_some());
assert!(buf.len() >= MAX_SIG_DIGITS);
// `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}`
let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal};
// estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`.
// the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later.
let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp);
// convert `{mant, plus, minus} * 2^exp` into the fractional form so that:
// - `v = mant / scale`
// - `low = (mant - minus) / scale`
// - `high = (mant + plus) / scale`
let mut mant = Big::from_u64(d.mant);
let mut minus = Big::from_u64(d.minus);
let mut plus = Big::from_u64(d.plus);
let mut scale = Big::from_small(1);
if d.exp < 0 {
scale.mul_pow2(-d.exp as usize);
} else {
mant.mul_pow2(d.exp as usize);
minus.mul_pow2(d.exp as usize);
plus.mul_pow2(d.exp as usize);
}
// divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
if k >= 0 {
mul_pow10(&mut scale, k as usize);
} else {
mul_pow10(&mut mant, -k as usize);
mul_pow10(&mut minus, -k as usize);
mul_pow10(&mut plus, -k as usize);
}
// fixup when `mant + plus > scale` (or `>=`).
// we are not actually modifying `scale`, since we can skip the initial multiplication instead.
// now `scale < mant + plus <= scale * 10` and we are ready to generate digits.
//
// note that `d[0]` *can* be zero, when `scale - plus < mant < scale`.
// in this case rounding-up condition (`up` below) will be triggered immediately.
if scale.cmp(mant.clone().add(&plus)) < rounding {
// equivalent to scaling `scale` by 10
k += 1;
} else {
mant.mul_small(10);
minus.mul_small(10);
plus.mul_small(10);
}
// cache `(2, 4, 8) * scale` for digit generation.
let mut scale2 = scale.clone(); scale2.mul_pow2(1);
let mut scale4 = scale.clone(); scale4.mul_pow2(2);
let mut scale8 = scale.clone(); scale8.mul_pow2(3);
let mut down;
let mut up;
let mut i = 0;
loop {
// invariants, where `d[0..n-1]` are digits generated so far:
// - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)`
// - `v - low = minus / scale * 10^(k-n-1)`
// - `high - v = plus / scale * 1 | static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; | random_line_split |
|
dragon.rs | 1, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6,
0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e,
0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7];
#[doc(hidden)]
pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big {
debug_assert!(n < 512);
if n & 7 != 0 { x.mul_small(POW10[n & 7]); }
if n & 8 != 0 { x.mul_small(POW10[8]); }
if n & 16 != 0 { x.mul_digits(&POW10TO16); }
if n & 32 != 0 { x.mul_digits(&POW10TO32); }
if n & 64 != 0 { x.mul_digits(&POW10TO64); }
if n & 128 != 0 { x.mul_digits(&POW10TO128); }
if n & 256 != 0 { x.mul_digits(&POW10TO256); }
x
}
fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big {
let largest = POW10.len() - 1;
while n > largest {
x.div_rem_small(POW10[largest]);
n -= largest;
}
x.div_rem_small(TWOPOW10[n]);
x
}
// only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)`
fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big,
scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) {
let mut d = 0;
if *x >= *scale8 { x.sub(scale8); d += 8; }
if *x >= *scale4 { x.sub(scale4); d += 4; }
if *x >= *scale2 { x.sub(scale2); d += 2; }
if *x >= *scale { x.sub(scale); d += 1; }
debug_assert!(*x < *scale);
(d, x)
}
/// The shortest mode implementation for Dragon.
pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) | // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}`
let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal};
// estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`.
// the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later.
let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp);
// convert `{mant, plus, minus} * 2^exp` into the fractional form so that:
// - `v = mant / scale`
// - `low = (mant - minus) / scale`
// - `high = (mant + plus) / scale`
let mut mant = Big::from_u64(d.mant);
let mut minus = Big::from_u64(d.minus);
let mut plus = Big::from_u64(d.plus);
let mut scale = Big::from_small(1);
if d.exp < 0 {
scale.mul_pow2(-d.exp as usize);
} else {
mant.mul_pow2(d.exp as usize);
minus.mul_pow2(d.exp as usize);
plus.mul_pow2(d.exp as usize);
}
// divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
if k >= 0 {
mul_pow10(&mut scale, k as usize);
} else {
mul_pow10(&mut mant, -k as usize);
mul_pow10(&mut minus, -k as usize);
mul_pow10(&mut plus, -k as usize);
}
// fixup when `mant + plus > scale` (or `>=`).
// we are not actually modifying `scale`, since we can skip the initial multiplication instead.
// now `scale < mant + plus <= scale * 10` and we are ready to generate digits.
//
// note that `d[0]` *can* be zero, when `scale - plus < mant < scale`.
// in this case rounding-up condition (`up` below) will be triggered immediately.
if scale.cmp(mant.clone().add(&plus)) < rounding {
// equivalent to scaling `scale` by 10
k += 1;
} else {
mant.mul_small(10);
minus.mul_small(10);
plus.mul_small(10);
}
// cache `(2, 4, 8) * scale` for digit generation.
let mut scale2 = scale.clone(); scale2.mul_pow2(1);
let mut scale4 = scale.clone(); scale4.mul_pow2(2);
let mut scale8 = scale.clone(); scale8.mul_pow2(3);
let mut down;
let mut up;
let mut i = 0;
loop {
// invariants, where `d[0..n-1]` are digits generated so far:
// - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)`
// - `v - low = minus / scale * 10^(k-n-1)`
// - `high - v = plus / scale * 10^(k-n-1)`
// - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`)
// where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) + ... + d[j-1] * 10 + d[j]`.
// generate one digit: `d[n] = floor(mant / scale) < 10`.
let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8);
debug_assert!(d < 10);
buf[i] = b'0' + d;
i += 1;
// this is a simplified description of the modified Dragon algorithm.
// many intermediate derivations and completeness arguments are omitted for convenience.
//
// start with modified invariants, as we've updated `n`:
// - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)`
// - `v - low = minus / scale * 10^(k-n)`
// - `high - v = plus / scale * 10^(k-n)`
//
// assume that `d[0..n-1]` is the shortest representation between | {
// the number `v` to format is known to be:
// - equal to `mant * 2^exp`;
// - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and
// - followed by `(mant + 2 * plus) * 2^exp` in the original type.
//
// obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.)
// also we assume that at least one digit is generated, i.e. `mant` cannot be zero too.
//
// this also means that any number between `low = (mant - minus) * 2^exp` and
// `high = (mant + plus) * 2^exp` will map to this exact floating point number,
// with bounds included when the original mantissa was even (i.e. `!mant_was_odd`).
assert!(d.mant > 0);
assert!(d.minus > 0);
assert!(d.plus > 0);
assert!(d.mant.checked_add(d.plus).is_some());
assert!(d.mant.checked_sub(d.minus).is_some());
assert!(buf.len() >= MAX_SIG_DIGITS);
| identifier_body |
dragon.rs | <= scale * 10`.
if k >= 0 {
mul_pow10(&mut scale, k as usize);
} else {
mul_pow10(&mut mant, -k as usize);
mul_pow10(&mut minus, -k as usize);
mul_pow10(&mut plus, -k as usize);
}
// fixup when `mant + plus > scale` (or `>=`).
// we are not actually modifying `scale`, since we can skip the initial multiplication instead.
// now `scale < mant + plus <= scale * 10` and we are ready to generate digits.
//
// note that `d[0]` *can* be zero, when `scale - plus < mant < scale`.
// in this case rounding-up condition (`up` below) will be triggered immediately.
if scale.cmp(mant.clone().add(&plus)) < rounding {
// equivalent to scaling `scale` by 10
k += 1;
} else {
mant.mul_small(10);
minus.mul_small(10);
plus.mul_small(10);
}
// cache `(2, 4, 8) * scale` for digit generation.
let mut scale2 = scale.clone(); scale2.mul_pow2(1);
let mut scale4 = scale.clone(); scale4.mul_pow2(2);
let mut scale8 = scale.clone(); scale8.mul_pow2(3);
let mut down;
let mut up;
let mut i = 0;
loop {
// invariants, where `d[0..n-1]` are digits generated so far:
// - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)`
// - `v - low = minus / scale * 10^(k-n-1)`
// - `high - v = plus / scale * 10^(k-n-1)`
// - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`)
// where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) + ... + d[j-1] * 10 + d[j]`.
// generate one digit: `d[n] = floor(mant / scale) < 10`.
let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8);
debug_assert!(d < 10);
buf[i] = b'0' + d;
i += 1;
// this is a simplified description of the modified Dragon algorithm.
// many intermediate derivations and completeness arguments are omitted for convenience.
//
// start with modified invariants, as we've updated `n`:
// - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)`
// - `v - low = minus / scale * 10^(k-n)`
// - `high - v = plus / scale * 10^(k-n)`
//
// assume that `d[0..n-1]` is the shortest representation between `low` and `high`,
// i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't:
// - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and
// - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct).
//
// the second condition simplifies to `2 * mant <= scale`.
// solving invariants in terms of `mant`, `low` and `high` yields
// a simpler version of the first condition: `-plus < mant < minus`.
// since `-plus < 0 <= mant`, we have the correct shortest representation
// when `mant < minus` and `2 * mant <= scale`.
// (the former becomes `mant <= minus` when the original mantissa is even.)
//
// when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit.
// this is enough for restoring that condition: we already know that
// the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`.
// in this case, the first condition becomes `-plus < mant - scale < minus`.
// since `mant < scale` after the generation, we have `scale < mant + plus`.
// (again, this becomes `scale <= mant + plus` when the original mantissa is even.)
//
// in short:
// - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`).
// - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`).
// - keep generating otherwise.
down = mant.cmp(&minus) < rounding;
up = scale.cmp(mant.clone().add(&plus)) < rounding;
if down || up { break; } // we have the shortest representation, proceed to the rounding
// restore the invariants.
// this makes the algorithm always terminating: `minus` and `plus` always increases,
// but `mant` is clipped modulo `scale` and `scale` is fixed.
mant.mul_small(10);
minus.mul_small(10);
plus.mul_small(10);
}
// rounding up happens when
// i) only the rounding-up condition was triggered, or
// ii) both conditions were triggered and tie breaking prefers rounding up.
if up && (!down || *mant.mul_pow2(1) >= scale) {
// if rounding up changes the length, the exponent should also change.
// it seems that this condition is very hard to satisfy (possibly impossible),
// but we are just being safe and consistent here.
if let Some(c) = round_up(buf, i) {
buf[i] = c;
i += 1;
k += 1;
}
}
(i, k)
}
/// The exact and fixed mode implementation for Dragon.
pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) {
assert!(d.mant > 0);
assert!(d.minus > 0);
assert!(d.plus > 0);
assert!(d.mant.checked_add(d.plus).is_some());
assert!(d.mant.checked_sub(d.minus).is_some());
// estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`.
let mut k = estimate_scaling_factor(d.mant, d.exp);
// `v = mant / scale`.
let mut mant = Big::from_u64(d.mant);
let mut scale = Big::from_small(1);
if d.exp < 0 {
scale.mul_pow2(-d.exp as usize);
} else {
mant.mul_pow2(d.exp as usize);
}
// divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`.
if k >= 0 {
mul_pow10(&mut scale, k as usize);
} else {
mul_pow10(&mut mant, -k as usize);
}
// fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`.
// in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`.
// we are not actually modifying `scale`, since we can skip the initial multiplication instead.
// again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up.
if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale {
// equivalent to scaling `scale` by 10
k += 1;
} else {
mant.mul_small(10);
}
// if we are working with the last-digit limitation, we need to shorten the buffer
// before the actual rendering in order to avoid double rounding.
// note that we have to enlarge the buffer again when rounding up happens!
let mut len = if k < limit {
// oops, we cannot even produce *one* digit.
// this is possible when, say, we've got something like 9.5 and it's being rounded to 10.
// we return an empty buffer, with an exception of the later rounding-up case
// which occurs when `k == limit` and has to produce exactly one digit.
0
} else if ((k as i32 - limit as i32) as usize) < buf.len() | {
(k - limit) as usize
} | conditional_block |
|
table-errors.d.ts | * found in the LICENSE file at https://angular.io/license
*/
/**
* Returns an error to be thrown when attempting to find an unexisting column.
* @param id Id whose lookup failed.
* @docs-private
*/
export declare function getTableUnknownColumnError(id: string): Error;
/**
* Returns an error to be thrown when two column definitions have the same name.
* @docs-private
*/
export declare function getTableDuplicateColumnNameError(name: string): Error;
/**
* Returns an error to be thrown when there are multiple rows that are missing a when function.
* @docs-private
*/
export declare function getTableMultipleDefaultRowDefsError(): Error;
/**
* Returns an error to be thrown when there are no matching row defs for a particular set of data.
* @docs-private
*/
export declare function getTableMissingMatchingRowDefError(): Error; | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be | random_line_split |
|
scalar.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use collections::HashMap;
use std::usize;
use test::{black_box, Bencher};
use tipb::ScalarFuncSig;
fn get_scalar_args_with_match(sig: ScalarFuncSig) -> (usize, usize) {
// Only select some functions to benchmark
let (min_args, max_args) = match sig {
ScalarFuncSig::LtInt => (2, 2),
ScalarFuncSig::CastIntAsInt => (1, 1),
ScalarFuncSig::IfInt => (3, 3),
ScalarFuncSig::JsonArraySig => (0, usize::MAX),
ScalarFuncSig::CoalesceDecimal => (1, usize::MAX),
ScalarFuncSig::JsonExtractSig => (2, usize::MAX),
ScalarFuncSig::JsonSetSig => (3, usize::MAX),
_ => (0, 0),
};
(min_args, max_args)
}
fn init_scalar_args_map() -> HashMap<ScalarFuncSig, (usize, usize)> {
let mut m: HashMap<ScalarFuncSig, (usize, usize)> = HashMap::default();
let tbls = vec![
(ScalarFuncSig::LtInt, (2, 2)),
(ScalarFuncSig::CastIntAsInt, (1, 1)),
(ScalarFuncSig::IfInt, (3, 3)),
(ScalarFuncSig::JsonArraySig, (0, usize::MAX)),
(ScalarFuncSig::CoalesceDecimal, (1, usize::MAX)),
(ScalarFuncSig::JsonExtractSig, (2, usize::MAX)),
(ScalarFuncSig::JsonSetSig, (3, usize::MAX)),
(ScalarFuncSig::Acos, (0, 0)),
];
for tbl in tbls {
m.insert(tbl.0, tbl.1);
}
m
}
fn get_scalar_args_with_map(
m: &HashMap<ScalarFuncSig, (usize, usize)>,
sig: ScalarFuncSig,
) -> (usize, usize) {
if let Some((min_args, max_args)) = m.get(&sig).cloned() |
(0, 0)
}
#[bench]
fn bench_get_scalar_args_with_match(b: &mut Bencher) {
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_match(black_box(ScalarFuncSig::AbsInt)));
}
})
}
#[bench]
fn bench_get_scalar_args_with_map(b: &mut Bencher) {
let m = init_scalar_args_map();
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_map(
black_box(&m),
black_box(ScalarFuncSig::AbsInt),
));
}
})
}
| {
return (min_args, max_args);
} | conditional_block |
scalar.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use collections::HashMap;
use std::usize;
use test::{black_box, Bencher};
use tipb::ScalarFuncSig;
fn | (sig: ScalarFuncSig) -> (usize, usize) {
// Only select some functions to benchmark
let (min_args, max_args) = match sig {
ScalarFuncSig::LtInt => (2, 2),
ScalarFuncSig::CastIntAsInt => (1, 1),
ScalarFuncSig::IfInt => (3, 3),
ScalarFuncSig::JsonArraySig => (0, usize::MAX),
ScalarFuncSig::CoalesceDecimal => (1, usize::MAX),
ScalarFuncSig::JsonExtractSig => (2, usize::MAX),
ScalarFuncSig::JsonSetSig => (3, usize::MAX),
_ => (0, 0),
};
(min_args, max_args)
}
fn init_scalar_args_map() -> HashMap<ScalarFuncSig, (usize, usize)> {
let mut m: HashMap<ScalarFuncSig, (usize, usize)> = HashMap::default();
let tbls = vec![
(ScalarFuncSig::LtInt, (2, 2)),
(ScalarFuncSig::CastIntAsInt, (1, 1)),
(ScalarFuncSig::IfInt, (3, 3)),
(ScalarFuncSig::JsonArraySig, (0, usize::MAX)),
(ScalarFuncSig::CoalesceDecimal, (1, usize::MAX)),
(ScalarFuncSig::JsonExtractSig, (2, usize::MAX)),
(ScalarFuncSig::JsonSetSig, (3, usize::MAX)),
(ScalarFuncSig::Acos, (0, 0)),
];
for tbl in tbls {
m.insert(tbl.0, tbl.1);
}
m
}
fn get_scalar_args_with_map(
m: &HashMap<ScalarFuncSig, (usize, usize)>,
sig: ScalarFuncSig,
) -> (usize, usize) {
if let Some((min_args, max_args)) = m.get(&sig).cloned() {
return (min_args, max_args);
}
(0, 0)
}
#[bench]
fn bench_get_scalar_args_with_match(b: &mut Bencher) {
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_match(black_box(ScalarFuncSig::AbsInt)));
}
})
}
#[bench]
fn bench_get_scalar_args_with_map(b: &mut Bencher) {
let m = init_scalar_args_map();
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_map(
black_box(&m),
black_box(ScalarFuncSig::AbsInt),
));
}
})
}
| get_scalar_args_with_match | identifier_name |
scalar.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use collections::HashMap;
use std::usize;
use test::{black_box, Bencher};
use tipb::ScalarFuncSig;
fn get_scalar_args_with_match(sig: ScalarFuncSig) -> (usize, usize) {
// Only select some functions to benchmark
let (min_args, max_args) = match sig {
ScalarFuncSig::LtInt => (2, 2),
ScalarFuncSig::CastIntAsInt => (1, 1),
ScalarFuncSig::IfInt => (3, 3),
ScalarFuncSig::JsonArraySig => (0, usize::MAX),
ScalarFuncSig::CoalesceDecimal => (1, usize::MAX),
ScalarFuncSig::JsonExtractSig => (2, usize::MAX),
ScalarFuncSig::JsonSetSig => (3, usize::MAX),
_ => (0, 0),
};
(min_args, max_args)
}
fn init_scalar_args_map() -> HashMap<ScalarFuncSig, (usize, usize)> {
let mut m: HashMap<ScalarFuncSig, (usize, usize)> = HashMap::default();
let tbls = vec![
(ScalarFuncSig::LtInt, (2, 2)),
(ScalarFuncSig::CastIntAsInt, (1, 1)),
(ScalarFuncSig::IfInt, (3, 3)),
(ScalarFuncSig::JsonArraySig, (0, usize::MAX)),
(ScalarFuncSig::CoalesceDecimal, (1, usize::MAX)),
(ScalarFuncSig::JsonExtractSig, (2, usize::MAX)),
(ScalarFuncSig::JsonSetSig, (3, usize::MAX)),
(ScalarFuncSig::Acos, (0, 0)),
];
for tbl in tbls {
m.insert(tbl.0, tbl.1);
}
m
}
fn get_scalar_args_with_map(
m: &HashMap<ScalarFuncSig, (usize, usize)>,
sig: ScalarFuncSig,
) -> (usize, usize) {
if let Some((min_args, max_args)) = m.get(&sig).cloned() {
return (min_args, max_args);
}
(0, 0)
}
#[bench]
fn bench_get_scalar_args_with_match(b: &mut Bencher) {
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_match(black_box(ScalarFuncSig::AbsInt)));
}
})
}
#[bench]
fn bench_get_scalar_args_with_map(b: &mut Bencher) | {
let m = init_scalar_args_map();
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_map(
black_box(&m),
black_box(ScalarFuncSig::AbsInt),
));
}
})
} | identifier_body |
|
scalar.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use collections::HashMap;
use std::usize;
use test::{black_box, Bencher};
use tipb::ScalarFuncSig;
fn get_scalar_args_with_match(sig: ScalarFuncSig) -> (usize, usize) {
// Only select some functions to benchmark
let (min_args, max_args) = match sig {
ScalarFuncSig::LtInt => (2, 2),
ScalarFuncSig::CastIntAsInt => (1, 1),
ScalarFuncSig::IfInt => (3, 3),
ScalarFuncSig::JsonArraySig => (0, usize::MAX),
ScalarFuncSig::CoalesceDecimal => (1, usize::MAX),
ScalarFuncSig::JsonExtractSig => (2, usize::MAX),
ScalarFuncSig::JsonSetSig => (3, usize::MAX), | }
fn init_scalar_args_map() -> HashMap<ScalarFuncSig, (usize, usize)> {
let mut m: HashMap<ScalarFuncSig, (usize, usize)> = HashMap::default();
let tbls = vec![
(ScalarFuncSig::LtInt, (2, 2)),
(ScalarFuncSig::CastIntAsInt, (1, 1)),
(ScalarFuncSig::IfInt, (3, 3)),
(ScalarFuncSig::JsonArraySig, (0, usize::MAX)),
(ScalarFuncSig::CoalesceDecimal, (1, usize::MAX)),
(ScalarFuncSig::JsonExtractSig, (2, usize::MAX)),
(ScalarFuncSig::JsonSetSig, (3, usize::MAX)),
(ScalarFuncSig::Acos, (0, 0)),
];
for tbl in tbls {
m.insert(tbl.0, tbl.1);
}
m
}
fn get_scalar_args_with_map(
m: &HashMap<ScalarFuncSig, (usize, usize)>,
sig: ScalarFuncSig,
) -> (usize, usize) {
if let Some((min_args, max_args)) = m.get(&sig).cloned() {
return (min_args, max_args);
}
(0, 0)
}
#[bench]
fn bench_get_scalar_args_with_match(b: &mut Bencher) {
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_match(black_box(ScalarFuncSig::AbsInt)));
}
})
}
#[bench]
fn bench_get_scalar_args_with_map(b: &mut Bencher) {
let m = init_scalar_args_map();
b.iter(|| {
for _ in 0..1000 {
black_box(get_scalar_args_with_map(
black_box(&m),
black_box(ScalarFuncSig::AbsInt),
));
}
})
} | _ => (0, 0),
};
(min_args, max_args) | random_line_split |
libstdbuf.rs | #![crate_name = "libstdbuf"]
#![crate_type = "staticlib"]
#![feature(core, libc, os)]
extern crate libc;
use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf};
use std::ptr;
use std::os;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
extern {
static stdin: *mut FILE;
static stdout: *mut FILE;
static stderr: *mut FILE;
}
static NAME: &'static str = "libstdbuf";
fn set_buffer(stream: *mut FILE, value: &str) {
let (mode, size): (c_int, size_t) = match value {
"0" => (_IONBF, 0 as size_t),
"L" => (_IOLBF, 0 as size_t),
input => {
let buff_size: usize = match input.parse() {
Ok(num) => num,
Err(e) => crash!(1, "incorrect size of buffer!: {}", e)
};
(_IOFBF, buff_size as size_t)
}
};
let mut res: c_int;
unsafe {
let buffer: *mut c_char = ptr::null_mut();
assert!(buffer.is_null());
res = libc::setvbuf(stream, buffer, mode, size);
}
if res != 0 {
crash!(res, "error while calling setvbuf!");
}
}
| pub extern fn stdbuf() {
if let Some(val) = os::getenv("_STDBUF_E") {
set_buffer(stderr, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_I") {
set_buffer(stdin, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_O") {
set_buffer(stdout, val.as_slice());
}
} | #[no_mangle] | random_line_split |
libstdbuf.rs | #![crate_name = "libstdbuf"]
#![crate_type = "staticlib"]
#![feature(core, libc, os)]
extern crate libc;
use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf};
use std::ptr;
use std::os;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
extern {
static stdin: *mut FILE;
static stdout: *mut FILE;
static stderr: *mut FILE;
}
static NAME: &'static str = "libstdbuf";
fn set_buffer(stream: *mut FILE, value: &str) {
let (mode, size): (c_int, size_t) = match value {
"0" => (_IONBF, 0 as size_t),
"L" => (_IOLBF, 0 as size_t),
input => {
let buff_size: usize = match input.parse() {
Ok(num) => num,
Err(e) => crash!(1, "incorrect size of buffer!: {}", e)
};
(_IOFBF, buff_size as size_t)
}
};
let mut res: c_int;
unsafe {
let buffer: *mut c_char = ptr::null_mut();
assert!(buffer.is_null());
res = libc::setvbuf(stream, buffer, mode, size);
}
if res != 0 {
crash!(res, "error while calling setvbuf!");
}
}
#[no_mangle]
pub extern fn stdbuf() | {
if let Some(val) = os::getenv("_STDBUF_E") {
set_buffer(stderr, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_I") {
set_buffer(stdin, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_O") {
set_buffer(stdout, val.as_slice());
}
} | identifier_body |
|
libstdbuf.rs | #![crate_name = "libstdbuf"]
#![crate_type = "staticlib"]
#![feature(core, libc, os)]
extern crate libc;
use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf};
use std::ptr;
use std::os;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
extern {
static stdin: *mut FILE;
static stdout: *mut FILE;
static stderr: *mut FILE;
}
static NAME: &'static str = "libstdbuf";
fn set_buffer(stream: *mut FILE, value: &str) {
let (mode, size): (c_int, size_t) = match value {
"0" => (_IONBF, 0 as size_t),
"L" => (_IOLBF, 0 as size_t),
input => {
let buff_size: usize = match input.parse() {
Ok(num) => num,
Err(e) => crash!(1, "incorrect size of buffer!: {}", e)
};
(_IOFBF, buff_size as size_t)
}
};
let mut res: c_int;
unsafe {
let buffer: *mut c_char = ptr::null_mut();
assert!(buffer.is_null());
res = libc::setvbuf(stream, buffer, mode, size);
}
if res != 0 {
crash!(res, "error while calling setvbuf!");
}
}
#[no_mangle]
pub extern fn stdbuf() {
if let Some(val) = os::getenv("_STDBUF_E") {
set_buffer(stderr, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_I") {
set_buffer(stdin, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_O") |
}
| {
set_buffer(stdout, val.as_slice());
} | conditional_block |
libstdbuf.rs | #![crate_name = "libstdbuf"]
#![crate_type = "staticlib"]
#![feature(core, libc, os)]
extern crate libc;
use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf};
use std::ptr;
use std::os;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
extern {
static stdin: *mut FILE;
static stdout: *mut FILE;
static stderr: *mut FILE;
}
static NAME: &'static str = "libstdbuf";
fn set_buffer(stream: *mut FILE, value: &str) {
let (mode, size): (c_int, size_t) = match value {
"0" => (_IONBF, 0 as size_t),
"L" => (_IOLBF, 0 as size_t),
input => {
let buff_size: usize = match input.parse() {
Ok(num) => num,
Err(e) => crash!(1, "incorrect size of buffer!: {}", e)
};
(_IOFBF, buff_size as size_t)
}
};
let mut res: c_int;
unsafe {
let buffer: *mut c_char = ptr::null_mut();
assert!(buffer.is_null());
res = libc::setvbuf(stream, buffer, mode, size);
}
if res != 0 {
crash!(res, "error while calling setvbuf!");
}
}
#[no_mangle]
pub extern fn | () {
if let Some(val) = os::getenv("_STDBUF_E") {
set_buffer(stderr, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_I") {
set_buffer(stdin, val.as_slice());
}
if let Some(val) = os::getenv("_STDBUF_O") {
set_buffer(stdout, val.as_slice());
}
}
| stdbuf | identifier_name |
main.rs | extern crate rustc_serialize;
extern crate hyper;
use rustc_serialize::json;
use rustc_serialize::json::Json;
#[macro_use] extern crate nickel;
use nickel::status::StatusCode;
use nickel::{Nickel, HttpRouter, MediaType, JsonBody};
#[derive(RustcDecodable, RustcEncodable)]
struct | {
status: i32,
title: String,
}
fn main() {
let mut server = Nickel::new();
let mut router = Nickel::router();
// index
router.get("/api/todos", middleware! { |_, mut _res|
let mut v: Vec<Todo> = vec![];
let todo1 = Todo{
status: 0,
title: "Shopping".to_string(),
};
v.push(todo1);
let todo2 = Todo{
status: 1,
title: "Movie".to_string(),
};
v.push(todo2);
let json_obj = json::encode(&v).unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Ok);
return _res.send(json_obj);
});
// detail
router.get("/api/todos/:id", middleware! { |_req, mut _res|
let id = _req.param("id");
println!("id: {:?}", id);
let todo1 = Todo{
status: 0,
title: "Shopping".to_string(),
};
let json_obj = json::encode(&todo1).unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Ok);
return _res.send(json_obj);
});
// delete
router.delete("/api/todos/:id", middleware! { |_req, mut _res|
let id = _req.param("id");
println!("delete id: {:?}", id);
let json_obj = Json::from_str("{}").unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Ok);
return _res.send(json_obj);
});
// create
router.post("/api/todos", middleware! { |_req, mut _res|
let todo = _req.json_as::<Todo>().unwrap();
let status = todo.status;
let title = todo.title.to_string();
println!("create status {:?} title {}", status, title);
let json_obj = Json::from_str("{}").unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Created);
return _res.send(json_obj);
});
// update
router.put("/api/todos/:id", middleware! { |_req, mut _res|
let todo = _req.json_as::<Todo>().unwrap();
let status = todo.status;
let title = todo.title.to_string();
println!("update status {:?} title {}", status, title);
let json_obj = Json::from_str("{}").unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Ok);
return _res.send(json_obj);
});
server.utilize(router);
server.listen("127.0.0.1:6767");
}
| Todo | identifier_name |
main.rs | extern crate rustc_serialize;
extern crate hyper;
use rustc_serialize::json;
use rustc_serialize::json::Json;
#[macro_use] extern crate nickel;
use nickel::status::StatusCode;
use nickel::{Nickel, HttpRouter, MediaType, JsonBody};
#[derive(RustcDecodable, RustcEncodable)]
struct Todo {
status: i32,
title: String,
}
fn main() {
let mut server = Nickel::new();
let mut router = Nickel::router();
// index
router.get("/api/todos", middleware! { |_, mut _res|
let mut v: Vec<Todo> = vec![];
let todo1 = Todo{
status: 0,
title: "Shopping".to_string(),
};
v.push(todo1);
let todo2 = Todo{
status: 1,
title: "Movie".to_string(),
};
v.push(todo2);
let json_obj = json::encode(&v).unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Ok);
return _res.send(json_obj);
});
// detail
router.get("/api/todos/:id", middleware! { |_req, mut _res|
let id = _req.param("id");
println!("id: {:?}", id);
let todo1 = Todo{
status: 0,
title: "Shopping".to_string(),
};
let json_obj = json::encode(&todo1).unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Ok);
return _res.send(json_obj);
});
// delete
router.delete("/api/todos/:id", middleware! { |_req, mut _res|
let id = _req.param("id");
println!("delete id: {:?}", id);
let json_obj = Json::from_str("{}").unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Ok);
return _res.send(json_obj);
}); | let todo = _req.json_as::<Todo>().unwrap();
let status = todo.status;
let title = todo.title.to_string();
println!("create status {:?} title {}", status, title);
let json_obj = Json::from_str("{}").unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Created);
return _res.send(json_obj);
});
// update
router.put("/api/todos/:id", middleware! { |_req, mut _res|
let todo = _req.json_as::<Todo>().unwrap();
let status = todo.status;
let title = todo.title.to_string();
println!("update status {:?} title {}", status, title);
let json_obj = Json::from_str("{}").unwrap();
_res.set(MediaType::Json);
_res.set(StatusCode::Ok);
return _res.send(json_obj);
});
server.utilize(router);
server.listen("127.0.0.1:6767");
} |
// create
router.post("/api/todos", middleware! { |_req, mut _res| | random_line_split |
issue-14845.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.
struct X {
a: [u8; 1]
}
fn | () {
let x = X { a: [0] };
let _f = &x.a as *mut u8;
//~^ ERROR mismatched types
//~| expected `*mut u8`
//~| found `&[u8; 1]`
//~| expected u8
//~| found array of 1 elements
let local = [0u8];
let _v = &local as *mut u8;
//~^ ERROR mismatched types
//~| expected `*mut u8`
//~| found `&[u8; 1]`
//~| expected u8,
//~| found array of 1 elements
}
| main | identifier_name |
issue-14845.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.
struct X {
a: [u8; 1]
}
fn main() {
let x = X { a: [0] };
let _f = &x.a as *mut u8;
//~^ ERROR mismatched types
//~| expected `*mut u8`
//~| found `&[u8; 1]`
//~| expected u8
//~| found array of 1 elements
let local = [0u8];
let _v = &local as *mut u8;
//~^ ERROR mismatched types
//~| expected `*mut u8`
//~| found `&[u8; 1]`
//~| expected u8,
//~| found array of 1 elements | } | random_line_split |
|
show_tests.py | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickChill is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickChill. If not, see <http://www.gnu.org/licenses/>.
"""
Test shows
"""
# pylint: disable=line-too-long
from __future__ import print_function, unicode_literals
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
| from sickbeard.common import Quality
from sickbeard.tv import TVShow
from sickchill.helper.exceptions import MultipleShowObjectsException
from sickchill.show.Show import Show
class ShowTests(unittest.TestCase):
"""
Test shows
"""
def test_find(self):
"""
Test find tv shows by indexer_id
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
shows = [show123, show456, show789]
shows_duplicate = shows + shows
test_cases = {
(False, None): None,
(False, ''): None,
(False, '123'): None,
(False, 123): None,
(False, 12.3): None,
(True, None): None,
(True, ''): None,
(True, '123'): None,
(True, 123): show123,
(True, 12.3): None,
(True, 456): show456,
(True, 789): show789,
}
unicode_test_cases = {
(False, ''): None,
(False, '123'): None,
(True, ''): None,
(True, '123'): None,
}
for tests in test_cases, unicode_test_cases:
for ((use_shows, indexer_id), result) in six.iteritems(tests):
if use_shows:
self.assertEqual(Show.find(shows, indexer_id), result)
else:
self.assertEqual(Show.find(None, indexer_id), result)
with self.assertRaises(MultipleShowObjectsException):
Show.find(shows_duplicate, 456)
def test_validate_indexer_id(self):
"""
Tests if the indexer_id is valid and if so if it returns the right show
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
sickbeard.showList = [
show123,
show456,
show789,
]
invalid_show_id = ('Invalid show ID', None)
indexer_id_list = [
None, '', '', '123', '123', '456', '456', '789', '789', 123, 456, 789, ['123', '456'], ['123', '456'],
[123, 456]
]
results_list = [
invalid_show_id, invalid_show_id, invalid_show_id, (None, show123), (None, show123), (None, show456),
(None, show456), (None, show789), (None, show789), (None, show123), (None, show456), (None, show789),
invalid_show_id, invalid_show_id, invalid_show_id
]
self.assertEqual(
len(indexer_id_list), len(results_list),
'Number of parameters ({0:d}) and results ({1:d}) does not match'.format(len(indexer_id_list), len(results_list))
)
for (index, indexer_id) in enumerate(indexer_id_list):
self.assertEqual(Show._validate_indexer_id(indexer_id), results_list[index]) # pylint: disable=protected-access
class TestTVShow(TVShow):
"""
A test `TVShow` object that does not need DB access.
"""
def __init__(self, indexer, indexer_id):
super(TestTVShow, self).__init__(indexer, indexer_id)
def loadFromDB(self):
"""
Override TVShow.loadFromDB to avoid DB access during testing
"""
pass
if __name__ == '__main__':
print('=====> Testing {0}'.format(__file__))
SUITE = unittest.TestLoader().loadTestsFromTestCase(ShowTests)
unittest.TextTestRunner(verbosity=2).run(SUITE) | import sickbeard
import six
| random_line_split |
show_tests.py | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickChill is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickChill. If not, see <http://www.gnu.org/licenses/>.
"""
Test shows
"""
# pylint: disable=line-too-long
from __future__ import print_function, unicode_literals
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
import sickbeard
import six
from sickbeard.common import Quality
from sickbeard.tv import TVShow
from sickchill.helper.exceptions import MultipleShowObjectsException
from sickchill.show.Show import Show
class ShowTests(unittest.TestCase):
| (False, ''): None,
(False, '123'): None,
(False, 123): None,
(False, 12.3): None,
(True, None): None,
(True, ''): None,
(True, '123'): None,
(True, 123): show123,
(True, 12.3): None,
(True, 456): show456,
(True, 789): show789,
}
unicode_test_cases = {
(False, ''): None,
(False, '123'): None,
(True, ''): None,
(True, '123'): None,
}
for tests in test_cases, unicode_test_cases:
for ((use_shows, indexer_id), result) in six.iteritems(tests):
if use_shows:
self.assertEqual(Show.find(shows, indexer_id), result)
else:
self.assertEqual(Show.find(None, indexer_id), result)
with self.assertRaises(MultipleShowObjectsException):
Show.find(shows_duplicate, 456)
def test_validate_indexer_id(self):
"""
Tests if the indexer_id is valid and if so if it returns the right show
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
sickbeard.showList = [
show123,
show456,
show789,
]
invalid_show_id = ('Invalid show ID', None)
indexer_id_list = [
None, '', '', '123', '123', '456', '456', '789', '789', 123, 456, 789, ['123', '456'], ['123', '456'],
[123, 456]
]
results_list = [
invalid_show_id, invalid_show_id, invalid_show_id, (None, show123), (None, show123), (None, show456),
(None, show456), (None, show789), (None, show789), (None, show123), (None, show456), (None, show789),
invalid_show_id, invalid_show_id, invalid_show_id
]
self.assertEqual(
len(indexer_id_list), len(results_list),
'Number of parameters ({0:d}) and results ({1:d}) does not match'.format(len(indexer_id_list), len(results_list))
)
for (index, indexer_id) in enumerate(indexer_id_list):
self.assertEqual(Show._validate_indexer_id(indexer_id), results_list[index]) # pylint: disable=protected-access
class TestTVShow(TVShow):
"""
A test `TVShow` object that does not need DB access.
"""
def __init__(self, indexer, indexer_id):
super(TestTVShow, self).__init__(indexer, indexer_id)
def loadFromDB(self):
"""
Override TVShow.loadFromDB to avoid DB access during testing
"""
pass
if __name__ == '__main__':
print('=====> Testing {0}'.format(__file__))
SUITE = unittest.TestLoader().loadTestsFromTestCase(ShowTests)
unittest.TextTestRunner(verbosity=2).run(SUITE)
| """
Test shows
"""
def test_find(self):
"""
Test find tv shows by indexer_id
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
shows = [show123, show456, show789]
shows_duplicate = shows + shows
test_cases = {
(False, None): None, | identifier_body |
show_tests.py | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickChill is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickChill. If not, see <http://www.gnu.org/licenses/>.
"""
Test shows
"""
# pylint: disable=line-too-long
from __future__ import print_function, unicode_literals
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
import sickbeard
import six
from sickbeard.common import Quality
from sickbeard.tv import TVShow
from sickchill.helper.exceptions import MultipleShowObjectsException
from sickchill.show.Show import Show
class ShowTests(unittest.TestCase):
"""
Test shows
"""
def | (self):
"""
Test find tv shows by indexer_id
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
shows = [show123, show456, show789]
shows_duplicate = shows + shows
test_cases = {
(False, None): None,
(False, ''): None,
(False, '123'): None,
(False, 123): None,
(False, 12.3): None,
(True, None): None,
(True, ''): None,
(True, '123'): None,
(True, 123): show123,
(True, 12.3): None,
(True, 456): show456,
(True, 789): show789,
}
unicode_test_cases = {
(False, ''): None,
(False, '123'): None,
(True, ''): None,
(True, '123'): None,
}
for tests in test_cases, unicode_test_cases:
for ((use_shows, indexer_id), result) in six.iteritems(tests):
if use_shows:
self.assertEqual(Show.find(shows, indexer_id), result)
else:
self.assertEqual(Show.find(None, indexer_id), result)
with self.assertRaises(MultipleShowObjectsException):
Show.find(shows_duplicate, 456)
def test_validate_indexer_id(self):
"""
Tests if the indexer_id is valid and if so if it returns the right show
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
sickbeard.showList = [
show123,
show456,
show789,
]
invalid_show_id = ('Invalid show ID', None)
indexer_id_list = [
None, '', '', '123', '123', '456', '456', '789', '789', 123, 456, 789, ['123', '456'], ['123', '456'],
[123, 456]
]
results_list = [
invalid_show_id, invalid_show_id, invalid_show_id, (None, show123), (None, show123), (None, show456),
(None, show456), (None, show789), (None, show789), (None, show123), (None, show456), (None, show789),
invalid_show_id, invalid_show_id, invalid_show_id
]
self.assertEqual(
len(indexer_id_list), len(results_list),
'Number of parameters ({0:d}) and results ({1:d}) does not match'.format(len(indexer_id_list), len(results_list))
)
for (index, indexer_id) in enumerate(indexer_id_list):
self.assertEqual(Show._validate_indexer_id(indexer_id), results_list[index]) # pylint: disable=protected-access
class TestTVShow(TVShow):
"""
A test `TVShow` object that does not need DB access.
"""
def __init__(self, indexer, indexer_id):
super(TestTVShow, self).__init__(indexer, indexer_id)
def loadFromDB(self):
"""
Override TVShow.loadFromDB to avoid DB access during testing
"""
pass
if __name__ == '__main__':
print('=====> Testing {0}'.format(__file__))
SUITE = unittest.TestLoader().loadTestsFromTestCase(ShowTests)
unittest.TextTestRunner(verbosity=2).run(SUITE)
| test_find | identifier_name |
show_tests.py | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickChill is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickChill. If not, see <http://www.gnu.org/licenses/>.
"""
Test shows
"""
# pylint: disable=line-too-long
from __future__ import print_function, unicode_literals
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
import sickbeard
import six
from sickbeard.common import Quality
from sickbeard.tv import TVShow
from sickchill.helper.exceptions import MultipleShowObjectsException
from sickchill.show.Show import Show
class ShowTests(unittest.TestCase):
"""
Test shows
"""
def test_find(self):
"""
Test find tv shows by indexer_id
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
shows = [show123, show456, show789]
shows_duplicate = shows + shows
test_cases = {
(False, None): None,
(False, ''): None,
(False, '123'): None,
(False, 123): None,
(False, 12.3): None,
(True, None): None,
(True, ''): None,
(True, '123'): None,
(True, 123): show123,
(True, 12.3): None,
(True, 456): show456,
(True, 789): show789,
}
unicode_test_cases = {
(False, ''): None,
(False, '123'): None,
(True, ''): None,
(True, '123'): None,
}
for tests in test_cases, unicode_test_cases:
for ((use_shows, indexer_id), result) in six.iteritems(tests):
if use_shows:
self.assertEqual(Show.find(shows, indexer_id), result)
else:
self.assertEqual(Show.find(None, indexer_id), result)
with self.assertRaises(MultipleShowObjectsException):
Show.find(shows_duplicate, 456)
def test_validate_indexer_id(self):
"""
Tests if the indexer_id is valid and if so if it returns the right show
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
sickbeard.showList = [
show123,
show456,
show789,
]
invalid_show_id = ('Invalid show ID', None)
indexer_id_list = [
None, '', '', '123', '123', '456', '456', '789', '789', 123, 456, 789, ['123', '456'], ['123', '456'],
[123, 456]
]
results_list = [
invalid_show_id, invalid_show_id, invalid_show_id, (None, show123), (None, show123), (None, show456),
(None, show456), (None, show789), (None, show789), (None, show123), (None, show456), (None, show789),
invalid_show_id, invalid_show_id, invalid_show_id
]
self.assertEqual(
len(indexer_id_list), len(results_list),
'Number of parameters ({0:d}) and results ({1:d}) does not match'.format(len(indexer_id_list), len(results_list))
)
for (index, indexer_id) in enumerate(indexer_id_list):
|
class TestTVShow(TVShow):
"""
A test `TVShow` object that does not need DB access.
"""
def __init__(self, indexer, indexer_id):
super(TestTVShow, self).__init__(indexer, indexer_id)
def loadFromDB(self):
"""
Override TVShow.loadFromDB to avoid DB access during testing
"""
pass
if __name__ == '__main__':
print('=====> Testing {0}'.format(__file__))
SUITE = unittest.TestLoader().loadTestsFromTestCase(ShowTests)
unittest.TextTestRunner(verbosity=2).run(SUITE)
| self.assertEqual(Show._validate_indexer_id(indexer_id), results_list[index]) # pylint: disable=protected-access | conditional_block |
trace_analyzer_old.py | __author__= "barun"
__date__ = "$20 May, 2011 12:25:36 PM$"
from metrics import Metrics
from wireless_fields import *
DATA_PKTS = ('tcp', 'udp', 'ack',)
def is_control_pkt(pkt_type=''):
return pkt_type not in DATA_PKTS
class TraceAnalyzer(object):
'''
Trace Analyzer
'''
def __init__(self, file_name=None):
print 'Trace Analyzer'
self._receiveEvents = []
self._sendEvents = []
self._dropEvents = []
self._otherEvents = []
self._data_pkts_rcvd = []
self._cntrl_pkts_rcvd = []
self._sourceNodes = []
self._destinationNodes = []
self.parse_events(file_name)
self.get_statistics()
def parse_events(self, file_name):
'''
Parse the send, receive and drop events, and store them in a list. This
method should get called only once (from inside __init__) at the
beginning of processing.
'''
print 'Parse events -- Use normal record scan to filter receive events'
if file_name:
trace_file = None
try:
trace_file = open(file_name, 'r')
for event in trace_file:
if event[0] == EVENT_RECEIVE:
self._receiveEvents.append(event)
elif event[0] == EVENT_SEND:
self._sendEvents.append(event)
elif event[0] == EVENT_DROP:
self._dropEvents.append(event)
else:
self._otherEvents.append(event)
except IOError, ioe:
print 'IOError:', str(ioe)
finally:
if trace_file:
trace_file.close()
for event in self._receiveEvents:
event = event.split()
try:
if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and\
event[I_TRACE_LEVEL_TOKEN] == S_TRACE_LEVEL_TOKEN and\
event[I_PKT_TYPE] in DATA_PKTS:
self._data_pkts_rcvd.append(event)
else:
self._cntrl_pkts_rcvd.append(event)
except IndexError:
#print event
self._data_pkts_rcvd.append(event)
continue
# Determine sending and receiving nodes
for event in self._sendEvents:
try:
event = event.split()
if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and \
event[I_PKT_TYPE] in DATA_PKTS:
if event[I_SRC_FIELD_TOKEN] == S_SRC_FIELD_TOKEN:
src = event[I_SRC_ADDR_PORT].split('.')[0]
if src not in self._sourceNodes and int(src) >= 0:
self._sourceNodes.append(src)
else:
continue
# Is is required to have destination nodes???
# In case of TCP, source nodes themselves will become
# destination of acknowledgements
#
# if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and \
# event[I_PKT_TYPE] in DATA_PKTS:
# if event[I_DST_FIELD_TOKEN] == S_DST_FIELD_TOKEN:
# dst = event[I_DST_ADDR_PORT].split('.')[0]
# if dst not in self._destinationNodes and int(dst) >= 0:
# self._destinationNodes.append(dst)
# else:
# continue
except IndexError:
# IndexError can occur because certain log entries from MAC
# layer may not have source and destination infos -- don't
# know exactly why
continue
# Compute simulation times
try:
self._simulationStartTime = float(self._sendEvents[0].split()[I_TIMESTAMP])
except IndexError:
self._simulationStartTime = 0
try:
self._simulationEndTime = float(self._sendEvents[len(self._sendEvents)-1].split()[I_TIMESTAMP])
except IndexError:
self._simulationEndTime = 0
self._simulationDuration = self._simulationEndTime - self._simulationStartTime
def get_statistics(self):
msg = '''
Simulation start: %f
Simulation end: %f
Duration: %f
Source nodes: %s
# of packets sent: %d
# of packets received: %d
# of data packets: %d
# of control packets:%d
# of packets droped: %d
# of other events: %d
''' % (
self._simulationStartTime,
self._simulationEndTime,
self._simulationDuration,
self._sourceNodes,
len(self._sendEvents),
len(self._receiveEvents),
len(self._data_pkts_rcvd),
len(self._cntrl_pkts_rcvd),
len(self._dropEvents),
len(self._otherEvents),
)
print msg
def | (self):
Metrics.averageThroughput()
def get_instantaneous_throughput(self):
Metrics.instantaneousThroughput()
| get_average_throughput | identifier_name |
trace_analyzer_old.py | __author__= "barun"
__date__ = "$20 May, 2011 12:25:36 PM$"
from metrics import Metrics
from wireless_fields import *
DATA_PKTS = ('tcp', 'udp', 'ack',)
def is_control_pkt(pkt_type=''):
return pkt_type not in DATA_PKTS
class TraceAnalyzer(object):
'''
Trace Analyzer
'''
def __init__(self, file_name=None):
print 'Trace Analyzer'
self._receiveEvents = []
self._sendEvents = []
self._dropEvents = []
self._otherEvents = []
self._data_pkts_rcvd = []
self._cntrl_pkts_rcvd = []
self._sourceNodes = []
self._destinationNodes = []
self.parse_events(file_name)
self.get_statistics()
def parse_events(self, file_name):
'''
Parse the send, receive and drop events, and store them in a list. This
method should get called only once (from inside __init__) at the
beginning of processing.
'''
print 'Parse events -- Use normal record scan to filter receive events'
if file_name:
trace_file = None
try:
trace_file = open(file_name, 'r')
for event in trace_file:
if event[0] == EVENT_RECEIVE:
self._receiveEvents.append(event)
elif event[0] == EVENT_SEND:
self._sendEvents.append(event)
elif event[0] == EVENT_DROP:
self._dropEvents.append(event)
else:
self._otherEvents.append(event)
except IOError, ioe:
print 'IOError:', str(ioe)
finally:
if trace_file:
trace_file.close()
for event in self._receiveEvents:
event = event.split()
try:
if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and\
event[I_TRACE_LEVEL_TOKEN] == S_TRACE_LEVEL_TOKEN and\
event[I_PKT_TYPE] in DATA_PKTS:
self._data_pkts_rcvd.append(event)
else:
self._cntrl_pkts_rcvd.append(event)
except IndexError:
#print event
self._data_pkts_rcvd.append(event)
continue
# Determine sending and receiving nodes
for event in self._sendEvents:
| # self._destinationNodes.append(dst)
# else:
# continue
except IndexError:
# IndexError can occur because certain log entries from MAC
# layer may not have source and destination infos -- don't
# know exactly why
continue
# Compute simulation times
try:
self._simulationStartTime = float(self._sendEvents[0].split()[I_TIMESTAMP])
except IndexError:
self._simulationStartTime = 0
try:
self._simulationEndTime = float(self._sendEvents[len(self._sendEvents)-1].split()[I_TIMESTAMP])
except IndexError:
self._simulationEndTime = 0
self._simulationDuration = self._simulationEndTime - self._simulationStartTime
def get_statistics(self):
msg = '''
Simulation start: %f
Simulation end: %f
Duration: %f
Source nodes: %s
# of packets sent: %d
# of packets received: %d
# of data packets: %d
# of control packets:%d
# of packets droped: %d
# of other events: %d
''' % (
self._simulationStartTime,
self._simulationEndTime,
self._simulationDuration,
self._sourceNodes,
len(self._sendEvents),
len(self._receiveEvents),
len(self._data_pkts_rcvd),
len(self._cntrl_pkts_rcvd),
len(self._dropEvents),
len(self._otherEvents),
)
print msg
def get_average_throughput(self):
Metrics.averageThroughput()
def get_instantaneous_throughput(self):
Metrics.instantaneousThroughput()
| try:
event = event.split()
if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and \
event[I_PKT_TYPE] in DATA_PKTS:
if event[I_SRC_FIELD_TOKEN] == S_SRC_FIELD_TOKEN:
src = event[I_SRC_ADDR_PORT].split('.')[0]
if src not in self._sourceNodes and int(src) >= 0:
self._sourceNodes.append(src)
else:
continue
# Is is required to have destination nodes???
# In case of TCP, source nodes themselves will become
# destination of acknowledgements
#
# if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and \
# event[I_PKT_TYPE] in DATA_PKTS:
# if event[I_DST_FIELD_TOKEN] == S_DST_FIELD_TOKEN:
# dst = event[I_DST_ADDR_PORT].split('.')[0]
# if dst not in self._destinationNodes and int(dst) >= 0: | conditional_block |
trace_analyzer_old.py | __author__= "barun"
__date__ = "$20 May, 2011 12:25:36 PM$"
from metrics import Metrics
from wireless_fields import *
DATA_PKTS = ('tcp', 'udp', 'ack',)
def is_control_pkt(pkt_type=''):
return pkt_type not in DATA_PKTS
class TraceAnalyzer(object):
'''
Trace Analyzer
'''
def __init__(self, file_name=None):
print 'Trace Analyzer'
self._receiveEvents = []
self._sendEvents = []
self._dropEvents = []
self._otherEvents = []
self._data_pkts_rcvd = []
self._cntrl_pkts_rcvd = []
self._sourceNodes = []
self._destinationNodes = []
self.parse_events(file_name)
self.get_statistics()
def parse_events(self, file_name):
'''
Parse the send, receive and drop events, and store them in a list. This
method should get called only once (from inside __init__) at the
beginning of processing.
'''
print 'Parse events -- Use normal record scan to filter receive events'
if file_name:
trace_file = None
try:
trace_file = open(file_name, 'r')
for event in trace_file:
if event[0] == EVENT_RECEIVE:
self._receiveEvents.append(event)
elif event[0] == EVENT_SEND:
self._sendEvents.append(event)
elif event[0] == EVENT_DROP:
self._dropEvents.append(event)
else:
self._otherEvents.append(event)
except IOError, ioe:
print 'IOError:', str(ioe)
finally:
if trace_file:
trace_file.close()
for event in self._receiveEvents:
event = event.split()
try:
if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and\
event[I_TRACE_LEVEL_TOKEN] == S_TRACE_LEVEL_TOKEN and\
event[I_PKT_TYPE] in DATA_PKTS:
self._data_pkts_rcvd.append(event)
else:
self._cntrl_pkts_rcvd.append(event)
except IndexError:
#print event
self._data_pkts_rcvd.append(event)
continue
# Determine sending and receiving nodes
for event in self._sendEvents:
try:
event = event.split()
if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and \
event[I_PKT_TYPE] in DATA_PKTS:
if event[I_SRC_FIELD_TOKEN] == S_SRC_FIELD_TOKEN:
src = event[I_SRC_ADDR_PORT].split('.')[0]
if src not in self._sourceNodes and int(src) >= 0:
self._sourceNodes.append(src)
else:
continue
# Is is required to have destination nodes???
# In case of TCP, source nodes themselves will become
# destination of acknowledgements
#
# if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and \
# event[I_PKT_TYPE] in DATA_PKTS:
# if event[I_DST_FIELD_TOKEN] == S_DST_FIELD_TOKEN: | # continue
except IndexError:
# IndexError can occur because certain log entries from MAC
# layer may not have source and destination infos -- don't
# know exactly why
continue
# Compute simulation times
try:
self._simulationStartTime = float(self._sendEvents[0].split()[I_TIMESTAMP])
except IndexError:
self._simulationStartTime = 0
try:
self._simulationEndTime = float(self._sendEvents[len(self._sendEvents)-1].split()[I_TIMESTAMP])
except IndexError:
self._simulationEndTime = 0
self._simulationDuration = self._simulationEndTime - self._simulationStartTime
def get_statistics(self):
msg = '''
Simulation start: %f
Simulation end: %f
Duration: %f
Source nodes: %s
# of packets sent: %d
# of packets received: %d
# of data packets: %d
# of control packets:%d
# of packets droped: %d
# of other events: %d
''' % (
self._simulationStartTime,
self._simulationEndTime,
self._simulationDuration,
self._sourceNodes,
len(self._sendEvents),
len(self._receiveEvents),
len(self._data_pkts_rcvd),
len(self._cntrl_pkts_rcvd),
len(self._dropEvents),
len(self._otherEvents),
)
print msg
def get_average_throughput(self):
Metrics.averageThroughput()
def get_instantaneous_throughput(self):
Metrics.instantaneousThroughput() | # dst = event[I_DST_ADDR_PORT].split('.')[0]
# if dst not in self._destinationNodes and int(dst) >= 0:
# self._destinationNodes.append(dst)
# else: | random_line_split |
trace_analyzer_old.py | __author__= "barun"
__date__ = "$20 May, 2011 12:25:36 PM$"
from metrics import Metrics
from wireless_fields import *
DATA_PKTS = ('tcp', 'udp', 'ack',)
def is_control_pkt(pkt_type=''):
return pkt_type not in DATA_PKTS
class TraceAnalyzer(object):
'''
Trace Analyzer
'''
def __init__(self, file_name=None):
|
def parse_events(self, file_name):
'''
Parse the send, receive and drop events, and store them in a list. This
method should get called only once (from inside __init__) at the
beginning of processing.
'''
print 'Parse events -- Use normal record scan to filter receive events'
if file_name:
trace_file = None
try:
trace_file = open(file_name, 'r')
for event in trace_file:
if event[0] == EVENT_RECEIVE:
self._receiveEvents.append(event)
elif event[0] == EVENT_SEND:
self._sendEvents.append(event)
elif event[0] == EVENT_DROP:
self._dropEvents.append(event)
else:
self._otherEvents.append(event)
except IOError, ioe:
print 'IOError:', str(ioe)
finally:
if trace_file:
trace_file.close()
for event in self._receiveEvents:
event = event.split()
try:
if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and\
event[I_TRACE_LEVEL_TOKEN] == S_TRACE_LEVEL_TOKEN and\
event[I_PKT_TYPE] in DATA_PKTS:
self._data_pkts_rcvd.append(event)
else:
self._cntrl_pkts_rcvd.append(event)
except IndexError:
#print event
self._data_pkts_rcvd.append(event)
continue
# Determine sending and receiving nodes
for event in self._sendEvents:
try:
event = event.split()
if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and \
event[I_PKT_TYPE] in DATA_PKTS:
if event[I_SRC_FIELD_TOKEN] == S_SRC_FIELD_TOKEN:
src = event[I_SRC_ADDR_PORT].split('.')[0]
if src not in self._sourceNodes and int(src) >= 0:
self._sourceNodes.append(src)
else:
continue
# Is is required to have destination nodes???
# In case of TCP, source nodes themselves will become
# destination of acknowledgements
#
# if event[I_PKT_TYPE_TOKEN] == S_PKT_TYPE_TOKEN and \
# event[I_PKT_TYPE] in DATA_PKTS:
# if event[I_DST_FIELD_TOKEN] == S_DST_FIELD_TOKEN:
# dst = event[I_DST_ADDR_PORT].split('.')[0]
# if dst not in self._destinationNodes and int(dst) >= 0:
# self._destinationNodes.append(dst)
# else:
# continue
except IndexError:
# IndexError can occur because certain log entries from MAC
# layer may not have source and destination infos -- don't
# know exactly why
continue
# Compute simulation times
try:
self._simulationStartTime = float(self._sendEvents[0].split()[I_TIMESTAMP])
except IndexError:
self._simulationStartTime = 0
try:
self._simulationEndTime = float(self._sendEvents[len(self._sendEvents)-1].split()[I_TIMESTAMP])
except IndexError:
self._simulationEndTime = 0
self._simulationDuration = self._simulationEndTime - self._simulationStartTime
def get_statistics(self):
msg = '''
Simulation start: %f
Simulation end: %f
Duration: %f
Source nodes: %s
# of packets sent: %d
# of packets received: %d
# of data packets: %d
# of control packets:%d
# of packets droped: %d
# of other events: %d
''' % (
self._simulationStartTime,
self._simulationEndTime,
self._simulationDuration,
self._sourceNodes,
len(self._sendEvents),
len(self._receiveEvents),
len(self._data_pkts_rcvd),
len(self._cntrl_pkts_rcvd),
len(self._dropEvents),
len(self._otherEvents),
)
print msg
def get_average_throughput(self):
Metrics.averageThroughput()
def get_instantaneous_throughput(self):
Metrics.instantaneousThroughput()
| print 'Trace Analyzer'
self._receiveEvents = []
self._sendEvents = []
self._dropEvents = []
self._otherEvents = []
self._data_pkts_rcvd = []
self._cntrl_pkts_rcvd = []
self._sourceNodes = []
self._destinationNodes = []
self.parse_events(file_name)
self.get_statistics() | identifier_body |
objects.py |
class ObjectXEDA:
kind= -1
name= ''
posX= 0
posY= 0
centerX= 0
centerY= 0
w= 0
h= 0
angle= 0
selected= False
mirrored= False
locked= False
glow= False
dragging= False
def is_over(self, x, y):
'''responde se a coordenada indicado esta sobre esse objeto
'''
pass
def start_drag(self):
pass
def stop_drag(self):
pass
class | (ObjectXEDA):
'''
componentes (descritos aqui)
fios
juncoes
power
portas (entre folhas)
net names
textos livres
caixa de texto
bus
entradas de bus
graficos (linhas, circulos, retangulos, arcos, poligonos)
'''
def __init__(self):
self.pn= '74hc123'
self.ref= 'U12'
self.comment= '74HC123'
#parts deveria ser uma lista de parts do componentes, cada lista com uma lista dos pinos desta parte
#seguida dos graficos dessa parte
self.parts= 2
self.pins= [[(0, 0, 'bla', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (50, 0, 'ble', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (200, 0, 'bli', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id')],
[(0, 100, 'da', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (50, 150, 'de', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (200, 300, 'di', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (250, 50, 'do', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id')]
]
self.partId= 0
self.drawns= []
self.foots= ['so16', 'so16.3', 'dip16']
self.footId= 1
def draw(self):
pass
class PCBObject(ObjectXEDA):
'''
componentes (como descritos aqui)
pad isolado
via
linhas
arcos (partindo do centro e dos extermos)
textos
'''
def __init__(self):
self.foot= 'sop23'
self.ref= 'U12'
self.comment= 'teste'
self.pads= [(0, 0, 'id', 'quadrado', 'w', 'h', 'top', 'furo-diametro', 'net-name', 'mask'),
(25, 0, 'id', 'quadrado', 'w', 'h', 'top', 'furo-diametro', 'net-name', 'mask')
]
self.drawns= []
def draw(self):
pass
| SCHObject | identifier_name |
objects.py |
class ObjectXEDA:
kind= -1
name= ''
posX= 0
posY= 0
centerX= 0
centerY= 0
w= 0
h= 0
angle= 0
selected= False
mirrored= False
locked= False
glow= False
dragging= False
def is_over(self, x, y):
'''responde se a coordenada indicado esta sobre esse objeto
'''
pass
def start_drag(self):
pass
def stop_drag(self):
pass
class SCHObject(ObjectXEDA):
'''
componentes (descritos aqui)
fios
juncoes
power
portas (entre folhas)
net names
textos livres
caixa de texto
bus
entradas de bus
graficos (linhas, circulos, retangulos, arcos, poligonos)
'''
def __init__(self):
self.pn= '74hc123'
self.ref= 'U12'
self.comment= '74HC123'
#parts deveria ser uma lista de parts do componentes, cada lista com uma lista dos pinos desta parte
#seguida dos graficos dessa parte
self.parts= 2
self.pins= [[(0, 0, 'bla', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (50, 0, 'ble', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (200, 0, 'bli', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id')],
[(0, 100, 'da', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (50, 150, 'de', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (200, 300, 'di', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (250, 50, 'do', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id')]
]
self.partId= 0
self.drawns= []
self.foots= ['so16', 'so16.3', 'dip16']
self.footId= 1
def draw(self):
pass
class PCBObject(ObjectXEDA):
| '''
componentes (como descritos aqui)
pad isolado
via
linhas
arcos (partindo do centro e dos extermos)
textos
'''
def __init__(self):
self.foot= 'sop23'
self.ref= 'U12'
self.comment= 'teste'
self.pads= [(0, 0, 'id', 'quadrado', 'w', 'h', 'top', 'furo-diametro', 'net-name', 'mask'),
(25, 0, 'id', 'quadrado', 'w', 'h', 'top', 'furo-diametro', 'net-name', 'mask')
]
self.drawns= []
def draw(self):
pass | identifier_body |
|
objects.py | class ObjectXEDA:
kind= -1
name= ''
posX= 0
posY= 0
centerX= 0
centerY= 0
w= 0
h= 0
angle= 0
selected= False
mirrored= False
locked= False
glow= False
dragging= False
def is_over(self, x, y):
'''responde se a coordenada indicado esta sobre esse objeto
'''
pass
def start_drag(self):
pass
def stop_drag(self):
pass
| juncoes
power
portas (entre folhas)
net names
textos livres
caixa de texto
bus
entradas de bus
graficos (linhas, circulos, retangulos, arcos, poligonos)
'''
def __init__(self):
self.pn= '74hc123'
self.ref= 'U12'
self.comment= '74HC123'
#parts deveria ser uma lista de parts do componentes, cada lista com uma lista dos pinos desta parte
#seguida dos graficos dessa parte
self.parts= 2
self.pins= [[(0, 0, 'bla', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (50, 0, 'ble', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (200, 0, 'bli', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id')],
[(0, 100, 'da', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (50, 150, 'de', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (200, 300, 'di', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id'), (250, 50, 'do', 'id', 'angle', 'clk', 'dot', 'show-name', 'show-id')]
]
self.partId= 0
self.drawns= []
self.foots= ['so16', 'so16.3', 'dip16']
self.footId= 1
def draw(self):
pass
class PCBObject(ObjectXEDA):
'''
componentes (como descritos aqui)
pad isolado
via
linhas
arcos (partindo do centro e dos extermos)
textos
'''
def __init__(self):
self.foot= 'sop23'
self.ref= 'U12'
self.comment= 'teste'
self.pads= [(0, 0, 'id', 'quadrado', 'w', 'h', 'top', 'furo-diametro', 'net-name', 'mask'),
(25, 0, 'id', 'quadrado', 'w', 'h', 'top', 'furo-diametro', 'net-name', 'mask')
]
self.drawns= []
def draw(self):
pass | class SCHObject(ObjectXEDA):
'''
componentes (descritos aqui)
fios | random_line_split |
lib.rs | extern crate lexer;
use lexer::{Item, StateFn, Lexer};
#[derive(Debug, PartialEq)]
pub enum ItemType {
Comma,
Text,
Comment,
EOF
}
fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
if l.remaining_input().starts_with("//") {
l.emit_nonempty(ItemType::Text);
l.next();
return Some(StateFn(lex_comment));
}
match l.next() {
None => break,
Some(',') => {
l.backup();
l.emit_nonempty(ItemType::Text);
l.next();
l.emit(ItemType::Comma);
},
Some(_) => {},
}
}
l.emit_nonempty(ItemType::Text);
l.emit(ItemType::EOF);
None
}
fn lex_comment(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
match l.next() {
None => break,
Some('\n') => {
l.backup();
l.emit_nonempty(ItemType::Comment);
l.next();
l.ignore();
return Some(StateFn(lex_text));
},
Some(_) => {},
}
}
l.emit_nonempty(ItemType::Comment);
l.emit(ItemType::EOF);
None
}
#[test]
fn test_lexer() {
let data = "foo,bar,baz // some comment\nfoo,bar";
let items = lexer::lex(data, lex_text);
let expected_items = vec!(
Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1},
Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1},
Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 1},
Item{typ: ItemType::Comma, val: ",", col: 8, lineno: 1},
Item{typ: ItemType::Text, val: "baz ", col: 9, lineno: 1},
Item{typ: ItemType::Comment, val: "// some comment", col: 13, lineno: 1},
Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 2},
Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 2},
Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 2},
Item{typ: ItemType::EOF, val: "", col: 8, lineno: 2}
);
for (item, expected) in items.iter().zip(expected_items.iter()) {
println!("ITEM: {:?}", item);
assert_eq!(item, expected);
}
| assert_eq!(items, expected_items);
} | random_line_split |
|
lib.rs | extern crate lexer;
use lexer::{Item, StateFn, Lexer};
#[derive(Debug, PartialEq)]
pub enum ItemType {
Comma,
Text,
Comment,
EOF
}
fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
if l.remaining_input().starts_with("//") {
l.emit_nonempty(ItemType::Text);
l.next();
return Some(StateFn(lex_comment));
}
match l.next() {
None => break,
Some(',') => {
l.backup();
l.emit_nonempty(ItemType::Text);
l.next();
l.emit(ItemType::Comma);
},
Some(_) => {},
}
}
l.emit_nonempty(ItemType::Text);
l.emit(ItemType::EOF);
None
}
fn lex_comment(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> |
#[test]
fn test_lexer() {
let data = "foo,bar,baz // some comment\nfoo,bar";
let items = lexer::lex(data, lex_text);
let expected_items = vec!(
Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1},
Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1},
Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 1},
Item{typ: ItemType::Comma, val: ",", col: 8, lineno: 1},
Item{typ: ItemType::Text, val: "baz ", col: 9, lineno: 1},
Item{typ: ItemType::Comment, val: "// some comment", col: 13, lineno: 1},
Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 2},
Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 2},
Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 2},
Item{typ: ItemType::EOF, val: "", col: 8, lineno: 2}
);
for (item, expected) in items.iter().zip(expected_items.iter()) {
println!("ITEM: {:?}", item);
assert_eq!(item, expected);
}
assert_eq!(items, expected_items);
}
| {
loop {
match l.next() {
None => break,
Some('\n') => {
l.backup();
l.emit_nonempty(ItemType::Comment);
l.next();
l.ignore();
return Some(StateFn(lex_text));
},
Some(_) => {},
}
}
l.emit_nonempty(ItemType::Comment);
l.emit(ItemType::EOF);
None
} | identifier_body |
lib.rs | extern crate lexer;
use lexer::{Item, StateFn, Lexer};
#[derive(Debug, PartialEq)]
pub enum | {
Comma,
Text,
Comment,
EOF
}
fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
if l.remaining_input().starts_with("//") {
l.emit_nonempty(ItemType::Text);
l.next();
return Some(StateFn(lex_comment));
}
match l.next() {
None => break,
Some(',') => {
l.backup();
l.emit_nonempty(ItemType::Text);
l.next();
l.emit(ItemType::Comma);
},
Some(_) => {},
}
}
l.emit_nonempty(ItemType::Text);
l.emit(ItemType::EOF);
None
}
fn lex_comment(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
match l.next() {
None => break,
Some('\n') => {
l.backup();
l.emit_nonempty(ItemType::Comment);
l.next();
l.ignore();
return Some(StateFn(lex_text));
},
Some(_) => {},
}
}
l.emit_nonempty(ItemType::Comment);
l.emit(ItemType::EOF);
None
}
#[test]
fn test_lexer() {
let data = "foo,bar,baz // some comment\nfoo,bar";
let items = lexer::lex(data, lex_text);
let expected_items = vec!(
Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1},
Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1},
Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 1},
Item{typ: ItemType::Comma, val: ",", col: 8, lineno: 1},
Item{typ: ItemType::Text, val: "baz ", col: 9, lineno: 1},
Item{typ: ItemType::Comment, val: "// some comment", col: 13, lineno: 1},
Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 2},
Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 2},
Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 2},
Item{typ: ItemType::EOF, val: "", col: 8, lineno: 2}
);
for (item, expected) in items.iter().zip(expected_items.iter()) {
println!("ITEM: {:?}", item);
assert_eq!(item, expected);
}
assert_eq!(items, expected_items);
}
| ItemType | identifier_name |
lib.rs | extern crate lexer;
use lexer::{Item, StateFn, Lexer};
#[derive(Debug, PartialEq)]
pub enum ItemType {
Comma,
Text,
Comment,
EOF
}
fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
if l.remaining_input().starts_with("//") {
l.emit_nonempty(ItemType::Text);
l.next();
return Some(StateFn(lex_comment));
}
match l.next() {
None => break,
Some(',') => {
l.backup();
l.emit_nonempty(ItemType::Text);
l.next();
l.emit(ItemType::Comma);
},
Some(_) => {},
}
}
l.emit_nonempty(ItemType::Text);
l.emit(ItemType::EOF);
None
}
fn lex_comment(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> {
loop {
match l.next() {
None => break,
Some('\n') => | ,
Some(_) => {},
}
}
l.emit_nonempty(ItemType::Comment);
l.emit(ItemType::EOF);
None
}
#[test]
fn test_lexer() {
let data = "foo,bar,baz // some comment\nfoo,bar";
let items = lexer::lex(data, lex_text);
let expected_items = vec!(
Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1},
Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1},
Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 1},
Item{typ: ItemType::Comma, val: ",", col: 8, lineno: 1},
Item{typ: ItemType::Text, val: "baz ", col: 9, lineno: 1},
Item{typ: ItemType::Comment, val: "// some comment", col: 13, lineno: 1},
Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 2},
Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 2},
Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 2},
Item{typ: ItemType::EOF, val: "", col: 8, lineno: 2}
);
for (item, expected) in items.iter().zip(expected_items.iter()) {
println!("ITEM: {:?}", item);
assert_eq!(item, expected);
}
assert_eq!(items, expected_items);
}
| {
l.backup();
l.emit_nonempty(ItemType::Comment);
l.next();
l.ignore();
return Some(StateFn(lex_text));
} | conditional_block |
libstdc++.a-gdb.py | # -*- python -*-
# Copyright (C) 2009 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import gdb
import os
import os.path
pythondir = '/opt/codesourcery/arm-none-eabi/share/gcc-4.5.1/python'
libdir = '/opt/codesourcery/arm-none-eabi/lib/armv6-m'
# This file might be loaded when there is no current objfile. This
# can happen if the user loads it manually. In this case we don't
# update sys.path; instead we just hope the user managed to do that
# beforehand.
if gdb.current_objfile () is not None:
# Update module path. We want to find the relative path from libdir
# to pythondir, and then we want to apply that relative path to the
# directory holding the objfile with which this file is associated.
# This preserves relocatability of the gcc tree.
# Do a simple normalization that removes duplicate separators.
| sys.path.insert(0, dir)
# Load the pretty-printers.
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (gdb.current_objfile ())
| pythondir = os.path.normpath (pythondir)
libdir = os.path.normpath (libdir)
prefix = os.path.commonprefix ([libdir, pythondir])
# In some bizarre configuration we might have found a match in the
# middle of a directory name.
if prefix[-1] != '/':
prefix = os.path.dirname (prefix) + '/'
# Strip off the prefix.
pythondir = pythondir[len (prefix):]
libdir = libdir[len (prefix):]
# Compute the ".."s needed to get from libdir to the prefix.
dotdots = ('..' + os.sep) * len (libdir.split (os.sep))
objfile = gdb.current_objfile ().filename
dir = os.path.join (os.path.dirname (objfile), dotdots, pythondir)
if not dir in sys.path: | conditional_block |
libstdc++.a-gdb.py | # -*- python -*-
# Copyright (C) 2009 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by | # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import gdb
import os
import os.path
pythondir = '/opt/codesourcery/arm-none-eabi/share/gcc-4.5.1/python'
libdir = '/opt/codesourcery/arm-none-eabi/lib/armv6-m'
# This file might be loaded when there is no current objfile. This
# can happen if the user loads it manually. In this case we don't
# update sys.path; instead we just hope the user managed to do that
# beforehand.
if gdb.current_objfile () is not None:
# Update module path. We want to find the relative path from libdir
# to pythondir, and then we want to apply that relative path to the
# directory holding the objfile with which this file is associated.
# This preserves relocatability of the gcc tree.
# Do a simple normalization that removes duplicate separators.
pythondir = os.path.normpath (pythondir)
libdir = os.path.normpath (libdir)
prefix = os.path.commonprefix ([libdir, pythondir])
# In some bizarre configuration we might have found a match in the
# middle of a directory name.
if prefix[-1] != '/':
prefix = os.path.dirname (prefix) + '/'
# Strip off the prefix.
pythondir = pythondir[len (prefix):]
libdir = libdir[len (prefix):]
# Compute the ".."s needed to get from libdir to the prefix.
dotdots = ('..' + os.sep) * len (libdir.split (os.sep))
objfile = gdb.current_objfile ().filename
dir = os.path.join (os.path.dirname (objfile), dotdots, pythondir)
if not dir in sys.path:
sys.path.insert(0, dir)
# Load the pretty-printers.
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (gdb.current_objfile ()) | # the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, | random_line_split |
method_registry.py | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A registry module for registering alert methods.
"""
from django.db import models
from method_base import AlertMethodBase
class MethodRegistry(dict):
"""
Dict with methods for handling method registration.
"""
def unregister(self, name):
method = self[name]
del self[name]
def register(self, name, module):
"""
Registers a method with its name and module.
"""
if not issubclass(module, AlertMethodBase):
raise AttributeError("Module given to MethodRegistry not valid") | if not name:
raise AttributeError("MethodRegistry not given a name for module.")
module.name = name
self[name] = module
def _autodiscover(registry):
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Import alert_methods from each app
try:
before_import_registry = copy.copy(registry)
import_module('%s.alert_methods' % app)
except:
registry = before_import_registry
if module_has_submodule(mod, 'alert_methods'):
raise
registry = MethodRegistry()
def autodiscover():
_autodiscover(registry)
def register(name, module):
"""Proxy for register method."""
return registry.register(name, module) | random_line_split |
|
method_registry.py | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A registry module for registering alert methods.
"""
from django.db import models
from method_base import AlertMethodBase
class MethodRegistry(dict):
"""
Dict with methods for handling method registration.
"""
def unregister(self, name):
method = self[name]
del self[name]
def register(self, name, module):
"""
Registers a method with its name and module.
"""
if not issubclass(module, AlertMethodBase):
raise AttributeError("Module given to MethodRegistry not valid")
if not name:
raise AttributeError("MethodRegistry not given a name for module.")
module.name = name
self[name] = module
def _autodiscover(registry):
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
|
registry = MethodRegistry()
def autodiscover():
_autodiscover(registry)
def register(name, module):
"""Proxy for register method."""
return registry.register(name, module)
| mod = import_module(app)
# Import alert_methods from each app
try:
before_import_registry = copy.copy(registry)
import_module('%s.alert_methods' % app)
except:
registry = before_import_registry
if module_has_submodule(mod, 'alert_methods'):
raise | conditional_block |
method_registry.py | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A registry module for registering alert methods.
"""
from django.db import models
from method_base import AlertMethodBase
class MethodRegistry(dict):
"""
Dict with methods for handling method registration.
"""
def unregister(self, name):
method = self[name]
del self[name]
def register(self, name, module):
"""
Registers a method with its name and module.
"""
if not issubclass(module, AlertMethodBase):
raise AttributeError("Module given to MethodRegistry not valid")
if not name:
raise AttributeError("MethodRegistry not given a name for module.")
module.name = name
self[name] = module
def _autodiscover(registry):
|
registry = MethodRegistry()
def autodiscover():
_autodiscover(registry)
def register(name, module):
"""Proxy for register method."""
return registry.register(name, module)
| import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Import alert_methods from each app
try:
before_import_registry = copy.copy(registry)
import_module('%s.alert_methods' % app)
except:
registry = before_import_registry
if module_has_submodule(mod, 'alert_methods'):
raise | identifier_body |
method_registry.py | # Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A registry module for registering alert methods.
"""
from django.db import models
from method_base import AlertMethodBase
class MethodRegistry(dict):
"""
Dict with methods for handling method registration.
"""
def | (self, name):
method = self[name]
del self[name]
def register(self, name, module):
"""
Registers a method with its name and module.
"""
if not issubclass(module, AlertMethodBase):
raise AttributeError("Module given to MethodRegistry not valid")
if not name:
raise AttributeError("MethodRegistry not given a name for module.")
module.name = name
self[name] = module
def _autodiscover(registry):
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Import alert_methods from each app
try:
before_import_registry = copy.copy(registry)
import_module('%s.alert_methods' % app)
except:
registry = before_import_registry
if module_has_submodule(mod, 'alert_methods'):
raise
registry = MethodRegistry()
def autodiscover():
_autodiscover(registry)
def register(name, module):
"""Proxy for register method."""
return registry.register(name, module)
| unregister | identifier_name |
user-profile.component.ts | import {Component, EventEmitter, Output, Input, OnInit} from '@angular/core';
import {UserModel, UserResponse} from "../user-management/user.model";
import {UserService} from "../user-management/user.service";
import {Config} from "../../../shared/configs/general.config";
@Component({
selector: 'user-profile',
templateUrl: './user-profile.html'
})
export class UserProfileComponent implements OnInit {
// @Input showInfo:boolean;
@Input() userId:string;
@Output() userEditEvent:EventEmitter<any> = new EventEmitter();
@Input() showView:boolean;
objUser:UserModel = new UserModel();
objResponse:UserResponse = new UserResponse();
imageSrc:string=Config.DefaultAvatar;
ngOnInit() {
this.getUserDetail();
}
constructor(private _objUserService:UserService) {
}
getUserDetail() {
this._objUserService.getUserDetail(this.userId)
.subscribe(resUser => this.bindDetail(resUser),
error => this.errorMessage(error));
}
errorMessage(objResponse:any) {
swal("Alert !", objResponse.message, "info");
}
bindDetail(objUser:UserModel) {
this.objUser = objUser;
if (!this.objUser.imageName)
this.imageSrc = Config.DefaultAvatar;
else {
let cl = Config.Cloudinary;
this.imageSrc = cl.url(this.objUser.imageName, {transformation: [{width: 100, crop: "scale"}]});
}
}
onShowView(args) |
onShowEdit() {
this.showView = false;
}
}
| {
if (!args) // isCanceled
this.getUserDetail();
this.showView = true;
} | identifier_body |
user-profile.component.ts | import {Component, EventEmitter, Output, Input, OnInit} from '@angular/core';
import {UserModel, UserResponse} from "../user-management/user.model";
import {UserService} from "../user-management/user.service";
import {Config} from "../../../shared/configs/general.config";
@Component({
selector: 'user-profile',
templateUrl: './user-profile.html' | })
export class UserProfileComponent implements OnInit {
// @Input showInfo:boolean;
@Input() userId:string;
@Output() userEditEvent:EventEmitter<any> = new EventEmitter();
@Input() showView:boolean;
objUser:UserModel = new UserModel();
objResponse:UserResponse = new UserResponse();
imageSrc:string=Config.DefaultAvatar;
ngOnInit() {
this.getUserDetail();
}
constructor(private _objUserService:UserService) {
}
getUserDetail() {
this._objUserService.getUserDetail(this.userId)
.subscribe(resUser => this.bindDetail(resUser),
error => this.errorMessage(error));
}
errorMessage(objResponse:any) {
swal("Alert !", objResponse.message, "info");
}
bindDetail(objUser:UserModel) {
this.objUser = objUser;
if (!this.objUser.imageName)
this.imageSrc = Config.DefaultAvatar;
else {
let cl = Config.Cloudinary;
this.imageSrc = cl.url(this.objUser.imageName, {transformation: [{width: 100, crop: "scale"}]});
}
}
onShowView(args) {
if (!args) // isCanceled
this.getUserDetail();
this.showView = true;
}
onShowEdit() {
this.showView = false;
}
} | random_line_split |
|
user-profile.component.ts | import {Component, EventEmitter, Output, Input, OnInit} from '@angular/core';
import {UserModel, UserResponse} from "../user-management/user.model";
import {UserService} from "../user-management/user.service";
import {Config} from "../../../shared/configs/general.config";
@Component({
selector: 'user-profile',
templateUrl: './user-profile.html'
})
export class UserProfileComponent implements OnInit {
// @Input showInfo:boolean;
@Input() userId:string;
@Output() userEditEvent:EventEmitter<any> = new EventEmitter();
@Input() showView:boolean;
objUser:UserModel = new UserModel();
objResponse:UserResponse = new UserResponse();
imageSrc:string=Config.DefaultAvatar;
ngOnInit() {
this.getUserDetail();
}
constructor(private _objUserService:UserService) {
}
getUserDetail() {
this._objUserService.getUserDetail(this.userId)
.subscribe(resUser => this.bindDetail(resUser),
error => this.errorMessage(error));
}
| (objResponse:any) {
swal("Alert !", objResponse.message, "info");
}
bindDetail(objUser:UserModel) {
this.objUser = objUser;
if (!this.objUser.imageName)
this.imageSrc = Config.DefaultAvatar;
else {
let cl = Config.Cloudinary;
this.imageSrc = cl.url(this.objUser.imageName, {transformation: [{width: 100, crop: "scale"}]});
}
}
onShowView(args) {
if (!args) // isCanceled
this.getUserDetail();
this.showView = true;
}
onShowEdit() {
this.showView = false;
}
}
| errorMessage | identifier_name |
mod.rs | extern crate sodiumoxide;
extern crate serialize;
extern crate sync;
extern crate extra;
use std::io::{Listener, Acceptor};
use std::io::{MemReader, BufReader};
use std::io::net::ip::{SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::from_str::{from_str};
use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader};
use capnp::serialize_packed;
use sync::Arc;
use sodiumoxide::crypto::asymmetricbox::{PublicKey, SecretKey, open, seal, gen_keypair};
use helpers::{KeyBytes, bytes_to_pubkey, bytes_to_nonce};
use super::comm;
fn process_new_connection(client: TcpStream, my_pubkey: Arc<PublicKey>, my_privkey: Arc<SecretKey>) {
use capnp::serialize_packed;
use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader};
let mut client = client;
println!("New connection from '{:s}'", client.peer_name().unwrap().to_str());
let hellopack = client.read_bytes(9).unwrap();
if (hellopack.as_slice() == comm::bare_msgs::HELLOBYTES) |
else {
fail!("sad :(");
}
client.write(comm::bare_msgs::HELLOBYTES);
client.write(my_pubkey.get().key_bytes());
let client_pubkey = ~{
let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap();
let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>();
let mut bufreader = BufReader::new(pack.get_data());
let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap();
let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>();
match packdata.which() {
Some(comm::pack_capnp::PackData::Pubkey(key)) => bytes_to_pubkey(key),
_ => { println!("Client didn't send pubkey, disconnecting"); return; }
}
};
println!("got client key:\n{:?}", client_pubkey);
let mut clientname = ~"";
loop {
let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap();
let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>();
let nonce = bytes_to_nonce(pack.get_nonce());
let databytes = match open(pack.get_data(), &nonce, client_pubkey, my_privkey.get()) {
Some(bytes) => bytes,
None => { println!("WARNING! Decrypt failed! "); continue; }
};
let mut bufreader = BufReader::new(databytes);
let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap();
let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>();
match packdata.which() {
Some(comm::pack_capnp::PackData::Login(login)) => {
println!("{:s} logged in", login.get_name());
clientname = login.get_name().to_owned();
},
Some(comm::pack_capnp::PackData::Message(message)) => {
println!("<{:s}>{:s}", clientname, message.get_message());
},
Some(comm::pack_capnp::PackData::Quit(reason)) => {
println!("quitreason: {:s}", reason);
break;
},
_ => println!("wut")
}
}
}
fn writer_task() {
}
fn setup_sync_task() {
}
pub fn main() {
sodiumoxide::init();
let (s_pubkey, s_privkey) = gen_keypair();
let a_pubkey = Arc::new(s_pubkey);
let a_privkey = Arc::new(s_privkey);
let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap();
let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind");
let mut s_acceptor = s_listener.listen().ok().expect("Failed to create connection listener");
loop {
let pub_clone = a_pubkey.clone();
let priv_clone = a_privkey.clone();
match s_acceptor.accept() {
Ok(c_sock) => spawn(proc(){process_new_connection(c_sock, pub_clone, priv_clone)}),
Err(err) => println!("Failed connection attempt: {:?}", err)
}
}
} | {
println!("Connection hello received");
} | conditional_block |
mod.rs | extern crate sodiumoxide;
extern crate serialize;
extern crate sync;
extern crate extra;
use std::io::{Listener, Acceptor};
use std::io::{MemReader, BufReader};
use std::io::net::ip::{SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::from_str::{from_str};
use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader};
use capnp::serialize_packed;
use sync::Arc;
use sodiumoxide::crypto::asymmetricbox::{PublicKey, SecretKey, open, seal, gen_keypair};
use helpers::{KeyBytes, bytes_to_pubkey, bytes_to_nonce};
use super::comm;
fn process_new_connection(client: TcpStream, my_pubkey: Arc<PublicKey>, my_privkey: Arc<SecretKey>) {
use capnp::serialize_packed;
use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader};
let mut client = client;
println!("New connection from '{:s}'", client.peer_name().unwrap().to_str());
let hellopack = client.read_bytes(9).unwrap();
if (hellopack.as_slice() == comm::bare_msgs::HELLOBYTES) {
println!("Connection hello received");
}
else {
fail!("sad :(");
}
client.write(comm::bare_msgs::HELLOBYTES);
client.write(my_pubkey.get().key_bytes());
let client_pubkey = ~{
let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap();
let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>();
let mut bufreader = BufReader::new(pack.get_data());
let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap();
let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>();
match packdata.which() {
Some(comm::pack_capnp::PackData::Pubkey(key)) => bytes_to_pubkey(key),
_ => { println!("Client didn't send pubkey, disconnecting"); return; }
}
};
println!("got client key:\n{:?}", client_pubkey);
let mut clientname = ~"";
loop {
let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap();
let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>();
let nonce = bytes_to_nonce(pack.get_nonce());
let databytes = match open(pack.get_data(), &nonce, client_pubkey, my_privkey.get()) {
Some(bytes) => bytes,
None => { println!("WARNING! Decrypt failed! "); continue; }
};
let mut bufreader = BufReader::new(databytes);
let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap();
let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>();
match packdata.which() {
Some(comm::pack_capnp::PackData::Login(login)) => {
println!("{:s} logged in", login.get_name());
clientname = login.get_name().to_owned();
},
Some(comm::pack_capnp::PackData::Message(message)) => {
println!("<{:s}>{:s}", clientname, message.get_message());
},
Some(comm::pack_capnp::PackData::Quit(reason)) => {
println!("quitreason: {:s}", reason);
break;
},
_ => println!("wut")
}
}
}
fn writer_task() {
}
fn setup_sync_task() {
}
pub fn | () {
sodiumoxide::init();
let (s_pubkey, s_privkey) = gen_keypair();
let a_pubkey = Arc::new(s_pubkey);
let a_privkey = Arc::new(s_privkey);
let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap();
let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind");
let mut s_acceptor = s_listener.listen().ok().expect("Failed to create connection listener");
loop {
let pub_clone = a_pubkey.clone();
let priv_clone = a_privkey.clone();
match s_acceptor.accept() {
Ok(c_sock) => spawn(proc(){process_new_connection(c_sock, pub_clone, priv_clone)}),
Err(err) => println!("Failed connection attempt: {:?}", err)
}
}
} | main | identifier_name |
mod.rs | extern crate sodiumoxide;
extern crate serialize;
extern crate sync;
extern crate extra;
use std::io::{Listener, Acceptor};
use std::io::{MemReader, BufReader};
use std::io::net::ip::{SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::from_str::{from_str};
use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader};
use capnp::serialize_packed;
use sync::Arc;
use sodiumoxide::crypto::asymmetricbox::{PublicKey, SecretKey, open, seal, gen_keypair};
use helpers::{KeyBytes, bytes_to_pubkey, bytes_to_nonce};
use super::comm;
fn process_new_connection(client: TcpStream, my_pubkey: Arc<PublicKey>, my_privkey: Arc<SecretKey>) {
use capnp::serialize_packed;
use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader};
let mut client = client;
println!("New connection from '{:s}'", client.peer_name().unwrap().to_str());
let hellopack = client.read_bytes(9).unwrap();
if (hellopack.as_slice() == comm::bare_msgs::HELLOBYTES) {
println!("Connection hello received");
}
else {
fail!("sad :(");
}
client.write(comm::bare_msgs::HELLOBYTES);
client.write(my_pubkey.get().key_bytes());
let client_pubkey = ~{
let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap();
let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>();
let mut bufreader = BufReader::new(pack.get_data());
let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap();
let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>();
match packdata.which() {
Some(comm::pack_capnp::PackData::Pubkey(key)) => bytes_to_pubkey(key),
_ => { println!("Client didn't send pubkey, disconnecting"); return; }
}
};
println!("got client key:\n{:?}", client_pubkey);
let mut clientname = ~"";
loop {
let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap();
let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>();
let nonce = bytes_to_nonce(pack.get_nonce());
let databytes = match open(pack.get_data(), &nonce, client_pubkey, my_privkey.get()) {
Some(bytes) => bytes,
None => { println!("WARNING! Decrypt failed! "); continue; }
};
let mut bufreader = BufReader::new(databytes);
let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap();
let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>();
match packdata.which() {
Some(comm::pack_capnp::PackData::Login(login)) => {
println!("{:s} logged in", login.get_name());
clientname = login.get_name().to_owned();
},
Some(comm::pack_capnp::PackData::Message(message)) => {
println!("<{:s}>{:s}", clientname, message.get_message());
},
Some(comm::pack_capnp::PackData::Quit(reason)) => {
println!("quitreason: {:s}", reason);
break;
},
_ => println!("wut")
}
}
}
fn writer_task() {
}
fn setup_sync_task() |
pub fn main() {
sodiumoxide::init();
let (s_pubkey, s_privkey) = gen_keypair();
let a_pubkey = Arc::new(s_pubkey);
let a_privkey = Arc::new(s_privkey);
let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap();
let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind");
let mut s_acceptor = s_listener.listen().ok().expect("Failed to create connection listener");
loop {
let pub_clone = a_pubkey.clone();
let priv_clone = a_privkey.clone();
match s_acceptor.accept() {
Ok(c_sock) => spawn(proc(){process_new_connection(c_sock, pub_clone, priv_clone)}),
Err(err) => println!("Failed connection attempt: {:?}", err)
}
}
} | {
} | identifier_body |
mod.rs | extern crate sodiumoxide;
extern crate serialize;
extern crate sync;
extern crate extra;
use std::io::{Listener, Acceptor};
use std::io::{MemReader, BufReader};
use std::io::net::ip::{SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::from_str::{from_str};
use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader};
use capnp::serialize_packed;
use sync::Arc;
use sodiumoxide::crypto::asymmetricbox::{PublicKey, SecretKey, open, seal, gen_keypair};
use helpers::{KeyBytes, bytes_to_pubkey, bytes_to_nonce};
use super::comm;
fn process_new_connection(client: TcpStream, my_pubkey: Arc<PublicKey>, my_privkey: Arc<SecretKey>) {
use capnp::serialize_packed;
use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader};
let mut client = client;
println!("New connection from '{:s}'", client.peer_name().unwrap().to_str());
let hellopack = client.read_bytes(9).unwrap();
if (hellopack.as_slice() == comm::bare_msgs::HELLOBYTES) {
println!("Connection hello received");
}
else {
fail!("sad :(");
}
client.write(comm::bare_msgs::HELLOBYTES);
client.write(my_pubkey.get().key_bytes());
let client_pubkey = ~{
let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap();
let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>();
let mut bufreader = BufReader::new(pack.get_data());
let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap();
let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>();
match packdata.which() {
Some(comm::pack_capnp::PackData::Pubkey(key)) => bytes_to_pubkey(key),
_ => { println!("Client didn't send pubkey, disconnecting"); return; }
}
};
println!("got client key:\n{:?}", client_pubkey);
let mut clientname = ~"";
loop {
let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap();
let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>();
let nonce = bytes_to_nonce(pack.get_nonce());
let databytes = match open(pack.get_data(), &nonce, client_pubkey, my_privkey.get()) {
Some(bytes) => bytes,
None => { println!("WARNING! Decrypt failed! "); continue; }
};
let mut bufreader = BufReader::new(databytes);
let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap();
let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>();
match packdata.which() {
Some(comm::pack_capnp::PackData::Login(login)) => {
println!("{:s} logged in", login.get_name());
clientname = login.get_name().to_owned();
},
Some(comm::pack_capnp::PackData::Message(message)) => {
println!("<{:s}>{:s}", clientname, message.get_message());
},
Some(comm::pack_capnp::PackData::Quit(reason)) => {
println!("quitreason: {:s}", reason);
break;
},
_ => println!("wut")
}
}
}
fn writer_task() {
}
fn setup_sync_task() {
}
pub fn main() {
sodiumoxide::init(); |
let (s_pubkey, s_privkey) = gen_keypair();
let a_pubkey = Arc::new(s_pubkey);
let a_privkey = Arc::new(s_privkey);
let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap();
let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind");
let mut s_acceptor = s_listener.listen().ok().expect("Failed to create connection listener");
loop {
let pub_clone = a_pubkey.clone();
let priv_clone = a_privkey.clone();
match s_acceptor.accept() {
Ok(c_sock) => spawn(proc(){process_new_connection(c_sock, pub_clone, priv_clone)}),
Err(err) => println!("Failed connection attempt: {:?}", err)
}
}
} | random_line_split |
|
resource.js | var model = require( "../../model.js" );
module.exports = function( host ) {
return {
name: "board",
actions: {
self: {
include: [ "id", "title" ],
method: "get",
url: "/:id",
embed: {
lanes: {
resource: "lane",
render: "self",
actions: [ "self", "cards" ]
}
},
handle: function( envelope ) {
envelope.hyped( model.board1 ).status( 200 ).render();
}
},
cards: {
method: "get",
url: "/:id/card",
render: { resource: "card", action: "self" },
handle: function( envelope ) {
return _.reduce( model.board1.lanes, function( acc, lane ) {
return acc.concat( lane.cards );
}, [] );
}
}
},
versions: {
2: {
self: {
include: [ "id", "title", "description" ] | }
};
}; | }
} | random_line_split |
test_brightbox.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.loadbalancer.base import Member, Algorithm
from libcloud.loadbalancer.drivers.brightbox import BrightboxLBDriver
from libcloud.loadbalancer.types import State
from libcloud.test import MockHttpTestCase
from libcloud.test.secrets import LB_BRIGHTBOX_PARAMS
from libcloud.test.file_fixtures import LoadBalancerFileFixtures
class BrightboxLBTests(unittest.TestCase):
def setUp(self):
BrightboxLBDriver.connectionCls.conn_classes = (None,
BrightboxLBMockHttp)
BrightboxLBMockHttp.type = None
self.driver = BrightboxLBDriver(*LB_BRIGHTBOX_PARAMS)
def test_list_protocols(self):
protocols = self.driver.list_protocols()
self.assertEqual(len(protocols), 2)
self.assertTrue('tcp' in protocols)
self.assertTrue('http' in protocols)
def test_list_balancers(self):
balancers = self.driver.list_balancers()
self.assertEqual(len(balancers), 1)
self.assertEqual(balancers[0].id, 'lba-1235f')
self.assertEqual(balancers[0].name, 'lb1')
def | (self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
self.assertEqual(balancer.id, 'lba-1235f')
self.assertEqual(balancer.name, 'lb1')
self.assertEqual(balancer.state, State.RUNNING)
def test_destroy_balancer(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
self.assertTrue(self.driver.destroy_balancer(balancer))
def test_create_balancer(self):
members = [Member('srv-lv426', None, None)]
balancer = self.driver.create_balancer(name='lb2', port=80,
protocol='http',
algorithm=Algorithm.ROUND_ROBIN,
members=members)
self.assertEqual(balancer.name, 'lb2')
self.assertEqual(balancer.port, 80)
self.assertEqual(balancer.state, State.PENDING)
def test_balancer_list_members(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
members = balancer.list_members()
self.assertEqual(len(members), 1)
self.assertEqual(members[0].balancer, balancer)
self.assertEqual('srv-lv426', members[0].id)
def test_balancer_attach_member(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
member = balancer.attach_member(Member('srv-kg983', ip=None,
port=None))
self.assertEqual(member.id, 'srv-kg983')
def test_balancer_detach_member(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
member = Member('srv-lv426', None, None)
self.assertTrue(balancer.detach_member(member))
class BrightboxLBMockHttp(MockHttpTestCase):
fixtures = LoadBalancerFileFixtures('brightbox')
def _token(self, method, url, body, headers):
if method == 'POST':
return self.response(httplib.OK, self.fixtures.load('token.json'))
def _1_0_load_balancers(self, method, url, body, headers):
if method == 'GET':
return self.response(httplib.OK,
self.fixtures.load('load_balancers.json'))
elif method == 'POST':
body = self.fixtures.load('load_balancers_post.json')
return self.response(httplib.ACCEPTED, body)
def _1_0_load_balancers_lba_1235f(self, method, url, body, headers):
if method == 'GET':
body = self.fixtures.load('load_balancers_lba_1235f.json')
return self.response(httplib.OK, body)
elif method == 'DELETE':
return self.response(httplib.ACCEPTED, '')
def _1_0_load_balancers_lba_1235f_add_nodes(self, method, url, body,
headers):
if method == 'POST':
return self.response(httplib.ACCEPTED, '')
def _1_0_load_balancers_lba_1235f_remove_nodes(self, method, url, body,
headers):
if method == 'POST':
return self.response(httplib.ACCEPTED, '')
def response(self, status, body):
return (status, body, {'content-type': 'application/json'},
httplib.responses[status])
if __name__ == "__main__":
sys.exit(unittest.main())
| test_get_balancer | identifier_name |
test_brightbox.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.loadbalancer.base import Member, Algorithm
from libcloud.loadbalancer.drivers.brightbox import BrightboxLBDriver
from libcloud.loadbalancer.types import State
from libcloud.test import MockHttpTestCase
from libcloud.test.secrets import LB_BRIGHTBOX_PARAMS
from libcloud.test.file_fixtures import LoadBalancerFileFixtures
class BrightboxLBTests(unittest.TestCase):
def setUp(self):
BrightboxLBDriver.connectionCls.conn_classes = (None,
BrightboxLBMockHttp)
BrightboxLBMockHttp.type = None
self.driver = BrightboxLBDriver(*LB_BRIGHTBOX_PARAMS)
def test_list_protocols(self):
protocols = self.driver.list_protocols()
self.assertEqual(len(protocols), 2)
self.assertTrue('tcp' in protocols)
self.assertTrue('http' in protocols)
def test_list_balancers(self):
balancers = self.driver.list_balancers()
self.assertEqual(len(balancers), 1)
self.assertEqual(balancers[0].id, 'lba-1235f')
self.assertEqual(balancers[0].name, 'lb1')
def test_get_balancer(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
self.assertEqual(balancer.id, 'lba-1235f')
self.assertEqual(balancer.name, 'lb1')
self.assertEqual(balancer.state, State.RUNNING)
def test_destroy_balancer(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
self.assertTrue(self.driver.destroy_balancer(balancer))
def test_create_balancer(self):
members = [Member('srv-lv426', None, None)]
balancer = self.driver.create_balancer(name='lb2', port=80,
protocol='http',
algorithm=Algorithm.ROUND_ROBIN,
members=members)
self.assertEqual(balancer.name, 'lb2')
self.assertEqual(balancer.port, 80)
self.assertEqual(balancer.state, State.PENDING)
def test_balancer_list_members(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
members = balancer.list_members()
self.assertEqual(len(members), 1)
self.assertEqual(members[0].balancer, balancer)
self.assertEqual('srv-lv426', members[0].id)
def test_balancer_attach_member(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
member = balancer.attach_member(Member('srv-kg983', ip=None,
port=None))
self.assertEqual(member.id, 'srv-kg983')
def test_balancer_detach_member(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
member = Member('srv-lv426', None, None)
self.assertTrue(balancer.detach_member(member))
class BrightboxLBMockHttp(MockHttpTestCase):
fixtures = LoadBalancerFileFixtures('brightbox')
def _token(self, method, url, body, headers):
if method == 'POST':
return self.response(httplib.OK, self.fixtures.load('token.json'))
def _1_0_load_balancers(self, method, url, body, headers):
if method == 'GET':
return self.response(httplib.OK,
self.fixtures.load('load_balancers.json'))
elif method == 'POST':
body = self.fixtures.load('load_balancers_post.json')
return self.response(httplib.ACCEPTED, body)
def _1_0_load_balancers_lba_1235f(self, method, url, body, headers):
if method == 'GET':
body = self.fixtures.load('load_balancers_lba_1235f.json')
return self.response(httplib.OK, body)
elif method == 'DELETE':
return self.response(httplib.ACCEPTED, '')
def _1_0_load_balancers_lba_1235f_add_nodes(self, method, url, body,
headers):
if method == 'POST':
return self.response(httplib.ACCEPTED, '')
def _1_0_load_balancers_lba_1235f_remove_nodes(self, method, url, body,
headers):
if method == 'POST':
return self.response(httplib.ACCEPTED, '')
def response(self, status, body):
return (status, body, {'content-type': 'application/json'},
httplib.responses[status])
if __name__ == "__main__":
| sys.exit(unittest.main()) | conditional_block |
|
test_brightbox.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.loadbalancer.base import Member, Algorithm
from libcloud.loadbalancer.drivers.brightbox import BrightboxLBDriver
from libcloud.loadbalancer.types import State
from libcloud.test import MockHttpTestCase
from libcloud.test.secrets import LB_BRIGHTBOX_PARAMS
from libcloud.test.file_fixtures import LoadBalancerFileFixtures
class BrightboxLBTests(unittest.TestCase):
def setUp(self):
BrightboxLBDriver.connectionCls.conn_classes = (None,
BrightboxLBMockHttp)
BrightboxLBMockHttp.type = None
self.driver = BrightboxLBDriver(*LB_BRIGHTBOX_PARAMS)
def test_list_protocols(self):
protocols = self.driver.list_protocols()
self.assertEqual(len(protocols), 2)
self.assertTrue('tcp' in protocols)
self.assertTrue('http' in protocols)
def test_list_balancers(self):
balancers = self.driver.list_balancers()
self.assertEqual(len(balancers), 1)
self.assertEqual(balancers[0].id, 'lba-1235f')
self.assertEqual(balancers[0].name, 'lb1')
def test_get_balancer(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
self.assertEqual(balancer.id, 'lba-1235f')
self.assertEqual(balancer.name, 'lb1')
self.assertEqual(balancer.state, State.RUNNING)
def test_destroy_balancer(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
self.assertTrue(self.driver.destroy_balancer(balancer))
def test_create_balancer(self):
members = [Member('srv-lv426', None, None)]
balancer = self.driver.create_balancer(name='lb2', port=80,
protocol='http',
algorithm=Algorithm.ROUND_ROBIN,
members=members)
self.assertEqual(balancer.name, 'lb2')
self.assertEqual(balancer.port, 80)
self.assertEqual(balancer.state, State.PENDING)
def test_balancer_list_members(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
members = balancer.list_members()
self.assertEqual(len(members), 1)
self.assertEqual(members[0].balancer, balancer)
self.assertEqual('srv-lv426', members[0].id)
def test_balancer_attach_member(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
member = balancer.attach_member(Member('srv-kg983', ip=None,
port=None))
self.assertEqual(member.id, 'srv-kg983')
def test_balancer_detach_member(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
member = Member('srv-lv426', None, None)
self.assertTrue(balancer.detach_member(member))
class BrightboxLBMockHttp(MockHttpTestCase):
fixtures = LoadBalancerFileFixtures('brightbox')
def _token(self, method, url, body, headers):
if method == 'POST':
return self.response(httplib.OK, self.fixtures.load('token.json'))
def _1_0_load_balancers(self, method, url, body, headers):
if method == 'GET':
return self.response(httplib.OK,
self.fixtures.load('load_balancers.json'))
elif method == 'POST':
body = self.fixtures.load('load_balancers_post.json')
return self.response(httplib.ACCEPTED, body)
def _1_0_load_balancers_lba_1235f(self, method, url, body, headers):
|
def _1_0_load_balancers_lba_1235f_add_nodes(self, method, url, body,
headers):
if method == 'POST':
return self.response(httplib.ACCEPTED, '')
def _1_0_load_balancers_lba_1235f_remove_nodes(self, method, url, body,
headers):
if method == 'POST':
return self.response(httplib.ACCEPTED, '')
def response(self, status, body):
return (status, body, {'content-type': 'application/json'},
httplib.responses[status])
if __name__ == "__main__":
sys.exit(unittest.main())
| if method == 'GET':
body = self.fixtures.load('load_balancers_lba_1235f.json')
return self.response(httplib.OK, body)
elif method == 'DELETE':
return self.response(httplib.ACCEPTED, '') | identifier_body |
test_brightbox.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.loadbalancer.base import Member, Algorithm
from libcloud.loadbalancer.drivers.brightbox import BrightboxLBDriver
from libcloud.loadbalancer.types import State
from libcloud.test import MockHttpTestCase
from libcloud.test.secrets import LB_BRIGHTBOX_PARAMS
from libcloud.test.file_fixtures import LoadBalancerFileFixtures
class BrightboxLBTests(unittest.TestCase):
def setUp(self):
BrightboxLBDriver.connectionCls.conn_classes = (None,
BrightboxLBMockHttp)
BrightboxLBMockHttp.type = None
self.driver = BrightboxLBDriver(*LB_BRIGHTBOX_PARAMS)
def test_list_protocols(self):
protocols = self.driver.list_protocols()
self.assertEqual(len(protocols), 2)
self.assertTrue('tcp' in protocols)
self.assertTrue('http' in protocols)
def test_list_balancers(self):
balancers = self.driver.list_balancers()
self.assertEqual(len(balancers), 1)
self.assertEqual(balancers[0].id, 'lba-1235f')
self.assertEqual(balancers[0].name, 'lb1')
def test_get_balancer(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
self.assertEqual(balancer.id, 'lba-1235f')
self.assertEqual(balancer.name, 'lb1')
self.assertEqual(balancer.state, State.RUNNING)
def test_destroy_balancer(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
self.assertTrue(self.driver.destroy_balancer(balancer))
def test_create_balancer(self):
members = [Member('srv-lv426', None, None)]
balancer = self.driver.create_balancer(name='lb2', port=80,
protocol='http',
algorithm=Algorithm.ROUND_ROBIN,
members=members)
self.assertEqual(balancer.name, 'lb2')
self.assertEqual(balancer.port, 80)
self.assertEqual(balancer.state, State.PENDING)
def test_balancer_list_members(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
members = balancer.list_members()
self.assertEqual(len(members), 1)
self.assertEqual(members[0].balancer, balancer)
self.assertEqual('srv-lv426', members[0].id)
def test_balancer_attach_member(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f')
member = balancer.attach_member(Member('srv-kg983', ip=None,
port=None))
self.assertEqual(member.id, 'srv-kg983')
def test_balancer_detach_member(self):
balancer = self.driver.get_balancer(balancer_id='lba-1235f') |
self.assertTrue(balancer.detach_member(member))
class BrightboxLBMockHttp(MockHttpTestCase):
fixtures = LoadBalancerFileFixtures('brightbox')
def _token(self, method, url, body, headers):
if method == 'POST':
return self.response(httplib.OK, self.fixtures.load('token.json'))
def _1_0_load_balancers(self, method, url, body, headers):
if method == 'GET':
return self.response(httplib.OK,
self.fixtures.load('load_balancers.json'))
elif method == 'POST':
body = self.fixtures.load('load_balancers_post.json')
return self.response(httplib.ACCEPTED, body)
def _1_0_load_balancers_lba_1235f(self, method, url, body, headers):
if method == 'GET':
body = self.fixtures.load('load_balancers_lba_1235f.json')
return self.response(httplib.OK, body)
elif method == 'DELETE':
return self.response(httplib.ACCEPTED, '')
def _1_0_load_balancers_lba_1235f_add_nodes(self, method, url, body,
headers):
if method == 'POST':
return self.response(httplib.ACCEPTED, '')
def _1_0_load_balancers_lba_1235f_remove_nodes(self, method, url, body,
headers):
if method == 'POST':
return self.response(httplib.ACCEPTED, '')
def response(self, status, body):
return (status, body, {'content-type': 'application/json'},
httplib.responses[status])
if __name__ == "__main__":
sys.exit(unittest.main()) | member = Member('srv-lv426', None, None) | random_line_split |
headergen.py | #!/usr/bin/env python3
# Copyright (C) 2010-2011 Marcin Kościelnicki <[email protected]>
# Copyright (C) 2010 Luca Barbieri <[email protected]>
# Copyright (C) 2010 Marcin Slusarz <[email protected]>
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import rnn
import sys
startcol = 64
fouts = {}
def printdef(name, val, file):
fout = fouts[file]
fout.write("#define {}{} {}\n".format(name, " " * (startcol - len(name)), val))
def printvalue(val, shift):
if val.varinfo.dead:
return
if val.value is not None:
printdef(val.fullname, hex(val.value << shift), val.file)
def printtypeinfo(ti, prefix, shift, file):
if isinstance(ti, rnn.TypeHex) or isinstance(ti, rnn.TypeInt):
if ti.shr:
printdef (prefix + "__SHR", str(ti.shr), file)
if ti.min is not None:
printdef (prefix + "__MIN", hex(ti.min), file)
if ti.max is not None:
printdef (prefix + "__MAX", hex(ti.max), file)
if ti.align is not None:
printdef (prefix + "__ALIGN", hex(ti.align), file)
if isinstance(ti, rnn.TypeFixed):
if ti.min is not None:
printdef (prefix + "__MIN", hex(ti.min), file)
if ti.max is not None:
printdef (prefix + "__MAX", hex(ti.max), file)
if ti.radix is not None:
printdef (prefix + "__RADIX", str(ti.radix), file)
if isinstance(ti, rnn.Enum) and ti.inline:
for val in ti.vals:
printvalue(val, shift)
if isinstance(ti, rnn.Bitset) and ti.inline:
for bitfield in ti.bitfields:
printbitfield(bitfield, shift)
def printbitfield(bf, shift):
if bf.varinfo.dead:
return
if isinstance(bf.typeinfo, rnn.TypeBoolean):
printdef(bf.fullname, hex(bf.mask << shift), bf.file)
else:
printdef(bf.fullname + "__MASK", hex(bf.mask << shift), bf.file)
printdef(bf.fullname + "__SHIFT", str(bf.low + shift), bf.file)
printtypeinfo(bf.typeinfo, bf.fullname, bf.low + shift, bf.file)
def printdelem(elem, offset, strides):
if elem.varinfo.dead:
return
if elem.length != 1:
strides = strides + [elem.stride]
offset = offset + elem.offset
if elem.name:
if strides:
name = elem.fullname + '(' + ", ".join("i{}".format(i) for i in range(len(strides))) + ')'
val = '(' + hex(offset) + "".join(" + {:x} * i{}".format(stride, i) for i, stride in enumerate(strides)) + ')'
printdef(name, val, elem.file)
else:
printdef(elem.fullname, hex(offset), elem.file)
if elem.stride:
printdef(elem.fullname +"__ESIZE", hex(elem.stride), elem.file)
if elem.length != 1:
printdef(elem.fullname + "__LEN", hex(elem.length), elem.file)
if isinstance(elem, rnn.Reg):
printtypeinfo(elem.typeinfo, elem.fullname, 0, elem.file)
fouts[elem.file].write("\n")
if isinstance(elem, rnn.Stripe):
for subelem in elem.elems:
printdelem(subelem, offset, strides)
def print_file_info(fout, file):
#struct stat sb;
#struct tm tm;
#stat(file, &sb);
#gmtime_r(&sb.st_mtime, &tm);
#char timestr[64];
#strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tm);
#fprintf(dst, "(%7Lu bytes, from %s)\n", (unsigned long long)sb->st_size, timestr);
fout.write("\n")
def printhead(file, db):
fout = fouts[file]
fout.write("#ifndef {}\n".format(guard(file)))
fout.write("#define {}\n".format(guard(file)))
fout.write("\n")
fout.write(
"/* Autogenerated file, DO NOT EDIT manually!\n"
"\n"
"This file was generated by the rules-ng-ng headergen tool in this git repository:\n"
"http://github.com/envytools/envytools/\n"
"git clone https://github.com/envytools/envytools.git\n"
"\n"
"The rules-ng-ng source files this header was generated from are:\n")
#struct stat sb;
#struct tm tm;
#stat(f.name, &sb);
#gmtime_r(&sb.st_mtime, &tm);
maxlen = max(len(file) for file in db.files)
for file in db.files:
fout.write("- {} ".format(file + " " * (maxlen - len(file))))
print_file_info(fout, file)
fout.write(
"\n"
"Copyright (C) ")
#if(db->copyright.firstyear && db->copyright.firstyear < (1900 + tm.tm_year))
# fout.write("%u-", db->copyright.firstyear);
#fout.write("%u", 1900 + tm.tm_year);
if db.copyright.authors:
fout.write(" by the following authors:")
for author in db.copyright.authors:
fout.write("\n- ")
if author.name:
fout.write(author.name)
if author.email:
fout.write(" <{}>".format(author.email))
if author.nicknames:
fout.write(" ({})".format(", ".join(author.nicknames)))
fout.write("\n")
if db.copyright.license:
fout.write("\n{}\n".format(db.copyright.license))
fout.write("*/\n\n\n")
def guard(file):
return ''.join(c.upper() if c.isalnum() else '_' for c in file)
def process(mainfile):
db = rnn.Database()
rnn.parsefile(db, mainfile)
db.prep()
for file in db.files:
fouts[file] = open(file.replace('/', '_') + '.h', 'w')
printhead(file, db)
for enum in db.enums:
if not enum.inline:
for val in enum.vals:
printvalue(val, 0)
for bitset in db.bitsets:
if not bitset.inline:
for bitfield in bitset.bitfields:
printbitfield(bitfield, 0)
for domain in db.domains:
if domain.size:
printdef(domain.fullname + "__SIZE", hex(domain.size), domain.file)
for elem in domain.elems:
printdelem(elem, 0, [])
for file in fouts:
f |
return db.estatus
if len(sys.argv) < 2:
sys.stdout.write ("Usage:\n"
"\theadergen file.xml\n"
)
sys.exit(2)
sys.exit(process(sys.argv[1]))
| outs[file].write("\n#endif /* {} */\n".format(guard(file)))
fouts[file].close()
| conditional_block |
headergen.py | #!/usr/bin/env python3
# Copyright (C) 2010-2011 Marcin Kościelnicki <[email protected]>
# Copyright (C) 2010 Luca Barbieri <[email protected]>
# Copyright (C) 2010 Marcin Slusarz <[email protected]>
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import rnn
import sys
startcol = 64
fouts = {}
def printdef(name, val, file):
fout = fouts[file]
fout.write("#define {}{} {}\n".format(name, " " * (startcol - len(name)), val))
def printvalue(val, shift):
if val.varinfo.dead:
return
if val.value is not None:
printdef(val.fullname, hex(val.value << shift), val.file)
def printtypeinfo(ti, prefix, shift, file):
if isinstance(ti, rnn.TypeHex) or isinstance(ti, rnn.TypeInt):
if ti.shr:
printdef (prefix + "__SHR", str(ti.shr), file)
if ti.min is not None:
printdef (prefix + "__MIN", hex(ti.min), file)
if ti.max is not None:
printdef (prefix + "__MAX", hex(ti.max), file)
if ti.align is not None:
printdef (prefix + "__ALIGN", hex(ti.align), file)
if isinstance(ti, rnn.TypeFixed):
if ti.min is not None:
printdef (prefix + "__MIN", hex(ti.min), file)
if ti.max is not None:
printdef (prefix + "__MAX", hex(ti.max), file)
if ti.radix is not None:
printdef (prefix + "__RADIX", str(ti.radix), file)
if isinstance(ti, rnn.Enum) and ti.inline:
for val in ti.vals:
printvalue(val, shift)
if isinstance(ti, rnn.Bitset) and ti.inline:
for bitfield in ti.bitfields:
printbitfield(bitfield, shift)
def printbitfield(bf, shift):
if bf.varinfo.dead:
return
if isinstance(bf.typeinfo, rnn.TypeBoolean):
printdef(bf.fullname, hex(bf.mask << shift), bf.file)
else:
printdef(bf.fullname + "__MASK", hex(bf.mask << shift), bf.file)
printdef(bf.fullname + "__SHIFT", str(bf.low + shift), bf.file)
printtypeinfo(bf.typeinfo, bf.fullname, bf.low + shift, bf.file)
def printdelem(elem, offset, strides):
i | for subelem in elem.elems:
printdelem(subelem, offset, strides)
def print_file_info(fout, file):
#struct stat sb;
#struct tm tm;
#stat(file, &sb);
#gmtime_r(&sb.st_mtime, &tm);
#char timestr[64];
#strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tm);
#fprintf(dst, "(%7Lu bytes, from %s)\n", (unsigned long long)sb->st_size, timestr);
fout.write("\n")
def printhead(file, db):
fout = fouts[file]
fout.write("#ifndef {}\n".format(guard(file)))
fout.write("#define {}\n".format(guard(file)))
fout.write("\n")
fout.write(
"/* Autogenerated file, DO NOT EDIT manually!\n"
"\n"
"This file was generated by the rules-ng-ng headergen tool in this git repository:\n"
"http://github.com/envytools/envytools/\n"
"git clone https://github.com/envytools/envytools.git\n"
"\n"
"The rules-ng-ng source files this header was generated from are:\n")
#struct stat sb;
#struct tm tm;
#stat(f.name, &sb);
#gmtime_r(&sb.st_mtime, &tm);
maxlen = max(len(file) for file in db.files)
for file in db.files:
fout.write("- {} ".format(file + " " * (maxlen - len(file))))
print_file_info(fout, file)
fout.write(
"\n"
"Copyright (C) ")
#if(db->copyright.firstyear && db->copyright.firstyear < (1900 + tm.tm_year))
# fout.write("%u-", db->copyright.firstyear);
#fout.write("%u", 1900 + tm.tm_year);
if db.copyright.authors:
fout.write(" by the following authors:")
for author in db.copyright.authors:
fout.write("\n- ")
if author.name:
fout.write(author.name)
if author.email:
fout.write(" <{}>".format(author.email))
if author.nicknames:
fout.write(" ({})".format(", ".join(author.nicknames)))
fout.write("\n")
if db.copyright.license:
fout.write("\n{}\n".format(db.copyright.license))
fout.write("*/\n\n\n")
def guard(file):
return ''.join(c.upper() if c.isalnum() else '_' for c in file)
def process(mainfile):
db = rnn.Database()
rnn.parsefile(db, mainfile)
db.prep()
for file in db.files:
fouts[file] = open(file.replace('/', '_') + '.h', 'w')
printhead(file, db)
for enum in db.enums:
if not enum.inline:
for val in enum.vals:
printvalue(val, 0)
for bitset in db.bitsets:
if not bitset.inline:
for bitfield in bitset.bitfields:
printbitfield(bitfield, 0)
for domain in db.domains:
if domain.size:
printdef(domain.fullname + "__SIZE", hex(domain.size), domain.file)
for elem in domain.elems:
printdelem(elem, 0, [])
for file in fouts:
fouts[file].write("\n#endif /* {} */\n".format(guard(file)))
fouts[file].close()
return db.estatus
if len(sys.argv) < 2:
sys.stdout.write ("Usage:\n"
"\theadergen file.xml\n"
)
sys.exit(2)
sys.exit(process(sys.argv[1]))
| f elem.varinfo.dead:
return
if elem.length != 1:
strides = strides + [elem.stride]
offset = offset + elem.offset
if elem.name:
if strides:
name = elem.fullname + '(' + ", ".join("i{}".format(i) for i in range(len(strides))) + ')'
val = '(' + hex(offset) + "".join(" + {:x} * i{}".format(stride, i) for i, stride in enumerate(strides)) + ')'
printdef(name, val, elem.file)
else:
printdef(elem.fullname, hex(offset), elem.file)
if elem.stride:
printdef(elem.fullname +"__ESIZE", hex(elem.stride), elem.file)
if elem.length != 1:
printdef(elem.fullname + "__LEN", hex(elem.length), elem.file)
if isinstance(elem, rnn.Reg):
printtypeinfo(elem.typeinfo, elem.fullname, 0, elem.file)
fouts[elem.file].write("\n")
if isinstance(elem, rnn.Stripe): | identifier_body |
headergen.py | #!/usr/bin/env python3
# Copyright (C) 2010-2011 Marcin Kościelnicki <[email protected]>
# Copyright (C) 2010 Luca Barbieri <[email protected]>
# Copyright (C) 2010 Marcin Slusarz <[email protected]>
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import rnn
import sys
startcol = 64
fouts = {}
def printdef(name, val, file):
fout = fouts[file]
fout.write("#define {}{} {}\n".format(name, " " * (startcol - len(name)), val))
def p | val, shift):
if val.varinfo.dead:
return
if val.value is not None:
printdef(val.fullname, hex(val.value << shift), val.file)
def printtypeinfo(ti, prefix, shift, file):
if isinstance(ti, rnn.TypeHex) or isinstance(ti, rnn.TypeInt):
if ti.shr:
printdef (prefix + "__SHR", str(ti.shr), file)
if ti.min is not None:
printdef (prefix + "__MIN", hex(ti.min), file)
if ti.max is not None:
printdef (prefix + "__MAX", hex(ti.max), file)
if ti.align is not None:
printdef (prefix + "__ALIGN", hex(ti.align), file)
if isinstance(ti, rnn.TypeFixed):
if ti.min is not None:
printdef (prefix + "__MIN", hex(ti.min), file)
if ti.max is not None:
printdef (prefix + "__MAX", hex(ti.max), file)
if ti.radix is not None:
printdef (prefix + "__RADIX", str(ti.radix), file)
if isinstance(ti, rnn.Enum) and ti.inline:
for val in ti.vals:
printvalue(val, shift)
if isinstance(ti, rnn.Bitset) and ti.inline:
for bitfield in ti.bitfields:
printbitfield(bitfield, shift)
def printbitfield(bf, shift):
if bf.varinfo.dead:
return
if isinstance(bf.typeinfo, rnn.TypeBoolean):
printdef(bf.fullname, hex(bf.mask << shift), bf.file)
else:
printdef(bf.fullname + "__MASK", hex(bf.mask << shift), bf.file)
printdef(bf.fullname + "__SHIFT", str(bf.low + shift), bf.file)
printtypeinfo(bf.typeinfo, bf.fullname, bf.low + shift, bf.file)
def printdelem(elem, offset, strides):
if elem.varinfo.dead:
return
if elem.length != 1:
strides = strides + [elem.stride]
offset = offset + elem.offset
if elem.name:
if strides:
name = elem.fullname + '(' + ", ".join("i{}".format(i) for i in range(len(strides))) + ')'
val = '(' + hex(offset) + "".join(" + {:x} * i{}".format(stride, i) for i, stride in enumerate(strides)) + ')'
printdef(name, val, elem.file)
else:
printdef(elem.fullname, hex(offset), elem.file)
if elem.stride:
printdef(elem.fullname +"__ESIZE", hex(elem.stride), elem.file)
if elem.length != 1:
printdef(elem.fullname + "__LEN", hex(elem.length), elem.file)
if isinstance(elem, rnn.Reg):
printtypeinfo(elem.typeinfo, elem.fullname, 0, elem.file)
fouts[elem.file].write("\n")
if isinstance(elem, rnn.Stripe):
for subelem in elem.elems:
printdelem(subelem, offset, strides)
def print_file_info(fout, file):
#struct stat sb;
#struct tm tm;
#stat(file, &sb);
#gmtime_r(&sb.st_mtime, &tm);
#char timestr[64];
#strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tm);
#fprintf(dst, "(%7Lu bytes, from %s)\n", (unsigned long long)sb->st_size, timestr);
fout.write("\n")
def printhead(file, db):
fout = fouts[file]
fout.write("#ifndef {}\n".format(guard(file)))
fout.write("#define {}\n".format(guard(file)))
fout.write("\n")
fout.write(
"/* Autogenerated file, DO NOT EDIT manually!\n"
"\n"
"This file was generated by the rules-ng-ng headergen tool in this git repository:\n"
"http://github.com/envytools/envytools/\n"
"git clone https://github.com/envytools/envytools.git\n"
"\n"
"The rules-ng-ng source files this header was generated from are:\n")
#struct stat sb;
#struct tm tm;
#stat(f.name, &sb);
#gmtime_r(&sb.st_mtime, &tm);
maxlen = max(len(file) for file in db.files)
for file in db.files:
fout.write("- {} ".format(file + " " * (maxlen - len(file))))
print_file_info(fout, file)
fout.write(
"\n"
"Copyright (C) ")
#if(db->copyright.firstyear && db->copyright.firstyear < (1900 + tm.tm_year))
# fout.write("%u-", db->copyright.firstyear);
#fout.write("%u", 1900 + tm.tm_year);
if db.copyright.authors:
fout.write(" by the following authors:")
for author in db.copyright.authors:
fout.write("\n- ")
if author.name:
fout.write(author.name)
if author.email:
fout.write(" <{}>".format(author.email))
if author.nicknames:
fout.write(" ({})".format(", ".join(author.nicknames)))
fout.write("\n")
if db.copyright.license:
fout.write("\n{}\n".format(db.copyright.license))
fout.write("*/\n\n\n")
def guard(file):
return ''.join(c.upper() if c.isalnum() else '_' for c in file)
def process(mainfile):
db = rnn.Database()
rnn.parsefile(db, mainfile)
db.prep()
for file in db.files:
fouts[file] = open(file.replace('/', '_') + '.h', 'w')
printhead(file, db)
for enum in db.enums:
if not enum.inline:
for val in enum.vals:
printvalue(val, 0)
for bitset in db.bitsets:
if not bitset.inline:
for bitfield in bitset.bitfields:
printbitfield(bitfield, 0)
for domain in db.domains:
if domain.size:
printdef(domain.fullname + "__SIZE", hex(domain.size), domain.file)
for elem in domain.elems:
printdelem(elem, 0, [])
for file in fouts:
fouts[file].write("\n#endif /* {} */\n".format(guard(file)))
fouts[file].close()
return db.estatus
if len(sys.argv) < 2:
sys.stdout.write ("Usage:\n"
"\theadergen file.xml\n"
)
sys.exit(2)
sys.exit(process(sys.argv[1]))
| rintvalue( | identifier_name |
headergen.py | #!/usr/bin/env python3
# Copyright (C) 2010-2011 Marcin Kościelnicki <[email protected]>
# Copyright (C) 2010 Luca Barbieri <[email protected]>
# Copyright (C) 2010 Marcin Slusarz <[email protected]>
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import rnn
import sys
startcol = 64
fouts = {}
def printdef(name, val, file):
fout = fouts[file]
fout.write("#define {}{} {}\n".format(name, " " * (startcol - len(name)), val))
def printvalue(val, shift):
if val.varinfo.dead:
return
if val.value is not None:
printdef(val.fullname, hex(val.value << shift), val.file)
def printtypeinfo(ti, prefix, shift, file):
if isinstance(ti, rnn.TypeHex) or isinstance(ti, rnn.TypeInt):
if ti.shr:
printdef (prefix + "__SHR", str(ti.shr), file)
if ti.min is not None:
printdef (prefix + "__MIN", hex(ti.min), file)
if ti.max is not None:
printdef (prefix + "__MAX", hex(ti.max), file)
if ti.align is not None:
printdef (prefix + "__ALIGN", hex(ti.align), file)
if isinstance(ti, rnn.TypeFixed):
if ti.min is not None:
printdef (prefix + "__MIN", hex(ti.min), file)
if ti.max is not None:
printdef (prefix + "__MAX", hex(ti.max), file)
if ti.radix is not None:
printdef (prefix + "__RADIX", str(ti.radix), file)
if isinstance(ti, rnn.Enum) and ti.inline:
for val in ti.vals:
printvalue(val, shift)
if isinstance(ti, rnn.Bitset) and ti.inline:
for bitfield in ti.bitfields:
printbitfield(bitfield, shift)
def printbitfield(bf, shift):
if bf.varinfo.dead:
return
if isinstance(bf.typeinfo, rnn.TypeBoolean):
printdef(bf.fullname, hex(bf.mask << shift), bf.file)
else:
printdef(bf.fullname + "__MASK", hex(bf.mask << shift), bf.file)
printdef(bf.fullname + "__SHIFT", str(bf.low + shift), bf.file)
printtypeinfo(bf.typeinfo, bf.fullname, bf.low + shift, bf.file)
def printdelem(elem, offset, strides):
if elem.varinfo.dead:
return
if elem.length != 1:
strides = strides + [elem.stride]
offset = offset + elem.offset
if elem.name:
if strides:
name = elem.fullname + '(' + ", ".join("i{}".format(i) for i in range(len(strides))) + ')'
val = '(' + hex(offset) + "".join(" + {:x} * i{}".format(stride, i) for i, stride in enumerate(strides)) + ')'
printdef(name, val, elem.file)
else:
printdef(elem.fullname, hex(offset), elem.file)
if elem.stride:
printdef(elem.fullname +"__ESIZE", hex(elem.stride), elem.file)
if elem.length != 1:
printdef(elem.fullname + "__LEN", hex(elem.length), elem.file)
if isinstance(elem, rnn.Reg):
printtypeinfo(elem.typeinfo, elem.fullname, 0, elem.file)
fouts[elem.file].write("\n")
if isinstance(elem, rnn.Stripe):
for subelem in elem.elems:
printdelem(subelem, offset, strides)
def print_file_info(fout, file):
#struct stat sb;
#struct tm tm;
#stat(file, &sb);
#gmtime_r(&sb.st_mtime, &tm);
#char timestr[64];
#strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tm);
#fprintf(dst, "(%7Lu bytes, from %s)\n", (unsigned long long)sb->st_size, timestr);
fout.write("\n")
def printhead(file, db):
fout = fouts[file]
fout.write("#ifndef {}\n".format(guard(file)))
fout.write("#define {}\n".format(guard(file)))
fout.write("\n")
fout.write(
"/* Autogenerated file, DO NOT EDIT manually!\n" | "http://github.com/envytools/envytools/\n"
"git clone https://github.com/envytools/envytools.git\n"
"\n"
"The rules-ng-ng source files this header was generated from are:\n")
#struct stat sb;
#struct tm tm;
#stat(f.name, &sb);
#gmtime_r(&sb.st_mtime, &tm);
maxlen = max(len(file) for file in db.files)
for file in db.files:
fout.write("- {} ".format(file + " " * (maxlen - len(file))))
print_file_info(fout, file)
fout.write(
"\n"
"Copyright (C) ")
#if(db->copyright.firstyear && db->copyright.firstyear < (1900 + tm.tm_year))
# fout.write("%u-", db->copyright.firstyear);
#fout.write("%u", 1900 + tm.tm_year);
if db.copyright.authors:
fout.write(" by the following authors:")
for author in db.copyright.authors:
fout.write("\n- ")
if author.name:
fout.write(author.name)
if author.email:
fout.write(" <{}>".format(author.email))
if author.nicknames:
fout.write(" ({})".format(", ".join(author.nicknames)))
fout.write("\n")
if db.copyright.license:
fout.write("\n{}\n".format(db.copyright.license))
fout.write("*/\n\n\n")
def guard(file):
return ''.join(c.upper() if c.isalnum() else '_' for c in file)
def process(mainfile):
db = rnn.Database()
rnn.parsefile(db, mainfile)
db.prep()
for file in db.files:
fouts[file] = open(file.replace('/', '_') + '.h', 'w')
printhead(file, db)
for enum in db.enums:
if not enum.inline:
for val in enum.vals:
printvalue(val, 0)
for bitset in db.bitsets:
if not bitset.inline:
for bitfield in bitset.bitfields:
printbitfield(bitfield, 0)
for domain in db.domains:
if domain.size:
printdef(domain.fullname + "__SIZE", hex(domain.size), domain.file)
for elem in domain.elems:
printdelem(elem, 0, [])
for file in fouts:
fouts[file].write("\n#endif /* {} */\n".format(guard(file)))
fouts[file].close()
return db.estatus
if len(sys.argv) < 2:
sys.stdout.write ("Usage:\n"
"\theadergen file.xml\n"
)
sys.exit(2)
sys.exit(process(sys.argv[1])) | "\n"
"This file was generated by the rules-ng-ng headergen tool in this git repository:\n" | random_line_split |
test_ce_is_is_instance.py | # (c) 2019 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.cloudengine import ce_is_is_instance
from units.modules.network.cloudengine.ce_module import TestCloudEngineModule, load_fixture
from units.modules.utils import set_module_args
class TestCloudEngineLacpModule(TestCloudEngineModule):
module = ce_is_is_instance
def setUp(self):
super(TestCloudEngineLacpModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.cloudengine.ce_is_is_instance.get_nc_config')
self.get_nc_config = self.mock_get_config.start()
self.mock_set_config = patch('ansible.modules.network.cloudengine.ce_is_is_instance.set_nc_config')
self.set_nc_config = self.mock_set_config.start()
self.set_nc_config.return_value = None
def tearDown(self):
super(TestCloudEngineLacpModule, self).tearDown()
self.mock_set_config.stop()
self.mock_get_config.stop()
def test_isis_instance_present(self):
xml_existing = load_fixture('ce_is_is_instance', 'before.txt')
xml_end_state = load_fixture('ce_is_is_instance', 'after.txt')
update = ['isis 100', 'vpn-instance __public__'] | config = dict(
instance_id=100,
vpn_name='__public__',
state='present')
set_module_args(config)
result = self.execute_module(changed=True)
self.assertEquals(sorted(result['updates']), sorted(update))
def test_isis_instance_present(self):
xml_existing = load_fixture('ce_is_is_instance', 'after.txt')
xml_end_state = load_fixture('ce_is_is_instance', 'before.txt')
update = ['undo isis 100']
self.get_nc_config.side_effect = (xml_existing, xml_end_state)
config = dict(
instance_id=100,
vpn_name='__public__',
state='absent')
set_module_args(config)
result = self.execute_module(changed=True)
self.assertEquals(sorted(result['updates']), sorted(update)) | self.get_nc_config.side_effect = (xml_existing, xml_end_state) | random_line_split |
test_ce_is_is_instance.py | # (c) 2019 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.cloudengine import ce_is_is_instance
from units.modules.network.cloudengine.ce_module import TestCloudEngineModule, load_fixture
from units.modules.utils import set_module_args
class TestCloudEngineLacpModule(TestCloudEngineModule):
module = ce_is_is_instance
def setUp(self):
super(TestCloudEngineLacpModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.cloudengine.ce_is_is_instance.get_nc_config')
self.get_nc_config = self.mock_get_config.start()
self.mock_set_config = patch('ansible.modules.network.cloudengine.ce_is_is_instance.set_nc_config')
self.set_nc_config = self.mock_set_config.start()
self.set_nc_config.return_value = None
def tearDown(self):
super(TestCloudEngineLacpModule, self).tearDown()
self.mock_set_config.stop()
self.mock_get_config.stop()
def test_isis_instance_present(self):
|
def test_isis_instance_present(self):
xml_existing = load_fixture('ce_is_is_instance', 'after.txt')
xml_end_state = load_fixture('ce_is_is_instance', 'before.txt')
update = ['undo isis 100']
self.get_nc_config.side_effect = (xml_existing, xml_end_state)
config = dict(
instance_id=100,
vpn_name='__public__',
state='absent')
set_module_args(config)
result = self.execute_module(changed=True)
self.assertEquals(sorted(result['updates']), sorted(update))
| xml_existing = load_fixture('ce_is_is_instance', 'before.txt')
xml_end_state = load_fixture('ce_is_is_instance', 'after.txt')
update = ['isis 100', 'vpn-instance __public__']
self.get_nc_config.side_effect = (xml_existing, xml_end_state)
config = dict(
instance_id=100,
vpn_name='__public__',
state='present')
set_module_args(config)
result = self.execute_module(changed=True)
self.assertEquals(sorted(result['updates']), sorted(update)) | identifier_body |
test_ce_is_is_instance.py | # (c) 2019 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.cloudengine import ce_is_is_instance
from units.modules.network.cloudengine.ce_module import TestCloudEngineModule, load_fixture
from units.modules.utils import set_module_args
class TestCloudEngineLacpModule(TestCloudEngineModule):
module = ce_is_is_instance
def setUp(self):
super(TestCloudEngineLacpModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.cloudengine.ce_is_is_instance.get_nc_config')
self.get_nc_config = self.mock_get_config.start()
self.mock_set_config = patch('ansible.modules.network.cloudengine.ce_is_is_instance.set_nc_config')
self.set_nc_config = self.mock_set_config.start()
self.set_nc_config.return_value = None
def tearDown(self):
super(TestCloudEngineLacpModule, self).tearDown()
self.mock_set_config.stop()
self.mock_get_config.stop()
def test_isis_instance_present(self):
xml_existing = load_fixture('ce_is_is_instance', 'before.txt')
xml_end_state = load_fixture('ce_is_is_instance', 'after.txt')
update = ['isis 100', 'vpn-instance __public__']
self.get_nc_config.side_effect = (xml_existing, xml_end_state)
config = dict(
instance_id=100,
vpn_name='__public__',
state='present')
set_module_args(config)
result = self.execute_module(changed=True)
self.assertEquals(sorted(result['updates']), sorted(update))
def | (self):
xml_existing = load_fixture('ce_is_is_instance', 'after.txt')
xml_end_state = load_fixture('ce_is_is_instance', 'before.txt')
update = ['undo isis 100']
self.get_nc_config.side_effect = (xml_existing, xml_end_state)
config = dict(
instance_id=100,
vpn_name='__public__',
state='absent')
set_module_args(config)
result = self.execute_module(changed=True)
self.assertEquals(sorted(result['updates']), sorted(update))
| test_isis_instance_present | identifier_name |
where-clauses-no-bounds-or-predicates.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.
// compile-flags: -Z parse-only
fn equal1<T>(_: &T, _: &T) -> bool where |
fn equal2<T>(_: &T, _: &T) -> bool where T: {
//~^ ERROR each predicate in a `where` clause must have at least one bound
true
}
fn main() {
}
| {
//~^ ERROR a `where` clause must have at least one predicate in it
true
} | identifier_body |
where-clauses-no-bounds-or-predicates.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.
// compile-flags: -Z parse-only
fn equal1<T>(_: &T, _: &T) -> bool where {
//~^ ERROR a `where` clause must have at least one predicate in it
true
}
fn | <T>(_: &T, _: &T) -> bool where T: {
//~^ ERROR each predicate in a `where` clause must have at least one bound
true
}
fn main() {
}
| equal2 | identifier_name |
where-clauses-no-bounds-or-predicates.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.
| true
}
fn equal2<T>(_: &T, _: &T) -> bool where T: {
//~^ ERROR each predicate in a `where` clause must have at least one bound
true
}
fn main() {
} | // compile-flags: -Z parse-only
fn equal1<T>(_: &T, _: &T) -> bool where {
//~^ ERROR a `where` clause must have at least one predicate in it | random_line_split |
compute_capabilities_filter.py | # Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from oslo_serialization import jsonutils
import six
from nova.scheduler import filters
from nova.scheduler.filters import extra_specs_ops
LOG = logging.getLogger(__name__)
class ComputeCapabilitiesFilter(filters.BaseHostFilter):
| if getattr(cap, scope[index], None) is None:
# If can't find, check stats dict
cap = cap.stats.get(scope[index], None)
else:
cap = getattr(cap, scope[index], None)
else:
cap = cap.get(scope[index], None)
except AttributeError as e:
LOG.debug("%(host_state)s fails. The capabilities couldn't "
"be retrieved: %(error)s.",
{'host_state': host_state, 'error': e})
return None
if cap is None:
LOG.debug("%(host_state)s fails. There are no capabilities "
"to retrieve.",
{'host_state': host_state})
return None
return cap
def _satisfies_extra_specs(self, host_state, instance_type):
"""Check that the host_state provided by the compute service
satisfies the extra specs associated with the instance type.
"""
if 'extra_specs' not in instance_type:
return True
for key, req in instance_type.extra_specs.items():
# Either not scope format, or in capabilities scope
scope = key.split(':')
# If key does not have a namespace, the scope's size is 1, check
# whether host_state contains the key as an attribute. If not,
# ignore it. If it contains, deal with it in the same way as
# 'capabilities:key'. This is for backward-compatible.
# If the key has a namespace, the scope's size will be bigger than
# 1, check that whether the namespace is 'capabilities'. If not,
# ignore it.
if len(scope) == 1:
stats = getattr(host_state, 'stats', {})
has_attr = hasattr(host_state, key) or key in stats
if not has_attr:
continue
else:
if scope[0] != "capabilities":
continue
else:
del scope[0]
cap = self._get_capabilities(host_state, scope)
if cap is None:
return False
if not extra_specs_ops.match(str(cap), req):
LOG.debug("%(host_state)s fails extra_spec requirements. "
"'%(req)s' does not match '%(cap)s'",
{'host_state': host_state, 'req': req,
'cap': cap})
return False
return True
def host_passes(self, host_state, spec_obj):
"""Return a list of hosts that can create instance_type."""
instance_type = spec_obj.flavor
if not self._satisfies_extra_specs(host_state, instance_type):
LOG.debug("%(host_state)s fails instance_type extra_specs "
"requirements", {'host_state': host_state})
return False
return True
| """HostFilter hard-coded to work with InstanceType records."""
# Instance type and host capabilities do not change within a request
run_filter_once_per_request = True
def _get_capabilities(self, host_state, scope):
cap = host_state
for index in range(0, len(scope)):
try:
if isinstance(cap, six.string_types):
try:
cap = jsonutils.loads(cap)
except ValueError as e:
LOG.debug("%(host_state)s fails. The capabilities "
"'%(cap)s' couldn't be loaded from JSON: "
"%(error)s",
{'host_state': host_state, 'cap': cap,
'error': e})
return None
if not isinstance(cap, dict): | identifier_body |
compute_capabilities_filter.py | # Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software |
from oslo_log import log as logging
from oslo_serialization import jsonutils
import six
from nova.scheduler import filters
from nova.scheduler.filters import extra_specs_ops
LOG = logging.getLogger(__name__)
class ComputeCapabilitiesFilter(filters.BaseHostFilter):
"""HostFilter hard-coded to work with InstanceType records."""
# Instance type and host capabilities do not change within a request
run_filter_once_per_request = True
def _get_capabilities(self, host_state, scope):
cap = host_state
for index in range(0, len(scope)):
try:
if isinstance(cap, six.string_types):
try:
cap = jsonutils.loads(cap)
except ValueError as e:
LOG.debug("%(host_state)s fails. The capabilities "
"'%(cap)s' couldn't be loaded from JSON: "
"%(error)s",
{'host_state': host_state, 'cap': cap,
'error': e})
return None
if not isinstance(cap, dict):
if getattr(cap, scope[index], None) is None:
# If can't find, check stats dict
cap = cap.stats.get(scope[index], None)
else:
cap = getattr(cap, scope[index], None)
else:
cap = cap.get(scope[index], None)
except AttributeError as e:
LOG.debug("%(host_state)s fails. The capabilities couldn't "
"be retrieved: %(error)s.",
{'host_state': host_state, 'error': e})
return None
if cap is None:
LOG.debug("%(host_state)s fails. There are no capabilities "
"to retrieve.",
{'host_state': host_state})
return None
return cap
def _satisfies_extra_specs(self, host_state, instance_type):
"""Check that the host_state provided by the compute service
satisfies the extra specs associated with the instance type.
"""
if 'extra_specs' not in instance_type:
return True
for key, req in instance_type.extra_specs.items():
# Either not scope format, or in capabilities scope
scope = key.split(':')
# If key does not have a namespace, the scope's size is 1, check
# whether host_state contains the key as an attribute. If not,
# ignore it. If it contains, deal with it in the same way as
# 'capabilities:key'. This is for backward-compatible.
# If the key has a namespace, the scope's size will be bigger than
# 1, check that whether the namespace is 'capabilities'. If not,
# ignore it.
if len(scope) == 1:
stats = getattr(host_state, 'stats', {})
has_attr = hasattr(host_state, key) or key in stats
if not has_attr:
continue
else:
if scope[0] != "capabilities":
continue
else:
del scope[0]
cap = self._get_capabilities(host_state, scope)
if cap is None:
return False
if not extra_specs_ops.match(str(cap), req):
LOG.debug("%(host_state)s fails extra_spec requirements. "
"'%(req)s' does not match '%(cap)s'",
{'host_state': host_state, 'req': req,
'cap': cap})
return False
return True
def host_passes(self, host_state, spec_obj):
"""Return a list of hosts that can create instance_type."""
instance_type = spec_obj.flavor
if not self._satisfies_extra_specs(host_state, instance_type):
LOG.debug("%(host_state)s fails instance_type extra_specs "
"requirements", {'host_state': host_state})
return False
return True | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License. | random_line_split |
compute_capabilities_filter.py | # Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from oslo_serialization import jsonutils
import six
from nova.scheduler import filters
from nova.scheduler.filters import extra_specs_ops
LOG = logging.getLogger(__name__)
class ComputeCapabilitiesFilter(filters.BaseHostFilter):
"""HostFilter hard-coded to work with InstanceType records."""
# Instance type and host capabilities do not change within a request
run_filter_once_per_request = True
def _get_capabilities(self, host_state, scope):
cap = host_state
for index in range(0, len(scope)):
try:
if isinstance(cap, six.string_types):
try:
cap = jsonutils.loads(cap)
except ValueError as e:
LOG.debug("%(host_state)s fails. The capabilities "
"'%(cap)s' couldn't be loaded from JSON: "
"%(error)s",
{'host_state': host_state, 'cap': cap,
'error': e})
return None
if not isinstance(cap, dict):
if getattr(cap, scope[index], None) is None:
# If can't find, check stats dict
cap = cap.stats.get(scope[index], None)
else:
cap = getattr(cap, scope[index], None)
else:
cap = cap.get(scope[index], None)
except AttributeError as e:
LOG.debug("%(host_state)s fails. The capabilities couldn't "
"be retrieved: %(error)s.",
{'host_state': host_state, 'error': e})
return None
if cap is None:
LOG.debug("%(host_state)s fails. There are no capabilities "
"to retrieve.",
{'host_state': host_state})
return None
return cap
def _satisfies_extra_specs(self, host_state, instance_type):
"""Check that the host_state provided by the compute service
satisfies the extra specs associated with the instance type.
"""
if 'extra_specs' not in instance_type:
return True
for key, req in instance_type.extra_specs.items():
# Either not scope format, or in capabilities scope
scope = key.split(':')
# If key does not have a namespace, the scope's size is 1, check
# whether host_state contains the key as an attribute. If not,
# ignore it. If it contains, deal with it in the same way as
# 'capabilities:key'. This is for backward-compatible.
# If the key has a namespace, the scope's size will be bigger than
# 1, check that whether the namespace is 'capabilities'. If not,
# ignore it.
if len(scope) == 1:
stats = getattr(host_state, 'stats', {})
has_attr = hasattr(host_state, key) or key in stats
if not has_attr:
continue
else:
if scope[0] != "capabilities":
continue
else:
del scope[0]
cap = self._get_capabilities(host_state, scope)
if cap is None:
|
if not extra_specs_ops.match(str(cap), req):
LOG.debug("%(host_state)s fails extra_spec requirements. "
"'%(req)s' does not match '%(cap)s'",
{'host_state': host_state, 'req': req,
'cap': cap})
return False
return True
def host_passes(self, host_state, spec_obj):
"""Return a list of hosts that can create instance_type."""
instance_type = spec_obj.flavor
if not self._satisfies_extra_specs(host_state, instance_type):
LOG.debug("%(host_state)s fails instance_type extra_specs "
"requirements", {'host_state': host_state})
return False
return True
| return False | conditional_block |
compute_capabilities_filter.py | # Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from oslo_serialization import jsonutils
import six
from nova.scheduler import filters
from nova.scheduler.filters import extra_specs_ops
LOG = logging.getLogger(__name__)
class ComputeCapabilitiesFilter(filters.BaseHostFilter):
"""HostFilter hard-coded to work with InstanceType records."""
# Instance type and host capabilities do not change within a request
run_filter_once_per_request = True
def | (self, host_state, scope):
cap = host_state
for index in range(0, len(scope)):
try:
if isinstance(cap, six.string_types):
try:
cap = jsonutils.loads(cap)
except ValueError as e:
LOG.debug("%(host_state)s fails. The capabilities "
"'%(cap)s' couldn't be loaded from JSON: "
"%(error)s",
{'host_state': host_state, 'cap': cap,
'error': e})
return None
if not isinstance(cap, dict):
if getattr(cap, scope[index], None) is None:
# If can't find, check stats dict
cap = cap.stats.get(scope[index], None)
else:
cap = getattr(cap, scope[index], None)
else:
cap = cap.get(scope[index], None)
except AttributeError as e:
LOG.debug("%(host_state)s fails. The capabilities couldn't "
"be retrieved: %(error)s.",
{'host_state': host_state, 'error': e})
return None
if cap is None:
LOG.debug("%(host_state)s fails. There are no capabilities "
"to retrieve.",
{'host_state': host_state})
return None
return cap
def _satisfies_extra_specs(self, host_state, instance_type):
"""Check that the host_state provided by the compute service
satisfies the extra specs associated with the instance type.
"""
if 'extra_specs' not in instance_type:
return True
for key, req in instance_type.extra_specs.items():
# Either not scope format, or in capabilities scope
scope = key.split(':')
# If key does not have a namespace, the scope's size is 1, check
# whether host_state contains the key as an attribute. If not,
# ignore it. If it contains, deal with it in the same way as
# 'capabilities:key'. This is for backward-compatible.
# If the key has a namespace, the scope's size will be bigger than
# 1, check that whether the namespace is 'capabilities'. If not,
# ignore it.
if len(scope) == 1:
stats = getattr(host_state, 'stats', {})
has_attr = hasattr(host_state, key) or key in stats
if not has_attr:
continue
else:
if scope[0] != "capabilities":
continue
else:
del scope[0]
cap = self._get_capabilities(host_state, scope)
if cap is None:
return False
if not extra_specs_ops.match(str(cap), req):
LOG.debug("%(host_state)s fails extra_spec requirements. "
"'%(req)s' does not match '%(cap)s'",
{'host_state': host_state, 'req': req,
'cap': cap})
return False
return True
def host_passes(self, host_state, spec_obj):
"""Return a list of hosts that can create instance_type."""
instance_type = spec_obj.flavor
if not self._satisfies_extra_specs(host_state, instance_type):
LOG.debug("%(host_state)s fails instance_type extra_specs "
"requirements", {'host_state': host_state})
return False
return True
| _get_capabilities | identifier_name |
test_msvc9compiler.py | """Tests for distutils.msvc9compiler."""
import sys
import unittest
import os
from distutils.errors import DistutilsPlatformError
from distutils.tests import support
from test.support import run_unittest
_MANIFEST = """\
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security> | <requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false">
</requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC90.CRT"
version="9.0.21022.8" processorArchitecture="x86"
publicKeyToken="XXXX">
</assemblyIdentity>
</dependentAssembly>
</dependency>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC90.MFC"
version="9.0.21022.8" processorArchitecture="x86"
publicKeyToken="XXXX"></assemblyIdentity>
</dependentAssembly>
</dependency>
</assembly>
"""
_CLEANED_MANIFEST = """\
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false">
</requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
</dependency>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC90.MFC"
version="9.0.21022.8" processorArchitecture="x86"
publicKeyToken="XXXX"></assemblyIdentity>
</dependentAssembly>
</dependency>
</assembly>"""
if sys.platform=="win32":
from distutils.msvccompiler import get_build_version
if get_build_version()>=8.0:
SKIP_MESSAGE = None
else:
SKIP_MESSAGE = "These tests are only for MSVC8.0 or above"
else:
SKIP_MESSAGE = "These tests are only for win32"
@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE)
class msvc9compilerTestCase(support.TempdirManager,
unittest.TestCase):
def test_no_compiler(self):
# makes sure query_vcvarsall throws
# a DistutilsPlatformError if the compiler
# is not found
from distutils.msvc9compiler import query_vcvarsall
def _find_vcvarsall(version):
return None
from distutils import msvc9compiler
old_find_vcvarsall = msvc9compiler.find_vcvarsall
msvc9compiler.find_vcvarsall = _find_vcvarsall
try:
self.assertRaises(DistutilsPlatformError, query_vcvarsall,
'wont find this version')
finally:
msvc9compiler.find_vcvarsall = old_find_vcvarsall
def test_reg_class(self):
from distutils.msvc9compiler import Reg
self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx')
# looking for values that should exist on all
# windows registeries versions.
path = r'Control Panel\Desktop'
v = Reg.get_value(path, 'dragfullwindows')
self.assertTrue(v in ('0', '1', '2'))
import winreg
HKCU = winreg.HKEY_CURRENT_USER
keys = Reg.read_keys(HKCU, 'xxxx')
self.assertEqual(keys, None)
keys = Reg.read_keys(HKCU, r'Control Panel')
self.assertTrue('Desktop' in keys)
def test_remove_visual_c_ref(self):
from distutils.msvc9compiler import MSVCCompiler
tempdir = self.mkdtemp()
manifest = os.path.join(tempdir, 'manifest')
f = open(manifest, 'w')
try:
f.write(_MANIFEST)
finally:
f.close()
compiler = MSVCCompiler()
compiler._remove_visual_c_ref(manifest)
# see what we got
f = open(manifest)
try:
# removing trailing spaces
content = '\n'.join([line.rstrip() for line in f.readlines()])
finally:
f.close()
# makes sure the manifest was properly cleaned
self.assertEqual(content, _CLEANED_MANIFEST)
def test_suite():
return unittest.makeSuite(msvc9compilerTestCase)
if __name__ == "__main__":
run_unittest(test_suite()) | random_line_split |
|
test_msvc9compiler.py | """Tests for distutils.msvc9compiler."""
import sys
import unittest
import os
from distutils.errors import DistutilsPlatformError
from distutils.tests import support
from test.support import run_unittest
_MANIFEST = """\
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false">
</requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC90.CRT"
version="9.0.21022.8" processorArchitecture="x86"
publicKeyToken="XXXX">
</assemblyIdentity>
</dependentAssembly>
</dependency>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC90.MFC"
version="9.0.21022.8" processorArchitecture="x86"
publicKeyToken="XXXX"></assemblyIdentity>
</dependentAssembly>
</dependency>
</assembly>
"""
_CLEANED_MANIFEST = """\
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false">
</requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
</dependency>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC90.MFC"
version="9.0.21022.8" processorArchitecture="x86"
publicKeyToken="XXXX"></assemblyIdentity>
</dependentAssembly>
</dependency>
</assembly>"""
if sys.platform=="win32":
from distutils.msvccompiler import get_build_version
if get_build_version()>=8.0:
SKIP_MESSAGE = None
else:
SKIP_MESSAGE = "These tests are only for MSVC8.0 or above"
else:
SKIP_MESSAGE = "These tests are only for win32"
@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE)
class msvc9compilerTestCase(support.TempdirManager,
unittest.TestCase):
def test_no_compiler(self):
# makes sure query_vcvarsall throws
# a DistutilsPlatformError if the compiler
# is not found
from distutils.msvc9compiler import query_vcvarsall
def _find_vcvarsall(version):
return None
from distutils import msvc9compiler
old_find_vcvarsall = msvc9compiler.find_vcvarsall
msvc9compiler.find_vcvarsall = _find_vcvarsall
try:
self.assertRaises(DistutilsPlatformError, query_vcvarsall,
'wont find this version')
finally:
msvc9compiler.find_vcvarsall = old_find_vcvarsall
def test_reg_class(self):
from distutils.msvc9compiler import Reg
self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx')
# looking for values that should exist on all
# windows registeries versions.
path = r'Control Panel\Desktop'
v = Reg.get_value(path, 'dragfullwindows')
self.assertTrue(v in ('0', '1', '2'))
import winreg
HKCU = winreg.HKEY_CURRENT_USER
keys = Reg.read_keys(HKCU, 'xxxx')
self.assertEqual(keys, None)
keys = Reg.read_keys(HKCU, r'Control Panel')
self.assertTrue('Desktop' in keys)
def test_remove_visual_c_ref(self):
from distutils.msvc9compiler import MSVCCompiler
tempdir = self.mkdtemp()
manifest = os.path.join(tempdir, 'manifest')
f = open(manifest, 'w')
try:
f.write(_MANIFEST)
finally:
f.close()
compiler = MSVCCompiler()
compiler._remove_visual_c_ref(manifest)
# see what we got
f = open(manifest)
try:
# removing trailing spaces
content = '\n'.join([line.rstrip() for line in f.readlines()])
finally:
f.close()
# makes sure the manifest was properly cleaned
self.assertEqual(content, _CLEANED_MANIFEST)
def | ():
return unittest.makeSuite(msvc9compilerTestCase)
if __name__ == "__main__":
run_unittest(test_suite())
| test_suite | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.