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
gzip_util.py
import zlib import struct import time def parse_encoding_header(header): """ Break up the `HTTP_ACCEPT_ENCODING` header into a dict of the form, {'encoding-name':qvalue}. """ encodings = {'identity':1.0} for encoding in header.split(","): if(encoding.find(";") > -1): encodi...
chunks.close()
random_line_split
gzip_util.py
import zlib import struct import time def parse_encoding_header(header): """ Break up the `HTTP_ACCEPT_ENCODING` header into a dict of the form, {'encoding-name':qvalue}. """ encodings = {'identity':1.0} for encoding in header.split(","): if(encoding.find(";") > -1): encodi...
# After much Googling and gnashing of teeth, this function stolen from # cherrypy.lib.encoding seems to be the most straightforward way to do gzip # encoding of a stream without loading the whole thing into memory at once. def compress(chunks, compress_level, close=True): """ Compress 'chunks' at the given c...
""" Check to see if the client can accept gzipped output, and whether or not it is even the preferred method. If `identity` is higher, then no gzipping should occur. """ encodings = parse_encoding_header(accept_encoding_header) # Do the actual comparisons if('gzip' in encodings): re...
identifier_body
gzip_util.py
import zlib import struct import time def parse_encoding_header(header): """ Break up the `HTTP_ACCEPT_ENCODING` header into a dict of the form, {'encoding-name':qvalue}. """ encodings = {'identity':1.0} for encoding in header.split(","): if(encoding.find(";") > -1): encodi...
(accept_encoding_header): """ Check to see if the client can accept gzipped output, and whether or not it is even the preferred method. If `identity` is higher, then no gzipping should occur. """ encodings = parse_encoding_header(accept_encoding_header) # Do the actual comparisons if('...
gzip_requested
identifier_name
regions-static-closure.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#![allow(unknown_features)] #![feature(box_syntax)] #![feature(unboxed_closures)] struct closure_box<'a> { cl: Box<FnMut() + 'a>, } fn box_it<'a>(x: Box<FnMut() + 'a>) -> closure_box<'a> { closure_box {cl: x} } fn call_static_closure(mut cl: closure_box<'static>) { cl.cl.call_mut(()) } pub fn main() { ...
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
regions-static-closure.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let cl_box = box_it(box || println!("Hello, world!")); call_static_closure(cl_box); }
main
identifier_name
build-es5.ts
import * as fs from 'fs-extra'; import * as path from 'path'; import * as uglifyJsPlugin from 'uglifyjs-webpack-plugin'; import * as unminifiedPlugin from 'unminified-webpack-plugin'; import * as webpack from 'webpack'; import { ROOT } from '../build/helpers'; import { cleanEmittedData, EMIT_PATH, InjectableClassEntry...
() { let fileContent = ''; fileContent += INJECTABLE_CLASSES.map(getPluginImport).join('\n'); fileContent += `\nwindow.IonicNative = {\n`; fileContent += INJECTABLE_CLASSES.map(e => e.className).join(',\n'); fileContent += '\n};\n'; fileContent += `require('./@ionic-native/core/bootstrap').checkReady();\n`;...
createIndexFile
identifier_name
build-es5.ts
import * as fs from 'fs-extra'; import * as path from 'path'; import * as uglifyJsPlugin from 'uglifyjs-webpack-plugin'; import * as unminifiedPlugin from 'unminified-webpack-plugin'; import * as webpack from 'webpack'; import { ROOT } from '../build/helpers'; import { cleanEmittedData, EMIT_PATH, InjectableClassEntry...
function createIndexFile() { let fileContent = ''; fileContent += INJECTABLE_CLASSES.map(getPluginImport).join('\n'); fileContent += `\nwindow.IonicNative = {\n`; fileContent += INJECTABLE_CLASSES.map(e => e.className).join(',\n'); fileContent += '\n};\n'; fileContent += `require('./@ionic-native/core/boot...
function getPluginImport(entry: InjectableClassEntry) { return `import { ${entry.className} } from '${entry.file}';`; }
random_line_split
build-es5.ts
import * as fs from 'fs-extra'; import * as path from 'path'; import * as uglifyJsPlugin from 'uglifyjs-webpack-plugin'; import * as unminifiedPlugin from 'unminified-webpack-plugin'; import * as webpack from 'webpack'; import { ROOT } from '../build/helpers'; import { cleanEmittedData, EMIT_PATH, InjectableClassEntry...
function createIndexFile() { let fileContent = ''; fileContent += INJECTABLE_CLASSES.map(getPluginImport).join('\n'); fileContent += `\nwindow.IonicNative = {\n`; fileContent += INJECTABLE_CLASSES.map(e => e.className).join(',\n'); fileContent += '\n};\n'; fileContent += `require('./@ionic-native/core/boo...
{ return `import { ${entry.className} } from '${entry.file}';`; }
identifier_body
duosecurity.js
function (user, context, callback) { // /!\ DO NOT EDIT THIS FILE /!\ // Please use http://github.com/mozilla-iam/auth0-rules instead var WHITELIST = [ 'moc-sso-monitoring@mozilla.com', // MOC see https://bugzilla.mozilla.org/show_bug.cgi?id=1423903 'moc+servicenow@mozilla.com' // MOC see https://bugzilla...
if (WHITELIST.indexOf(user.email) >= 0) { console.log('duosecurity: whitelisted account '+user.email+', no 2FA check performed'); // Fake 2FA context.multifactor = true; return callback(null, user, context); } // Any user logging in with LDAP (ad) requires MFA authentication. if (context.connec...
{ console.log('duosecurity: user primary email NOT verified, refusing login for '+user.email); return callback(null, user, global.postError('notingroup', context)); }
conditional_block
duosecurity.js
function (user, context, callback) { // /!\ DO NOT EDIT THIS FILE /!\ // Please use http://github.com/mozilla-iam/auth0-rules instead var WHITELIST = [ 'moc-sso-monitoring@mozilla.com', // MOC see https://bugzilla.mozilla.org/show_bug.cgi?id=1423903 'moc+servicenow@mozilla.com' // MOC see https://bugzilla...
if (context.connectionStrategy === 'ad') { context.multifactor = { provider: 'duo', ikey: configuration.duo_ikey_mozilla, skey: configuration.duo_skey_mozilla, host: configuration.duo_apihost_mozilla, // optional: // Force DuoSecurity everytime this rule runs. Defaults to fals...
random_line_split
_tickfont.py
import _plotly_utils.basevalidators class TickfontValidator(_plotly_utils.basevalidators.CompoundValidator): def
( self, plotly_name="tickfont", parent_name="layout.ternary.aaxis", **kwargs ): super(TickfontValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Tickfont"), data_docs=kwargs.pop( ...
__init__
identifier_name
_tickfont.py
import _plotly_utils.basevalidators class TickfontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="tickfont", parent_name="layout.ternary.aaxis", **kwargs ):
select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow"...
super(TickfontValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Tickfont"), data_docs=kwargs.pop( "data_docs", """ color family ...
identifier_body
_tickfont.py
import _plotly_utils.basevalidators class TickfontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="tickfont", parent_name="layout.ternary.aaxis", **kwargs ): super(TickfontValidator, self).__init__( plotly_name=plotly_name, par...
), **kwargs )
""",
random_line_split
loader.py
import csv from dateutil.parser import parse from adoptarbol.tree.models import Tree def load(filename): with open(filename, encoding='utf-8') as f: reader = csv.reader(f) header = next(reader) def pos_for(field): return header.index(field) def float_or_none(string)...
'notes': row[pos_for('notas')], 'phenology': row[pos_for('fenologia')], 'observation': row[pos_for('obs')], 'surveyed_on': parse(row[pos_for('fechahora')]), } t = Tree(**tree) t.save() """ if ...
print('Procesando ', row) tree = {'code': row[pos_for('codigo')], 'common_name': row[pos_for('especie')], 'scientific_name': row[pos_for('cientifico')], 'family': row[pos_for('familia')], 'coord_utm_e': float_or_none(row[pos_fo...
conditional_block
loader.py
import csv from dateutil.parser import parse from adoptarbol.tree.models import Tree def load(filename): with open(filename, encoding='utf-8') as f: reader = csv.reader(f) header = next(reader) def pos_for(field): return header.index(field) def
(string): try: return(float(string)) except ValueError: return None for row in reader: # codigo = str(row[pos_for('codigo')]), print('Procesando ', row) tree = {'code': row[pos_for('codigo')], 'comm...
float_or_none
identifier_name
loader.py
import csv from dateutil.parser import parse from adoptarbol.tree.models import Tree def load(filename): with open(filename, encoding='utf-8') as f: reader = csv.reader(f) header = next(reader) def pos_for(field):
def float_or_none(string): try: return(float(string)) except ValueError: return None for row in reader: # codigo = str(row[pos_for('codigo')]), print('Procesando ', row) tree = {'code': row[pos_for('codigo')]...
return header.index(field)
identifier_body
loader.py
import csv from dateutil.parser import parse from adoptarbol.tree.models import Tree def load(filename): with open(filename, encoding='utf-8') as f: reader = csv.reader(f) header = next(reader) def pos_for(field): return header.index(field) def float_or_none(string)...
'quality': float_or_none(row[pos_for('calidad')].replace(',', '.')), 'relevance': row[pos_for('relevancia')], 'notes': row[pos_for('notas')], 'phenology': row[pos_for('fenologia')], 'observation': row[pos_for('obs')], ...
'circ': row[pos_for('circ')], 'base_area': float_or_none(row[pos_for('areabasal')].replace(',', '.')), 'size_class': row[pos_for('clasetamano')],
random_line_split
compile.js
/* * oskari-compile */ module.exports = function(grunt) { grunt.registerMultiTask('compile', 'Compile appsetup js', function() { var starttime = (new Date()).getTime(); var options = this.data.options; // Run some sync stuff. grunt.log.writeln('Compiling...'); // Catch...
if ( !options.dest ) { grunt.fail.warn('No destination path provided for Compile to use.'); } var fs = require('fs'), UglifyJS = require('uglify-js'), parser = require('../parser.js'), processedAppSetup = parser.getComponents(options.appSetupFile...
{ grunt.fail.warn('No path provided for Compile to scan.'); }
conditional_block
compile.js
/* * oskari-compile */ module.exports = function(grunt) { grunt.registerMultiTask('compile', 'Compile appsetup js', function() { var starttime = (new Date()).getTime(); var options = this.data.options; // Run some sync stuff. grunt.log.writeln('Compiling...'); // Catch...
fileMap = {}, result = null; for (var i = 0; i < files.length; ++i) { if (!fs.existsSync(files[i])) { var msg = 'Couldnt locate ' + files[i]; throw msg; } // do not put duplicates on com...
random_line_split
angular-locale_lv.js
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid is distrib...
function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "priek\u0161pusdien\u0101"...
{ n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; }
identifier_body
angular-locale_lv.js
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid is distrib...
(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide....
getDecimals
identifier_name
angular-locale_lv.js
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid is distrib...
var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "priek\u0161pusdien\u0101", "p\u0113cpusdien\u0101" ], "DAY": [ "sv\u0113tdiena", "pirmdiena", "otrdiena", "tre\u016...
{ v = Math.min(getDecimals(n), 3); }
conditional_block
angular-locale_lv.js
/* * This file is part of huborcid. * * huborcid is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * huborcid is distrib...
return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "priek\u0161pusdien\u0101", "p\u0113cpusdien\u0101" ], "DAY": [ "sv\u0113tdiena", "pirmdiena", "otrdiena", "tre\u0161diena", "ceturtdiena", "piektdiena", "sestdiena"...
random_line_split
exception_sink.py
cls._reset_exiter(new_exiter) yield cls._reset_exiter(previous_exiter) @classmethod @contextmanager def exiter_as_until_exception( cls, new_exiter_fun: Callable[[Optional[Exiter]], Exiter] ) -> Iterator[None]: """Temporarily override the global exiter, except thi...
timestamp_msg = ( f"timestamp: {cls._iso_timestamp_for_now()}\n" if cls._should_print_backtrace_to_terminal else "" ) details_msg = ( "" if cls._should_print_backtrace_to_terminal else "\n\n(Use --print-exception-stacktrace to see m...
identifier_body
exception_sink.py
"""Temporarily override the global exiter, except this will unset it when an exception happens.""" previous_exiter = cls._exiter new_exiter = new_exiter_fun(previous_exiter) try: cls._reset_exiter(new_exiter) yield finally: cls._reset_e...
"""A sys.excepthook implementation which logs the error and exits with failure.""" exc_class = exc_class or sys.exc_info()[0]
random_line_split
exception_sink.py
cls._shared_error_fileobj`. OS state: - May create a new directory. - Overwrites signal handlers for many fatal and non-fatal signals (but not SIGUSR2). :raises: :class:`ExceptionSink.ExceptionSinkError` if the directory does not exist or is not writable. """ ...
toggle_ignoring_sigint_v2_engine
identifier_name
exception_sink.py
def _toggle_ignoring_sigint_v2_engine(self, toggle: bool): with self._ignore_sigint_lock: self._ignoring_sigint_v2_engine = toggle @contextmanager def _ignoring_sigint(self): with self._ignore_sigint_lock: self._check_sigint_gate_is_correct() self._thre...
self.handle_sigint(signum, _frame)
conditional_block
js.js
'use strict'; var path = require('path'); var browserify = require('browserify'), eventStream = require('event-stream'), glob = require('glob'), vinylBuffer = require('vinyl-buffer'), vinylSource = require('vinyl-source-stream'), watchify = require('watchify'), eslintify = require('eslintify')...
poll: true }); this.bundle.on('update', function(id) { var eventFile = path.relative(src, id[0]); plug.util.log( plug.util.colors.yellow('☀ ') + 'File ' + plug.util.colors.magenta(eventFile) + ' updated. ' + 'Bundling ' + plug.util.colors.magenta(file) + '...' ); this.ou...
{ var srcFile = path.join(src, file), watchMsg = 'Watching bundle ' + plug.util.colors.magenta(file) + '...'; this.bundle = watchify(browserify({ entries: [srcFile], insertGlobals: false, paths: [ src, path.join(plug.paths.cwd, 'node_modules'), path.join(plug.paths.cwd, '...
identifier_body
js.js
'use strict'; var path = require('path'); var browserify = require('browserify'), eventStream = require('event-stream'), glob = require('glob'), vinylBuffer = require('vinyl-buffer'), vinylSource = require('vinyl-source-stream'), watchify = require('watchify'), eslintify = require('eslintify')...
(plug, file, src, dest, watch) { var srcFile = path.join(src, file), watchMsg = 'Watching bundle ' + plug.util.colors.magenta(file) + '...'; this.bundle = watchify(browserify({ entries: [srcFile], insertGlobals: false, paths: [ src, path.join(plug.paths.cwd, 'node_modules'), ...
Bundler
identifier_name
js.js
'use strict'; var path = require('path'); var browserify = require('browserify'), eventStream = require('event-stream'), glob = require('glob'), vinylBuffer = require('vinyl-buffer'), vinylSource = require('vinyl-source-stream'), watchify = require('watchify'), eslintify = require('eslintify')...
} module.exports = [ 'browserify javascripts', function(done) { var plug = this, watch = plug.watchify === true, src = path.join(plug.paths.assets, 'js'), dest = path.join(plug.paths.staticAssets, 'js'); glob('*.js', {cwd: src}, function(err, files) { if (err) return plug...
watchMsg = false; } }.bind(this)); };
random_line_split
app_result.rs
use std::io; use std::error::FromError; use std::fmt::{self, Display, Formatter}; use glob; /// The result used in the whole application. pub type AppResult<T> = Result<T, AppErr>; /// The generic error used in the whole application. pub struct AppErr { error: String } pub fn app_err(string: String) -> AppErr { ...
{ fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { writeln!(f, "{}", self.error) } } impl FromError<io::Error> for AppErr { fn from_error(err: io::Error) -> AppErr { AppErr { error: format!("{}", err) } } } impl FromError<glob::PatternError> for AppErr { fn from_error(err:...
impl Display for AppErr
random_line_split
app_result.rs
use std::io; use std::error::FromError; use std::fmt::{self, Display, Formatter}; use glob; /// The result used in the whole application. pub type AppResult<T> = Result<T, AppErr>; /// The generic error used in the whole application. pub struct AppErr { error: String } pub fn app_err(string: String) -> AppErr { ...
} impl FromError<io::Error> for AppErr { fn from_error(err: io::Error) -> AppErr { AppErr { error: format!("{}", err) } } } impl FromError<glob::PatternError> for AppErr { fn from_error(err: glob::PatternError) -> AppErr { AppErr { error: format!("{}", err) } } }
{ writeln!(f, "{}", self.error) }
identifier_body
app_result.rs
use std::io; use std::error::FromError; use std::fmt::{self, Display, Formatter}; use glob; /// The result used in the whole application. pub type AppResult<T> = Result<T, AppErr>; /// The generic error used in the whole application. pub struct AppErr { error: String } pub fn app_err(string: String) -> AppErr { ...
(string: String) -> AppErr { AppErr { error: string } } } impl Display for AppErr { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { writeln!(f, "{}", self.error) } } impl FromError<io::Error> for AppErr { fn from_error(err: io::Error) -> AppErr { AppErr { error: for...
from_string
identifier_name
models.py
from __future__ import absolute_import, unicode_literals import django
from django.utils.translation import ugettext_lazy as _ from .managers import QueueManager, MessageManager class Queue(models.Model): name = models.CharField(_('name'), max_length=200, unique=True) objects = QueueManager() class Meta: if django.VERSION >= (1, 7): app_label = 'karell...
from django.db import models
random_line_split
models.py
from __future__ import absolute_import, unicode_literals import django from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import QueueManager, MessageManager class
(models.Model): name = models.CharField(_('name'), max_length=200, unique=True) objects = QueueManager() class Meta: if django.VERSION >= (1, 7): app_label = 'karellen_kombu_transport_django' db_table = 'djkombu_queue' verbose_name = _('queue') verbose_name_plur...
Queue
identifier_name
models.py
from __future__ import absolute_import, unicode_literals import django from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import QueueManager, MessageManager class Queue(models.Model): name = models.CharField(_('name'), max_length=200, unique=True) objects ...
class Message(models.Model): visible = models.BooleanField(default=True, db_index=True) sent_at = models.DateTimeField(null=True, blank=True, db_index=True, auto_now_add=True) payload = models.TextField(_('payload'), null=False) queue = models.ForeignKey(Queue, rela...
if django.VERSION >= (1, 7): app_label = 'karellen_kombu_transport_django' db_table = 'djkombu_queue' verbose_name = _('queue') verbose_name_plural = _('queues')
identifier_body
models.py
from __future__ import absolute_import, unicode_literals import django from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import QueueManager, MessageManager class Queue(models.Model): name = models.CharField(_('name'), max_length=200, unique=True) objects ...
db_table = 'djkombu_message' verbose_name = _('message') verbose_name_plural = _('messages')
app_label = 'karellen_kombu_transport_django'
conditional_block
ConfigComponent.js
var React = require('react'); var ProfileComponent = require('../components/ProfileComponent'); var RawJSONComponent = require('../components/RawJSONComponent'); var ConfigComponent = React.createClass({ displayName: "ConfigComponent", render: function () { // get all the profile names from the config va...
return( <div> {html} <h3>Raw Json</h3> <RawJSONComponent json={this.props.config} /> </div> )} }); module.exports = ConfigComponent;
{ var name = profileNames[ii]; html.push( <ProfileComponent key={name} name={name} profile={this.props.config.profiles[name]} /> ); html.push( <hr key={'hr_'+name} />); }
conditional_block
ConfigComponent.js
var React = require('react'); var ProfileComponent = require('../components/ProfileComponent'); var RawJSONComponent = require('../components/RawJSONComponent'); var ConfigComponent = React.createClass({ displayName: "ConfigComponent", render: function () { // get all the profile names from the config va...
{html} <h3>Raw Json</h3> <RawJSONComponent json={this.props.config} /> </div> )} }); module.exports = ConfigComponent;
return( <div>
random_line_split
common.py
from __future__ import absolute_import import weakref import threading import asyncore import socket from walky.objects import * from walky.port import * from walky.engine import * class Client(object): engine = None settings = None connection = None port = None engine_class = Engine object...
self.engine = self.settings['engine_class']() def connect(self,*args,**kwargs): """ Start the engine and the asyncore """ self.engine.start() self.connection = self.engine.connection_new(*args,**kwargs) def run(self): pass def on_readline(self,line): ...
self.engine.shutdown()
conditional_block
common.py
from __future__ import absolute_import import weakref import threading import asyncore import socket from walky.objects import * from walky.port import * from walky.engine import * class Client(object):
if self.engine: self.engine.shutdown() self.engine = self.settings['engine_class']() def connect(self,*args,**kwargs): """ Start the engine and the asyncore """ self.engine.start() self.connection = self.engine.connection_new(*args,**kwargs) def run(self): ...
engine = None settings = None connection = None port = None engine_class = Engine object_class = ObjectStub def __init__( self, **settings ): settings.setdefault('engine_class',self.engine_class) settings.setdefault('port_class',self.port_class) settin...
identifier_body
common.py
from __future__ import absolute_import import weakref import threading import asyncore import socket from walky.objects import * from walky.port import * from walky.engine import * class Client(object): engine = None settings = None connection = None port = None engine_class = Engine object...
pass except Exception as ex: pass def sendline(self,line): self.port().sendline(line) def object_get(self,reg_obj_id): return self.object_class(self.connection,reg_obj_id) def close(self): self.engine.shutdown()
try:
random_line_split
common.py
from __future__ import absolute_import import weakref import threading import asyncore import socket from walky.objects import * from walky.port import * from walky.engine import * class
(object): engine = None settings = None connection = None port = None engine_class = Engine object_class = ObjectStub def __init__( self, **settings ): settings.setdefault('engine_class',self.engine_class) settings.setdefault('port_class',self.port_class)...
Client
identifier_name
harfbuzz.rs
glyph_data.len() { let loc = glyph_data.byte_offset_of_glyph(i) as usize; if loc < byte_max { byte_to_glyph[loc] = i as i32; } else { debug!("ERROR: tried to set out of range byte_to_glyph: idx={}, glyph idx={}", loc, ...
lyph_h_kerning_func(
identifier_name
harfbuzz.rs
byte_offset_of_glyph(&self, i: usize) -> u32 { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i as isize); (*glyph_info_i).cluster } } pub fn len(&self) -> usize { self.count } /// Returns shaped glyph data for one...
// Otherwise, the bytes we have seen so far correspond to a non-contiguous set of // glyphs. Keep extending byte_range until we fill in all the holes in the glyph // span or reach the end of the text. } assert!(byte_range.len() > 0); ...
{ break }
conditional_block
harfbuzz.rs
byte_offset_of_glyph(&self, i: usize) -> u32 { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i as isize); (*glyph_info_i).cluster } } pub fn len(&self) -> usize { self.count } /// Returns shaped glyph data for one...
fixed_to_float(16, i) } } impl ShaperMethods for Shaper { /// Calculate the layout metrics associated with the given text when painted in a specific /// font. fn shape_text(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) { unsafe { let hb_buffer: *mut h...
fn fixed_to_float(i: hb_position_t) -> f64 {
random_line_split
harfbuzz.rs
byte_offset_of_glyph(&self, i: usize) -> u32 { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i as isize); (*glyph_info_i).cluster } } pub fn len(&self) -> usize { self.count } /// Returns shaped glyph data for one...
fn fixed_to_float(i: hb_position_t) -> f64 { fixed_to_float(16, i) } } impl ShaperMethods for Shaper { /// Calculate the layout metrics associated with the given text when painted in a specific /// font. fn shape_text(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {...
{ float_to_fixed(16, f) }
identifier_body
heapprof.py
#!/usr/bin/python import sys, commands, struct, operator, subprocess, os if len(sys.argv) != 3: print 'usage:',sys.argv[0],'<program> <core>' sys.exit(1) prog, core = sys.argv[1:] # finds out the size of void*/size_t. could be hardcoded for speed... try: cell = int(commands.getoutput('gdb '+prog+r''' -ex 'prin...
print ' 0x%x'%addr, syminfo[addr] blocks = find_blocks(open(core,'rb').read()) if not blocks: print 'no heap blocks found in the core dump (searched for metadata enclosed in the magic string HeaP...ProF)' sys.exit(1) syminfo = sym_info(code_addrs(blocks), prog) report(blocks, syminfo)
print '%d%% %d %s'%(int(100.*size/heapsize), size, stack2sizes[stack]) for addr in stack: if addr:
random_line_split
heapprof.py
#!/usr/bin/python import sys, commands, struct, operator, subprocess, os if len(sys.argv) != 3: print 'usage:',sys.argv[0],'<program> <core>' sys.exit(1) prog, core = sys.argv[1:] # finds out the size of void*/size_t. could be hardcoded for speed... try: cell = int(commands.getoutput('gdb '+prog+r''' -ex 'prin...
return info def sym_info(addrs,exe): if 'HEAPPROF_ADDR2LINE' in os.environ: gdb_found = 0 else: syminfo, gdb_found = gdb_sym_info(addrs, prog) if gdb_found < 1: # gdb didn't manage to find anything - perhaps the core dump is in a custom format syminfo = addr2line_sym_info(addrs, prog) return sym...
if addr: addr2line.stdin.write('0x%x\n'%addr) addr2line.stdin.flush() info[addr] = addr2line.stdout.readline().strip()+' '+addr2line.stdout.readline().strip()
conditional_block
heapprof.py
#!/usr/bin/python import sys, commands, struct, operator, subprocess, os if len(sys.argv) != 3: print 'usage:',sys.argv[0],'<program> <core>' sys.exit(1) prog, core = sys.argv[1:] # finds out the size of void*/size_t. could be hardcoded for speed... try: cell = int(commands.getoutput('gdb '+prog+r''' -ex 'prin...
(addrs,exe): addr2line = subprocess.Popen('addr2line -f -e'.split()+[exe], stdin=subprocess.PIPE, stdout=subprocess.PIPE) info = {} for addr in addrs: if addr: addr2line.stdin.write('0x%x\n'%addr) addr2line.stdin.flush() info[addr] = addr2line.stdout.readline().strip()+' '+addr2line.stdout.r...
addr2line_sym_info
identifier_name
heapprof.py
#!/usr/bin/python import sys, commands, struct, operator, subprocess, os if len(sys.argv) != 3: print 'usage:',sys.argv[0],'<program> <core>' sys.exit(1) prog, core = sys.argv[1:] # finds out the size of void*/size_t. could be hardcoded for speed... try: cell = int(commands.getoutput('gdb '+prog+r''' -ex 'prin...
class Block: def __init__(self, metadata): self.size = struct.unpack(fmt, metadata[0:cell])[0] self.stack = struct.unpack('%d'%(len(metadata)/cell - 1)+fmt, metadata[cell:]) def find_blocks(bytes): blocks = [] end_index = 0 while True: start_index = bytes.find('HeaP',end_index) end_index = by...
return (e-s)%cell == 0 and (e-s)/cell < 100
identifier_body
thread.rs
use core::time::Duration; use crate::syscall; use alloc::string::String; pub struct Thread { name: Option<String>, stack_size: usize, stack_top: * const u8, id: ThreadId, } pub struct Builder { name: Option<String>, stack_size: usize, } impl Builder { const DEFAULT_SIZE: ...
pub fn stack_size(self, stack_size: usize) -> Self { Self { name: self.name, stack_size } } } #[derive(Clone)] pub struct ThreadId(u16); impl Thread { pub fn unpark(&self) { } pub fn id(&self) -> ThreadId { self.id.clone() } pub fn name(&se...
{ Self { name: Some(name), stack_size: self.stack_size } }
identifier_body
thread.rs
use core::time::Duration; use crate::syscall; use alloc::string::String; pub struct Thread { name: Option<String>, stack_size: usize, stack_top: * const u8, id: ThreadId, } pub struct Builder { name: Option<String>, stack_size: usize, } impl Builder { const DEFAULT_SIZE: ...
impl Thread { pub fn unpark(&self) { } pub fn id(&self) -> ThreadId { self.id.clone() } pub fn name(&self) -> Option<&str> { self.name.as_ref().map(|s| s.as_str()) } /* fn new(name: Option<String>, stack_size: usize) -> Thread { let (stack_memory, stack_size) = mapping::allocate_stack_memo...
pub struct ThreadId(u16);
random_line_split
thread.rs
use core::time::Duration; use crate::syscall; use alloc::string::String; pub struct Thread { name: Option<String>, stack_size: usize, stack_top: * const u8, id: ThreadId, } pub struct Builder { name: Option<String>, stack_size: usize, } impl Builder { const DEFAULT_SIZE: ...
(&self) { } pub fn id(&self) -> ThreadId { self.id.clone() } pub fn name(&self) -> Option<&str> { self.name.as_ref().map(|s| s.as_str()) } /* fn new(name: Option<String>, stack_size: usize) -> Thread { let (stack_memory, stack_size) = mapping::allocate_stack_memory(stack_size); Threa...
unpark
identifier_name
sprite_renderer.rs
/* use cgmath::Vector2; use gfx; use gfx_device_gl; use gfx_device_gl::{Resources}; use gfx::{Device, CommandQueue,FrameSync, GraphicsPoolExt, Surface, Swapchain, SwapchainExt, WindowExt}; use gfx::traits::DeviceExt; use graphics::render_thread::RenderPackage; type ColorFormat = gfx::format::Rgba8; const BL...
2 + (i * 4), 1 + (i * 4), 3 + (i * 4)]);//bottom right triangle } let (vertex_buffer, index_buffer) = render_package.device.create_vertex_buffer_with_slice(&vertex_info, &*index_info); let text_sampler = render_package.device.create_sampler_linear(); ...
let i = i as u16; index_info.extend(&[0 + (i * 4), 1 + (i * 4), 2 + (i * 4),//top left triangle
random_line_split
main.rs
//! # Beamium. //! //! Beamium scrap Prometheus endpoint and forward metrics to Warp10. extern crate backoff; extern crate bytes; extern crate cast; extern crate clap; extern crate core; extern crate ctrlc; extern crate flate2; extern crate futures; extern crate humantime; extern crate hyper; extern crate hyper_timeout...
// Bootstrap config let config_path = matches.value_of("config").unwrap_or(""); let config = match config::load_config(&config_path) { Ok(config) => config, Err(err) => { crit!("Fail to load config {}: {}", &config_path, err); std::process::abort(); } }; ...
{ // Setup a bare logger log::bootstrap(); let matches = App::new("beamium") .version(&*format!( "{} ({}#{})", env!("CARGO_PKG_VERSION"), COMMIT, PROFILE, )) .author("d33d33 <kevin@d33d33.fr>") .about("Send Prometheus metrics t...
identifier_body
main.rs
//! # Beamium. //! //! Beamium scrap Prometheus endpoint and forward metrics to Warp10. extern crate backoff; extern crate bytes; extern crate cast; extern crate clap; extern crate core; extern crate ctrlc; extern crate flate2; extern crate futures; extern crate humantime; extern crate hyper; extern crate hyper_timeout...
std::process::abort(); } }; if matches.is_present("t") { info!("config ok"); std::process::exit(0); } info!("starting"); // Setup logging match log::log(&config.parameters, matches.occurrences_of("v")) { Ok(()) => {} Err(err) => { ...
let config = match config::load_config(&config_path) { Ok(config) => config, Err(err) => { crit!("Fail to load config {}: {}", &config_path, err);
random_line_split
main.rs
//! # Beamium. //! //! Beamium scrap Prometheus endpoint and forward metrics to Warp10. extern crate backoff; extern crate bytes; extern crate cast; extern crate clap; extern crate core; extern crate ctrlc; extern crate flate2; extern crate futures; extern crate humantime; extern crate hyper; extern crate hyper_timeout...
() { // Setup a bare logger log::bootstrap(); let matches = App::new("beamium") .version(&*format!( "{} ({}#{})", env!("CARGO_PKG_VERSION"), COMMIT, PROFILE, )) .author("d33d33 <kevin@d33d33.fr>") .about("Send Prometheus metric...
main
identifier_name
main.rs
//! # Beamium. //! //! Beamium scrap Prometheus endpoint and forward metrics to Warp10. extern crate backoff; extern crate bytes; extern crate cast; extern crate clap; extern crate core; extern crate ctrlc; extern crate flate2; extern crate futures; extern crate humantime; extern crate hyper; extern crate hyper_timeout...
}; match fs::create_dir_all(&config.parameters.sink_dir) { Ok(()) => {} Err(err) => { crit!( "Fail to create sink directory {}: {}", &config.parameters.source_dir, err ); std::process::abort(); } }; ...
{ crit!( "Fail to create source directory {}: {}", &config.parameters.source_dir, err ); std::process::abort(); }
conditional_block
regex.rs
// Copyright (c) 2014 Michael Woerister // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publis...
() { let sm = compile(&Kleene(~Leaf('a'))); assert!(matches(&sm, "")); assert!(matches(&sm, "a")); assert!(matches(&sm, "aaa")); assert!(matches(&sm, "aaaaaaaaaaaaaaaaaaaaaaaaaa")); assert!(!matches(&sm, "b")); assert!(!matches(&sm, "caaaa")); assert!(!m...
test_kleene
identifier_name
regex.rs
// Copyright (c) 2014 Michael Woerister // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publis...
Seq(ref left, ref right) => { let (mut left_sm, left_start, left_end) = left.to_state_machine(); let (right_sm, right_start, right_end) = right.to_state_machine(); left_sm.consume(right_sm); left_sm.add_transition(left_end, right_start, Epsi...
{ let (mut sm, sub_start, sub_end) = sub.to_state_machine(); let start_state = sm.add_state(); let end_state = sm.add_state(); sm.add_transition(start_state, sub_start, Epsilon); sm.add_transition(sub_end, sub_start, Epsilon); ...
conditional_block
regex.rs
// Copyright (c) 2014 Michael Woerister // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publis...
assert!(!matches(&sm, "ab")); } #[test] fn test_seq() { let sm = compile(&Seq(~Leaf('a'), ~Seq(~Leaf('b'),~Leaf('c')))); assert!(!matches(&sm, "")); assert!(!matches(&sm, "a")); assert!(!matches(&sm, "ab")); assert!(matches(&sm, "abc")); assert!(!mat...
assert!(!matches(&sm, "b")); assert!(!matches(&sm, "caaaa")); assert!(!matches(&sm, "daaa")); assert!(!matches(&sm, "e"));
random_line_split
regex.rs
// Copyright (c) 2014 Michael Woerister // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publis...
fn matches(&(ref sm, start_state, ref end_states): &(StateMachine, StateId, ~[StateId]), s: &str) -> bool { let result_state = sm.run(start_state, s); end_states.iter().any(|&x| Some(x) == result_state) } #[test] fn test_kleene() { let sm = compile(&Kleene(~Leaf('a'))); ...
{ let (sm, start, end) = regex.to_state_machine(); let end_states = [end]; let end_states: StateSet = end_states.iter().map(|x| *x).collect(); let ToDfaResult { dfa, start_state, end_state_map } = sm.to_dfa(start, &end_states); let dfa_end_states = end_state_map.keys().map(|x| *x...
identifier_body
svgIcon.tsx
import React from 'react'; import PropTypes from 'prop-types'; import theme, {Aliases, Color, IconSize} from 'app/utils/theme'; type Props = React.SVGAttributes<SVGElement> & { color?: Color | keyof Aliases; // TODO (Priscila): make size prop theme icon size only size?: IconSize | string; className?: string; ...
const SvgIcon = React.forwardRef<SVGSVGElement, Props>(function SvgIcon( { color: providedColor = 'currentColor', size: providedSize = 'sm', viewBox = '0 0 16 16', ...props }, ref ) { const color = theme[providedColor] ?? providedColor; const size = theme.iconSizes[providedSize] ?? providedSiz...
random_line_split
regions-close-associated-type-into-object.rs
trait X {} trait Iter { type Item: X; fn into_item(self) -> Self::Item; fn as_item(&self) -> &Self::Item; } fn bad1<T: Iter>(v: T) -> Box<dyn X + 'static> { let item = v.into_item(); Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough } fn bad2<T: Iter>(v: T) ...
fn ok1<'a, T: Iter>(v: T) -> Box<dyn X + 'a> where T::Item : 'a { let item = v.into_item(); Box::new(item) // OK, T::Item : 'a is declared } fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<dyn X + 'a> where T::Item : Clone { let item = Clone::clone(w); Box::new(item) // OK, T::Item : 'a is ...
{ let item: Box<_> = Box::new(v.into_item()); Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough }
identifier_body
regions-close-associated-type-into-object.rs
trait X {} trait Iter { type Item: X; fn into_item(self) -> Self::Item; fn as_item(&self) -> &Self::Item; } fn bad1<T: Iter>(v: T) -> Box<dyn X + 'static> { let item = v.into_item(); Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough } fn bad2<T: Iter>(v: T) ...
<'a, T: Iter>(v: T) -> Box<dyn X + 'a> where T::Item : 'a { let item = v.into_item(); Box::new(item) // OK, T::Item : 'a is declared } fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<dyn X + 'a> where T::Item : Clone { let item = Clone::clone(w); Box::new(item) // OK, T::Item : 'a is implied ...
ok1
identifier_name
regions-close-associated-type-into-object.rs
trait X {}
trait Iter { type Item: X; fn into_item(self) -> Self::Item; fn as_item(&self) -> &Self::Item; } fn bad1<T: Iter>(v: T) -> Box<dyn X + 'static> { let item = v.into_item(); Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough } fn bad2<T: Iter>(v: T) -> Box<dyn X +...
random_line_split
__init__.py
# PyTransit: fast and easy exoplanet transit modelling in Python. # Copyright (C) 2010-2019 Hannu Parviainen # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
sdss_griz = (sdss_g, sdss_r, sdss_i, sdss_z) __all__ = ("SMContamination BBContamination Instrument DeltaFilter BoxcarFilter TabulatedFilter".split() + "true_radius_ratio apparent_radius_ratio sdss_z sdss_i sdss_r sdss_g sdss_griz".split() + ["contaminate_light_curve"])
return true_k * sqrt(1 - contamination)
identifier_body
__init__.py
# PyTransit: fast and easy exoplanet transit modelling in Python. # Copyright (C) 2010-2019 Hannu Parviainen # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
(apparent_k: float, contamination: float) -> float: return apparent_k / sqrt(1 - contamination) def apparent_radius_ratio(true_k: float, contamination: float) -> float: return true_k * sqrt(1 - contamination) sdss_griz = (sdss_g, sdss_r, sdss_i, sdss_z) __all__ = ("SMContamination BBContamination Instrument...
true_radius_ratio
identifier_name
__init__.py
# PyTransit: fast and easy exoplanet transit modelling in Python. # Copyright (C) 2010-2019 Hannu Parviainen # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
"true_radius_ratio apparent_radius_ratio sdss_z sdss_i sdss_r sdss_g sdss_griz".split() + ["contaminate_light_curve"])
sdss_griz = (sdss_g, sdss_r, sdss_i, sdss_z) __all__ = ("SMContamination BBContamination Instrument DeltaFilter BoxcarFilter TabulatedFilter".split() +
random_line_split
quicksort.ts
import { IComparable } from "./icomparable"; export class Sort { public static quickSort<T>(arr: Array<T>, left: number, right: number, compare: (a: T, b: T) => boolean)
private static partition<T>(arr: Array<T>, pivot: number, left: number, right: number, compare: (a: T, b: T) => boolean) { let partitionIndex = left; for (var i = left; i < right; i++) { if (compare(arr[i], arr[pivot])) { this.swap(arr, i, partitionIndex); ...
{ let pivot: number let partitionIndex: number if (left < right) { pivot = right; partitionIndex = this.partition(arr, pivot, left, right, compare); //sort left and right this.quickSort(arr, left, partitionIndex - 1, compare); this.qu...
identifier_body
quicksort.ts
import { IComparable } from "./icomparable"; export class Sort { public static quickSort<T>(arr: Array<T>, left: number, right: number, compare: (a: T, b: T) => boolean) { let pivot: number let partitionIndex: number if (left < right) { pivot = right; partitionInde...
} this.swap(arr, right, partitionIndex); return partitionIndex; } private static swap<T>(arr: Array<T>, i: number, j: number) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
{ this.swap(arr, i, partitionIndex); partitionIndex++; }
conditional_block
quicksort.ts
import { IComparable } from "./icomparable"; export class Sort { public static quickSort<T>(arr: Array<T>, left: number, right: number, compare: (a: T, b: T) => boolean) { let pivot: number let partitionIndex: number if (left < right) { pivot = right; partitionInde...
}
random_line_split
quicksort.ts
import { IComparable } from "./icomparable"; export class
{ public static quickSort<T>(arr: Array<T>, left: number, right: number, compare: (a: T, b: T) => boolean) { let pivot: number let partitionIndex: number if (left < right) { pivot = right; partitionIndex = this.partition(arr, pivot, left, right, compare); ...
Sort
identifier_name
login.ctrl.js
'use strict'; /** * @ngdoc function * @name com.module.users.controller:LoginCtrl * @description Login Controller * @requires $scope * @requires $routeParams * @requires $location * Contrller for Login Page **/ angular.module('com.module.users') .controller('LoginCtrl', function($scope, $routeParams, $locatio...
}); $scope.login = function() { $scope.loginResult = User.login({ include: 'user', rememberMe: $scope.credentials.rememberMe }, $scope.credentials, function(user) { console.log(user.id); // => acess token console.log(user.ttl); // => 1209600 tim...
{ AuthProvider.find(function(result) { $scope.authProviders = result; }); }
conditional_block
login.ctrl.js
'use strict'; /** * @ngdoc function * @name com.module.users.controller:LoginCtrl * @description Login Controller * @requires $scope * @requires $routeParams * @requires $location * Contrller for Login Page **/ angular.module('com.module.users') .controller('LoginCtrl', function($scope, $routeParams, $locatio...
console.log(user.created); // => 2013-12-20T21:10:20.377Z console.log(user.userId); // => 1 var next = $location.nextAfterLogin || '/'; $location.nextAfterLogin = null; AppAuth.currentUser = $scope.loginResult.user; CoreService.toastSuccess(gettextCatalog.get...
}, $scope.credentials, function(user) { console.log(user.id); // => acess token console.log(user.ttl); // => 1209600 time to live
random_line_split
REThread.py
'''Enhanced Thread with support for return values and exception propagation.''' # Copyright (C) 2007 Canonical Ltd. # Author: Martin Pitt <martin.pitt@ubuntu.com> # # 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 ...
except: if sys: self._exception = sys.exc_info() def return_value(self): '''Return value from target function. This can only be called after the thread has finished, i. e. when isAlive() is False and did not terminate with an exception. ...
'''Thread with return values and exception propagation.''' def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, verbose=None): '''Initialize Thread, identical to threading.Thread.__init__().''' threading.Thread.__init__(self, group, target, name, args, kwargs, ...
identifier_body
REThread.py
'''Enhanced Thread with support for return values and exception propagation.''' # Copyright (C) 2007 Canonical Ltd. # Author: Martin Pitt <martin.pitt@ubuntu.com> # # 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 ...
def return_value(self): '''Return value from target function. This can only be called after the thread has finished, i. e. when isAlive() is False and did not terminate with an exception. ''' assert not self.isAlive() assert not self._exception return self....
try: self._retval = self.__target(*self.__args, **self.__kwargs) except: if sys: self._exception = sys.exc_info()
conditional_block
REThread.py
'''Enhanced Thread with support for return values and exception propagation.''' # Copyright (C) 2007 Canonical Ltd. # Author: Martin Pitt <martin.pitt@ubuntu.com> # # 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 ...
(self): '''exception in thread is caught and passed.''' t = REThread(target=div, args=(1, 0)) t.start() t.join() # thread did not terminate normally, no return value self.assertRaises(AssertionError, t.return_value) self.assertTrue(t.e...
test_exception
identifier_name
REThread.py
'''Enhanced Thread with support for return values and exception propagation.''' # Copyright (C) 2007 Canonical Ltd. # Author: Martin Pitt <martin.pitt@ubuntu.com> # # 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 ...
self.assertTrue(exc[-1].startswith('ZeroDivisionError'), 'not a ZeroDivisionError:' + str(e)) self.assertTrue(exc[-2].endswith('return x / y\n')) self.assertTrue(raised) unittest.main()
random_line_split
test.rs
extern crate rimd; use rimd::{SMF,SMFError}; use std::env::{args,Args}; use std::path::Path; fn
() { let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Please pass a path to an SMF to test") }, }; println!("Reading: {}",pathstr); match SMF::from_file(&Path::new(&pathstr[..])) { Ok(smf) => { println...
main
identifier_name
test.rs
extern crate rimd; use rimd::{SMF,SMFError}; use std::env::{args,Args}; use std::path::Path; fn main() { let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Please pass a path to an SMF to test") }, }; println!("Reading: {}",p...
println!("\n{}: {}\nevents:",tnum,track); tnum+=1; for event in track.events.iter() { println!(" {}",event.fmt_with_time_offset(time)); time += event.vtime; } } } Err(e) => { ...
println!("division: {}",smf.division); let mut tnum = 1; for track in smf.tracks.iter() { let mut time: u64 = 0;
random_line_split
test.rs
extern crate rimd; use rimd::{SMF,SMFError}; use std::env::{args,Args}; use std::path::Path; fn main()
time += event.vtime; } } } Err(e) => { match e { SMFError::InvalidSMFFile(s) => {println!("{}",s);} SMFError::Error(e) => {println!("io: {}",e);} SMFError::MidiError(e) => {println!("Midi Error: {...
{ let mut args: Args = args(); args.next(); let pathstr = match args.next() { Some(s) => s, None => { panic!("Please pass a path to an SMF to test") }, }; println!("Reading: {}",pathstr); match SMF::from_file(&Path::new(&pathstr[..])) { Ok(smf) => { println!("...
identifier_body
server.ts
/** * Web Server */ import * as ms from 'ms'; // express modules import * as express from 'express'; import * as bodyParser from 'body-parser'; import * as favicon from 'serve-favicon'; import * as compression from 'compression'; const subdomain = require('subdomain'); import client from './serve-client';
* Init app */ const app = express(); app.disable('x-powered-by'); app.set('view engine', 'pug'); app.use(bodyParser.urlencoded({ extended: true })); app.use(compression()); /** * Initialize requests */ app.use((req, res, next) => { res.header('X-Frame-Options', 'DENY'); next(); }); /** * Static resources */ ...
import config from '../config'; /**
random_line_split
home_widgets.js
(function(panel, $) { var originalTitle; function home_formatTime(s) { var h = Math.floor(s / 3600); var m = Math.floor((s - h * 3600) / 60); var s = s - h * 3600 - m * 60; if(isNaN(h) || isNaN(m)) return ''; return (h > 0? (h < 9? '0' + h: h) + ':': '') + (m < 10? '0' + m: m) + ':' + (s < 10? ...
} }); })(window.__panel, jQuery);
random_line_split
home_widgets.js
(function(panel, $) { var originalTitle; function home_formatTime(s) { var h = Math.floor(s / 3600); var m = Math.floor((s - h * 3600) / 60); var s = s - h * 3600 - m * 60; if(isNaN(h) || isNaN(m)) return ''; return (h > 0? (h < 9? '0' + h: h) + ':': '') + (m < 10? '0' + m: m) + ':' + (s < 10? ...
home_health_timer.apply(that, [health]); if(this.hp_current >= health.hp_max || !health.hp_speed) return; this.healthUpdInterval = panel.setInterval(function() { home_health_timer.apply(that, [health]); }, 1000); } else if(health.hp_start >= health.hp_max) { this.progressBar.c...
{ if(!health) return; if(((!this.hp_current && health.hp_start != health.hp_max) || this.hp_current < health.hp_start || init)) { if(this.options.autohide) this.fadeIn(); if(this.healthUpdInterval) { clearInterval(this.healthUpdInterval); } if(health.hp_start / health.hp_max > 0...
identifier_body
home_widgets.js
(function(panel, $) { var originalTitle; function
(s) { var h = Math.floor(s / 3600); var m = Math.floor((s - h * 3600) / 60); var s = s - h * 3600 - m * 60; if(isNaN(h) || isNaN(m)) return ''; return (h > 0? (h < 9? '0' + h: h) + ':': '') + (m < 10? '0' + m: m) + ':' + (s < 10? '0' + s: s); } function home_health_timer(health) { var width...
home_formatTime
identifier_name
cbc.js
'use strict'; /** * @ngdoc function * @name quickNewsApp.controller:CbcCtrl * @description * # CbcCtrl * Controller of the quickNewsApp */ angular.module('quickNewsApp') .controller('CbcCtrl', function ($scope, $http) { this.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ...
this.tab = activeTab; $scope.postLimit = 10; $scope.getFeed(activeTab); }; $scope.getActiveTab = function() { return this.tab; }; $scope.getFeed = function(category) { /*jshint unused: false */ $scope.loading = true; var url = '//quicknews.amanuppal.ca:5000/cbc?url=' + category; $http.get(url) ....
}; $scope.setTab = function(activeTab) {
random_line_split
timezoneapi.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! ApiSet Contract for api-ms-win-core-timezone-l1 pub const TIME_ZONE_ID_INVALID: ::DWORD = 0xFFFFFFFF; STRUCT!{struct TIME_ZONE_INFORMATION { Bias: ::LONG, StandardName: [::WCHAR; 32], StandardDate: ::SYSTEMTIME, Stand...
pub type PDYNAMIC_TIME_ZONE_INFORMATION = *mut DYNAMIC_TIME_ZONE_INFORMATION;
random_line_split
scripts.js
var gulp = require("gulp"); var runSeq = require("run-sequence"); var merge = require("merge2"); var typescript = require("typescript"); var dtsGen = require("dts-generator"); var Builder = require("systemjs-builder"); var tsc = require("gulp-typescript"); var sourcemaps = require("gulp-sourcemaps"); var plumber = req...
return dtsGen.generate({ name: `${config.packageName}`, baseDir: `${config.root}/`, files: ["./index.ts", `../${config.src.tsd}`], out: `${config.artifact}/${config.packageName}.d.ts`, main: `${config.packageName}/index`, //externs: ["../angularjs/angular.d.ts"] }, (msg) => { console.log(`Generating ${c...
}); // d.ts generation using dts-generator gulp.task("compile:dts", () => {
random_line_split
rc-compiled.js
#! /usr/bin/env node 'use strict'; var cc = require('./lib/utils'); var join = require('path').join; var deepExtend = require('deep-extend'); var etc = '/etc'; var win = process.platform === "win32"; var home = win ? process.env.USERPROFILE : process.env.HOME; module.exports = function (name, defaults, argv, parse) {...
(file) { if (configFiles.indexOf(file) >= 0) return; var fileConfig = cc.file(file); if (fileConfig) { configs.push(parse(fileConfig)); configFiles.push(file); } } // which files do we look at? if (!win) [join(etc, name, 'config'), join(etc, name + 'rc')].forEach(addConfigFile); if ...
addConfigFile
identifier_name
rc-compiled.js
#! /usr/bin/env node
'use strict'; var cc = require('./lib/utils'); var join = require('path').join; var deepExtend = require('deep-extend'); var etc = '/etc'; var win = process.platform === "win32"; var home = win ? process.env.USERPROFILE : process.env.HOME; module.exports = function (name, defaults, argv, parse) { if ('string' !== t...
random_line_split
rc-compiled.js
#! /usr/bin/env node 'use strict'; var cc = require('./lib/utils'); var join = require('path').join; var deepExtend = require('deep-extend'); var etc = '/etc'; var win = process.platform === "win32"; var home = win ? process.env.USERPROFILE : process.env.HOME; module.exports = function (name, defaults, argv, parse) {...
// which files do we look at? if (!win) [join(etc, name, 'config'), join(etc, name + 'rc')].forEach(addConfigFile); if (home) [join(home, '.config', name, 'config'), join(home, '.config', name), join(home, '.' + name, 'config'), join(home, '.' + name + 'rc')].forEach(addConfigFile); addConfigFile(cc.find('.' ...
{ if (configFiles.indexOf(file) >= 0) return; var fileConfig = cc.file(file); if (fileConfig) { configs.push(parse(fileConfig)); configFiles.push(file); } }
identifier_body
server.py
from cherrypy.process.plugins import PIDFile import argparse import cherrypy from PressUI.cherrypy.PressConfig import PressConfig import PressUI.cherrypy.PressProduction as PressProduction parser = argparse.ArgumentParser() parser.add_argument( '--production', help = 'Run app in production mode', action =...
(app, app_name, fun_callback = None): args = parser.parse_args() PressConfig.init(args.config) if fun_callback is not None: fun_callback() cherrypy.config.update({ 'server.socket_port': args.port, 'server.socket_host': '127.0.0.1', 'tools.gzip.on': True, }) if...
quickstart
identifier_name
server.py
from cherrypy.process.plugins import PIDFile import argparse import cherrypy from PressUI.cherrypy.PressConfig import PressConfig import PressUI.cherrypy.PressProduction as PressProduction parser = argparse.ArgumentParser() parser.add_argument( '--production', help = 'Run app in production mode', action =...
PIDFile( cherrypy.engine, '/tmp/{}.pid'.format(app_name), ).subscribe() PressProduction.set_production(True) cherrypy.quickstart(app())
args = parser.parse_args() PressConfig.init(args.config) if fun_callback is not None: fun_callback() cherrypy.config.update({ 'server.socket_port': args.port, 'server.socket_host': '127.0.0.1', 'tools.gzip.on': True, }) if args.production: cherrypy.config....
identifier_body
server.py
from cherrypy.process.plugins import PIDFile import argparse import cherrypy from PressUI.cherrypy.PressConfig import PressConfig import PressUI.cherrypy.PressProduction as PressProduction parser = argparse.ArgumentParser() parser.add_argument( '--production', help = 'Run app in production mode', action =...
cherrypy.config.update({ 'server.socket_port': args.port, 'server.socket_host': '127.0.0.1', 'tools.gzip.on': True, }) if args.production: cherrypy.config.update({ 'environment': 'production', 'tools.proxy.on': True, 'log.access_file': '...
fun_callback()
conditional_block
server.py
from cherrypy.process.plugins import PIDFile import argparse import cherrypy from PressUI.cherrypy.PressConfig import PressConfig import PressUI.cherrypy.PressProduction as PressProduction parser = argparse.ArgumentParser() parser.add_argument( '--production', help = 'Run app in production mode', action =...
'log.access_file': '/tmp/{}.access.log'.format(app_name), 'log.error_file': '/tmp/{}.error.log'.format(app_name), }) PIDFile( cherrypy.engine, '/tmp/{}.pid'.format(app_name), ).subscribe() PressProduction.set_production(True) cherrypy....
'tools.proxy.on': True,
random_line_split
dashboard.js
:00Z', step: '1h0m0s', data: { 'latency.ms.p50': [ 46.924528301886795, 56.10526315789474, 41.19642857142857, 60.388888888888886, 54.94642857142857, 59.160714285714285, 45.24528301886792, 54.592592592592595, 43.51851851851852, 55, 44.160714285714285, 31.181818181818183, 36.089285714285715, 43.98275862068966,...
.then(() => longboard.done()) .then(() => telex.done()) .then(() => heroku.done()) }) }) describe('with no telex', () => { it('shows the dashboard', () => { let longboard = nock('https://longboard.heroku.com:443') .get('/favorites?type=app').reply(200, []) let he...
`)) .then(() => expect(cli.stderr, 'to be', 'Loading... done\n ▸ Add apps to this dashboard by favoriting them with heroku\n ▸ apps:favorites:add\n'))
random_line_split
floating-position.ts
// http://officeopenxml.com/drwPicFloating-position.php // http://officeopenxml.com/drwPicFloating.php import { HorizontalPositionAlign, VerticalPositionAlign } from "file/shared/alignment"; import { ITextWrapping } from "../text-wrap"; export enum HorizontalPositionRelativeFrom { CHARACTER = "character", COL...
PARAGRAPH = "paragraph", TOP_MARGIN = "topMargin", } export interface IHorizontalPositionOptions { readonly relative?: HorizontalPositionRelativeFrom; readonly align?: HorizontalPositionAlign; readonly offset?: number; } export interface IVerticalPositionOptions { readonly relative?: VerticalP...
OUTSIDE_MARGIN = "outsideMargin", PAGE = "page",
random_line_split
4chan.py
import re import json import requests from util import irc from util.handler_utils import cmdhook, authenticate, get_target from qtbot3_common.types.message import Message def scrape(board: str, filtertext: str): try: data = requests.get("http://boards.4chan.org/{board}/catalog".format(board=board)).tex...
(message: Message, match, nick: str): board = match['board'] filtertext = match['filtertext'] print("searching 4chan's {board} board for {filtertext}...".format(**match)) baseurl = "http://boards.4chan.org/{board}/thread/{number}/{semantic_url}" lines = [] for number, thread in scrape(board, f...
handle_scrape
identifier_name