file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
__openerp__.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2014 Didotech SRL (info at didotech.com) # All Rights Reserved. # # WARNING: This program as such is intended to be used by professional # programmers who take the whole re...
{ "name": "Export Customers - Exporting customer's data in .csv file for italian fiscal program.", 'version': '2.0.1.0', 'category': 'Generic Modules/Sales customers', "description": """Exporting customer's data in .csv file """, "author": "Didotech SRL", 'website': 'http://www.didotech.com', ...
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ##############################################################################
random_line_split
widgets.py
# -*- coding: utf-8 -*- from itertools import chain from django.contrib.sites.models import Site from django.core.urlresolvers import NoReverseMatch, reverse_lazy from django.forms.widgets import Select, MultiWidget, TextInput from django.utils.encoding import force_text from django.utils.safestring import mark_safe ...
else: data_value = data if initial is None: initial_value = u'' else: initial_value = initial if force_unicode(initial_value) != force_unicode(data_value): return True return False def render(self, name, value, attrs=None)...
data_value = u''
conditional_block
widgets.py
# -*- coding: utf-8 -*- from itertools import chain from django.contrib.sites.models import Site from django.core.urlresolvers import NoReverseMatch, reverse_lazy from django.forms.widgets import Select, MultiWidget, TextInput from django.utils.encoding import force_text from django.utils.safestring import mark_safe ...
: css = { 'all': ('cms/js/select2/select2.css', 'cms/js/select2/select2-bootstrap.css',) } js = (#'cms/js/libs/jquery.min.js', 'cms/js/select2/select2.js',) class UserSelectAdminWidget(Select): """Special widget used in page permission inlines,...
Media
identifier_name
widgets.py
# -*- coding: utf-8 -*- from itertools import chain from django.contrib.sites.models import Site from django.core.urlresolvers import NoReverseMatch, reverse_lazy from django.forms.widgets import Select, MultiWidget, TextInput from django.utils.encoding import force_text from django.utils.safestring import mark_safe ...
except NoReverseMatch: raise Exception( 'You should provide an ajax_view argument that can be reversed to the PageSmartLinkWidget' ) def render(self, name=None, value=None, attrs=None): final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id',...
def get_ajax_url(self, ajax_view): try: return reverse_lazy(ajax_view)
random_line_split
widgets.py
# -*- coding: utf-8 -*- from itertools import chain from django.contrib.sites.models import Site from django.core.urlresolvers import NoReverseMatch, reverse_lazy from django.forms.widgets import Select, MultiWidget, TextInput from django.utils.encoding import force_text from django.utils.safestring import mark_safe ...
def format_output(self, rendered_widgets): return u' '.join(rendered_widgets) class PageSmartLinkWidget(TextInput): def __init__(self, attrs=None, ajax_view=None): super(PageSmartLinkWidget, self).__init__(attrs) self.ajax_url = self.get_ajax_url(ajax_view=ajax_view) def ge...
site_choices = get_site_choices() page_choices = get_page_choices() self.site_choices = site_choices self.choices = page_choices self.widgets = (Select(choices=site_choices ), Select(choices=[('', '----')]), Select(choices=self.choices, attrs={'style...
identifier_body
type_to_value.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {TypeValueReference} from './host'; /** * Potentially convert a `ts.Type...
else if (firstDecl && isImportSource(firstDecl)) { const origin = extractModuleAndNameFromImport(firstDecl, symbols.importName); return {local: false, valueDeclaration: decl.valueDeclaration, ...origin}; } else { const expression = typeNodeToValueExpr(typeNode); if (expression !== null) { retur...
{ // This is a default import. return { local: true, // Copying the name here ensures the generated references will be correctly transformed along // with the import. expression: ts.updateIdentifier(firstDecl.name), defaultImportStatement: firstDecl.parent, }; }
conditional_block
type_to_value.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {TypeValueReference} from './host'; /** * Potentially convert a `ts.Type...
case ts.SyntaxKind.NamespaceImport: // The symbol was imported via a namespace import. In this case, the name to use when // importing it was extracted by resolveTypeSymbols. if (localName === null) { // resolveTypeSymbols() should have extracted the correct local name for the import. ...
random_line_split
type_to_value.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {TypeValueReference} from './host'; /** * Potentially convert a `ts.Type...
function isImportSource(node: ts.Declaration): node is(ts.ImportSpecifier | ts.NamespaceImport) { return ts.isImportSpecifier(node) || ts.isNamespaceImport(node); } function extractModuleAndNameFromImport( node: ts.ImportSpecifier | ts.NamespaceImport | ts.ImportClause, localName: string | null): {name: st...
{ if (ts.isQualifiedName(node)) { const left = entityNameToValue(node.left); return left !== null ? ts.createPropertyAccess(left, node.right) : null; } else if (ts.isIdentifier(node)) { return ts.getMutableClone(node); } else { return null; } }
identifier_body
type_to_value.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {TypeValueReference} from './host'; /** * Potentially convert a `ts.Type...
(node: ts.Declaration): node is(ts.ImportSpecifier | ts.NamespaceImport) { return ts.isImportSpecifier(node) || ts.isNamespaceImport(node); } function extractModuleAndNameFromImport( node: ts.ImportSpecifier | ts.NamespaceImport | ts.ImportClause, localName: string | null): {name: string, moduleName: string}...
isImportSource
identifier_name
accept_language.rs
use header::{Language, QualityItem}; header! { #[doc="`Accept-Language` header, defined in"] #[doc="[RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)"] #[doc=""] #[doc="The `Accept-Language` header field can be used by user agents to"] #[doc="indicate the set of natural languages that are...
#[doc="* `da, en-gb;q=0.8, en;q=0.7`"] #[doc="* `en-us;q=1.0, en;q=0.5, fr`"] (AcceptLanguage, "Accept-Language") => (QualityItem<Language>)+ test_accept_language { // From the RFC test_header!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]); // Own test test_header!( ...
#[doc="language-range = <language-range, see [RFC4647], Section 2.1>"] #[doc="```"] #[doc=""] #[doc="# Example values"]
random_line_split
manticore_protocol_cerberus_GetCert__req_to_wire.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // !! DO NOT EDIT !! // To regenerate this file, run `fuzz/generate_proto_tests.py`. #![no_main] #![allow(non_snake_case)] use libfuzzer_sys::fuzz_target; use mantico...
let _ = Req::borrow(&data).to_wire(&mut &mut out[..]); });
random_line_split
boxed.rs
// Copyright 2012-2015 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-MI...
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let raw = Box::into_raw(self); let to: TraitObject = mem::transmute::<*mut Any, TraitObje...
impl Box<Any> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type.
random_line_split
boxed.rs
// Copyright 2012-2015 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-MI...
} #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for Box<T> { /// Returns a new box with a `clone()` of this box's contents. /// /// # Examples /// /// ``` /// let x = Box::new(5); /// let y = x.clone(); /// ``` #[inline] fn clone(&self) -> Box<T> { box {(**...
{ Box::<[T; 0]>::new([]) }
identifier_body
boxed.rs
// Copyright 2012-2015 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-MI...
else { Err(self) } } } impl Box<Any + Send> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> { <Box<Any>>::downcast(self).map_err(|s| unsafe { ...
{ unsafe { // Get the raw representation of the trait object let raw = Box::into_raw(self); let to: TraitObject = mem::transmute::<*mut Any, TraitObject>(raw); // Extract the data pointer Ok(Box::from_raw(to...
conditional_block
boxed.rs
// Copyright 2012-2015 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-MI...
<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> { <Box<Any>>::downcast(self).map_err(|s| unsafe { // reapply the Send marker mem::transmute::<Box<Any>, Box<Any + Send>>(s) }) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Display + ?Sized> fmt::Display for ...
downcast
identifier_name
serialization_profile.py
from __future__ import print_function import shutil import os.path import tempfile import cProfile import pstats import nineml from nineml.utils.comprehensive_example import ( instances_of_all_types, v1_safe_docs) from nineml.serialization import ext_to_format, format_to_serializer format_to_ext = dict((v, k) for...
(): for version in (1.0, 2.0): if version == 1.0: docs = v1_safe_docs else: docs = list(instances_of_all_types['NineML'].values()) for format in format_to_serializer: # @ReservedAssignment try: ext = format_to_ext[format] excep...
function
identifier_name
serialization_profile.py
from __future__ import print_function import shutil import os.path import tempfile import cProfile import pstats import nineml from nineml.utils.comprehensive_example import ( instances_of_all_types, v1_safe_docs) from nineml.serialization import ext_to_format, format_to_serializer format_to_ext = dict((v, k) for...
shutil.rmtree(_tmp_dir) out_file = os.path.join(os.getcwd(), 'serial_profile.out') cProfile.run('function()', out_file) p = pstats.Stats(out_file) p.sort_stats('cumtime').print_stats()
try: ext = format_to_ext[format] except KeyError: continue # ones that can't be written to file (e.g. dict) for i, document in enumerate(docs): doc = document.clone() url = os.path.join( _tmp_dir, 'test{}v{}{}'....
conditional_block
serialization_profile.py
from __future__ import print_function import shutil import os.path import tempfile import cProfile import pstats import nineml from nineml.utils.comprehensive_example import ( instances_of_all_types, v1_safe_docs) from nineml.serialization import ext_to_format, format_to_serializer format_to_ext = dict((v, k) for...
p = pstats.Stats(out_file) p.sort_stats('cumtime').print_stats()
cProfile.run('function()', out_file)
random_line_split
serialization_profile.py
from __future__ import print_function import shutil import os.path import tempfile import cProfile import pstats import nineml from nineml.utils.comprehensive_example import ( instances_of_all_types, v1_safe_docs) from nineml.serialization import ext_to_format, format_to_serializer format_to_ext = dict((v, k) for...
out_file = os.path.join(os.getcwd(), 'serial_profile.out') cProfile.run('function()', out_file) p = pstats.Stats(out_file) p.sort_stats('cumtime').print_stats()
for version in (1.0, 2.0): if version == 1.0: docs = v1_safe_docs else: docs = list(instances_of_all_types['NineML'].values()) for format in format_to_serializer: # @ReservedAssignment try: ext = format_to_ext[format] except KeyErr...
identifier_body
NetWkstaInfo1059.py
# encoding: utf-8 # module samba.dcerpc.wkssvc # from /usr/lib/python2.7/dist-packages/samba/dcerpc/wkssvc.so # by generator 1.135 """ wkssvc DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class NetWkstaInfo1059(__talloc.Object): # no doc def __init__(self, *args, **kwargs): # real...
buf_read_only_files = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass
identifier_body
NetWkstaInfo1059.py
# encoding: utf-8 # module samba.dcerpc.wkssvc # from /usr/lib/python2.7/dist-packages/samba/dcerpc/wkssvc.so # by generator 1.135 """ wkssvc DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class NetWkstaInfo1059(__talloc.Object): # no doc def
(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass buf_read_only_files = property(lambda self:...
__init__
identifier_name
NetWkstaInfo1059.py
# encoding: utf-8 # module samba.dcerpc.wkssvc
""" wkssvc DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class NetWkstaInfo1059(__talloc.Object): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; res...
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/wkssvc.so # by generator 1.135
random_line_split
index.js
'use strict'; (function() { var env = ''; if (typeof module !== 'undefined' && module.exports) env = 'node'; var exports = {}; if (env === 'node') { var layer = require('layer'); } else { exports = this; var layer = layer || this.layer; } exports.intercept = function (ctx, fn, interceptFn) { var result = fals...
resultFn.reset = function() { var status = true; try { layer.unset(f[0][f[1]]); } catch(e) { status = false; } return status; } return resultFn; } if (env === 'node') module.exports = exports.intercept; })();
}
random_line_split
gash.rs
// // gash.rs // // Starting code for PS2 // Running on Rust 0.9 // // University of Virginia - cs4414 Spring 2014 // Weilin Xu, David Evans // Version 0.4 // extern mod extra; use std::{io, run, os}; use std::io::buffered::BufferedReader; use std::io::stdin; use extra::getopts; use std::io::File; use std::io::signal...
fn run_cmdline(&mut self, cmd_line: &str, output: bool) -> ~str { let mut argv: ~[~str] = cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec(); let length = argv.len()-1; if argv[length] == ~"&" { argv.remove(length); let pr...
} ~"fine" }
random_line_split
gash.rs
// // gash.rs // // Starting code for PS2 // Running on Rust 0.9 // // University of Virginia - cs4414 Spring 2014 // Weilin Xu, David Evans // Version 0.4 // extern mod extra; use std::{io, run, os}; use std::io::buffered::BufferedReader; use std::io::stdin; use extra::getopts; use std::io::File; use std::io::signal...
fn run_cd(&mut self, cmd_line: &str) { let mut argv: ~[~str] = cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec(); if argv.len() > 0 { if argv.len() == 1 { self.go_to_home_dir(); return ;...
{ if output == false{ for i in range(0, self.log.len()) { println!("{}", self.log[i]); } return ~"none"; } else { let mut out: ~str = ~""; for i in range(0, self.log.len()){ out = out + self.log[i].to_owned(); } return out; } }
identifier_body
gash.rs
// // gash.rs // // Starting code for PS2 // Running on Rust 0.9 // // University of Virginia - cs4414 Spring 2014 // Weilin Xu, David Evans // Version 0.4 // extern mod extra; use std::{io, run, os}; use std::io::buffered::BufferedReader; use std::io::stdin; use extra::getopts; use std::io::File; use std::io::signal...
(&mut self, cmd_line : &str, output: bool) -> ~str{ let program = cmd_line.splitn(' ', 1).nth(0).expect("no program"); // get command match program { "" => { return ~"continue"; } "exit" => { return ~"return"; } "history" => { ...
find_prog
identifier_name
gash.rs
// // gash.rs // // Starting code for PS2 // Running on Rust 0.9 // // University of Virginia - cs4414 Spring 2014 // Weilin Xu, David Evans // Version 0.4 // extern mod extra; use std::{io, run, os}; use std::io::buffered::BufferedReader; use std::io::stdin; use extra::getopts; use std::io::File; use std::io::signal...
} fn go_to_home_dir(&mut self){ match std::os::homedir() { Some(path) => { std::os::change_dir(&path); } None => { println("$HOME is not set"); } } } } fn write_file(filename: ~str, message: ~...
{ println("Invalid input"); }
conditional_block
scouter.js
// Generated by CoffeeScript 1.3.3 (function() { describe('Scouter', function() { it('can properly score the specificity of W3C\'s examples', function() { var score, scouter, selector, selectors, _results; scouter = new Scouter(); selectors = { '*': 0, 'LI': 1, 'UL LI': ...
'#x34y': 100, '#s12:not(F00)': 101 }; _results = []; for (selector in selectors) { score = selectors[selector]; _results.push(expect(scouter.score(selector)).toBe(score)); } return _results; }); return it('can sort an array of selectors', function() ...
'UL OL+LI': 3, 'H1 + *[REL=up]': 11, 'UL OL LI.red': 13, 'LI.red.level': 21,
random_line_split
properties-defined.pipe.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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 ...
(collectionConfig: CalendarStemConfig, properties: string[]): boolean { return collectionConfig && properties.every(property => !!collectionConfig.barsProperties[property]); } }
transform
identifier_name
properties-defined.pipe.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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 ...
* 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 {Pipe, PipeTransform} from '@angular/core'; import {CalendarStemConfig} from '../../../core/store/calendars/calendar'; @Pipe({ name: 'propertiesDefined', }) export...
*
random_line_split
properties-defined.pipe.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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 ...
}
{ return collectionConfig && properties.every(property => !!collectionConfig.barsProperties[property]); }
identifier_body
issue-10806.rs
// Copyright 2013-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-MI...
3 } pub fn bar() -> int { 4 } pub mod baz { use {foo, bar}; pub fn quux() -> int { foo() + bar() } } pub mod grault { use {foo}; pub fn garply() -> int { foo() } } pub mod waldo { use {}; pub fn plugh() -> int { 0 } } pub fn main() { let _x = b...
pub fn foo() -> int {
random_line_split
issue-10806.rs
// Copyright 2013-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-MI...
() -> int { foo() + bar() } } pub mod grault { use {foo}; pub fn garply() -> int { foo() } } pub mod waldo { use {}; pub fn plugh() -> int { 0 } } pub fn main() { let _x = baz::quux(); let _y = grault::garply(); let _z = waldo::plugh(); }
quux
identifier_name
issue-10806.rs
// Copyright 2013-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-MI...
} pub mod waldo { use {}; pub fn plugh() -> int { 0 } } pub fn main() { let _x = baz::quux(); let _y = grault::garply(); let _z = waldo::plugh(); }
{ foo() }
identifier_body
NestedListEditor.py
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # # This file is part of the E-Cell System # # Copyright (C) 1996-2016 Keio University # Copyright (C) 2008-2016 RIKEN # Copyright (C) 2005-2009 The Molecular Sciences Institute # #:::::::::::::::::::::::::::::::::::::::...
elif aChar == '(': openPara +=1 actualWord += aChar elif aChar == ')': openPara -=1 actualWord += aChar else: actualWord += aChar if openPara!=0: raise BadNestedList( aString...
returnList.append( actualWord ) actualWord = ''
conditional_block
NestedListEditor.py
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # # This file is part of the E-Cell System # # Copyright (C) 1996-2016 Keio University # Copyright (C) 2008-2016 RIKEN # Copyright (C) 2005-2009 The Molecular Sciences Institute # #:::::::::::::::::::::::::::::::::::::::...
parsedList = map( self.__stringToNestedList, stringList ) if len(parsedList) == 1 and type( parsedList[0]) != type(parsedList ): return stringList[0] return parsedList else: return aString def __split( self, aString ): openPara = 0...
random_line_split
NestedListEditor.py
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # # This file is part of the E-Cell System # # Copyright (C) 1996-2016 Keio University # Copyright (C) 2008-2016 RIKEN # Copyright (C) 2005-2009 The Molecular Sciences Institute # #:::::::::::::::::::::::::::::::::::::::...
def __stringToNestedList( self, aString ): # should return a nestedlist if string format is OK # should return None if string format is not OK, should display an error message in this case. aString=aString.strip() # decide whether list or string if aString.__cont...
if type(aNestedList ) == type(''): return aNestedList stringList = [] for aSubList in aNestedList: stringList.append( self.__nestedListToString( aSubList ) ) if level == 0: separator = '\n,' else: separator = ', ' return '(...
identifier_body
NestedListEditor.py
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # # This file is part of the E-Cell System # # Copyright (C) 1996-2016 Keio University # Copyright (C) 2008-2016 RIKEN # Copyright (C) 2005-2009 The Molecular Sciences Institute # #:::::::::::::::::::::::::::::::::::::::...
( self, aString ): # should return a nestedlist if string format is OK # should return None if string format is not OK, should display an error message in this case. aString=aString.strip() # decide whether list or string if aString.__contains__(',') or aString.__contain...
__stringToNestedList
identifier_name
talleres.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { TalleresService } from './talleres.service' @Component({ selector: 'app-talleres', templateUrl: './talleres.component.html', styleUrls: ['./talleres.component.css'], provi...
}
} }
random_line_split
talleres.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { TalleresService } from './talleres.service' @Component({ selector: 'app-talleres', templateUrl: './talleres.component.html', styleUrls: ['./talleres.component.css'], provi...
else { if( (localStorage.getItem('currentNacimiento')=='00/00/0000') || (localStorage.getItem('currentSexo')=='')) { this.router.navigate(['/editar/personales']); } } } }
{ this.router.navigate(['/login']); }
conditional_block
talleres.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { TalleresService } from './talleres.service' @Component({ selector: 'app-talleres', templateUrl: './talleres.component.html', styleUrls: ['./talleres.component.css'], provi...
implements OnInit { Talleres: string; constructor( private _TalleresService: TalleresService, private router: Router ) { this._TalleresService.getTalleres() .subscribe( data => this.Talleres = data, error => alert(...
TalleresComponent
identifier_name
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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...
fn description(&self) -> &str { match *self { HexError::BadLength(_) => "sha256d hex string non-64 length", HexError::BadCharacter(_) => "sha256d bad hex character" } } }
{ None }
identifier_body
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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...
pub mod strings; pub mod vrf; use std::time; use std::thread; use std::time::{SystemTime, UNIX_EPOCH}; use std::fmt; use std::error; pub fn get_epoch_time_secs() -> u64 { let start = SystemTime::now(); let since_the_epoch = start.duration_since(UNIX_EPOCH) .expect("Time went backwards"); return si...
random_line_split
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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...
(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { HexError::BadLength(n) => write!(f, "bad length {} for sha256d hex string", n), HexError::BadCharacter(c) => write!(f, "bad character {} in sha256d hex string", c) } } } impl error::Error for HexError { fn ca...
fmt
identifier_name
account_chart.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...
(self, cr, uid, context=None): """Return default Fiscalyear value""" return self.pool.get('account.fiscalyear').find(cr, uid, context=context) def onchange_fiscalyear(self, cr, uid, ids, fiscalyear_id=False, context=None): res = {} if fiscalyear_id: start_period = end_pe...
_get_fiscalyear
identifier_name
account_chart.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...
result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_tree') id = result and result[1] or False result = act_obj.read(cr, uid, [id], context=context)[0] fiscalyear_id = data.get('fiscalyear', False) and data['fiscalyear'][0] or False result['periods'] = [] ...
if context is None: context = {} data = self.read(cr, uid, ids, context=context)[0]
random_line_split
account_chart.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...
else: res['value'] = {'period_from': False, 'period_to': False} return res def account_chart_open_window(self, cr, uid, ids, context=None): """ Opens chart of Accounts @param cr: the current row, from the database cursor, @param uid: the current user’s I...
start_period = end_period = False cr.execute(''' SELECT * FROM (SELECT p.id FROM account_period p LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id) WHERE f.id = %s ...
conditional_block
account_chart.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...
_defaults = { 'target_move': 'posted', 'fiscalyear': _get_fiscalyear, }
""" Opens chart of Accounts @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of account chart’s IDs @return: dictionary of Open account chart window on given fiscalyear and all Entries or posted entries ...
identifier_body
__init__.py
import time import datetime from MyPy.core.exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError ) from MyPy.constants import fieldtypes apilevel = '2.0' threadsafety = 1 paramstyle = 'format' def Co...
else: return -1 STRING = DBAPITypeObject(fieldtypes.FIELD_TYPE_ENUM, fieldtypes.FIELD_TYPE_STRING, fieldtypes.FIELD_TYPE_VAR_STRING) BINARY = DBAPITypeObject(fieldtypes.FIELD_TYPE_BLOB, fieldtypes.FIELD_TYPE_LONG_BLOB, fieldtypes.FI...
return 1
conditional_block
__init__.py
import time import datetime from MyPy.core.exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError ) from MyPy.constants import fieldtypes apilevel = '2.0' threadsafety = 1 paramstyle = 'format' def Co...
def TimeFromTicks(ticks): return Time(*time.localtime(ticks)[3:6]) def TimestampFromTicks(ticks): return Timestamp(*time.localtime(ticks)[:6]) Binary = str class DBAPITypeObject: def __init__(self, *values): self.values = values def __cmp__(self, other): if other in self.v...
return Date(*time.localtime(ticks)[:3])
identifier_body
__init__.py
import time import datetime from MyPy.core.exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError ) from MyPy.constants import fieldtypes apilevel = '2.0'
threadsafety = 1 paramstyle = 'format' def Connect(*args, **kwargs): from MyPy.core.connection import Connection return Connection(*args, **kwargs) connect = Connection = Connect Date = datetime.date Time = datetime.time Timestamp = datetime.datetime def DateFromTicks(ticks): return Date(*time.localtime...
random_line_split
__init__.py
import time import datetime from MyPy.core.exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError ) from MyPy.constants import fieldtypes apilevel = '2.0' threadsafety = 1 paramstyle = 'format' def Co...
: def __init__(self, *values): self.values = values def __cmp__(self, other): if other in self.values: return 0 if other < self.values: return 1 else: return -1 STRING = DBAPITypeObject(fieldtypes.FIELD_TYPE_ENUM, fieldtype...
DBAPITypeObject
identifier_name
main.ts
import {Aurelia} from 'aurelia-framework'; import {HttpClient} from 'aurelia-fetch-client'; import {UnhandledExceptionProvider} from './utils/module'; import {UnhandledExceptionHandler} from './utils/module'; import 'fetch'; import 'toastr'; import 'bootstrap'; import "velocity/velocity.ui"; export function configure(...
, response(response) { console.log(`Received ${response.status} ${response.url}`); return response; // you can return a modified Response } }); }); }
{ console.log(`Requesting ${request.method} ${request.url}`); return request; // you can return a modified Request, or you can short-circuit the request by returning a Response }
identifier_body
main.ts
import {Aurelia} from 'aurelia-framework'; import {HttpClient} from 'aurelia-fetch-client'; import {UnhandledExceptionProvider} from './utils/module'; import {UnhandledExceptionHandler} from './utils/module'; import 'fetch'; import 'toastr'; import 'bootstrap'; import "velocity/velocity.ui"; export function configure(...
(httpClient) { httpClient.configure(config => { config .withBaseUrl('http://localhost:8080/') .withDefaults({ headers: { 'Accept': 'application/json', 'X-Requested-With': 'Fetch' } }) .wit...
configureHttpClient
identifier_name
main.ts
import {Aurelia} from 'aurelia-framework'; import {HttpClient} from 'aurelia-fetch-client'; import {UnhandledExceptionProvider} from './utils/module'; import {UnhandledExceptionHandler} from './utils/module';
export function configure(aurelia: Aurelia) { aurelia.use .standardConfiguration() .developmentLogging() .plugin('aurelia-animator-velocity', instance => { instance.options.duration = 300; instance.options.easing = "linear"; instance.enterAnimation = { pr...
import 'fetch'; import 'toastr'; import 'bootstrap'; import "velocity/velocity.ui";
random_line_split
kendo.culture.en-NZ.js
/** * Copyright 2014 Telerik AD * * 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 ...
namesAbbr: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""] }, AM: ["a.m.","a.m.","A.M."], PM: ["p.m.","p.m.","P.M."], patterns: { d: "d/MM/yyyy", D: "dddd, d MMMM yyyy...
}, months: { names: ["January","February","March","April","May","June","July","August","September","October","November","December",""],
random_line_split
parsing.rs
//! Utility functions for Header implementations. use std::str; use std::fmt::{self, Display}; /// Reads a single raw string when parsing a header pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> { if raw.len() != 1 { return None; } // we JUST checked that raw.len() == 1, so ...
} None } /// Reads a comma-delimited raw header into a Vec. #[inline] pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> { if raw.len() != 1 { return None; } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. from_one_comma_delimited(& unsafe { ra...
random_line_split
parsing.rs
//! Utility functions for Header implementations. use std::str; use std::fmt::{self, Display}; /// Reads a single raw string when parsing a header pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> { if raw.len() != 1 { return None; } // we JUST checked that raw.len() == 1, so ...
/// Reads a comma-delimited raw string into a Vec. pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> { match str::from_utf8(raw) { Ok(s) => { Some(s .split(',') .filter_map(|x| match x.trim() { "" => None, ...
{ if raw.len() != 1 { return None; } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..]) }
identifier_body
parsing.rs
//! Utility functions for Header implementations. use std::str; use std::fmt::{self, Display}; /// Reads a single raw string when parsing a header pub fn
<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> { if raw.len() != 1 { return None; } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. if let Ok(s) = str::from_utf8(& unsafe { raw.get_unchecked(0) }[..]) { if s != "" { return str::FromStr::from_str(s).ok(); ...
from_one_raw_str
identifier_name
index.js
/* global appSettings */ var $result, $resultContainer, $resultsButton, $resultsPane, $renderingLabel, $window = $(window), path = require('path'), _ = require('lodash'), isEnabled = true, messenger = require(path.resolve(__dirname, '../messenger')), renderer = require(path...
}; var handlers = { opened: function(fileInfo){ refreshSubscriptions(); $result.animate({ scrollTop: $result.offset().top }, 10); }, sourceChanged: function(fileInfo){ handlers.contentChanged(fileInfo); }, contentChanged: function (fileInfo) { i...
{ formatter = currentFormatter; rendererPath = path.resolve(__dirname, './' + formatter.name.toLowerCase()); renderer = require(rendererPath).get(); messenger.publish.file('formatChanged', formatter); }
conditional_block
index.js
/* global appSettings */ var $result, $resultContainer, $resultsButton, $resultsPane, $renderingLabel, $window = $(window), path = require('path'), _ = require('lodash'), isEnabled = true, messenger = require(path.resolve(__dirname, '../messenger')), renderer = require(path...
$resultsButton = $('#result-button'); $renderingLabel = $('#rendering-label'); $resultsPane .css('left', appSettings.split()) .css('width', appSettings.resultsWidth()); $resultsButton.one('click', handlers.hideResults); setHeight(appSettings.editingContainerOffset()); });
$resultsPane = $('#result-pane');
random_line_split
no_0977_squares_of_a_sorted_array.rs
struct Solution; impl Solution { // 官方题解中的思路 pub fn sorted_squares(a: Vec<i32>) -> Vec<i32> { let mut ans = vec![0; a.len()]; if a.is_empty() { return ans; } // 这个减少了一半的时间。 if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } ...
pub fn sorted_squares1(a: Vec<i32>) -> Vec<i32> { if a.is_empty() { return Vec::new(); } if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } let n = a.len(); // 第一个 >= 0 的索引,或者 a.len() let r = a.iter().position(|&v| v >= 0); ...
} } ans }
conditional_block
no_0977_squares_of_a_sorted_array.rs
struct Solution; impl Solution { // 官方题解中的思路 pub fn sorted_squares(a
Vec<i32> { let mut ans = vec![0; a.len()]; if a.is_empty() { return ans; } // 这个减少了一半的时间。 if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } let (mut l, mut r) = (0, a.len() - 1); // 选择 l 和 r 中较大的那个,逆序放入 ans 中。 ...
: Vec<i32>) ->
identifier_name
no_0977_squares_of_a_sorted_array.rs
struct Solution; impl Solution { // 官方题解中的思路 pub fn sorted_squares(a: Vec<i32>) -> Vec<i32> { let mut ans = vec![0; a.len()]; if a.is_empty() { return ans; } // 这个减少了一半的时间。 if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } ...
pub fn sorted_squares1(a: Vec<i32>) -> Vec<i32> { if a.is_empty() { return Vec::new(); } if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } let n = a.len(); // 第一个 >= 0 的索引,或者 a.len() let r = a.iter().position(|&v| v >= 0);...
random_line_split
vote.test.js
var expect = require("chai").expect, proxyquire = require("proxyquire"), sinon = require("sinon"); var models = {}; var app = sinon.stub(); var auth = { authenticated: sinon.stub() }; var get = app.get = sinon.stub(); var post = app.post = sinon.stub(); var Country = models.Country = sinon.stub(); var Vote = models....
}); it("should respond OK if no error thrown", function() { submit(req, res); expect(res.sendStatus.calledWith(200)).to.equal(true); }); it("should respond with an error message if there is an error", function() { var err = "test error"; promise.then.onSecondCall().yields([err]); submit(req,...
{ var call = Vote.create.getCall(i); expect(call.calledWith(sinon.match({ CountryId: votes[i].id, score: votes[i].score }))); }
conditional_block
vote.test.js
var expect = require("chai").expect, proxyquire = require("proxyquire"), sinon = require("sinon"); var models = {}; var app = sinon.stub(); var auth = { authenticated: sinon.stub() }; var get = app.get = sinon.stub(); var post = app.post = sinon.stub(); var Country = models.Country = sinon.stub(); var Vote = models....
submit(req, res); expect(res.status.calledWith(500)).to.equal(true); expect(res.send.calledOnce).to.equal(true); }); }); });
it("should respond with an error message if there is an error", function() { var err = "test error"; promise.then.onSecondCall().yields([err]);
random_line_split
__init__.py
metadata = { "abbreviation": "ex", "capitol_timezone": "Etc/UTC", "legislature_name": "Example Legislature", "lower_chamber_name": "House of Representatives", "lower_chamber_term": 2, "lower_chamber_title": "Representative", "upper_chamber_name": "Senate", "upper_chamber_term": 6, "u...
{ "name": "T2", "sessions": [ "S2", "Special2" ], "start_year": 2013, "end_year": 2014 } ], "session_details": { "S0": {"start_date": 1250000000.0, "type": "primary", "display_name": "Session Zero"...
], "start_year": 2011, "end_year": 2012 },
random_line_split
logger.rs
//! This module is a trimmed-down copy of rtx_core::util::logger, //! which is still waiting to get released as a crate... //! maybe there is a simple logger crate that achieves this exact behavior? use ansi_term::Colour::{Green, Red, White, Yellow}; use ansi_term::Style; use chrono::Local; use log::max_level; use log:...
(&self, metadata: &Metadata) -> bool { metadata.level() <= max_level() } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { let record_target = record.target(); let details = record.args(); let category_object = if record_target.is_empty() { "" // "unknown:unkno...
enabled
identifier_name
logger.rs
//! This module is a trimmed-down copy of rtx_core::util::logger, //! which is still waiting to get released as a crate... //! maybe there is a simple logger crate that achieves this exact behavior? use ansi_term::Colour::{Green, Red, White, Yellow}; use ansi_term::Style; use chrono::Local; use log::max_level; use log:...
let painted_message = match record.level() { Level::Info => Green.paint(message), Level::Warn => Yellow.paint(message), Level::Error => Red.paint(message), Level::Debug => Style::default().paint(message), _ => White.paint(message), } .to_string() + &det...
random_line_split
logger.rs
//! This module is a trimmed-down copy of rtx_core::util::logger, //! which is still waiting to get released as a crate... //! maybe there is a simple logger crate that achieves this exact behavior? use ansi_term::Colour::{Green, Red, White, Yellow}; use ansi_term::Style; use chrono::Local; use log::max_level; use log:...
fn log(&self, record: &Record) { if self.enabled(record.metadata()) { let record_target = record.target(); let details = record.args(); let category_object = if record_target.is_empty() { "" // "unknown:unknown" ??? } else { record_target }; // Following the r...
{ metadata.level() <= max_level() }
identifier_body
modesGlyphHover.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(lineNumber: number, messages: IHoverMessage[]): void { var fragment = document.createDocumentFragment(); messages.forEach((msg) => { var row:HTMLElement = document.createElement('div'); var span:HTMLElement = null; if (msg.className) { span = document.createElement('span'); span.textContent = ...
_renderMessages
identifier_name
modesGlyphHover.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
fragment.appendChild(row); }); this._domNode.textContent = ''; this._domNode.appendChild(fragment); // show this.showAt(lineNumber); } }
{ row.textContent = msg.value; }
conditional_block
modesGlyphHover.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public setLineNumber(lineNumber: number): void { this._lineNumber = lineNumber; this._result = []; } public clearResult(): void { this._result = []; } public computeSync(): IHoverMessage[] { var result: IHoverMessage[] = [], lineDecorations = this._editor.getLineDecorations(this._lineNumber), i: nu...
random_line_split
mnist_ebgan_generate.py
import sugartensor as tf import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from model import * __author__ = 'namju.kim@kakaobrain.com' # set log level to debug tf.sg_verbosity(10) # # hyper parameters # batch_size = 100 # random uniform seed z = tf.random_uniform((batch_size, z_dim)) # ge...
plt.savefig('asset/train/sample.png', dpi=600) tf.sg_info('Sample image saved to "asset/train/sample.png"') plt.close()
for j in range(10): ax[i][j].imshow(imgs[i * 10 + j], 'gray') ax[i][j].set_axis_off()
random_line_split
mnist_ebgan_generate.py
import sugartensor as tf import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from model import * __author__ = 'namju.kim@kakaobrain.com' # set log level to debug tf.sg_verbosity(10) # # hyper parameters # batch_size = 100 # random uniform seed z = tf.random_uniform((batch_size, z_dim)) # ge...
plt.savefig('asset/train/sample.png', dpi=600) tf.sg_info('Sample image saved to "asset/train/sample.png"') plt.close()
for j in range(10): ax[i][j].imshow(imgs[i * 10 + j], 'gray') ax[i][j].set_axis_off()
conditional_block
SPRITE_OVERLAP.py
# !/usr/bin/env python """Testing a sprite. The ball should bounce off the sides of the window. You may resize the window. This test should just run without failing. """ __docformat__ = 'restructuredtext' __version__ = '$Id$' import os import unittest from pyglet.gl import glClear import pyglet.window import pygl...
class SpriteOverlapTest(unittest.TestCase): def test_sprite(self): w = pyglet.window.Window(width=320, height=320) image = Image2d.load(ball_png) ball1 = BouncySprite(0, 0, 64, 64, image, properties=dict(dx=10, dy=5)) ball2 = BouncySprite(288, 0, 64, 64, image, ...
def update(self): # move, check bounds p = self.properties self.x += p['dx'] self.y += p['dy'] if self.left < 0: self.left = 0 p['dx'] = -p['dx'] elif self.right > 320: self.right = 320 p['dx'] = -p['dx'] if self.bot...
identifier_body
SPRITE_OVERLAP.py
# !/usr/bin/env python """Testing a sprite. The ball should bounce off the sides of the window. You may resize the window. This test should just run without failing. """ __docformat__ = 'restructuredtext' __version__ = '$Id$' import os import unittest from pyglet.gl import glClear import pyglet.window import pygl...
elif self.top > 320: self.top = 320 p['dy'] = -p['dy'] class SpriteOverlapTest(unittest.TestCase): def test_sprite(self): w = pyglet.window.Window(width=320, height=320) image = Image2d.load(ball_png) ball1 = BouncySprite(0, 0, 64, 64, image, properties=d...
self.bottom = 0 p['dy'] = -p['dy']
conditional_block
SPRITE_OVERLAP.py
# !/usr/bin/env python """Testing a sprite. The ball should bounce off the sides of the window. You may resize the window. This test should just run without failing. """ __docformat__ = 'restructuredtext' __version__ = '$Id$' import os import unittest from pyglet.gl import glClear import pyglet.window import pygl...
if self.left < 0: self.left = 0 p['dx'] = -p['dx'] elif self.right > 320: self.right = 320 p['dx'] = -p['dx'] if self.bottom < 0: self.bottom = 0 p['dy'] = -p['dy'] elif self.top > 320: self.top = 320 ...
self.y += p['dy']
random_line_split
SPRITE_OVERLAP.py
# !/usr/bin/env python """Testing a sprite. The ball should bounce off the sides of the window. You may resize the window. This test should just run without failing. """ __docformat__ = 'restructuredtext' __version__ = '$Id$' import os import unittest from pyglet.gl import glClear import pyglet.window import pygl...
(Sprite): def update(self): # move, check bounds p = self.properties self.x += p['dx'] self.y += p['dy'] if self.left < 0: self.left = 0 p['dx'] = -p['dx'] elif self.right > 320: self.right = 320 p['dx'] = -p['dx'] ...
BouncySprite
identifier_name
equal_tests.py
from python.equal import Equal def count_steps_test(): equal_instance = Equal() array_a = [2, 2, 3, 7] array_b = [53, 361, 188, 665, 786, 898, 447, 562, 272, 123, 229, 629, 670, 848, 994, 54, 822, 46, 208, 17, 449, 302, 466, 832, 931, 778, 156, 39, 31, 777, 749, 436, 138, 289...
178, 273, 113, 612, 771, 497, 142, 133, 341, 914, 521, 488, 147, 953, 26, 284, 160, 648, 500, 463, 298, 568, 31, 958, 422, 379, 385, 264, 622, 716, 619, 800, 341, 732, 764, 464, 581, 258, 949, 922, 173, 470, 411, 672, 423, 789, 956, 583, 789, 808, 46, 439, ...
658, 785, 76, 415, 635, 895, 904, 514, 935, 942, 757, 434, 498, 32, 178, 10, 844, 772, 36, 795, 880, 432, 537, 785, 855, 270, 864, 951, 649, 716, 568, 308, 854, 996, 75, 489, 891, 331, 355,
random_line_split
equal_tests.py
from python.equal import Equal def
(): equal_instance = Equal() array_a = [2, 2, 3, 7] array_b = [53, 361, 188, 665, 786, 898, 447, 562, 272, 123, 229, 629, 670, 848, 994, 54, 822, 46, 208, 17, 449, 302, 466, 832, 931, 778, 156, 39, 31, 777, 749, 436, 138, 289, 453, 276, 539, 901, 839, 811, 24, 42...
count_steps_test
identifier_name
equal_tests.py
from python.equal import Equal def count_steps_test():
equal_instance = Equal() array_a = [2, 2, 3, 7] array_b = [53, 361, 188, 665, 786, 898, 447, 562, 272, 123, 229, 629, 670, 848, 994, 54, 822, 46, 208, 17, 449, 302, 466, 832, 931, 778, 156, 39, 31, 777, 749, 436, 138, 289, 453, 276, 539, 901, 839, 811, 24, 420, 440, ...
identifier_body
link.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from .generic import * from criacao.forms import * from criacao.models import * from gerenciamento.models import * logger = logging.getLogger(__name__) class LinkView(GenericView): def criar(self, request): if request.method == 'POST': try: ...
try: pk = self.kwargs['key'] except Exception, e: logger.error(str(e)) data = { 'leftover' : { 'alert-error' : 'Não foi possível processar essa edição!', } } else: museu, museu_nome = UTIL_informacoes_museu() link = Link.objects.get(pk=pk); form = LinkForm(initial={...
pk = self.kwargs['key'] name = request.POST['name'] url = request.POST['url'] except Exception, e: logger.error(str(e)) data = { 'leftover' : { 'alert-error' : 'Não foi possível processar esta edição!', } } else: link = Link.objects.get(pk=pk); link.name=name li...
conditional_block
link.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from .generic import * from criacao.forms import * from criacao.models import * from gerenciamento.models import * logger = logging.getLogger(__name__) class LinkView(GenericView): def criar(self, request): if request.method == 'POST': try: ...
except Exception, e: logger.error(str(e)) data = { 'leftover' : { 'alert-error' : 'Não foi possível processar essa edição!', } } else: museu, museu_nome = UTIL_informacoes_museu() link = Link.objects.get(pk=pk); form = LinkForm(initial={ 'name': link.name, 'ur...
return data else: try: pk = self.kwargs['key']
random_line_split
link.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from .generic import * from criacao.forms import * from criacao.models import * from gerenciamento.models import * logger = logging.getLogger(__name__) class LinkView(GenericView): def
(self, request): if request.method == 'POST': try: name = request.POST['name'] url = request.POST['url'] except Exception, e: logger.error(str(e)) data = { 'leftover' : { 'alert-error' : 'Está faltando alguma informação, por favor, verifique os campos!', } } else: l...
criar
identifier_name
link.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from .generic import * from criacao.forms import * from criacao.models import * from gerenciamento.models import * logger = logging.getLogger(__name__) class LinkView(GenericView): def criar(self, request): if request.method == 'POST': try: ...
self, request): try: pk = self.kwargs['key'] except Exception, e: logger.error(str(e)) data = { 'leftover' : { 'alert-error' : 'Não foi possível processar essa exclusão!', } } else: Link.objects.get(pk=pk).delete() data = { 'leftover' : { 'alert-success' : 'Link deletado...
est.method == 'POST': try: pk = self.kwargs['key'] name = request.POST['name'] url = request.POST['url'] except Exception, e: logger.error(str(e)) data = { 'leftover' : { 'alert-error' : 'Não foi possível processar esta edição!', } } else: link = Link.objects.get(pk...
identifier_body
server.py
import BaseHTTPServer, SimpleHTTPServer import subprocess, shlex import ssl import time import os from optparse import OptionParser port = 4443 execfile('./variables.py') parser = OptionParser() parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT') (options, args) = parser....
(self, format, *args): return if os.path.exists('./server.pem'): httpd = BaseHTTPServer.HTTPServer(('localhost', port), SKWebHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True) httpd.serve_forever()
log_message
identifier_name
server.py
import BaseHTTPServer, SimpleHTTPServer import subprocess, shlex import ssl import time import os from optparse import OptionParser port = 4443 execfile('./variables.py') parser = OptionParser() parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT') (options, args) = parser....
if os.path.exists('./server.pem'): httpd = BaseHTTPServer.HTTPServer(('localhost', port), SKWebHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True) httpd.serve_forever()
def do_GET(self): if (self.path == '/' or self.path == ''): self.path = '/index.html' if os.path.exists('content' + self.path): f = open('content' + self.path) page = f.read() page = replaceVariables(page) self.send_response(200) ...
identifier_body
server.py
import BaseHTTPServer, SimpleHTTPServer import subprocess, shlex import ssl import time import os from optparse import OptionParser port = 4443 execfile('./variables.py') parser = OptionParser() parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT') (options, args) = parser....
else: self.send_response(400) self.send_header('X-SelfKit-Version', skp['SKVersion']) self.end_headers() self.wfile.write('<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL ' + self.path + ' was not found on this server.<...
f = open('content' + self.path) page = f.read() page = replaceVariables(page) self.send_response(200) self.send_header('Content-Type', 'text/html') self.send_header('X-SelfKit-Version', skp['SKVersion']) self.end_headers()...
conditional_block
server.py
import BaseHTTPServer, SimpleHTTPServer import subprocess, shlex import ssl import time import os from optparse import OptionParser port = 4443 execfile('./variables.py') parser = OptionParser() parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT') (options, args) = parser....
httpd = BaseHTTPServer.HTTPServer(('localhost', port), SKWebHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True) httpd.serve_forever()
random_line_split
buck_project.py
# Copyright 2018-present Facebook, 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 i...
: def __init__(self, root): self.root = root self._buck_out = os.path.join(root, "buck-out") buck_out_tmp = os.path.join(self._buck_out, "tmp") makedirs(buck_out_tmp) self._buck_out_log = os.path.join(self._buck_out, "log") makedirs(self._buck_out_log) self.tm...
BuckProject
identifier_name
buck_project.py
# Copyright 2018-present Facebook, 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 i...
class NoBuckConfigFoundException(Exception): def __init__(self): no_buckconfig_message_path = ".no_buckconfig_message" default_message = textwrap.dedent( """\ This does not appear to be the root of a Buck project. Please 'cd' to the root of your project before ...
try: shutil.rmtree(self.tmp_dir) except OSError as e: if e.errno != errno.ENOENT: raise
conditional_block
buck_project.py
# Copyright 2018-present Facebook, 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 i...
no_buckconfig_message_path = ".no_buckconfig_message" default_message = textwrap.dedent( """\ This does not appear to be the root of a Buck project. Please 'cd' to the root of your project before running buck. If this really is the root of your project, run ...
identifier_body
buck_project.py
# Copyright 2018-present Facebook, 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 i...
class BuckProject: def __init__(self, root): self.root = root self._buck_out = os.path.join(root, "buck-out") buck_out_tmp = os.path.join(self._buck_out, "tmp") makedirs(buck_out_tmp) self._buck_out_log = os.path.join(self._buck_out, "log") makedirs(self._buck_out_l...
# should just swallow the error. # This is mostly equivalent to os.makedirs(path, exist_ok=True) in # Python 3. if e.errno != errno.EEXIST and os.path.isdir(path): raise
random_line_split
main.rs
//! See <https://github.com/matklad/cargo-xtask/>. //! //! This binary is integrated into the `cargo` command line by using an alias in //! `.cargo/config`. Run commands as `cargo xtask [command]`. #![allow(clippy::exhaustive_structs)] use std::path::PathBuf;
mod cargo; mod ci; mod flags; #[cfg(feature = "default")] mod release; #[cfg(feature = "default")] mod util; use ci::CiTask; #[cfg(feature = "default")] use release::ReleaseTask; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; fn main() { if let Err(e) = try_main() { eprintln!("{}", ...
use serde::Deserialize; use serde_json::from_str as from_json_str; #[cfg(feature = "default")]
random_line_split
main.rs
//! See <https://github.com/matklad/cargo-xtask/>. //! //! This binary is integrated into the `cargo` command line by using an alias in //! `.cargo/config`. Run commands as `cargo xtask [command]`. #![allow(clippy::exhaustive_structs)] use std::path::PathBuf; use serde::Deserialize; use serde_json::from_str as from_...
() -> Result<Self> { use std::{env, path::Path}; let path = Path::new(&env!("CARGO_MANIFEST_DIR")).join("config.toml"); let config = xshell::read_file(path)?; Ok(toml::from_str(&config)?) } } #[cfg(feature = "default")] #[derive(Debug, Deserialize)] struct GithubConfig { /// Th...
load
identifier_name
main.rs
//! See <https://github.com/matklad/cargo-xtask/>. //! //! This binary is integrated into the `cargo` command line by using an alias in //! `.cargo/config`. Run commands as `cargo xtask [command]`. #![allow(clippy::exhaustive_structs)] use std::path::PathBuf; use serde::Deserialize; use serde_json::from_str as from_...
} fn try_main() -> Result<()> { let flags = flags::Xtask::from_env()?; match flags.subcommand { flags::XtaskCmd::Help(_) => { println!("{}", flags::Xtask::HELP); Ok(()) } flags::XtaskCmd::Ci(ci) => { let task = CiTask::new(ci.version)?; t...
{ eprintln!("{}", e); std::process::exit(-1); }
conditional_block
runtests.py
#!/usr/bin/env python """ Custom test runner If args or options, we run the testsuite as quickly as possible. If args but no options, we default to using the spec plugin and aborting on first error/failure. If options, we ignore defaults and pass options onto Nose. Examples: Run all tests (as fast as possible) $ ....
(verbosity, *test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner(verbosity=verbosity) if not test_args: test_args = ['tests'] num_failures = test_runner.run_tests(test_args) if num_failures: sys.exit(num_failures) if __name__ == '__main__': ...
run_tests
identifier_name
runtests.py
#!/usr/bin/env python """ Custom test runner If args or options, we run the testsuite as quickly as possible. If args but no options, we default to using the spec plugin and aborting on first error/failure. If options, we ignore defaults and pass options onto Nose. Examples: Run all tests (as fast as possible) $ ....
else: # Remove options as nose will pick these up from sys.argv for arg in args: if arg.startswith('--verbosity'): verbosity = int(arg[-1]) args = [arg for arg in args if not arg.startswith('-')] configure() with warnings.catch_wa...
args.extend(['--nocapture', '--stop'])
conditional_block
runtests.py
#!/usr/bin/env python """ Custom test runner If args or options, we run the testsuite as quickly as possible. If args but no options, we default to using the spec plugin and aborting on first error/failure. If options, we ignore defaults and pass options onto Nose. Examples: Run all tests (as fast as possible) $ ....
Drop into pdb when a test fails $ ./runtests.py ... --pdb-failures """ import sys import logging import warnings from tests.config import configure from django.utils.six.moves import map # No logging logging.disable(logging.CRITICAL) def run_tests(verbosity, *test_args): from django_nose import NoseTestSuiteRu...
random_line_split