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 |
|---|---|---|---|---|
fields.py | # -*- coding: UTF-8 -*-
#------------------------------------------------------------------------------
# file: fields.py
# License: LICENSE.TXT
# Author: Ioannis Tziakos
#
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
i... |
def to_rst(self, indent=4):
""" Outputs field in rst as an itme in a definition list.
Arguments
---------
indent : int
The indent to use for the decription block.
Returns
-------
lines : list
A list of string lines of formated rst.
... | return cls(arg_name.strip(), arg_type.strip(), lines[1:])
else:
return cls(arg_name.strip(), arg_type.strip(), [''])
| random_line_split |
fields.py | # -*- coding: UTF-8 -*-
#------------------------------------------------------------------------------
# file: fields.py
# License: LICENSE.TXT
# Author: Ioannis Tziakos
#
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
i... | dent=''):
regex = indent + r'\w+\(.*\)\s*'
match = re.match(regex, line)
return match
def to_rst(self, length, first_column, second_column):
split_result = re.split('\((.*)\)', self.name)
method_name = split_result[0]
method_text = ':meth:`{0}... | line, in | identifier_name |
fields.py | # -*- coding: UTF-8 -*-
#------------------------------------------------------------------------------
# file: fields.py
# License: LICENSE.TXT
# Author: Ioannis Tziakos
#
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
i... | _length(fields):
""" Find the max length of the description in a list of fields.
Arguments
---------
fields : list
The list of the parsed fields.
"""
return max([len(' '.join([line.strip() for line in field[2]]))
for field in fields])
| ax length of the header in a list of fields.
Arguments
---------
fields : list
The list of the parsed fields.
"""
return max([len(field[0]) for field in fields])
def max_desc | identifier_body |
lib.rs | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | match_attr_data!(a, rhs, keep)
}
}
pub fn get_attribute_vec<'a, T>(
&'a self,
key: impl AsRef<str>,
) -> std::result::Result<&'a Vec<T>, String>
where
&'a Vec<T>: TryFrom<&'a AttributeData, Error = String>,
{
self.attributes
.get(key.a... | ($dtype:ident, $data:ident, $keep:expr) => {
$data.retain(|_| $keep.next().unwrap())
};
} | random_line_split |
lib.rs | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | <T>(
&mut self,
key: impl AsRef<str>,
) -> std::result::Result<Vec<T>, String>
where
Vec<T>: TryFrom<AttributeData, Error = String>,
{
self.attributes
.remove(key.as_ref())
.ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref()))
... | remove_attribute_vec | identifier_name |
lib.rs | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | else {
assert_eq!(self.attributes.len(), other.attributes.len());
self.position.append(&mut other.position);
for (s, o) in self
.attributes
.values_mut()
.zip(other.attributes.values_mut())
{
s.append(o)?;
... | {
*self = other.split_off(0);
} | conditional_block |
lib.rs | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
pub fn split_off(&mut self, at: usize) -> Self {
let position = self.position.split_off(at);
let attributes = self
.attributes
.iter_mut()
.map(|(n, a)| (n.clone(), a.split_off(at)))
.collect();
Self {
position,
attrib... | {
if self.position.is_empty() {
*self = other.split_off(0);
} else {
assert_eq!(self.attributes.len(), other.attributes.len());
self.position.append(&mut other.position);
for (s, o) in self
.attributes
.values_mut()
... | identifier_body |
DigitReader.js | "use strict";
let ImageVol = require('./ImageVol'); |
const DEFAULTS = {
// declare size of input
// output Vol is of size 128x128x4 here
input: {
type: 'input',
out_sx: 128,
out_sy: 128,
out_depth: 4
},
conv: [
// the first layer will perform convolution with 16 kernels, each of size 5x5.
// the input will be padded with 2 pixels on... | random_line_split | |
DigitReader.js | "use strict";
let ImageVol = require('./ImageVol');
const DEFAULTS = {
// declare size of input
// output Vol is of size 128x128x4 here
input: {
type: 'input',
out_sx: 128,
out_sy: 128,
out_depth: 4
},
conv: [
// the first layer will perform convolution with 16 kernels, each of size ... |
}
static cleanOptions(options, label, iteration) {
DigitReader.validate(label, iteration);
let newOptions = {};
let allowedKeys = Object.keys((typeof iteration === 'number') ? DEFAULTS[label][iteration] : DEFAULTS[label]);
allowedKeys.forEach(function(key) {
let opt = DigitReader.option(key,... | {
if (typeof iteration !== 'number')
throw new Error({message: "Iteration must be a number", context: iteration});
if (!DEFAULTS[label][iteration])
throw new Error({message: "Invalid iteration for " + label, context: iteration});
} | conditional_block |
DigitReader.js | "use strict";
let ImageVol = require('./ImageVol');
const DEFAULTS = {
// declare size of input
// output Vol is of size 128x128x4 here
input: {
type: 'input',
out_sx: 128,
out_sy: 128,
out_depth: 4
},
conv: [
// the first layer will perform convolution with 16 kernels, each of size ... | {
constructor(options) {
if (!options) options = {};
this.net = new ConvNetJS.Net();
if (options.net) {
console.log('Using previously saved neural network');
this.net.fromJSON(options.net);
} else {
console.log('Creating fresh neural network');
let layerDefinitions = [];
... | DigitReader | identifier_name |
card.js | /**
* @license Copyright (c) 2013, Viet Trinh All Rights Reserved.
* Available via MIT license.
*/
/**
* A card entity.
*/
define([ 'framework/entity/base_entity' ],
function(BaseEntity)
{
/**
* Constructor.
* @param rawObject (optional)
* The raw object to create the entity with.
*/
var Card = funct... | Card.RARITY.UNCOMMON = 'U';
Card.RARITY.COMMON = 'C';
Card.RARITY.LAND = 'L';
return Card;
}); | random_line_split | |
stage.ts | /**
* stage component for acting out a lesson
*/
import {Component, OnChanges, SimpleChange, EventEmitter} from "angular2/core";
import {Input} from "angular2/core";
export type Step = {id: number, op: number, arg: string};
enum Ops { BRK=1, SAY, ASK, CHK }
type Scene = {cards: string[], asking:boolean, checking: b... |
export type AnswerEvent = {answer:string, stepId: number};
export type Result = {correct:boolean, message:string};
// TODO: upgrade lodash typings to get _.clamp (on github but not in release yet as of 3/30/2016)
var _clamp = function (x,lo,hi) { return Math.max(lo, Math.min(hi, x))};
@Component({
selector: 'st... | { return {cards:[], asking:false, checking: false, stepId: 0}; } | identifier_body |
stage.ts | /**
* stage component for acting out a lesson
*/
import {Component, OnChanges, SimpleChange, EventEmitter} from "angular2/core";
import {Input} from "angular2/core";
export type Step = {id: number, op: number, arg: string};
enum Ops { BRK=1, SAY, ASK, CHK }
type Scene = {cards: string[], asking:boolean, checking: b... | var scene = newScene(), scenes=[scene];
this.script.forEach((step:Step)=> {
switch (step.op) {
case Ops.BRK:
scenes.push(scene = newScene());
break;
case Ops.SAY:
scene.cards.push(`<h1>${step.arg}</h1>`);
break;
case Ops.ASK:
sc... |
rebuild() { | random_line_split |
stage.ts | /**
* stage component for acting out a lesson
*/
import {Component, OnChanges, SimpleChange, EventEmitter} from "angular2/core";
import {Input} from "angular2/core";
export type Step = {id: number, op: number, arg: string};
enum Ops { BRK=1, SAY, ASK, CHK }
type Scene = {cards: string[], asking:boolean, checking: b... | implements OnChanges {
@Input() script: Step[] = [];
@Input() result: Result;
scene: Scene = newScene();
answer: string;
waiting: boolean = false;
reporting: boolean=false;
checkWork = new EventEmitter<AnswerEvent>();
private
_cursor: number;
_scenes: Scene[] = [];
constructor() {}
ngOnC... | StageComponent | identifier_name |
create_entry.rs | use super::*;
use crate::core::error::RepoError;
use diesel::Connection;
pub fn create_entry(
connections: &sqlite::Connections,
indexer: &mut EntryIndexer,
new_entry: usecases::NewEntry,
) -> Result<String> {
// Create and add new entry
let (entry, ratings) = {
let connection = connectio... | diesel::result::Error::RollbackTransaction
})?;
Ok((entry, ratings))
}
Err(err) => {
prepare_err = Some(err);
Err(diesel::result::Error::RollbackTra... | warn!("Failed to store newly created entry: {}", err); | random_line_split |
create_entry.rs | use super::*;
use crate::core::error::RepoError;
use diesel::Connection;
pub fn create_entry(
connections: &sqlite::Connections,
indexer: &mut EntryIndexer,
new_entry: usecases::NewEntry,
) -> Result<String> {
// Create and add new entry
let (entry, ratings) = {
let connection = connectio... |
})
}?;
// Index newly added entry
// TODO: Move to a separate task/thread that doesn't delay this request
if let Err(err) = usecases::index_entry(indexer, &entry, &ratings).and_then(|_| indexer.flush())
{
error!("Failed to index newly added entry {}: {}", entry.id, err);
}
... | {
RepoError::from(err).into()
} | conditional_block |
create_entry.rs | use super::*;
use crate::core::error::RepoError;
use diesel::Connection;
pub fn create_entry(
connections: &sqlite::Connections,
indexer: &mut EntryIndexer,
new_entry: usecases::NewEntry,
) -> Result<String> {
// Create and add new entry
let (entry, ratings) = {
let connection = connectio... | {
let (email_addresses, all_categories) = {
let connection = connections.shared()?;
let email_addresses =
usecases::email_addresses_by_coordinate(&*connection, entry.location.pos)?;
let all_categories = connection.all_categories()?;
(email_addresses, all_categories)
}... | identifier_body | |
create_entry.rs | use super::*;
use crate::core::error::RepoError;
use diesel::Connection;
pub fn create_entry(
connections: &sqlite::Connections,
indexer: &mut EntryIndexer,
new_entry: usecases::NewEntry,
) -> Result<String> {
// Create and add new entry
let (entry, ratings) = {
let connection = connectio... | (connections: &sqlite::Connections, entry: &Entry) -> Result<()> {
let (email_addresses, all_categories) = {
let connection = connections.shared()?;
let email_addresses =
usecases::email_addresses_by_coordinate(&*connection, entry.location.pos)?;
let all_categories = connection.a... | notify_entry_added | identifier_name |
EventTarget.js | /**
* @author Mat Groves http://matgroves.com/ @Doormat23
* @author Chad Engler https://github.com/englercj @Rolnaaba
*/
/**
* Originally based on https://github.com/mrdoob/eventtarget.js/ from mr Doob.
* Currently takes inspiration from the nodejs EventEmitter, EventEmitter3, and smokesignals
*/
/**
... |
},
/**
* Mixes in the properties of the EventTarget prototype onto another object
*
* @method Phaser.EventTarget.mixin
* @param object {Object} The obj to mix into
*/
mixin: function mixin(obj) {
/**
* Return a list of assigned event listeners.
... | {
obj = obj.prototype || obj;
Phaser.EventTarget.mixin(obj);
} | conditional_block |
EventTarget.js | /**
* @author Mat Groves http://matgroves.com/ @Doormat23
* @author Chad Engler https://github.com/englercj @Rolnaaba
*/
/**
* Originally based on https://github.com/mrdoob/eventtarget.js/ from mr Doob.
* Currently takes inspiration from the nodejs EventEmitter, EventEmitter3, and smokesignals
*/
/**
... | () {
fn.apply(self.off(eventName, onceHandlerWrapper), arguments);
}
onceHandlerWrapper._originalHandler = fn;
return this.on(eventName, onceHandlerWrapper);
};
/**
* Remove event listeners.
*
* @method Phaser.Ev... | onceHandlerWrapper | identifier_name |
EventTarget.js | /**
* @author Mat Groves http://matgroves.com/ @Doormat23
* @author Chad Engler https://github.com/englercj @Rolnaaba
*/
/**
* Originally based on https://github.com/mrdoob/eventtarget.js/ from mr Doob.
* Currently takes inspiration from the nodejs EventEmitter, EventEmitter3, and smokesignals
*/
/**
... |
onceHandlerWrapper._originalHandler = fn;
return this.on(eventName, onceHandlerWrapper);
};
/**
* Remove event listeners.
*
* @method Phaser.EventTarget.off
* @alias removeEventListener
* @param eventName {String} The eve... | {
fn.apply(self.off(eventName, onceHandlerWrapper), arguments);
} | identifier_body |
EventTarget.js | /**
* @author Mat Groves http://matgroves.com/ @Doormat23
* @author Chad Engler https://github.com/englercj @Rolnaaba
*/
/**
* Originally based on https://github.com/mrdoob/eventtarget.js/ from mr Doob.
* Currently takes inspiration from the nodejs EventEmitter, EventEmitter3, and smokesignals
*/
/**
... | var list = this._listeners[eventName],
i = fn ? list.length : 0;
while(i-- > 0) {
if(list[i] === fn || list[i]._originalHandler === fn) {
list.splice(i, 1);
}
}
if(list.length === 0) {
... | random_line_split | |
sprite.rs | /*
use glium::texture::Texture2d;
use glium;
use glium::backend::glutin_backend::GlutinFacade;
use glium::{VertexBuffer, IndexBuffer};
use graphics::vertex::Vertex;
pub struct Sprite {
texture: Texture2d,
vertex_buffer: VertexBuffer<Vertex>,
index_buffer: IndexBuffer<u16>,
}
impl Sprite {
pub fn new(... | pos: [-0.5, -0.5],
tex_coords: [0.0, 0.0],
};
let tr = Vertex {
pos: [0.5, -0.5],
tex_coords: [0.0, 1.0],
};
let shape = [tl, tr, bl, br];
let vertex_buffer = VertexBuffer::new(display, &shape).unwrap();
let indices = [0, ... | pos: [0.5, 0.5],
tex_coords: [1.0, 1.0],
};
let tl = Vertex { | random_line_split |
csssupportsrule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... | cssconditionrule: CSSConditionRule,
#[ignore_heap_size_of = "Arc"]
supportsrule: Arc<Locked<SupportsRule>>,
}
impl CSSSupportsRule {
fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>)
-> CSSSupportsRule {
let guard = parent_styleshe... | random_line_split | |
csssupportsrule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... | (&self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
let rule = self.supportsrule.read_with(&guard);
rule.condition.to_css_string().into()
}
/// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface
pub fn set_condition_text(&self, text:... | get_condition_text | identifier_name |
csssupportsrule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... |
}
}
impl SpecificCSSRule for CSSSupportsRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::SUPPORTS_RULE
}
fn get_css(&self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
self.... | {
let global = self.global();
let win = global.as_window();
let url = win.Document().url();
let quirks_mode = win.Document().quirks_mode();
let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports),
... | conditional_block |
csssupportsrule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... |
}
impl SpecificCSSRule for CSSSupportsRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::SUPPORTS_RULE
}
fn get_css(&self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
self.suppor... | {
let mut input = ParserInput::new(&text);
let mut input = Parser::new(&mut input);
let cond = SupportsCondition::parse(&mut input);
if let Ok(cond) = cond {
let global = self.global();
let win = global.as_window();
let url = win.Document().url();
... | identifier_body |
pad4d.ts | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
export const pad4d = op({pad4d_});
| {
assert(
paddings.length === 4 && paddings[0].length === 2 &&
paddings[1].length === 2 && paddings[2].length === 2 &&
paddings[3].length === 2,
() => 'Invalid number of paddings. Must be length of 2 each.');
return pad(x, paddings, constantValue);
} | identifier_body |
pad4d.ts | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | * =============================================================================
*/
import {Tensor4D} from '../tensor';
import {TensorLike} from '../types';
import {assert} from '../util';
import {op} from './operation';
import {pad} from './pad';
/**
* Pads a `tf.Tensor4D` with a given value and paddings. See `pad`... | random_line_split | |
pad4d.ts | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | (
x: Tensor4D|TensorLike,
paddings:
[
[number, number], [number, number], [number, number], [number, number]
],
constantValue = 0): Tensor4D {
assert(
paddings.length === 4 && paddings[0].length === 2 &&
paddings[1].length === 2 && paddings[2].length === 2 &&
... | pad4d_ | identifier_name |
router.rs | extern crate iron;
extern crate iron_mountrouter;
// To run, $ cargo run --example router
// To use, go to http://127.0.0.1:3000/
use std::fs::File;
use std::io::Read;
use iron::{Iron, Request, Response, IronResult};
use iron::headers::ContentType;
use iron::status;
use iron_mountrouter::{Router, StrippedUrl};
fn g... |
} | {
let ref query = req.extensions.get::<Router>()
.unwrap();
let mut res = Response::with((
status::Ok,
get_output(
&format!(
"<p>Url: {:?}<p>Query parts: {:?}<p>Stripped url: {:?}",
req.url.path,
*query,
req.extensions.get::<StrippedUrl>()
)
)
));
... | identifier_body |
router.rs | use std::fs::File;
use std::io::Read;
use iron::{Iron, Request, Response, IronResult};
use iron::headers::ContentType;
use iron::status;
use iron_mountrouter::{Router, StrippedUrl};
fn get_output(content: &str) -> String {
let mut res = String::new();
File::open("examples/router.html").unwrap().read_to_string(&mut... | extern crate iron;
extern crate iron_mountrouter;
// To run, $ cargo run --example router
// To use, go to http://127.0.0.1:3000/ | random_line_split | |
router.rs | extern crate iron;
extern crate iron_mountrouter;
// To run, $ cargo run --example router
// To use, go to http://127.0.0.1:3000/
use std::fs::File;
use std::io::Read;
use iron::{Iron, Request, Response, IronResult};
use iron::headers::ContentType;
use iron::status;
use iron_mountrouter::{Router, StrippedUrl};
fn | (content: &str) -> String {
let mut res = String::new();
File::open("examples/router.html").unwrap().read_to_string(&mut res).unwrap();
res.replace("<!-- content -->", content)
}
fn main() {
let mut router = Router::new();
router.add_route("/", handler, false);
router.add_route("/:query/:sub-query/", ha... | get_output | identifier_name |
token.rs | the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_key... | new_from_rc_str | identifier_name | |
token.rs | ed to break a circularity
}
impl fmt::Show for Nonterminal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("Nt... | pub type IdentInterner = StrInterner; | random_line_split | |
JLink.py | import ctypes
class JLinkException(Exception): pass
class JLink(object):
"Jlink api"
revser = 0
def __init__(self, dllpath):
self.jlink = ctypes.cdll.LoadLibrary(dllpath)
self.tif_select(1)
self.set_speed(1000)
self.reset()
def check_err(fn):
def che... |
@check_err
def set_tms(self): return self.jlink.JLINKARM_SetTMS()
@check_err
def read_reg(self,r): return self.jlink.JLINKARM_ReadReg(r)
@check_err
def write_reg(self,r,val): return self.jlink.JLINKARM_WriteReg(r,val)
@check_err
def write_U32(self,r,val): return self.jlink.JLINKARM_... | return self.jlink.JLINKARM_ClrTMS() | identifier_body |
JLink.py | import ctypes
class JLinkException(Exception): pass
class JLink(object):
"Jlink api"
revser = 0
def __init__(self, dllpath):
self.jlink = ctypes.cdll.LoadLibrary(dllpath)
self.tif_select(1)
self.set_speed(1000)
self.reset()
def check_err(fn):
def che... |
@check_err
def halt(self): return self.jlink.JLINKARM_Halt()
@check_err
def clear_tck(self): return self.jlink.JLINKARM_ClrTCK()
@check_err
def clear_tms(self): return self.jlink.JLINKARM_ClrTMS()
@check_err
def set_tms(self): return self.jlink.JLINKARM_SetTMS()
@check_err
d... | @check_err
def set_speed(self, khz): return self.jlink.JLINKARM_SetSpeed(khz)
@check_err
def reset(self): return self.jlink.JLINKARM_Reset() | random_line_split |
JLink.py | import ctypes
class JLinkException(Exception): pass
class JLink(object):
"Jlink api"
revser = 0
def __init__(self, dllpath):
self.jlink = ctypes.cdll.LoadLibrary(dllpath)
self.tif_select(1)
self.set_speed(1000)
self.reset()
def check_err(fn):
def che... |
return ret
return checked_transaction
@check_err
def tif_select(self, tif): return self.jlink.JLINKARM_TIF_Select(tif)
@check_err
def set_speed(self, khz): return self.jlink.JLINKARM_SetSpeed(khz)
@check_err
def reset(self): return self.jlink.JLINKARM_Reset()
@check_... | raise JLinkException(errno) | conditional_block |
JLink.py | import ctypes
class JLinkException(Exception): pass
class JLink(object):
"Jlink api"
revser = 0
def __init__(self, dllpath):
self.jlink = ctypes.cdll.LoadLibrary(dllpath)
self.tif_select(1)
self.set_speed(1000)
self.reset()
def check_err(fn):
def che... | (self, startaddress):
buf, ret = self.read_mem_U32(startaddress, 1)
return buf[0]
| read_U32 | identifier_name |
Validation.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// 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
... | implements IValidation {
protected validationRules: {};
private readonly validator;
constructor() {
this.validator = inspector;
this.validationRules = ValidationRules;
}
protected addValidationRules(rules) {
Object.assign(this.validationRules, rules);
}
validate(validationItem, data, options:IOptions =... | Validation | identifier_name |
Validation.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// 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
... | isError: boolean;
message?: string;
}
export default class Validation implements IValidation {
protected validationRules: {};
private readonly validator;
constructor() {
this.validator = inspector;
this.validationRules = ValidationRules;
}
protected addValidationRules(rules) {
Object.assign(this.validat... | random_line_split | |
Validation.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// 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
... |
schema.optional = !required;
const validation = this.validator.validate(schema, data);
return {
isError: !validation.valid,
message: errorText ||
(validation.error.length ? validation.error[0].message : ''),
};
}
}
| {
return {
isError: true,
message: 'Invalid validation schema',
};
} | conditional_block |
config-start.component.ts | import {Component, OnInit, ViewChild} from '@angular/core';
import {MoonGenService} from "../../services/moon-gen.service";
import {MoonConfigurationService} from "../../services/moon-configuration.service";
import {MoonHistoryService} from "../../services/moon-history.service";
import {ModalDirective} from "ng2-bootst... | () {
this.loadFileModal.show();
this.load = true;
}
/**
* At the end of the Loading process, the file is loaded as new configuration
* @param event
*/
public loadNewConfiguration(event){
this.loadFileModal.hide();
this.readThis(event.target);
}
/**
... | loadFile | identifier_name |
config-start.component.ts | import {Component, OnInit, ViewChild} from '@angular/core';
import {MoonGenService} from "../../services/moon-gen.service";
import {MoonConfigurationService} from "../../services/moon-configuration.service";
import {MoonHistoryService} from "../../services/moon-history.service";
import {ModalDirective} from "ng2-bootst... |
myReader.readAsText(file);
}
/**
* Gets the Property for the description based on the script number
* @param script The script number
* @returns {string }
*/
private getProbDescription(script: number) {
return this.configurationList[script].description;
}
/**
... | random_line_split | |
config-start.component.ts | import {Component, OnInit, ViewChild} from '@angular/core';
import {MoonGenService} from "../../services/moon-gen.service";
import {MoonConfigurationService} from "../../services/moon-configuration.service";
import {MoonHistoryService} from "../../services/moon-history.service";
import {ModalDirective} from "ng2-bootst... |
}, this);
}
/**
* Stops the MoonGen Process after activated through the button
*/
stopMoonGen() {
this.moonGenService.stopMoonGen((error:boolean,component:ConfigStartComponent)=>{
if (error) {
component.status = true;
}
}, this);
... | {
component.status = false;
} | conditional_block |
config-start.component.ts | import {Component, OnInit, ViewChild} from '@angular/core';
import {MoonGenService} from "../../services/moon-gen.service";
import {MoonConfigurationService} from "../../services/moon-configuration.service";
import {MoonHistoryService} from "../../services/moon-history.service";
import {ModalDirective} from "ng2-bootst... |
/**
* Gets the Property for the description based on the script number
* @param script The script number
* @returns {string }
*/
private getProbDescription(script: number) {
return this.configurationList[script].description;
}
/**
* Downloads the File to save
* @... | {
let file:File = inputValue.files[0];
let myReader:FileReader = new FileReader();
let config = this.configurationService;
myReader.onloadend = function(){
let result = JSON.parse(myReader.result);
config.setJSONConfiguration(result);
};
myReader... | identifier_body |
dark_mode.rs | /// This is a simple implementation of support for Windows Dark Mode,
/// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use winapi::{
shared::{
basetsd::SIZE_T,
minwindef::{BOOL, DWORD, FALSE, UINT, ULONG, WO... | cbData: SIZE_T,
}
lazy_static! {
static ref SET_WINDOW_COMPOSITION_ATTRIBUTE: Option<SetWindowCompositionAttribute> =
get_function!("user32.dll", SetWindowCompositionAttribute);
}
if let Some(set_window_composition_attribute) = *SET_WINDOW_COMPOSITION_ATTRIBUTE {
un... | struct WINDOWCOMPOSITIONATTRIBDATA {
Attrib: WINDOWCOMPOSITIONATTRIB,
pvData: PVOID, | random_line_split |
dark_mode.rs | /// This is a simple implementation of support for Windows Dark Mode,
/// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use winapi::{
shared::{
basetsd::SIZE_T,
minwindef::{BOOL, DWORD, FALSE, UINT, ULONG, WO... | (hwnd: HWND, is_dark_mode: bool) -> bool {
// Uses Windows undocumented API SetWindowCompositionAttribute,
// as seen in win32-darkmode example linked at top of file.
type SetWindowCompositionAttribute =
unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
#[allow(non_sna... | set_dark_mode_for_window | identifier_name |
dark_mode.rs | /// This is a simple implementation of support for Windows Dark Mode,
/// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use winapi::{
shared::{
basetsd::SIZE_T,
minwindef::{BOOL, DWORD, FALSE, UINT, ULONG, WO... |
fn widestring(src: &'static str) -> Vec<u16> {
OsStr::new(src)
.encode_wide()
.chain(Some(0).into_iter())
.collect()
}
| {
let mut hc = HIGHCONTRASTA {
cbSize: 0,
dwFlags: 0,
lpszDefaultScheme: std::ptr::null_mut(),
};
let ok = unsafe {
winuser::SystemParametersInfoA(
winuser::SPI_GETHIGHCONTRAST,
std::mem::size_of_val(&hc) as _,
&mut hc as *mut _ as _,
... | identifier_body |
backend.py | 'connect', 'contact', 'contest', 'create', 'css', 'dashboard', 'data',
'db', 'delete', 'design', 'dev', 'devel', 'dir', 'directory', 'doc',
'docs', 'domain', 'download', 'downloads', 'downvote', 'ecommerce', 'edit',
'editor', 'email', 'faq', 'favorite', 'feed', 'feedback', 'file', 'files',
'find', 'flo... | (user_id):
"""Is there a user object with `user_id`?
"""
return bool(m.db.users.find_one({'_id': user_id}, {}))
def authenticate(username, password):
"""Authenticate a username/password combination.
"""
# Case-insensitive login
username = username.lower()
if '@' in username:
... | user_exists | identifier_name |
backend.py | 'connect', 'contact', 'contest', 'create', 'css', 'dashboard', 'data',
'db', 'delete', 'design', 'dev', 'devel', 'dir', 'directory', 'doc',
'docs', 'domain', 'download', 'downloads', 'downvote', 'ecommerce', 'edit',
'editor', 'email', 'faq', 'favorite', 'feed', 'feedback', 'file', 'files',
'find', 'flo... |
# Insert the new user in to Mongo. If this fails a None will be
# returned
result = m.db.users.insert(user)
return uid if result else None
except DuplicateKeyError: # pragma: no cover
# Oh no something went wrong. Pass over it. A None will be returned.
... | user['tip_{}'.format(tip_name)] = True | conditional_block |
backend.py | ', 'ihasalerts', 'image', 'images', 'imap', 'img',
'index', 'info', 'information', 'invite', 'java', 'javascript', 'job',
'jobs', 'js', 'list', 'lists', 'log', 'login', 'logout', 'logs', 'mail',
'master', 'media', 'message', 'messages', 'name', 'net', 'network', 'new',
'news', 'newsletter', 'nick', 'nic... | """Will delete a users account.
This **REMOVES ALL** details, posts, replies, etc. Not votes though.
.. note: Ensure the user has authenticated this request. This is going to
be the most *expensive* task in Pjuu, be warned.
:param user_id: The `user_id` of the user to delete
:type user_i... | identifier_body | |
backend.py | task',
'tasks', 'template', 'templatestest', 'terms', 'terms_and_conditions',
'terms_of_service', 'termsandconditions', 'termsofservice', 'tests',
'theme', 'themes', 'tmp', 'todo', 'tools', 'unfollow', 'update', 'upload',
'upvote', 'url', 'usage', 'user', 'username', 'video', 'videos', 'web',
'webma... | r.delete(k.USER_FOLLOWING.format(user_id))
# Delete the users feed, this may have been added too during this process. | random_line_split | |
editorQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (controller: QuickOpenController, opts: IQuickOpenOpts): void {
controller.run({
inputAriaLabel: this._inputAriaLabel,
getModel: (value: string): QuickOpenModel => opts.getModel(value),
getAutoFocus: (searchValue: string): IAutoFocus => opts.getAutoFocus(searchValue)
});
}
}
export interface IDecorator {... | _show | identifier_name |
editorQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () => onClose(false),
() => onClose(true),
(value: string) => {
this.widget.setInput(opts.getModel(value), opts.getAutoFocus(value));
},
{
inputAriaLabel: opts.inputAriaLabel
},
this.themeService
);
// Remember selection to be able to restore on cancel
if (!this.lastKnownEditorSelect... | this.editor, | random_line_split |
editorQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
// Create goto line widget
let onClose = (canceled: boolean) => {
// Clear Highlight Decorations if present
this.clearDecorations();
// Restore selection if canceled
if (canceled && this.lastKnownEditorSelection) {
this.editor.setSelection(this.lastKnownEditorSelection);
this.editor.revealRan... | {
this.widget.destroy();
this.widget = null;
} | conditional_block |
uploadFormView.ts | /// <reference path='./../plupload.d.ts' />
import {UploadFileCollection, UploadFileModel} from '../../../entities/uploadFile';
let uploadFormTemplate: string = require('./uploadFormView.hbs');
class UploadFormModel extends Backbone.Model{
name: string;
}
interface IUploadFormOptions {
uploadFileCollection:... |
onFileUploaded(up: any, file: any) {
/*(<any>this.ui.progressBar).addClass('bar-success');
(<any>this.ui.progressBar).parent().removeClass('active');
(<any>this.ui.message).html('<div class='alert alert-success'>' + this.successMessage + '</div>');*/
}
handleUploadErrors(up: any, ... | {
let fileFromQueue: UploadFileModel = this.uploadFileCollection.get(file.id);
fileFromQueue.set('percent', file.percent);
// (<any>this.ui.progressBar).width(file.percent + '%');
} | identifier_body |
uploadFormView.ts | /// <reference path='./../plupload.d.ts' />
import {UploadFileCollection, UploadFileModel} from '../../../entities/uploadFile';
let uploadFormTemplate: string = require('./uploadFormView.hbs');
class UploadFormModel extends Backbone.Model{
name: string;
}
interface IUploadFormOptions {
uploadFileCollection:... |
}
onFileSelect(e: any) {
// e.preventDefault();
// console.log('click select')
}
// @TODO should delegate display to another sibling view
onFilesAdded(up: any, files: any) {
// var uploadFileModel = new FileModel(files[0]);
this.uploadFileCollection.add(files);
... | {
target.ondragover = function(event: any) {
event.dataTransfer.dropEffect = 'copy';
};
target.ondragenter = function() {
this.className = 'dragover';
};
target.ondragleave = function() {
this.className = '';... | conditional_block |
uploadFormView.ts | /// <reference path='./../plupload.d.ts' />
import {UploadFileCollection, UploadFileModel} from '../../../entities/uploadFile';
let uploadFormTemplate: string = require('./uploadFormView.hbs');
class UploadFormModel extends Backbone.Model{
name: string;
}
interface IUploadFormOptions {
uploadFileCollection:... | */
up.refresh(); // reposition Flash/Silverlight
}
onUploadProgress(up: any, file: any) {
let fileFromQueue: UploadFileModel = this.uploadFileCollection.get(file.id);
fileFromQueue.set('percent', file.percent);
// (<any>this.ui.progressBar).width(file.percent + '%');
... |
// document.getElementById('filelist').innerHTML += html;
(<any>this.ui.message).html('<div class='alert alert-info'>' + html + '</div>'); | random_line_split |
uploadFormView.ts | /// <reference path='./../plupload.d.ts' />
import {UploadFileCollection, UploadFileModel} from '../../../entities/uploadFile';
let uploadFormTemplate: string = require('./uploadFormView.hbs');
class UploadFormModel extends Backbone.Model{
name: string;
}
interface IUploadFormOptions {
uploadFileCollection:... | (up: any, params: any) {
var target = (<any>this.ui.dropTarget).get(0);
if (this.uploader.features.dragdrop) {
target.ondragover = function(event: any) {
event.dataTransfer.dropEffect = 'copy';
};
target.ondragenter = function() {
th... | onUploaderInit | identifier_name |
orderpoint_procurement.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | # GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
#
# Order Point Method:
# ... | random_line_split | |
orderpoint_procurement.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
def procure_calculation(self, cr, uid, ids, context=None):
"""
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: List of IDs selected
@param context: A standard dictionary
"""
thr... | """
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: List of IDs selected
@param context: A standard dictionary
"""
proc_obj = self.pool.get('procurement.order')
#As this function is i... | identifier_body |
orderpoint_procurement.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | (osv.osv_memory):
_name = 'procurement.orderpoint.compute'
_description = 'Automatic Order Point'
_columns = {
'automatic': fields.boolean('Automatic Orderpoint', help='If the stock of a product is under 0, it will act like an orderpoint'),
}
_defaults = {
'automatic': False... | procurement_compute | identifier_name |
orderpoint_procurement.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
#close the new cursor
new_cr.close()
return {}
def procure_calculation(self, cr, uid, ids, context=None):
"""
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: List of IDs selecte... | proc_obj._procure_orderpoint_confirm(new_cr, uid, automatic=proc.automatic, use_new_cursor=new_cr.dbname, context=context) | conditional_block |
sample_index_range.rs | use std::{fmt, ops::Div};
use metadata::Duration;
| #[derive(Clone, Copy, Default, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct SampleIndexRange(usize);
impl SampleIndexRange {
pub const fn new(value: usize) -> Self {
SampleIndexRange(value)
}
#[track_caller]
pub fn from_duration(duration: Duration, sample_duration: Duration) -> Self {
... | random_line_split | |
sample_index_range.rs | use std::{fmt, ops::Div};
use metadata::Duration;
#[derive(Clone, Copy, Default, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct SampleIndexRange(usize);
impl SampleIndexRange {
pub const fn new(value: usize) -> Self {
SampleIndexRange(value)
}
#[track_caller]
pub fn from_duration(duratio... |
#[track_caller]
pub fn duration(self, sample_duration: Duration) -> Duration {
sample_duration * (self.0 as u64)
}
#[track_caller]
pub fn scale(self, num: SampleIndexRange, denom: SampleIndexRange) -> Self {
SampleIndexRange(self.0 * num.0 / denom.0)
}
#[track_caller]
... | {
SampleIndexRange((duration / sample_duration).as_usize())
} | identifier_body |
sample_index_range.rs | use std::{fmt, ops::Div};
use metadata::Duration;
#[derive(Clone, Copy, Default, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct SampleIndexRange(usize);
impl SampleIndexRange {
pub const fn new(value: usize) -> Self {
SampleIndexRange(value)
}
#[track_caller]
pub fn from_duration(duratio... | (self, sample_step: SampleIndexRange) -> usize {
self.0 / sample_step.0
}
pub fn as_f64(self) -> f64 {
self.0 as f64
}
pub fn as_usize(self) -> usize {
self.0
}
}
impl From<usize> for SampleIndexRange {
fn from(value: usize) -> Self {
Self(value)
}
}
impl ... | step_range | identifier_name |
app.js | define(['services/services', 'controllers/controllers', 'directives/directives'], function () {
var app = angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','starter.directives', 'ngCordova', 'ngSanitize']);
app.run(function($ionicPlatform, $rootScope, $ionicHistory) {
$rootScope.goBa... | controller : 'ConcernCtrl'
}
}
})
//论坛中 添加关注页面
.state('addconcern',{
url:'/addconcern',
templateUrl: 'view/post/post_add_concern.html',
controller: 'AddConcernCtrl'
})
//欢迎页
.state('tour',{
url: '/tour',
templateU... | views:{
'tab-post-concern':{
templateUrl: 'view/post/post_concern.html', | random_line_split |
app.js | define(['services/services', 'controllers/controllers', 'directives/directives'], function () {
var app = angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','starter.directives', 'ngCordova', 'ngSanitize']);
app.run(function($ionicPlatform, $rootScope, $ionicHistory) {
$rootScope.goBa... |
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
});
//统一Android和iOS的风格。Android下Tab放到页面下
app.config(function($ionicConfigProvider) {
$ionicConfigProvider.platform.ios.tabs.style('ios');
$ionicConfigProvider.platform.ios.tabs... | {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
} | conditional_block |
pyramid.rs | use hitable::{
Hitable,
HitRecord,
HitableList,
};
use ray::Ray3;
use aabb::AABB;
use material::Material;
use triangle::Triangle;
use quad::Quad;
use cgmath::{
Point3,
Vector3,
Quaternion,
Rotation,
One,
};
use std::time::Instant;
pub struct | {
hitable_list: HitableList,
}
impl Pyramid {
pub fn new(position: Point3<f32>, base_length: f32, height: f32, rotation: Quaternion<f32>, material: Material) -> Self {
let base_vertices = [
position + rotation.rotate_vector(Vector3::new(-0.5, 0.0, 0.5) * base_length),
position ... | Pyramid | identifier_name |
pyramid.rs | use hitable::{
Hitable,
HitRecord,
HitableList,
};
use ray::Ray3;
use aabb::AABB;
use material::Material;
use triangle::Triangle;
use quad::Quad;
use cgmath::{
Point3, | Rotation,
One,
};
use std::time::Instant;
pub struct Pyramid {
hitable_list: HitableList,
}
impl Pyramid {
pub fn new(position: Point3<f32>, base_length: f32, height: f32, rotation: Quaternion<f32>, material: Material) -> Self {
let base_vertices = [
position + rotation.rotate_vec... | Vector3,
Quaternion, | random_line_split |
gcp.py | """ Launcher functionality for the Google Compute Engine (GCE)
"""
import json
import logging
import os
from dcos_launch import onprem, util
from dcos_launch.platforms import gcp
from dcos_test_utils.helpers import Host
from googleapiclient.errors import HttpError
log = logging.getLogger(__name__)
def get_credentia... |
def get_bootstrap_host(self) -> Host:
return list(self.deployment.hosts)[0]
def wait(self):
""" Waits for the deployment to complete: first, the network that will contain the cluster is deployed. Once
the network is deployed, a firewall for the network and an instance template are depl... | random_line_split | |
gcp.py | """ Launcher functionality for the Google Compute Engine (GCE)
"""
import json
import logging
import os
from dcos_launch import onprem, util
from dcos_launch.platforms import gcp
from dcos_test_utils.helpers import Host
from googleapiclient.errors import HttpError
log = logging.getLogger(__name__)
def get_credentia... |
raise e
def create(self) -> dict:
self.key_helper()
node_count = 1 + (self.config['num_masters'] + self.config['num_public_agents']
+ self.config['num_private_agents'])
gcp.BareClusterDeployment.create(
self.gcp_wrapper,
self.co... | raise util.LauncherError('DeploymentNotFound',
"The deployment you are trying to access doesn't exist") from e | conditional_block |
gcp.py | """ Launcher functionality for the Google Compute Engine (GCE)
"""
import json
import logging
import os
from dcos_launch import onprem, util
from dcos_launch.platforms import gcp
from dcos_test_utils.helpers import Host
from googleapiclient.errors import HttpError
log = logging.getLogger(__name__)
def get_credentia... | (self):
""" Deletes all the resources associated with the deployment (instance template, network, firewall, instance
group manager and all its instances.
"""
self.deployment.delete()
| delete | identifier_name |
gcp.py | """ Launcher functionality for the Google Compute Engine (GCE)
"""
import json
import logging
import os
from dcos_launch import onprem, util
from dcos_launch.platforms import gcp
from dcos_test_utils.helpers import Host
from googleapiclient.errors import HttpError
log = logging.getLogger(__name__)
def get_credentia... |
class OnPremLauncher(onprem.AbstractOnpremLauncher):
# Launches a homogeneous cluster of plain GMIs intended for onprem DC/OS
def __init__(self, config: dict, env=None):
creds_string, _ = get_credentials(env)
self.gcp_wrapper = gcp.GcpWrapper(json.loads(creds_string))
self.config = co... | path = None
if env is None:
env = os.environ.copy()
if 'GCE_CREDENTIALS' in env:
json_credentials = env['GCE_CREDENTIALS']
elif 'GOOGLE_APPLICATION_CREDENTIALS' in env:
path = env['GOOGLE_APPLICATION_CREDENTIALS']
json_credentials = util.read_file(path)
else:
rais... | identifier_body |
Experiment.ts | module MultiPass {
import IAdapter = MultiPass.Adapters.IAdapter;
import GoogleAnalytics = MultiPass.Adapters.GoogleAnalytics;
Quartz.Storage.getInstance().setNamespace('multi-pass');
export interface IVariant {
activate: (experiment: Experiment) => void;
}
export interface IExperiment... |
/**
* This picks one of the variants available and sets up the experiment
*
* @returns {string}
*/
private applyVariant(): string {
let variantName: string = this.storage.get(this.name + ':variant');
if (!this.inSample()) {
re... | {
if (unqiue && this.storage.get(this.name + ':' + name)) {
return;
}
let variant: string = this.storage.get(this.name + ':variant');
if (!variant) {
return;
}
if (unqiue) {
this.storage.set(this.na... | identifier_body |
Experiment.ts | module MultiPass {
import IAdapter = MultiPass.Adapters.IAdapter;
import GoogleAnalytics = MultiPass.Adapters.GoogleAnalytics;
Quartz.Storage.getInstance().setNamespace('multi-pass');
export interface IVariant {
activate: (experiment: Experiment) => void;
}
export interface IExperiment... | (): string {
let variantName: string = this.storage.get(this.name + ':variant');
if (!this.inSample()) {
return;
}
if (variantName === null) {
variantName = this.chooseVariant();
this.tracker.start(this.name, variantName);
... | applyVariant | identifier_name |
Experiment.ts | module MultiPass {
import IAdapter = MultiPass.Adapters.IAdapter;
import GoogleAnalytics = MultiPass.Adapters.GoogleAnalytics;
Quartz.Storage.getInstance().setNamespace('multi-pass');
export interface IVariant {
activate: (experiment: Experiment) => void;
}
export interface IExperiment... |
if (unqiue) {
this.storage.set(this.name + ':' + name, true);
}
return this.tracker.complete(this.name, variant, name);
}
/**
* This picks one of the variants available and sets up the experiment
*
* @returns {string}
... | {
return;
} | conditional_block |
Experiment.ts | module MultiPass {
import IAdapter = MultiPass.Adapters.IAdapter;
import GoogleAnalytics = MultiPass.Adapters.GoogleAnalytics;
Quartz.Storage.getInstance().setNamespace('multi-pass');
export interface IVariant {
activate: (experiment: Experiment) => void;
}
export interface IExperiment... | private inSample(): boolean {
let isIn: string = this.storage.get(this.name + ':isIn');
if (null !== isIn) {
return isIn === 'true';
}
let isInreal: boolean = Math.random() <= this.sample;
this.storage.set(this.name + ':isIn', isInreal... | */ | random_line_split |
search.js | /**
* Adapted from https://github.com/camptocamp/agridea_geoacorda/blob/master/jsapi/src/searchcontrol.js
*/
goog.provide('app.MapSearchController');
goog.provide('app.mapSearchDirective');
goog.require('app');
goog.require('app.constants');
/** @suppress {extraRequire} */
goog.require('ngeo.searchDirective');
goog.... | /**
* @return {Bloodhound} The bloodhound engine.
* @private
*/
app.MapSearchController.prototype.createAndInitBloodhound_ = function() {
var url = app.MapSearchController.SEARCH_URL;
url += '?q=%QUERY';
var bloodhound = new Bloodhound(/** @type {BloodhoundOptions} */({
limit: 10,
queryTokenizer: Bloo... | */
app.MapSearchController.SEARCH_URL = 'https://photon.komoot.de/api/';
| random_line_split |
search.js | /**
* Adapted from https://github.com/camptocamp/agridea_geoacorda/blob/master/jsapi/src/searchcontrol.js
*/
goog.provide('app.MapSearchController');
goog.provide('app.mapSearchDirective');
goog.require('app');
goog.require('app.constants');
/** @suppress {extraRequire} */
goog.require('ngeo.searchDirective');
goog.... |
if (feature.get('country')) {
addressInfo.push(feature.get('country'));
}
if (addressInfo.length > 0) {
var name = feature.get('name') + ' (' + addressInfo.join(', ') + ')';
feature.set('name', name);
}
});
return features;
... | {
addressInfo.push(feature.get('state'));
} | conditional_block |
Fish.ts | module example.components {
import Container = PIXI.Container;
import Component = artemis.Component;
import PooledComponent = artemis.PooledComponent;
import Pooled = artemis.annotations.Pooled;
import Sprite = PIXI.Sprite;
@Pooled()
export class Fish extends PooledComponent {
public static classNam... | (layer:Container) {
layer.removeChild(this.sprite);
}
}
Fish.prototype.sprite = null;
Fish.prototype.direction = 0;
Fish.prototype.speed = 0;
Fish.prototype.turnSpeed = 0;
}
| removeFrom | identifier_name |
Fish.ts | module example.components {
import Container = PIXI.Container;
import Component = artemis.Component;
import PooledComponent = artemis.PooledComponent;
import Pooled = artemis.annotations.Pooled;
import Sprite = PIXI.Sprite;
@Pooled()
export class Fish extends PooledComponent {
public static classNam... |
removeFrom(layer:Container) {
layer.removeChild(this.sprite);
}
}
Fish.prototype.sprite = null;
Fish.prototype.direction = 0;
Fish.prototype.speed = 0;
Fish.prototype.turnSpeed = 0;
}
| {
layer.addChild(this.sprite);
} | identifier_body |
Fish.ts | module example.components {
import Container = PIXI.Container;
import Component = artemis.Component;
import PooledComponent = artemis.PooledComponent;
import Pooled = artemis.annotations.Pooled;
import Sprite = PIXI.Sprite;
@Pooled()
export class Fish extends PooledComponent {
public static classNam... |
addTo(layer:Container) {
layer.addChild(this.sprite);
}
removeFrom(layer:Container) {
layer.removeChild(this.sprite);
}
}
Fish.prototype.sprite = null;
Fish.prototype.direction = 0;
Fish.prototype.speed = 0;
Fish.prototype.turnSpeed = 0;
} | this.sprite.anchor.x = this.sprite.anchor.y = 0.5;
if (lambda) lambda(this);
} | random_line_split |
client.rs | // Copyright © 2014, Peter Atashian
use std::io::timer::sleep;
use std::io::{TcpStream};
use std::sync::Arc;
use std::sync::atomics::{AtomicUint, SeqCst};
use std::task::TaskBuilder;
use std::time::duration::Duration;
fn m | ) {
let count = Arc::new(AtomicUint::new(0));
loop {
let clone = count.clone();
TaskBuilder::new().stack_size(32768).spawn(proc() {
let mut tcp = match TcpStream::connect("127.0.0.1", 273) {
Ok(tcp) => tcp,
Err(_) => return,
};
... | ain( | identifier_name |
client.rs | // Copyright © 2014, Peter Atashian
use std::io::timer::sleep; | use std::io::{TcpStream};
use std::sync::Arc;
use std::sync::atomics::{AtomicUint, SeqCst};
use std::task::TaskBuilder;
use std::time::duration::Duration;
fn main() {
let count = Arc::new(AtomicUint::new(0));
loop {
let clone = count.clone();
TaskBuilder::new().stack_size(32768).spawn(proc() {
... | random_line_split | |
client.rs | // Copyright © 2014, Peter Atashian
use std::io::timer::sleep;
use std::io::{TcpStream};
use std::sync::Arc;
use std::sync::atomics::{AtomicUint, SeqCst};
use std::task::TaskBuilder;
use std::time::duration::Duration;
fn main() { |
let count = Arc::new(AtomicUint::new(0));
loop {
let clone = count.clone();
TaskBuilder::new().stack_size(32768).spawn(proc() {
let mut tcp = match TcpStream::connect("127.0.0.1", 273) {
Ok(tcp) => tcp,
Err(_) => return,
};
pri... | identifier_body | |
main.js | /*global Motio */
jQuery(function ($) {
'use strict';
var windowSpy = new $.Espy(window);
// ==========================================================================
// Header clouds
// ==========================================================================
(function () {
var header = $('header')[0];
... | request = 'run';
facing = 'left';
break;
// Right arrow
case 39:
request = 'run';
facing = 'right';
break;
// Spacebar
case 32:
request = 'jump';
break;
// B
case 66:
request = 'kick';
break;
}
// Show concerned animation
$mations.hi... | random_line_split | |
main.js | /*global Motio */
jQuery(function ($) {
'use strict';
var windowSpy = new $.Espy(window);
// ==========================================================================
// Header clouds
// ==========================================================================
(function () {
var header = $('header')[0];
... | () {
if (pos === 0 && facing === 'left' || pos === posMax && facing === 'right') {
return;
}
pos += (facing === 'right' ? moveSpeed : -moveSpeed) / moveFps;
if (pos < 0) {
pos = 0;
} else if (pos > posMax) {
pos = posMax;
}
$char[0].style.left = pos + 'px';
mIndex = setTimeout(mov... | move | identifier_name |
main.js | /*global Motio */
jQuery(function ($) {
'use strict';
var windowSpy = new $.Espy(window);
// ==========================================================================
// Header clouds
// ==========================================================================
(function () {
var header = $('header')[0];
... |
pos += (facing === 'right' ? moveSpeed : -moveSpeed) / moveFps;
if (pos < 0) {
pos = 0;
} else if (pos > posMax) {
pos = posMax;
}
$char[0].style.left = pos + 'px';
mIndex = setTimeout(move, 1000 / moveFps);
}
});
}); | {
return;
} | conditional_block |
main.js | /*global Motio */
jQuery(function ($) {
'use strict';
var windowSpy = new $.Espy(window);
// ==========================================================================
// Header clouds
// ==========================================================================
(function () {
var header = $('header')[0];
... |
});
}); | {
if (pos === 0 && facing === 'left' || pos === posMax && facing === 'right') {
return;
}
pos += (facing === 'right' ? moveSpeed : -moveSpeed) / moveFps;
if (pos < 0) {
pos = 0;
} else if (pos > posMax) {
pos = posMax;
}
$char[0].style.left = pos + 'px';
mIndex = setTimeout(move, ... | identifier_body |
urls.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(
template_name='pages/home.htm... | urlpatterns += [
url(r'^400/$', 'django.views.defaults.bad_request'),
url(r'^403/$', 'django.views.defaults.permission_denied'),
url(r'^404/$', 'django.views.defaults.page_not_found'),
url(r'^500/$', 'django.views.defaults.server_error'),
] | conditional_block | |
urls.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(
template_name='pages/home.htm... | ] | url(r'^500/$', 'django.views.defaults.server_error'), | random_line_split |
compiler_required.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (pub fn() -> bool);
pub struct StaticTestName(pub &'static str);
pub struct TestDesc {
// Indicates a test case should run but not fail the overall test suite.
// This was introduced in https://github.com/rust-lang/rust/pull/42219. It
// is not expected to become stable:
// https://github.com/rust-lang... | StaticTestFn | identifier_name |
compiler_required.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | pub test_type: TestType,
}
pub struct TestDescAndFn {
pub desc: TestDesc,
pub testfn: StaticTestFn,
}
pub enum TestType { UnitTest }
// The test harness's equivalent of main() (it is called by a compiler-generated
// shim).
pub fn test_main_static(tests: &[&TestDescAndFn]) {
use libtock::println;
... | random_line_split | |
compiler_required.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
maybe_drivers.ok().unwrap().console.create_console();
println!("Starting tests.");
let mut overall_success = true;
for test_case in tests {
// Skip ignored test cases.
let desc = &test_case.desc;
let name = desc.name.0;
if desc.ignore {
println!("Skipping ig... | {
panic!("Could not retrieve drivers.");
} | conditional_block |
compiler_required.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
// -----------------------------------------------------------------------------
// Compiler-generated test list types. The compiler generates a [&TestDescAndFn]
// array and passes it to test_main_static.
// -----------------------------------------------------------------------------
// A ShouldPanic enum is requi... | { result } | identifier_body |
common.py | import string
import random
import json
from collections import defaultdict
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from catmaid.fields import Double3D
from catmaid.models import Log, NeuronSearch, CELL_BODY_CHOICES, \
... |
elif column == 'gal4':
neurons.sort(key=lambda x: x.cached_sorted_lines_str)
elif column == 'cell_body':
neurons.sort(key=lambda x: x.cached_cell_body)
else:
raise Exception("Unknown column (%s) in order_neurons" % (column,))
if reverse:
n... | neurons.sort(key=lambda x: x.name) | conditional_block |
common.py | import string
import random
import json
from collections import defaultdict
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from catmaid.fields import Double3D
from catmaid.models import Log, NeuronSearch, CELL_BODY_CHOICES, \
... | else:
search_form = NeuronSearch({'search': '',
'cell_body_location': 'a',
'order_by': 'name'})
if search_form.is_valid():
search = search_form.cleaned_data['search']
cell_body_location = search_form.cleaned_data['ce... | search_form = NeuronSearch({'search': kw_search,
'cell_body_location': kw_cell_body_choice,
'order_by': kw_order_by})
elif request.method == 'POST':
search_form = NeuronSearch(request.POST) | random_line_split |
common.py | import string
import random
import json
from collections import defaultdict
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from catmaid.fields import Double3D
from catmaid.models import Log, NeuronSearch, CELL_BODY_CHOICES, \
... | cell_body_location = 'a'
order_by = 'name'
cell_body_choices_dict = dict(CELL_BODY_CHOICES)
all_neurons = ClassInstance.objects.filter(
project__id=project_id,
class_column__class_name='neuron',
name__icontains=search).exclude(name='orphaned pre').exclude(name='orphaned... | rest_keys = ('search', 'cell_body_location', 'order_by')
if any((x in kwargs) for x in rest_keys):
kw_search = kwargs.get('search', None) or ""
kw_cell_body_choice = kwargs.get('cell_body_location', None) or "a"
kw_order_by = kwargs.get('order_by', None) or 'name'
search_form = Neuro... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.