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 |
|---|---|---|---|---|
cache.py | (object):
"""
A simple struct for maintaining a cached object with an expiration date.
Parameters
----------
value : object
The object to cache.
expires : datetime-like
Expiration date of `value`. The cache is considered invalid for dates
**strictly greater** than `expir... | has expired.
"""
try:
return self._cache[key].unwrap(dt)
except Expired:
del self._cache[key]
raise KeyError(key)
def set(self, key, value, expiration_dt):
"""Adds a new key value pair to the cache.
Parameters
--------... | random_line_split | |
cache.py | ):
"""
A simple struct for maintaining a cached object with an expiration date.
Parameters
----------
value : object
The object to cache.
expires : datetime-like
Expiration date of `value`. The cache is considered invalid for dates
**strictly greater** than `expires`.
... |
with self.lock:
try:
with open(self._keypath(key), 'rb') as f:
return self.deserialize(f)
except IOError as e:
if e.errno != errno.ENOENT:
raise
raise KeyError(key)
def __setitem__(self, key, v... | return dict(self.items()) | conditional_block |
cache.py | doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Expired: 2014-01-01 00:00:00+00:00
"""
def __init__(self, value, expires):
self._value = value
self._expires = expires
@classmethod
def expired(cls):
"""Construct a CachedObject that's expi... | """Ensures a subdirectory of the working directory.
Parameters
----------
path_parts : iterable[str]
The parts of the path after the working directory.
"""
path = self.getpath(*path_parts)
ensure_directory(path)
return path | identifier_body | |
caddi2018_e.py | def main() -> None:
|
left[i] = i-1
else:
pass
ans = 10 ** 9
for i in range(N + 1):
A = AA[:]
cnt = 0
if i > 0:
A[i-1] *= -2
cnt += 1
for j in reversed(range(i-1)):
A[j] *= -2
cnt += 1
while... | N = int(input())
A = [int(x) for x in input().split()]
rev_A = A[:]
left = [-1] * N
left_cnt = [0] * N
A_left = [A[0]]
for i in range(1, N):
if rev_A[i-1] < rev_A[i]:
cnt = 0
while rev_A[i-1]
pass
elif rev_A[i-1] < rev_A[i] * 4:
now... | identifier_body |
caddi2018_e.py | def main() -> None:
N = int(input())
A = [int(x) for x in input().split()]
rev_A = A[:]
left = [-1] * N
left_cnt = [0] * N
A_left = [A[0]]
for i in range(1, N):
if rev_A[i-1] < rev_A[i]:
cnt = 0
while rev_A[i-1]
pass
elif rev_A[i-1] < rev_A... |
print(i, cnt, A)
ans = min(ans, cnt)
print(ans)
if __name__ == '__main__':
main()
| A[j] *= 4
cnt += 2 | conditional_block |
caddi2018_e.py | def | () -> None:
N = int(input())
A = [int(x) for x in input().split()]
rev_A = A[:]
left = [-1] * N
left_cnt = [0] * N
A_left = [A[0]]
for i in range(1, N):
if rev_A[i-1] < rev_A[i]:
cnt = 0
while rev_A[i-1]
pass
elif rev_A[i-1] < rev_A[i] * 4:... | main | identifier_name |
caddi2018_e.py | def main() -> None:
N = int(input())
A = [int(x) for x in input().split()]
rev_A = A[:]
left = [-1] * N
left_cnt = [0] * N
A_left = [A[0]]
for i in range(1, N):
if rev_A[i-1] < rev_A[i]: | while rev_A[i-1]
pass
elif rev_A[i-1] < rev_A[i] * 4:
now = i-1
while left[now] != -1:
now = left[now]
left[i] = now
A_left.append(A[i])
left[i] = i-1
else:
pass
ans = 10 ** 9
for i... | cnt = 0 | random_line_split |
pants_daemon.py | def isatty(self):
return False
def fileno(self):
return self._handler.stream.fileno()
@property
def buffer(self):
return self
class PantsDaemonSignalHandler(SignalHandler):
def __init__(self, daemon):
super().__init__()
self._daemon = daemon
def handl... | self._logger.log(self._log_level, line.rstrip())
def flush(self):
return
| random_line_split | |
pants_daemon.py | (self):
return False
def fileno(self):
return self._handler.stream.fileno()
@property
def buffer(self):
return self
class PantsDaemonSignalHandler(SignalHandler):
def __init__(self, daemon):
super().__init__()
self._daemon = daemon
def handle_sigint(self,... | isatty | identifier_name | |
pants_daemon.py | (include_watchman=False)
class PantsDaemon(FingerprintedProcessManager):
"""A daemon that manages PantsService instances."""
JOIN_TIMEOUT_SECONDS = 1
LOG_NAME = "pantsd.log"
class StartupFailure(Exception):
"""Represents a failure to start pantsd."""
class RuntimeFailure(Exception):
... |
# Redirect stdio to /dev/null for the rest of the run, to reserve those file descriptors
# for further forks.
with stdio_as(stdin_fd=-1, stdout_fd=-1, stderr_fd=-1):
# Reinitialize logging for the daemon context.
init_rust_logger(self._log_level, self._log_show_rust_3rd... | try:
os.fdopen(fd)
raise AssertionError(f"pantsd logging cannot initialize while stdio is open: {fd}")
except OSError:
pass | conditional_block |
pants_daemon.py | (include_watchman=False)
class PantsDaemon(FingerprintedProcessManager):
"""A daemon that manages PantsService instances."""
JOIN_TIMEOUT_SECONDS = 1
LOG_NAME = "pantsd.log"
class StartupFailure(Exception):
"""Represents a failure to start pantsd."""
class RuntimeFailure(Exception):
... | )
self._log_dir = os.path.join(work_dir, self.name)
self._logger = logging.getLogger(__name__)
# N.B. This Event is used as nothing more than a convenient atomic flag - nothing waits on it.
self._kill_switch = threading.Event()
@memoized_property
def watchman_launcher(... | """
:param Native native: A `Native` instance.
:param string build_root: The pants build root.
:param string work_dir: The pants work directory.
:param string log_level: The log level to use for daemon logging.
:param PantsServices services: A registry of services to use in this ... | identifier_body |
issue-2356.rs | // Copyright 2012-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... | (other:usize) {
whiskers = 4;
//~^ ERROR cannot find value `whiskers`
purr_louder();
//~^ ERROR cannot find function `purr_louder`
}
}
fn main() {
self += 1;
//~^ ERROR expected value, found module `self`
}
| grow_older | identifier_name |
issue-2356.rs | // Copyright 2012-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... |
}
fn purr(&self) {
grow_older();
//~^ ERROR cannot find function `grow_older`
shave();
//~^ ERROR cannot find function `shave`
}
fn burn_whiskers(&mut self) {
whiskers = 0;
//~^ ERROR cannot find value `whiskers`
}
pub fn grow_older(other:usize) {
whiskers = 4;
//~^ ERROR... | {
//~^ ERROR expected value, found module `self`
println!("MEOW");
} | conditional_block |
issue-2356.rs | // Copyright 2012-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... |
}
impl Groom for cat {
fn shave(other: usize) {
whiskers -= other;
//~^ ERROR cannot find value `whiskers`
shave(4);
//~^ ERROR cannot find function `shave`
purr();
//~^ ERROR cannot find function `purr`
}
}
impl cat {
fn static_method() {}
fn purr_louder() {
static_metho... | {
default();
//~^ ERROR cannot find function `default`
loop {}
} | identifier_body |
issue-2356.rs | // Copyright 2012-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... | impl Default for cat {
fn default() -> Self {
default();
//~^ ERROR cannot find function `default`
loop {}
}
}
impl Groom for cat {
fn shave(other: usize) {
whiskers -= other;
//~^ ERROR cannot find value `whiskers`
shave(4);
//~^ ERROR cannot find function `shave`
purr();
//~... | //~^ ERROR cannot find function `clone`
loop {}
}
} | random_line_split |
callee.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | };
span_err!(tcx.sess, span, E0174,
"explicit use of unboxed closure method `{}` is experimental",
method);
span_help!(tcx.sess, span,
"add `#![feature(unboxed_closures)]` to the crate attributes to enable");
}
}
| {
let tcx = ccx.tcx;
let did = Some(trait_id);
let li = &tcx.lang_items;
if did == li.drop_trait() {
span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
} else if !tcx.sess.features.borrow().unboxed_closures {
// the #[feature(unboxed_closures)] feature isn't
... | identifier_body |
callee.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) {
let tcx = ccx.tcx;
let did = Some(trait_id);
let li = &tcx.lang_items;
if did == li.drop_trait() {
span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
} else if !tcx.sess.features.borrow().unboxed_closures {
//... | check_legal_trait_for_method_call | identifier_name |
callee.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else if !tcx.sess.features.borrow().unboxed_closures {
// the #[feature(unboxed_closures)] feature isn't
// activated so we need to enforce the closure
// restrictions.
let method = if did == li.fn_trait() {
"call"
} else if did == li.fn_mut_trait() {
"c... | {
span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
} | conditional_block |
callee.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
if did == li.drop_trait() {
span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
} else if !tcx.sess.features.borrow().unboxed_closures {
// the #[feature(unboxed_closures)] feature isn't
// activated so we need to enforce the closure
// restrictions.
... | let did = Some(trait_id);
let li = &tcx.lang_items; | random_line_split |
cmp.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cmp::Ordering::{self, Less, Equal, Greater};
// impl Ord for str {
// #[inline]
// fn cmp(&self, other: &str) -> Ordering {
// for (s_b, o_b) in self.bytes().zip(other.bytes()) {
// ... | () {
let x: &str = "日"; // '\u{65e5}'
let other: &str = "月"; // '\u{6708}'
let result: Ordering = x.cmp(other);
assert_eq!(result, Less);
}
#[test]
fn cmp_test2() {
let x: &str = "天"; // '\u{5929}'
let other: &str = "地"; // '\u{5730}'
let result: Ordering = x.cmp(other);
assert_eq!(result, Greate... | cmp_test1 | identifier_name |
cmp.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cmp::Ordering::{self, Less, Equal, Greater};
// impl Ord for str {
// #[inline]
// fn cmp(&self, other: &str) -> Ordering {
// for (s_b, o_b) in self.bytes().zip(other.bytes()) {
// ... | "人";
let other: &str = "人種";
let result: Ordering = x.cmp(other);
assert_eq!(result, Less);
}
}
| identifier_body | |
cmp.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cmp::Ordering::{self, Less, Equal, Greater};
// impl Ord for str {
// #[inline]
// fn cmp(&self, other: &str) -> Ordering {
// for (s_b, o_b) in self.bytes().zip(other.bytes()) {
// ... | let other: &str = "人";
let result: Ordering = x.cmp(other);
assert_eq!(result, Greater);
}
#[test]
fn cmp_test5() {
let x: &str = "人";
let other: &str = "人種";
let result: Ordering = x.cmp(other);
assert_eq!(result, Less);
}
} | random_line_split | |
admin.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# 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 versio... | def SUC(self, obj):
return u", ".join(o.name for o in obj.SUC_tag.all())
# def get_queryset(self, request):
# return super(LayerAdmin, self).get_queryset(request).prefetch_related('SUC_tag')
# def SUC(self, obj):
# return u", ".join(o.name for o in obj.SUC_tag.all())
inlines = [A... | list_display = (
'id',
'typename',
'service_type',
'title',
'Floodplains',
'SUC',
'date',
'category')
list_display_links = ('id',)
list_editable = ('title', 'category')
list_filter = ('owner', 'category',
'restriction_code_ty... | identifier_body |
admin.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# 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 versio... |
class AttributeInline(admin.TabularInline):
model = Attribute
class LayerAdmin(MediaTranslationAdmin):
list_display = (
'id',
'typename',
'service_type',
'title',
'Floodplains',
'SUC',
'date',
'category')
list_display_links = ('id',)
li... |
class LayerAdminForm(ResourceBaseAdminForm):
class Meta:
model = Layer | random_line_split |
admin.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# 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 versio... | (admin.ModelAdmin):
model = Style
list_display_links = ('sld_title',)
list_display = ('id', 'name', 'sld_title', 'workspace', 'sld_url')
list_filter = ('workspace',)
search_fields = ('name', 'workspace',)
class LayerFileInline(admin.TabularInline):
model = LayerFile
class UploadSessionAdmin(... | StyleAdmin | identifier_name |
block_drag_surface.js | /**
* @license
* Visual Blocks Editor
*
* Copyright 2016 Google Inc.
* https://developers.google.com/blockly/
*
* 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.apach... | * @private
*/
Blockly.BlockDragSurfaceSvg.prototype.container_ = null;
/**
* Cached value for the scale of the drag surface.
* Used to set/get the correct translation during and after a drag.
* @type {number}
* @private
*/
Blockly.BlockDragSurfaceSvg.prototype.scale_ = 1;
/**
* Cached value for the translatio... | Blockly.BlockDragSurfaceSvg.prototype.dragGroup_ = null;
/**
* Containing HTML element; parent of the workspace and the drag surface.
* @type {Element} | random_line_split |
block_drag_surface.js | /**
* @license
* Visual Blocks Editor
*
* Copyright 2016 Google Inc.
* https://developers.google.com/blockly/
*
* 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.apach... |
this.SVG_ = Blockly.utils.createSvgElement('svg', {
'xmlns': Blockly.SVG_NS,
'xmlns:html': Blockly.HTML_NS,
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
'version': '1.1',
'class': 'blocklyBlockDragSurface'
}, this.container_);
this.dragGroup_ = Blockly.utils.createSvgElement('g', {}, this.S... | {
return; // Already created.
} | conditional_block |
_drop_test2.js | import { expect } from 'chai'
import _drop from '../../src/array/_drop2'
describe('_drop', function(){
it('is a function', function(){
expect(_drop).to.be.a('function')
})
it('returns an array', function(){
const droppedArray = _drop([5,7,2])
expect(droppedArray).to.be.a('array')
})
it('return... | })
it('returns [] when given [5,7,2], 17', function(){
const droppedArray = _drop([5,7,2], 17)
expect(droppedArray).to.be.deep.equal([])
})
}) | expect(droppedArray).to.be.deep.equal([7, 2]) | random_line_split |
SwapView.js | !./SwapView/themes/{{theme}}/SwapView.css"
], function (dcl, register, $, dpointer, ViewStack) {
/**
* SwapView container widget. Extends ViewStack to let the user swap the visible child using a swipe gesture.
* You can also use the Page Up / Down keyboard keys to go to the next/previous child.
*
* @example:
... |
},
/**
* Cleanup all CSS classes and added rules after transition.
* @private
*/
_endTransition: function () {
if (this._drag) {
$(this).removeClass("-d-swap-view-drag");
if (this._drag.slideBack) {
// Hide the "in" view if the wap was cancelled (slide back).
this._drag.childIn.st... | {
this._endTransitionHandler = function () {
if (this._endTransitionHandler) {
this._addTransitionEndHandlers(this._drag.childIn, false);
this._addTransitionEndHandlers(this._drag.childOut, false);
this._endTransitionHandler = null;
}
this._endTransition();
}.bind(this);
thi... | conditional_block |
SwapView.js | !./SwapView/themes/{{theme}}/SwapView.css"
], function (dcl, register, $, dpointer, ViewStack) {
/**
* SwapView container widget. Extends ViewStack to let the user swap the visible child using a swipe gesture.
* You can also use the Page Up / Down keyboard keys to go to the next/previous child.
*
* @example:
... | if (this._drag) {
var dx = e.clientX - this._drag.start;
if (!this._drag.started && Math.abs(dx) > this._dragThreshold) {
// user dragged (more than the threshold), start sliding children.
var childOut = this._visibleChild;
var childIn = (this.effectiveDir === "ltr" ? dx < 0 : dx > 0) ? childO... | * @private
*/
_pointerMoveHandler: function (e) {
/* jshint maxcomplexity: 13 */ | random_line_split |
eui48.py | , \
words_to_int as _words_to_int, \
valid_bits as _valid_bits, \
bits_to_int as _bits_to_int, \
int_to_bits as _int_to_bits, \
valid_bin as _valid_bin, \
int_to_bin as _int_to_bin, \
bin_to_int as _bin_to_int
from netaddr.compat import _is_str
#: The width (in bits) of this addr... | int_to_bits | identifier_name | |
eui48.py | valid_bits, \
bits_to_int as _bits_to_int, \
int_to_bits as _int_to_bits, \
valid_bin as _valid_bin, \
int_to_bin as _int_to_bin, \
bin_to_int as _bin_to_int
from netaddr.compat import _is_str
#: The width (in bits) of this address type.
width = 48
#: The AF_* constant value of this addre... | dialect = DEFAULT_DIALECT | conditional_block | |
eui48.py | containing no delimiters.
"""
import struct as _struct
import re as _re
# Check whether we need to use fallback code or not.
try:
from socket import AF_LINK
except ImportError:
AF_LINK = 48
from netaddr.core import AddrFormatError
from netaddr.strategy import \
valid_words as _valid_words, \
int_t... | from netaddr.compat import _is_str
#: The width (in bits) of this address type.
width = 48
#: The AF_* constant value of this address type.
family = AF_LINK
#: A friendly string name address type.
family_name = 'MAC'
#: The version of this address type.
version = 48
#: The maximum integer value that can be represe... | int_to_bin as _int_to_bin, \
bin_to_int as _bin_to_int | random_line_split |
eui48.py | no delimiters.
"""
import struct as _struct
import re as _re
# Check whether we need to use fallback code or not.
try:
from socket import AF_LINK
except ImportError:
AF_LINK = 48
from netaddr.core import AddrFormatError
from netaddr.strategy import \
valid_words as _valid_words, \
int_to_words as ... |
#: The default dialect to be used when not specified by the user.
DEFAULT_DIALECT = mac_eui48
#-----------------------------------------------------------------------------
#: Regular expressions to match all supported MAC address formats.
RE_MAC_FORMATS = (
# 2 bytes x 6 (UNIX, Windows, EUI-48)
'^' + ':'.... | """A PostgreSQL style (2 x 24-bit words) MAC address dialect class."""
word_size = 24
num_words = width // word_size
word_sep = ':'
word_fmt = '%.6x'
word_base = 16 | identifier_body |
builder.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# module builder script
#
import os, sys, shutil, tempfile, subprocess, platform
template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename))
support_dir = os.path.join(template_dir, 'support')
sdk_dir = os.path.dirname(template_dir)
android_suppo... |
if len(line) == 0 or '=' not in line: continue
key, value = line.split('=', 1)
properties[key.strip()] = value.strip().replace('\\\\', '\\')
return properties
def main(args):
global android_sdk
# command platform project_dir
command = args[1]
platform = args[2]
project_dir = os.path.expanduser(args[3])
... | continue | conditional_block |
builder.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# module builder script
#
import os, sys, shutil, tempfile, subprocess, platform
template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename))
support_dir = os.path.join(template_dir, 'support')
sdk_dir = os.path.dirname(template_dir)
android_suppo... | print "[ERROR] Build Failed. See: %s" % os.path.abspath(error)
else:
print "[ERROR] Build Failed."
stage(platform, project_dir, manifest, run_callback)
elif command == 'run-emulator':
if is_android(platform):
def run_emulator_callback(gen_project_dir):
script = os.path.abspath(os.path.join(... |
# run the project
if rc==1:
if is_ios(platform):
error = os.path.join(gen_project_dir,'build','iphone','build','build.log') | random_line_split |
builder.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# module builder script
#
import os, sys, shutil, tempfile, subprocess, platform
template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename))
support_dir = os.path.join(template_dir, 'support')
sdk_dir = os.path.dirname(template_dir)
android_suppo... |
def print_emulator_line(line):
if line:
s = line.strip()
if s!='':
if s.startswith("["):
print s
else:
print "[DEBUG] %s" % s
sys.stdout.flush()
def run_python(args, cwd=None):
args.insert(0, sys.executable)
return run(args, cwd=cwd)
def run(args, cwd=None):
proc = run_pipe(args, cwd)
rc... | return subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=cwd) | identifier_body |
builder.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# module builder script
#
import os, sys, shutil, tempfile, subprocess, platform
template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename))
support_dir = os.path.join(template_dir, 'support')
sdk_dir = os.path.dirname(template_dir)
android_suppo... | (args, cwd=None):
proc = run_pipe(args, cwd)
rc = None
while True:
print_emulator_line(proc.stdout.readline())
rc = proc.poll()
if rc!=None: break
return rc
def run_ant(project_dir):
build_xml = os.path.join(project_dir, 'build.xml')
ant = 'ant'
if 'ANT_HOME' in os.environ:
ant = os.path.join(os.environ... | run | identifier_name |
packageHandler.py | #!/usr/bin/python
import piksemel
import os
def updateGConf (filepath, remove=False):
parse = piksemel.parse (filepath)
schemaList = list()
for xmlfile in parse.tags ("File"):
path = xmlfile.getTagData ("Path")
# Only interested in /etc/gconf/schemas
if "etc/gconf/schemas" in pat... |
def setupPackage (metapath, filepath):
updateGConf (filepath)
def postCleanupPackage (metapath, filepath):
updateGConf (filepath) | if len(schemaList) > 0:
os.environ['GCONF_CONFIG_SOURCE'] = 'xml:merged:/etc/gconf/gconf.xml.defaults'
operation = "--makefile-uninstall-rule" if remove else "--makefile-install-rule"
cmd = "/usr/bin/gconftool-2 %s %s" % (operation, " ".join(schemaList))
os.system (cmd) | random_line_split |
packageHandler.py | #!/usr/bin/python
import piksemel
import os
def updateGConf (filepath, remove=False):
parse = piksemel.parse (filepath)
schemaList = list()
for xmlfile in parse.tags ("File"):
path = xmlfile.getTagData ("Path")
# Only interested in /etc/gconf/schemas
if "etc/gconf/schemas" in pat... |
def postCleanupPackage (metapath, filepath):
updateGConf (filepath)
| updateGConf (filepath) | identifier_body |
packageHandler.py | #!/usr/bin/python
import piksemel
import os
def | (filepath, remove=False):
parse = piksemel.parse (filepath)
schemaList = list()
for xmlfile in parse.tags ("File"):
path = xmlfile.getTagData ("Path")
# Only interested in /etc/gconf/schemas
if "etc/gconf/schemas" in path:
schemaList.append ("/%s" % path)
if len(s... | updateGConf | identifier_name |
packageHandler.py | #!/usr/bin/python
import piksemel
import os
def updateGConf (filepath, remove=False):
parse = piksemel.parse (filepath)
schemaList = list()
for xmlfile in parse.tags ("File"):
|
if len(schemaList) > 0:
os.environ['GCONF_CONFIG_SOURCE'] = 'xml:merged:/etc/gconf/gconf.xml.defaults'
operation = "--makefile-uninstall-rule" if remove else "--makefile-install-rule"
cmd = "/usr/bin/gconftool-2 %s %s" % (operation, " ".join(schemaList))
os.system (cmd)
def setupP... | path = xmlfile.getTagData ("Path")
# Only interested in /etc/gconf/schemas
if "etc/gconf/schemas" in path:
schemaList.append ("/%s" % path) | conditional_block |
http.js | /**
* @namespace http
*
* The C<http> namespace groups functions and classes used while making
* HTTP Requests.
*
*/
ECMAScript.Extend('http', function (ecma) {
// Intentionally private
var _documentLocation = null
function _getDocumentLocation () |
/**
* @constant HTTP_STATUS_NAMES
* HTTP/1.1 Status Code Definitions
*
* Taken from, RFC 2616 Section 10:
* L<http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
*
* These names are used in conjuction with L<ecma.http.Request> for
* indicating callback functions. The name is prepended ... | {
if (!_documentLocation) _documentLocation = new ecma.http.Location();
return _documentLocation;
} | identifier_body |
http.js | /**
* @namespace http
*
* The C<http> namespace groups functions and classes used while making
* HTTP Requests.
*
*/
ECMAScript.Extend('http', function (ecma) {
// Intentionally private
var _documentLocation = null
function | () {
if (!_documentLocation) _documentLocation = new ecma.http.Location();
return _documentLocation;
}
/**
* @constant HTTP_STATUS_NAMES
* HTTP/1.1 Status Code Definitions
*
* Taken from, RFC 2616 Section 10:
* L<http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
*
* These names ... | _getDocumentLocation | identifier_name |
http.js | /**
* @namespace http
*
* The C<http> namespace groups functions and classes used while making
* HTTP Requests.
*
*/
ECMAScript.Extend('http', function (ecma) {
// Intentionally private
var _documentLocation = null
function _getDocumentLocation () {
if (!_documentLocation) _documentLocation = new ecm... | 505: 'HTTPVersionNotSupported'
};
/**
* @function isSameOrigin
*
* Compare originating servers.
*
* var bool = ecma.http.isSameOrigin(uri);
* var bool = ecma.http.isSameOrigin(uri, uri);
*
* Is the resource located on the server at the port using the same protocol
* which served th... | 501: 'NotImplemented',
502: 'BadGateway',
503: 'ServiceUnavailable',
504: 'GatewayTimeout', | random_line_split |
index.js | import React from 'react'
import {HOC, Link} from 'cerebral-view-react'
import PageProgress from '../PageProgress'
// View
class AutoReload extends React.Component {
constructor (props) {
super(props)
this.state = {
secondsElapsed: 0
}
this.onInterval = this.onInterval.bind(this)
}
compone... | secondsElapsed: {this.state.secondsElapsed}<br />
secondsBeforeReload: {this.props.triggerAfterSeconds - this.state.secondsElapsed}<br />
-------------------------<br />
<Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br />
... | [{'='.repeat(this.state.secondsElapsed)}{'.'.repeat(this.props.triggerAfterSeconds - this.state.secondsElapsed - 1)}]<br />
isEnabled: {this.props.isEnabled ? 'yepp' : 'nope'}<br />
triggerAfterSeconds: {this.props.triggerAfterSeconds}<br />
numberOfTriggers: {this.props.triggers... | random_line_split |
index.js | import React from 'react'
import {HOC, Link} from 'cerebral-view-react'
import PageProgress from '../PageProgress'
// View
class AutoReload extends React.Component {
constructor (props) {
super(props)
this.state = {
secondsElapsed: 0
}
this.onInterval = this.onInterval.bind(this)
}
compone... |
}
if (secondsElapsed !== this.state.secondsElapsed) {
this.setState({
secondsElapsed: secondsElapsed
})
}
}
trigger () {
this.props.triggers.map((trigger) => trigger())
}
triggerNow (e) {
if (e) {
e.preventDefault()
}
if (this.props.isEnabled) {
if (t... | {
this.trigger()
secondsElapsed = 0
} | conditional_block |
index.js | import React from 'react'
import {HOC, Link} from 'cerebral-view-react'
import PageProgress from '../PageProgress'
// View
class AutoReload extends React.Component {
constructor (props) {
super(props)
this.state = {
secondsElapsed: 0
}
this.onInterval = this.onInterval.bind(this)
}
compone... | -------------------------<br />
<Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br />
--<br />
<Link signal={signals.app.reload.reloadingEnabled}>clickmeto_<b>enable</b>_reloading</Link><br />
--<br />
<Link signal... | {
const signals = this.props.signals
const progress = {
isEnabled: this.props.isEnabled,
elapsed: this.state.secondsElapsed,
total: this.props.triggerAfterSeconds
}
return (
<div>
<PageProgress {...progress} />
<hr />
<pre>
BastardAutoloaderFromH... | identifier_body |
index.js | import React from 'react'
import {HOC, Link} from 'cerebral-view-react'
import PageProgress from '../PageProgress'
// View
class | extends React.Component {
constructor (props) {
super(props)
this.state = {
secondsElapsed: 0
}
this.onInterval = this.onInterval.bind(this)
}
componentWillMount () {
this.intervals = []
}
componentWillUnmount () {
this.intervals.forEach(clearInterval)
}
componentDidMount ()... | AutoReload | identifier_name |
doctor_attentions_diseases_inherit.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 GN... | def _check_duplicated_disease(self, cr, uid, ids, context=None):
'''
verify duplicated disease
'''
for r in self.browse(cr, uid, ids, context=context):
diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_id','=',r.diseases_id.id)])
... | _name = "doctor.attentions.diseases"
_inherit = 'doctor.attentions.diseases'
_columns = {
}
def _check_main_disease(self, cr, uid, ids, context=None):
'''
verify there's only one main disease
'''
for r in self.browse(cr, uid, ids, context=context):
... | identifier_body |
doctor_attentions_diseases_inherit.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 GN... |
return True
def _check_duplicated_disease(self, cr, uid, ids, context=None):
'''
verify duplicated disease
'''
for r in self.browse(cr, uid, ids, context=context):
diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_id','=... | return False | conditional_block |
doctor_attentions_diseases_inherit.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 GN... | (self, cr, uid, ids, context=None):
'''
verify there's only one main disease
'''
for r in self.browse(cr, uid, ids, context=context):
diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_type','=','main')])
if len(diseases_i... | _check_main_disease | identifier_name |
doctor_attentions_diseases_inherit.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 GN... | if len(diseases_ids) > 1:
return False
return True
def _check_duplicated_disease(self, cr, uid, ids, context=None):
'''
verify duplicated disease
'''
for r in self.browse(cr, uid, ids, context=context):
diseases_ids = self.search(... | random_line_split | |
util.rs | use std::str;
use nom::{self, InputLength, IResult, Needed};
pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> {
if input.len() < len {
return Err(nom::Err::Incomplete(Needed::Size(len))); |
for i in 0..len {
match input[i] {
0 => {
// This is the end
let s = unsafe { str::from_utf8_unchecked(&input[..i]) };
return Ok((&input[len..], s));
}
32 ... 126 => {
// OK
}
_ => {
... | } | random_line_split |
util.rs | use std::str;
use nom::{self, InputLength, IResult, Needed};
pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> {
if input.len() < len {
return Err(nom::Err::Incomplete(Needed::Size(len)));
}
for i in 0..len {
match input[i] {
0 => {
/... |
_ => {
// Totally bogus character
return Err(nom::Err::Error(nom::Context::Code(&input[i..], nom::ErrorKind::Custom(0))));
}
}
}
Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) }))
}
/// Like nom's eof!(), except it actually... | {
// OK
} | conditional_block |
util.rs | use std::str;
use nom::{self, InputLength, IResult, Needed};
pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> | }
Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) }))
}
/// Like nom's eof!(), except it actually works on buffers -- which means it won't work on streams
pub fn naive_eof(input: &[u8]) -> IResult<&[u8], ()> {
if input.input_len() == 0 {
Ok((input, ()))
} else {
E... | {
if input.len() < len {
return Err(nom::Err::Incomplete(Needed::Size(len)));
}
for i in 0..len {
match input[i] {
0 => {
// This is the end
let s = unsafe { str::from_utf8_unchecked(&input[..i]) };
return Ok((&input[len..], s));
... | identifier_body |
util.rs | use std::str;
use nom::{self, InputLength, IResult, Needed};
pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> {
if input.len() < len {
return Err(nom::Err::Incomplete(Needed::Size(len)));
}
for i in 0..len {
match input[i] {
0 => {
/... | (input: &[u8]) -> IResult<&[u8], ()> {
if input.input_len() == 0 {
Ok((input, ()))
} else {
Err(nom::Err::Error(error_position!(input, nom::ErrorKind::Eof::<u32>)))
}
}
| naive_eof | identifier_name |
mod.rs | // Copyright 2020 The Exonum Team
//
// 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... | entry::Entry,
group::Group,
iter::{Entries, IndexIterator, Keys, Values},
key_set::KeySetIndex,
list::ListIndex,
map::MapIndex,
proof_entry::ProofEntry,
sparse_list::SparseListIndex,
value_set::ValueSetIndex,
};
mod entry;
mod group;
mod iter;
mod key_set;
mod list;
mod map;
mod pro... | pub use self::{ | random_line_split |
methodManager.py | minimization.")
# parser.add_argument("-B", "--blockyModel", dest="blockyModel",
# action="store_true", default=False,
# help="Blocky model (L1 norm) regularization.")
parser.add_argument('-l', "--lambda", dest="lam", type=float,
... | random_line_split | ||
methodManager.py | , ax=None, **kwargs):
"""Show the last inversion result.
TODO
----
DRY: decide showModel or showResult
Parameters
----------
ax : mpl axes
Axes object to draw into. Create a new if its not given.
model : iterable [None]
Model va... | self.fop.setRegionProperties('*', limits=limits) | conditional_block | |
methodManager.py | if fop is None:
pg.critical("It seems that createForwardOperator method "
"does not return a valid forward operator.")
if self.fw is not None:
self.fw.reset()
self.fw.setForwardOperator(fop)
else:
pg.critical("No inversion framewor... |
def setData(self, data):
"""Set a data and distribute it to the forward operator"""
self.data = data
self.applyData(data)
def applyData(self, data):
""" """
self.fop.data = data
def checkData(self, data):
"""Overwrite for special checks to return data valu... | ra = self.fop.response(par=model)
noiseLevel = kwargs.pop('noiseLevel', 0.0)
if noiseLevel > 0:
err = self.estimateError(ra, errLevel=noiseLevel)
ra *= 1. + pg.randn(ra.size(), seed=kwargs.pop('seed', None)) * err
return ra, err
return ra | identifier_body |
methodManager.py | y model (L1 norm) regularization.")
parser.add_argument('-l', "--lambda", dest="lam", type=float,
default=100,
help="Regularization strength.")
parser.add_argument('-i', "--maxIter", dest="maxIter", type=int,
default=20,... | _init__( | identifier_name | |
edu_dp_o.py | import sys
import ctypes
def popcount(N):
if sys.platform.startswith('linux'):
libc = ctypes.cdll.LoadLibrary('libc.so.6')
return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N))
elif sys.platform == 'darwin':
libc = ctypes.cdll.LoadLibrary('libSystem.dylib')... |
if __name__ == '__main__':
main()
| N = int(input())
mod = 10 ** 9 + 7
A = [[int(x) for x in input().split()] for _ in range(N)]
dp = [0] * (1 << N)
dp[0] = 1
for state in range(1 << N):
dp[state] %= mod
i = popcount(state)
for j in range(N):
if (state >> j & 1) == 0 and A[i][j]:
dp[... | identifier_body |
edu_dp_o.py | import sys
import ctypes
def popcount(N):
if sys.platform.startswith('linux'):
libc = ctypes.cdll.LoadLibrary('libc.so.6')
return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N))
elif sys.platform == 'darwin':
libc = ctypes.cdll.LoadLibrary('libSystem.dylib')... | ():
N = int(input())
mod = 10 ** 9 + 7
A = [[int(x) for x in input().split()] for _ in range(N)]
dp = [0] * (1 << N)
dp[0] = 1
for state in range(1 << N):
dp[state] %= mod
i = popcount(state)
for j in range(N):
if (state >> j & 1) == 0 and A[i][j]:
... | main | identifier_name |
edu_dp_o.py | import sys
import ctypes
def popcount(N):
if sys.platform.startswith('linux'):
|
elif sys.platform == 'darwin':
libc = ctypes.cdll.LoadLibrary('libSystem.dylib')
return libc.__popcountdi2(N)
else:
assert(False)
def main():
N = int(input())
mod = 10 ** 9 + 7
A = [[int(x) for x in input().split()] for _ in range(N)]
dp = [0] * (1 << N)
dp[0] = 1
... | libc = ctypes.cdll.LoadLibrary('libc.so.6')
return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N)) | conditional_block |
edu_dp_o.py | import sys
import ctypes
def popcount(N):
if sys.platform.startswith('linux'):
libc = ctypes.cdll.LoadLibrary('libc.so.6')
return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N))
elif sys.platform == 'darwin': |
def main():
N = int(input())
mod = 10 ** 9 + 7
A = [[int(x) for x in input().split()] for _ in range(N)]
dp = [0] * (1 << N)
dp[0] = 1
for state in range(1 << N):
dp[state] %= mod
i = popcount(state)
for j in range(N):
if (state >> j & 1) == 0 and A[i][j]:
... | libc = ctypes.cdll.LoadLibrary('libSystem.dylib')
return libc.__popcountdi2(N)
else:
assert(False) | random_line_split |
tables.py | import logging
from django.utils.html import format_html
import django_tables2 as tables
from django_tables2.rows import BoundPinnedRow, BoundRow
logger = logging.getLogger(__name__)
# A cheat to force BoundPinnedRows to use the same rendering as BoundRows
# otherwise links don't work
# BoundPinnedRow._get_and_ren... |
except ValueError:
continue
# Use self.text as a format string
if self.text:
return self.text.format(instance=instance, record=record,
value=value)
else:
return str(instance)
... | raise ValueError | conditional_block |
tables.py | import logging
from django.utils.html import format_html
import django_tables2 as tables
from django_tables2.rows import BoundPinnedRow, BoundRow
logger = logging.getLogger(__name__)
# A cheat to force BoundPinnedRows to use the same rendering as BoundRows
# otherwise links don't work
# BoundPinnedRow._get_and_ren... |
class CurrencyColumn(tables.Column):
"""Render a table column as GBP."""
def render(self, value):
return f'£{value:,.2f}'
class NumberColumn(tables.Column):
"""Only render decimal places if necessary."""
def render(self, value):
if value is not None:
return f'{value:n}'
... | class Meta(BaseTable.Meta):
exclude = ('id',) | identifier_body |
tables.py | import logging
from django.utils.html import format_html
import django_tables2 as tables
from django_tables2.rows import BoundPinnedRow, BoundRow
logger = logging.getLogger(__name__)
# A cheat to force BoundPinnedRows to use the same rendering as BoundRows
# otherwise links don't work
# BoundPinnedRow._get_and_ren... | exclude = ('id',)
class CurrencyColumn(tables.Column):
"""Render a table column as GBP."""
def render(self, value):
return f'£{value:,.2f}'
class NumberColumn(tables.Column):
"""Only render decimal places if necessary."""
def render(self, value):
if value is not None:
... | class Meta(BaseTable.Meta): | random_line_split |
tables.py | import logging
from django.utils.html import format_html
import django_tables2 as tables
from django_tables2.rows import BoundPinnedRow, BoundRow
logger = logging.getLogger(__name__)
# A cheat to force BoundPinnedRows to use the same rendering as BoundRows
# otherwise links don't work
# BoundPinnedRow._get_and_ren... | self, value):
if value is not None:
return f'{value:n}'
class ColorColumn(tables.Column):
"""Render the colour in a box."""
def __init__(self, *args, **kwargs):
"""This will ignore other attrs passed in."""
kwargs.setdefault('attrs', {'td': {'class': "small-width text-cente... | ender( | identifier_name |
game.js | /* Game namespace */
var game = {
// an object where to store game information
data : {
// score
score : 0
},
// Run on page load.
"onload" : function () {
// Initialize the video.
if (!me.video.init("screen", me.video.CANVAS, 1067, 600, true, '1.0')) {
alert("Your browser does not support HTML5 canv... | }
// Initialize the audio.
me.audio.init("mp3,ogg");
// Set a callback to run when loading is complete.
me.loader.onload = this.loaded.bind(this);
// Load the resources.
me.loader.preload(game.resources);
// Initialize melonJS and display a loading screen.
me.state.change(me.state.LOADING);
},
// Run on ... | // add "#debug" to the URL to enable the debug Panel
if (document.location.hash === "#debug") {
window.onReady(function () {
me.plugin.register.defer(this, debugPanel, "debug");
}); | random_line_split |
game.js |
/* Game namespace */
var game = {
// an object where to store game information
data : {
// score
score : 0
},
// Run on page load.
"onload" : function () {
// Initialize the video.
if (!me.video.init("screen", me.video.CANVAS, 1067, 600, true, '1.0')) |
// add "#debug" to the URL to enable the debug Panel
if (document.location.hash === "#debug") {
window.onReady(function () {
me.plugin.register.defer(this, debugPanel, "debug");
});
}
// Initialize the audio.
me.audio.init("mp3,ogg");
// Set a callback to run when loading is complete.
me.loader.onload... | {
alert("Your browser does not support HTML5 canvas.");
return;
} | conditional_block |
declaration.js | 'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writabl... | ,
set: function set(val) {
(0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value');
this.raws.value = val;
}
/* istanbul ignore next */
}, {
key: '_important',
get: function get() {
(0, _warnOnce2.default)('Node... | }
/* istanbul ignore next */ | random_line_split |
declaration.js | 'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writabl... | (defaults) {
_classCallCheck(this, Declaration);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'decl';
return _this;
}
/* istanbul ignore next */
_createClass(Declaration, [{
key: '_value',
get: function get() {
... | Declaration | identifier_name |
declaration.js | 'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writabl... |
var Declaration = function (_Node) {
_inherits(Declaration, _Node);
function Declaration(defaults) {
_classCallCheck(this, Declaration);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'decl';
return _this;
}
/* istanbul ignore... | { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable... | identifier_body |
pico.js | /**
* Pico's Default Theme - JavaScript helper
*
* Pico is a stupidly simple, blazing fast, flat file CMS.
*
* @author Daniel Rudolf
* @link http://picocms.org
* @license http://opensource.org/licenses/MIT The MIT License
* @version 1.1
*/
function main()
{
// capability CSS classes
document.docum... |
};
window.addEventListener('resize', onResizeEvent);
onResizeEvent();
}
main();
| {
menu.className = '';
menu.removeAttribute('data-slide-id');
menuToggle.removeEventListener('click', toggleMenuEvent);
menuToggle.removeEventListener('keydown', toggleMenuEvent);
} | conditional_block |
pico.js | /**
* Pico's Default Theme - JavaScript helper
*
* Pico is a stupidly simple, blazing fast, flat file CMS.
*
* @author Daniel Rudolf
* @link http://picocms.org
* @license http://opensource.org/licenses/MIT The MIT License
* @version 1.1
*/
function main()
{
// capability CSS classes
document.docum... | tableWrapper.appendChild(tables[i]);
}
}
// responsive menu
var menu = document.getElementById('nav'),
menuToggle = document.getElementById('nav-toggle'),
toggleMenuEvent = function (event) {
if (event.type === 'keydown') {
if ((event.keyCode ... | var tableWrapper = document.createElement('div');
tableWrapper.className = 'table-responsive';
tables[i].parentElement.insertBefore(tableWrapper, tables[i]); | random_line_split |
pico.js | /**
* Pico's Default Theme - JavaScript helper
*
* Pico is a stupidly simple, blazing fast, flat file CMS.
*
* @author Daniel Rudolf
* @link http://picocms.org
* @license http://opensource.org/licenses/MIT The MIT License
* @version 1.1
*/
function main()
| if (event.type === 'keydown') {
if ((event.keyCode != 13) && (event.keyCode != 32)) {
return;
}
}
event.preventDefault();
if (menuToggle.getAttribute('aria-expanded') === 'false') {
menuToggle.setAttrib... | {
// capability CSS classes
document.documentElement.className = 'js';
// wrap tables
var tables = document.querySelectorAll('#main > .container > table');
for (var i = 0; i < tables.length; i++) {
if (!/\btable-responsive\b/.test(tables[i].parentElement.className)) {
var tableW... | identifier_body |
pico.js | /**
* Pico's Default Theme - JavaScript helper
*
* Pico is a stupidly simple, blazing fast, flat file CMS.
*
* @author Daniel Rudolf
* @link http://picocms.org
* @license http://opensource.org/licenses/MIT The MIT License
* @version 1.1
*/
function | ()
{
// capability CSS classes
document.documentElement.className = 'js';
// wrap tables
var tables = document.querySelectorAll('#main > .container > table');
for (var i = 0; i < tables.length; i++) {
if (!/\btable-responsive\b/.test(tables[i].parentElement.className)) {
var tab... | main | identifier_name |
test_tahoelafs.py | #!/usr/bin/python
"""
Test the TahoeLAFS
@author: Marek Palatinus <marek@palatinus.cz>
"""
import sys
import logging
import unittest
from fs.base import FS
import fs.errors as errors
from fs.tests import FSTestCases, ThreadingTestCases
from fs.contrib.tahoelafs import TahoeLAFS, Connection
... |
def tearDown(self):
self.fs.close()
def test_dircap(self):
# Is dircap in correct format?
self.assert_(self.dircap.startswith('URI:DIR2:') and len(self.dircap) > 50)
def test_concurrent_copydir(self):
# makedir() on TahoeLAFS is curre... | self.dircap = TahoeLAFS.createdircap(WEBAPI)
self.fs = TahoeLAFS(self.dircap, cache_timeout=0, webapi=WEBAPI) | identifier_body |
test_tahoelafs.py | #!/usr/bin/python
"""
Test the TahoeLAFS
@author: Marek Palatinus <marek@palatinus.cz>
"""
import sys
import logging
import unittest
from fs.base import FS
import fs.errors as errors
from fs.tests import FSTestCases, ThreadingTestCases
from fs.contrib.tahoelafs import TahoeLAFS, Connection
... | unittest.main() | conditional_block | |
test_tahoelafs.py | #!/usr/bin/python
"""
Test the TahoeLAFS
@author: Marek Palatinus <marek@palatinus.cz>
"""
import sys
import logging
import unittest
from fs.base import FS
import fs.errors as errors
from fs.tests import FSTestCases, ThreadingTestCases
from fs.contrib.tahoelafs import TahoeLAFS, Connection
... | (self):
pass
if __name__ == '__main__':
unittest.main()
| test_big_file | identifier_name |
test_tahoelafs.py | #!/usr/bin/python
"""
Test the TahoeLAFS
@author: Marek Palatinus <marek@palatinus.cz>
"""
import sys
import logging
import unittest
from fs.base import FS
import fs.errors as errors
from fs.tests import FSTestCases, ThreadingTestCases
from fs.contrib.tahoelafs import TahoeLAFS, Connection
... | def test_big_file(self):
pass
if __name__ == '__main__':
unittest.main() | random_line_split | |
models.py | .fields.related_descriptors import ForwardManyToOneDescriptor
except ImportError:
from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor
from django.utils.encoding import python_2_unicode_compatible
import logging
logger = logging.getLogger(__name__)
# Pytho... | (self):
if self.formatted != '':
txt = '%s'%self.formatted
elif self.locality:
txt = ''
if self.street_number:
txt = '%s'%self.street_number
if self.route:
if txt:
txt += ' %s'%self.route
loca... | __str__ | identifier_name |
models.py | .fields.related_descriptors import ForwardManyToOneDescriptor
except ImportError:
from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor
from django.utils.encoding import python_2_unicode_compatible
import logging
logger = logging.getLogger(__name__)
# Pytho... |
else:
state_obj = None
# Handle the locality.
try:
locality_obj = Locality.objects.get(name=locality, state=state_obj)
except Locality.DoesNotExist:
if locality:
locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj)
... | if len(state_code) > State._meta.get_field('code').max_length:
if state_code != state:
raise ValueError('Invalid state code (too long): %s'%state_code)
state_code = ''
state_obj = State.objects.create(name=state, code=state_code, country=country_obj) | conditional_block |
models.py | .fields.related_descriptors import ForwardManyToOneDescriptor
except ImportError:
from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor
from django.utils.encoding import python_2_unicode_compatible
import logging
logger = logging.getLogger(__name__)
# Pytho... |
def __str__(self):
txt = '%s'%self.name
state = self.state.to_str() if self.state else ''
if txt and state:
txt += ', '
txt += state
if self.postal_code:
txt += ' %s'%self.postal_code
cntry = '%s'%(self.state.country if self.state and self.st... | verbose_name_plural = 'Localities'
unique_together = ('name', 'state')
ordering = ('state', 'name') | identifier_body |
models.py | .fields.related_descriptors import ForwardManyToOneDescriptor
except ImportError:
from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor
from django.utils.encoding import python_2_unicode_compatible
import logging
logger = logging.getLogger(__name__)
# Pytho... | if not address_obj.formatted:
address_obj.formatted = unicode(address_obj)
# Need to save.
address_obj.save()
# Done.
return address_obj
##
## Convert a dictionary to an address.
##
def to_python(value):
# Keep `None`s.
if value is None:
return None
#... | )
# If "formatted" is empty try to construct it from other values. | random_line_split |
utils.py | # -*- coding: utf-8 -*-
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------... |
def commonprefix(paths):
""" Find common directory for all paths
Python's ``os.path.commonprefix`` will not return a valid directory path in
some cases, so we wrote this convenience method.
Examples
--------
>>> # os.path.commonprefix returns '/disk1/foo'
>>> commonprefix(['/disk1/foob... | """ Deterministic token
>>> tokenize('Hello') == tokenize('Hello')
True
"""
if kwargs:
args = args + (kwargs,)
return md5(str(tuple(args)).encode()).hexdigest() | identifier_body |
utils.py | # -*- coding: utf-8 -*-
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------... |
return bytes
def tokenize(*args, **kwargs):
""" Deterministic token
>>> tokenize('Hello') == tokenize('Hello')
True
"""
if kwargs:
args = args + (kwargs,)
return md5(str(tuple(args)).encode()).hexdigest()
def commonprefix(paths):
""" Find common directory for all paths
... | max_record = 2**22
if length > max_record:
raise IndexError('Records larger than ' + str(max_record) + ' bytes are not supported. The length requested was: ' + str(length) + 'bytes')
# get the last index of the delimiter if it exists
try:
last_delim_index = len(bytes) -1 ... | conditional_block |
utils.py | # -*- coding: utf-8 -*-
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------... | (*args, **kwargs):
""" Deterministic token
>>> tokenize('Hello') == tokenize('Hello')
True
"""
if kwargs:
args = args + (kwargs,)
return md5(str(tuple(args)).encode()).hexdigest()
def commonprefix(paths):
""" Find common directory for all paths
Python's ``os.path.commonprefix... | tokenize | identifier_name |
utils.py | # -*- coding: utf-8 -*-
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------... |
>>> commonprefix(['a/b/c', 'd/e/f', 'g/h/i'])
''
"""
return os.path.dirname(os.path.commonprefix(paths))
def clamp(n, smallest, largest):
""" Limit a value to a given range
This is equivalent to smallest <= n <= largest.
Examples
--------
>>> clamp(0, 1, 100)
1
>>> cla... | '/disk1'
>>> commonprefix(['a/b/c', 'a/b/d', 'a/c/d'])
'a' | random_line_split |
client_stress_test.rs | the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//... | else {
println!("\n\tAccount Creation");
println!("\t================");
println!("\nTrying to create an account ...");
unwrap!(Client::registered(
&secret_0,
&secret_1,
&invitation,
el_h,
core_tx.clone(),
net_tx,
... | {
unwrap!(Client::login(
&secret_0,
&secret_1,
el_h,
core_tx.clone(),
net_tx,
))
} | conditional_block |
client_stress_test.rs | Software.
//! Safe client example.
// For explanation of lint checks, run `rustc -W help` or see
// https://github.
// com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md
#![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items,
unknown_crate_types, warnings)]
#![de... | .into_box()
.into() | random_line_split | |
client_stress_test.rs | the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//... | () {
unwrap!(maidsafe_utilities::log::init(true));
let args: Args = Docopt::new(USAGE)
.and_then(|docopt| docopt.decode())
.unwrap_or_else(|error| error.exit());
let immutable_data_count = unwrap!(args.flag_immutable);
let mutable_data_count = unwrap!(args.flag_mutable);
let mut rn... | main | identifier_name |
page.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... |
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
// Child Pages.
pub children: DOMRefCell<Vec<Rc<Page>>>,
}
pub struct PageIterator {
stack: Vec<Rc<Page>>,
}
pub trait IterablePage {
fn iter(&self) -> PageIterator;
fn find(&self, id: PipelineId) -> Option<Rc<... | id: PipelineId,
/// The outermost frame containing the document and window.
frame: DOMRefCell<Option<Frame>>, | random_line_split |
page.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... | (&self, id: PipelineId) -> Option<Rc<Page>> {
let remove_idx = {
self.children
.borrow_mut()
.iter_mut()
.position(|page_tree| page_tree.id == id)
};
match remove_idx {
Some(idx) => Some(self.children.borrow_mut().remove(idx... | remove | identifier_name |
plugin.py | # -*- coding: utf-8 -*-
"""
Base Class for InvenTree plugins
"""
import warnings
from django.db.utils import OperationalError, ProgrammingError
from django.utils.text import slugify
class InvenTreePluginBase():
"""
Base class for a plugin
DO NOT USE THIS DIRECTLY, USE plugin.IntegrationPluginBase
"""... |
# TODO @matmair remove after InvenTree 0.7.0 release
class InvenTreePlugin(InvenTreePluginBase):
"""
This is here for leagcy reasons and will be removed in the next major release
"""
def __init__(self):
warnings.warn("Using the InvenTreePlugin is depreceated", DeprecationWarning)
supe... | return False | conditional_block |
plugin.py | # -*- coding: utf-8 -*-
"""
Base Class for InvenTree plugins
"""
import warnings
from django.db.utils import OperationalError, ProgrammingError
from django.utils.text import slugify
class InvenTreePluginBase():
"""
Base class for a plugin
DO NOT USE THIS DIRECTLY, USE plugin.IntegrationPluginBase
"""... | """
cfg = self.plugin_config()
if cfg:
return cfg.active
else:
return False
# TODO @matmair remove after InvenTree 0.7.0 release
class InvenTreePlugin(InvenTreePluginBase):
"""
This is here for leagcy reasons and will be removed in the next major relea... |
def is_active(self):
"""
Return True if this plugin is currently active | random_line_split |
plugin.py | # -*- coding: utf-8 -*-
"""
Base Class for InvenTree plugins
"""
import warnings
from django.db.utils import OperationalError, ProgrammingError
from django.utils.text import slugify
class InvenTreePluginBase():
"""
Base class for a plugin
DO NOT USE THIS DIRECTLY, USE plugin.IntegrationPluginBase
"""... | (self, raise_error=False):
"""
Return the PluginConfig object associated with this plugin
"""
try:
import plugin.models
cfg, _ = plugin.models.PluginConfig.objects.get_or_create(
key=self.plugin_slug(),
name=self.plugin_name(),
... | plugin_config | identifier_name |
plugin.py | # -*- coding: utf-8 -*-
"""
Base Class for InvenTree plugins
"""
import warnings
from django.db.utils import OperationalError, ProgrammingError
from django.utils.text import slugify
class InvenTreePluginBase():
"""
Base class for a plugin
DO NOT USE THIS DIRECTLY, USE plugin.IntegrationPluginBase
"""... | """
This is here for leagcy reasons and will be removed in the next major release
"""
def __init__(self):
warnings.warn("Using the InvenTreePlugin is depreceated", DeprecationWarning)
super().__init__() | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.