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 |
|---|---|---|---|---|
subscriptions.js | //Meteor.subscribe('a_collection');
searchTextPatients = new ReactiveVar();
searchTextPatients.set('');
Tracker.autorun(function() {
Meteor.subscribe('patients', searchTextPatients.get());
});
searchTextVisits = new ReactiveVar();
searchTextVisits.set('');
Tracker.autorun(function() {
Meteor.subscribe('visits',... | scheduler.init("scheduler_here", new Date());
scheduler.load("./visits.xml");
}); | random_line_split | |
DiscountFilter.tsx | import * as React from 'react'
import produce from 'immer'
import styled from 'styled-components'
import { dev, parsePathname } from '../utils'
import { Color } from '../config'
import { fillBookPrice } from '../scripts/general'
function flatten<T>(arr: T[], next: T|T[]) : T[] {
if (Array.isArray(next)) {
return... | st { checker, counter } = this.state
return (
<form >
<Label style={{ color: Color.Red }}>
<input type="checkbox" checked={ checker.notWorth } onChange={ this.onCheck('notWorth') } />
显示高于最低价格的书籍({ counter.notWorth })
</Label>
<Label style={{ color: Color.Blue }}>
... | con | identifier_name |
DiscountFilter.tsx | import * as React from 'react'
import produce from 'immer'
import styled from 'styled-components'
import { dev, parsePathname } from '../utils' | import { fillBookPrice } from '../scripts/general'
function flatten<T>(arr: T[], next: T|T[]) : T[] {
if (Array.isArray(next)) {
return [...arr, ...next.reduce((arr: T[], next: T|T[]) => flatten(arr, next), [])]
}
return [...arr, next]
}
function addBookElementObserver(listener: (anchorList: HTMLAnchorEleme... | import { Color } from '../config' | random_line_split |
DiscountFilter.tsx | import * as React from 'react'
import produce from 'immer'
import styled from 'styled-components'
import { dev, parsePathname } from '../utils'
import { Color } from '../config'
import { fillBookPrice } from '../scripts/general'
function flatten<T>(arr: T[], next: T|T[]) : T[] |
function addBookElementObserver(listener: (anchorList: HTMLAnchorElement[]) => void) {
new MutationObserver(mutations => {
const elements = mutations
.map(mutation => mutation.addedNodes)
.filter(nodes => nodes.length > 0)
.map(nodes => Array.from(nodes))
.reduce(flatten, [])
.filt... | {
if (Array.isArray(next)) {
return [...arr, ...next.reduce((arr: T[], next: T|T[]) => flatten(arr, next), [])]
}
return [...arr, next]
} | identifier_body |
DiscountFilter.tsx | import * as React from 'react'
import produce from 'immer'
import styled from 'styled-components'
import { dev, parsePathname } from '../utils'
import { Color } from '../config'
import { fillBookPrice } from '../scripts/general'
function flatten<T>(arr: T[], next: T|T[]) : T[] {
if (Array.isArray(next)) {
return... | e {
if (isCostEffective) {
costEffective++
} else if (isNoLoss) {
noLoss++
} else if (isNotWorth) {
notWorth++
}
}
if ((isCostEffective && !this.state.checker.costEffective)
|| (isNoLoss && !this.state.checker.noLoss)
|| (isNotWorth ... | shouldDisplay = false
}
} els | conditional_block |
bundle.py | # SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
'''
Bundle a context and its packages into a relocatable dir.
'''
from __future__ import print_function
import os
import os.path
import sys
def setup_parser(parser, completions=False):
group = parser.add_mutually_exclusive_group(... |
rxt_filepath = os.path.abspath(os.path.expanduser(opts.RXT))
dest_dir = os.path.abspath(os.path.expanduser(opts.DEST_DIR))
# sanity checks
if not os.path.exists(rxt_filepath):
print_error("File does not exist: %s", rxt_filepath)
sys.exit(1)
context = ResolvedContext.load(rxt_filep... | from rez.resolved_context import ResolvedContext | random_line_split |
bundle.py | # SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
'''
Bundle a context and its packages into a relocatable dir.
'''
from __future__ import print_function
import os
import os.path
import sys
def setup_parser(parser, completions=False):
|
def command(opts, parser, extra_arg_groups=None):
from rez.utils.logging_ import print_error
from rez.bundle_context import bundle_context
from rez.resolved_context import ResolvedContext
rxt_filepath = os.path.abspath(os.path.expanduser(opts.RXT))
dest_dir = os.path.abspath(os.path.expanduser(o... | group = parser.add_mutually_exclusive_group()
group.add_argument(
"-s", "--skip-non-relocatable", action="store_true",
help="leave non-relocatable packages non-bundled, rather than raise an error")
group.add_argument(
"-f", "--force", action="store_true",
help="bundle package eve... | identifier_body |
bundle.py | # SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
'''
Bundle a context and its packages into a relocatable dir.
'''
from __future__ import print_function
import os
import os.path
import sys
def setup_parser(parser, completions=False):
group = parser.add_mutually_exclusive_group(... |
context = ResolvedContext.load(rxt_filepath)
bundle_context(
context=context,
dest_dir=dest_dir,
force=opts.force,
skip_non_relocatable=opts.skip_non_relocatable,
verbose=opts.verbose,
patch_libs=(not opts.no_lib_patch)
)
| print_error("File does not exist: %s", rxt_filepath)
sys.exit(1) | conditional_block |
bundle.py | # SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
'''
Bundle a context and its packages into a relocatable dir.
'''
from __future__ import print_function
import os
import os.path
import sys
def | (parser, completions=False):
group = parser.add_mutually_exclusive_group()
group.add_argument(
"-s", "--skip-non-relocatable", action="store_true",
help="leave non-relocatable packages non-bundled, rather than raise an error")
group.add_argument(
"-f", "--force", action="store_true",... | setup_parser | identifier_name |
lib.rs | From!`](./macros/index.html#tryfrom!) - derives an implementation of [`TryFrom`](./trait.TryFrom.html).
If you are implementing your own types, you may also be interested in the traits contained in the [`misc`](./misc/index.html) module.
## Provided Implementations
The crate provides several blanket implementations:... | # Examples
```
# extern crate conv;
# use conv::*;
# fn main() {
// This *cannot* fail, so we can use `unwrap_ok` to discard the `Result`.
assert_eq!(u8::value_from(0u8).unwrap_ok(), 0u8);
// This *can* fail. Specifically, it can underflow.
assert_eq!(u8::value_from(0i8), Ok(0u8));
assert_eq!(u8::value_from(-1i8... | random_line_split | |
lib.rs | ));
assert_eq!(u8::value_from(256i16), Err(RangeError::Overflow));
// We can use the extension traits to simplify this a little.
assert_eq!(u8::value_from(-1i16).unwrap_or_saturate(), 0u8);
assert_eq!(u8::value_from(0i16).unwrap_or_saturate(), 0u8);
assert_eq!(u8::value_from(256i16).unwrap_or_saturate(), 255u8);
... | mpl Appr | identifier_name | |
lib.rs | errors`](./errors/index.html) module. Generally, conversions use whichever error type most *narrowly* defines the kinds of failures that can occur. For example:
- `ValueFrom<u8> for u16` cannot possibly fail, and as such it uses `NoError`.
- `ValueFrom<i8> for u16` can *only* fail with an underflow, thus it uses the... | src)
}
}
/**
This | identifier_body | |
migrateToPostgres.ts | /*
Copyright 2019 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in ... |
if (!user.slack_id || !user.team_id) {
const localpart = user.id.split(":")[0];
// XXX: we are making an assumption here that the prefix ends with _
const parts = localpart.slice(USER_PREFIX.length + 1).split("_"); // Remove any prefix.
// If we encounter more pa... | {
// Cannot migrate without ID.
return;
} | conditional_block |
migrateToPostgres.ts | /*
Copyright 2019 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in ... | new UserBridgeStore(userStore),
new RoomBridgeStore(roomStore),
new EventBridgeStore(eventStore),
teamStore,
);
try {
const startedAt = Date.now();
await migrateFromNedb(nedb, pgres);
log.info(`Completed migration in ${Math.round(Date.now() - startedAt)}ms... | log.error("Ensure you have given the correct path to the database.");
throw ex;
}
const nedb = new NedbDatastore( | random_line_split |
Search.ts | import {Observer} from "../common/Observer";
export class Search {
private _changeQueryObserver: Observer<string>;
private _keyDownObserver: Observer<string>;
private _query: string;
constructor() {
this._changeQueryObserver = new Observer();
this._keyDownObserver = new Observer();
this.triggerQue... | (): string {
return this._query;
}
public triggerQueryChange(newQuery: string): void {
this._query = newQuery;
this._changeQueryObserver.trigger(newQuery);
}
public triggerKeyDown(event: any): void {
this._keyDownObserver.trigger(event);
}
public onQueryChange(callback: (string) => void) ... | query | identifier_name |
Search.ts | import {Observer} from "../common/Observer";
export class Search {
private _changeQueryObserver: Observer<string>;
private _keyDownObserver: Observer<string>;
private _query: string;
constructor() |
get query(): string {
return this._query;
}
public triggerQueryChange(newQuery: string): void {
this._query = newQuery;
this._changeQueryObserver.trigger(newQuery);
}
public triggerKeyDown(event: any): void {
this._keyDownObserver.trigger(event);
}
public onQueryChange(callback: (stri... | {
this._changeQueryObserver = new Observer();
this._keyDownObserver = new Observer();
this.triggerQueryChange = this.triggerQueryChange.bind(this);
this.triggerKeyDown = this.triggerKeyDown.bind(this);
} | identifier_body |
Search.ts | import {Observer} from "../common/Observer";
export class Search {
private _changeQueryObserver: Observer<string>;
private _keyDownObserver: Observer<string>;
private _query: string;
constructor() {
this._changeQueryObserver = new Observer();
this._keyDownObserver = new Observer();
this.triggerQue... | public onKeyPress(callback: (event) => void) {
return this._keyDownObserver.subscribe(callback);
}
} |
public onQueryChange(callback: (string) => void) {
return this._changeQueryObserver.subscribe(callback);
}
| random_line_split |
stmt.rs | of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or d... | (&mut self,
mut block: BasicBlock,
expr: Expr<'tcx>,
opt_stmt_span: Option<StatementSpan>)
-> BlockAnd<()>
{
let this = self;
let expr_span = expr.span;
let source_info = this.source_info(expr.span);
... | stmt_expr | identifier_name |
stmt.rs | of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or d... | let rhs = this.hir.mirror(rhs);
let lhs_span = lhs.span;
// Note: we evaluate assignments right-to-left. This
// is better for borrowck interaction with overloaded
// operators like x[j] = x[i].
debug!("stmt_expr Assign bl... | {
let this = self;
let expr_span = expr.span;
let source_info = this.source_info(expr.span);
// Handle a number of expressions that don't need a destination at all. This
// avoids needing a mountain of temporary `()` variables.
let expr2 = expr.clone();
match expr... | identifier_body |
stmt.rs | this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or dist... |
None => {
this.cfg
.push_assign_unit(block, source_info, &Place::Local(RETURN_PLACE));
block
}
};
let region_scope = this.region_scope_of_return_scope();
l... | {
debug!("stmt_expr Return val block_context.push(SubExpr) : {:?}", expr2);
this.block_context.push(BlockFrame::SubExpr);
let result = unpack!(this.into(&Place::Local(RETURN_PLACE), block, value));
this.block_context.pop();
... | conditional_block |
stmt.rs | of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or d... | .collect::<Vec<_>>()
.into_boxed_slice();
let inputs = inputs
.into_iter()
.map(|input| {
(
input.span(),
unpack!(block = this.as_local_operand(... | debug!("stmt_expr InlineAsm block_context.push(SubExpr) : {:?}", expr2);
this.block_context.push(BlockFrame::SubExpr);
let outputs = outputs
.into_iter()
.map(|output| unpack!(block = this.as_place(block, output))) | random_line_split |
conf.py | to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it ... | # directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entitie... | # Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied | random_line_split |
thread.rs | use alloc::boxed::Box;
use syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, CLONE_VM, CLONE_FS, CLONE_FILES, TimeSpec};
use time::Duration;
//TODO: Mutex the result
pub struct JoinHandle<T> {
result_ptr: *mut Option<T>,
}
impl<T> JoinHandle<T> {
pub fn join(self) -> Option<T> {
unsafe {
... | sys_yield();
}
* Box::from_raw(self.result_ptr)
}
}
}
// Sleep for a duration
pub fn sleep(duration: Duration) {
let req = TimeSpec {
tv_sec: duration.secs,
tv_nsec: duration.nanos,
};
let mut rem = TimeSpec {
tv_sec: 0,
... | random_line_split | |
thread.rs | use alloc::boxed::Box;
use syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, CLONE_VM, CLONE_FS, CLONE_FILES, TimeSpec};
use time::Duration;
//TODO: Mutex the result
pub struct JoinHandle<T> {
result_ptr: *mut Option<T>,
}
impl<T> JoinHandle<T> {
pub fn join(self) -> Option<T> {
unsafe {
... |
JoinHandle {
result_ptr: result_ptr
}
}
}
| {
*result_ptr = Some(f());
sys_exit(0);
} | conditional_block |
thread.rs | use alloc::boxed::Box;
use syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, CLONE_VM, CLONE_FS, CLONE_FILES, TimeSpec};
use time::Duration;
//TODO: Mutex the result
pub struct JoinHandle<T> {
result_ptr: *mut Option<T>,
}
impl<T> JoinHandle<T> {
pub fn join(self) -> Option<T> {
unsafe {
... |
// Sleep for a number of milliseconds
pub fn sleep_ms(ms: u32) {
let secs = ms as i64 / 1000;
let nanos = (ms % 1000) as i32 * 1000000;
sleep(Duration::new(secs, nanos))
}
//TODO: Catch panic
pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T, F: Send + 'static, T: Send + 'static {
unsa... | {
let req = TimeSpec {
tv_sec: duration.secs,
tv_nsec: duration.nanos,
};
let mut rem = TimeSpec {
tv_sec: 0,
tv_nsec: 0
};
unsafe { sys_nanosleep(&req, &mut rem) };
//Duration::new(rem.tv_sec, rem.tv_nsec)
} | identifier_body |
thread.rs | use alloc::boxed::Box;
use syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, CLONE_VM, CLONE_FS, CLONE_FILES, TimeSpec};
use time::Duration;
//TODO: Mutex the result
pub struct JoinHandle<T> {
result_ptr: *mut Option<T>,
}
impl<T> JoinHandle<T> {
pub fn join(self) -> Option<T> {
unsafe {
... | (ms: u32) {
let secs = ms as i64 / 1000;
let nanos = (ms % 1000) as i32 * 1000000;
sleep(Duration::new(secs, nanos))
}
//TODO: Catch panic
pub fn spawn<F, T>(f: F) -> JoinHandle<T> where F: FnOnce() -> T, F: Send + 'static, T: Send + 'static {
unsafe {
let result_ptr: *mut Option<T> = Box::into... | sleep_ms | identifier_name |
cs.py | import sqlite3
from typing import List
from pyspatial.cs import CoordinatesSystem, Axis, CoordinatesSystemType, AxisOrientation, AxisType
from pyspatial.uom import UnitOfMeasure
from . import db, EPSGException, make_id, parse_id
from .uom import get_unit
def get_coordinates_system(uid: str) -> CoordinatesSystem:
... |
def _get_cs_axes(cs_code: int, conn: sqlite3.Connection) -> List[Axis]:
c = conn.execute('SELECT a.coord_axis_order, '
'a.coord_axis_code, '
'n.coord_axis_name AS "axis_type [AxisType]", '
'a.coord_axis_abbreviation, '
'a.coord_a... | raise EPSGException(f"No coordinates system with uid '{make_id(code)}'") | conditional_block |
cs.py | import sqlite3
from typing import List
from pyspatial.cs import CoordinatesSystem, Axis, CoordinatesSystemType, AxisOrientation, AxisType
from pyspatial.uom import UnitOfMeasure
from . import db, EPSGException, make_id, parse_id
from .uom import get_unit
def get_coordinates_system(uid: str) -> CoordinatesSystem:
... | (self) -> str:
return self.__name
@property
def cs_type(self) -> CoordinatesSystemType:
return self.__cs_type
@property
def dimension(self) -> int:
return len(self.__axes)
def get_axis(self, dim: int) -> Axis:
return self.__axes[dim]
| name | identifier_name |
cs.py | import sqlite3
from typing import List
from pyspatial.cs import CoordinatesSystem, Axis, CoordinatesSystemType, AxisOrientation, AxisType
from pyspatial.uom import UnitOfMeasure
from . import db, EPSGException, make_id, parse_id
from .uom import get_unit
def get_coordinates_system(uid: str) -> CoordinatesSystem:
... |
@property
def name(self) -> str:
return self.__name
@property
def cs_type(self) -> CoordinatesSystemType:
return self.__cs_type
@property
def dimension(self) -> int:
return len(self.__axes)
def get_axis(self, dim: int) -> Axis:
return self.__axes[dim]
| return make_id(self.__code) | identifier_body |
cs.py | import sqlite3
from typing import List
from pyspatial.cs import CoordinatesSystem, Axis, CoordinatesSystemType, AxisOrientation, AxisType
from pyspatial.uom import UnitOfMeasure
from . import db, EPSGException, make_id, parse_id
from .uom import get_unit
def get_coordinates_system(uid: str) -> CoordinatesSystem:
... | def _get_cs_axes(cs_code: int, conn: sqlite3.Connection) -> List[Axis]:
c = conn.execute('SELECT a.coord_axis_order, '
'a.coord_axis_code, '
'n.coord_axis_name AS "axis_type [AxisType]", '
'a.coord_axis_abbreviation, '
'a.coord_axis... | return EPSGCoordinatesSystem(code, name, cs_type, axes)
else:
raise EPSGException(f"No coordinates system with uid '{make_id(code)}'")
| random_line_split |
jquery.smooth-scroll.js | (function($) {
var version = '1.4.13',
optionOverrides = {},
defaults = {
exclude: [],
excludeWithin:[],
offset: 0,
// one of 'top' or 'left'
direction: 'top',
// jQuery set of elements you wish to scroll (for $.smoothScroll).
// if null (default), $('html, body').fi... |
})(jQuery); | {
return str.replace(/(:|\.)/g,'\\$1');
} | identifier_body |
jquery.smooth-scroll.js | (function($) {
var version = '1.4.13',
optionOverrides = {},
defaults = {
exclude: [],
excludeWithin:[],
offset: 0,
// one of 'top' or 'left'
direction: 'top',
// jQuery set of elements you wish to scroll (for $.smoothScroll).
// if null (default), $('html, body').fi... | (str) {
return str.replace(/(:|\.)/g,'\\$1');
}
})(jQuery); | escapeSelector | identifier_name |
jquery.smooth-scroll.js | (function($) {
var version = '1.4.13',
optionOverrides = {},
defaults = {
exclude: [],
excludeWithin:[],
offset: 0,
// one of 'top' or 'left'
direction: 'top',
// jQuery set of elements you wish to scroll (for $.smoothScroll).
// if null (default), $('html, body').fi... | dir = opts.dir && opts.dir == 'left' ? 'scrollLeft' : 'scrollTop';
this.each(function() {
if (this == document || this == window) { return; }
var el = $(this);
if ( el[dir]() > 0 ) {
scrollable.push(this);
} else {
// if scroll(Top|Left) === 0, nudge... |
getScrollable = function(opts) {
var scrollable = [],
scrolled = false, | random_line_split |
jquery.smooth-scroll.js | (function($) {
var version = '1.4.13',
optionOverrides = {},
defaults = {
exclude: [],
excludeWithin:[],
offset: 0,
// one of 'top' or 'left'
direction: 'top',
// jQuery set of elements you wish to scroll (for $.smoothScroll).
// if null (default), $('html, body').fi... |
scrollDir = opts.direction == 'left' ? 'scrollLeft' : scrollDir;
if ( opts.scrollElement ) {
$scroller = opts.scrollElement;
if ( !(/^(?:HTML|BODY)$/).test($scroller[0].nodeName) ) {
scrollerOffset = $scroller[scrollDir]();
}
} else {
$scroller = $('html, body').firstScrollable(opts.direc... | {
opts = $.extend({link: null}, $.fn.smoothScroll.defaults, options || {}, optionOverrides);
if (opts.scrollElement) {
offPos = 'position';
if (opts.scrollElement.css('position') == 'static') {
opts.scrollElement.css('position', 'relative');
}
}
} | conditional_block |
test_base.py | # Copyright (c) 2016 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | self.assertEqual('fake_name', self.copier.get_name())
self.copier.__class__.name = None
def test_clean_dst(self):
with self.mock_runner() as runner:
self.copier.clean_dst(self.data['host_dst'], self.data['path_dst'])
self.assertCalledOnce(runner.run_ignoring_errors)
... | self.assertIsNone(self.copier.name)
self.assertEqual(self.copier.__class__.__name__,
self.copier.get_name())
self.copier.__class__.name = 'fake_name' | random_line_split |
test_base.py | # Copyright (c) 2016 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | (self):
with mock.patch.object(self.copier, 'runner') as runner:
yield runner()
class BaseCopierTestCase(BaseTestCase):
copier_class = base.BaseCopier
def test_runner(self):
runner = self.copier.runner('fake_host', 'src')
self.assertIsInstance(runner, remote_runner.RemoteR... | mock_runner | identifier_name |
test_base.py | # Copyright (c) 2016 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... |
@contextlib.contextmanager
def mock_runner(self):
with mock.patch.object(self.copier, 'runner') as runner:
yield runner()
class BaseCopierTestCase(BaseTestCase):
copier_class = base.BaseCopier
def test_runner(self):
runner = self.copier.runner('fake_host', 'src')
... | super(BaseTestCase, self).setUp()
self.src_cloud = mock.Mock()
self.dst_cloud = mock.Mock()
self.copier = self.copier_class( # pylint: disable=not-callable
self.src_cloud, self.dst_cloud)
self.data = {
'host_src': 'fake_host_src',
'path_src': 'fake_pa... | identifier_body |
schedule.rs | free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRA... | else { 10 },
sha3_gas: 30,
sha3_word_gas: 6,
sload_gas: 200,
sstore_set_gas: 20000,
sstore_reset_gas: 5000,
sstore_refund_gas: 15000,
jumpdest_gas: 1,
log_gas: 375,
log_data_gas: 8,
log_topic_gas: 37... | { 50 } | conditional_block |
schedule.rs | free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRA... | create_data_gas: 200,
create_data_limit: max_code_size,
tx_gas: 21000,
tx_create_gas: 53000,
tx_data_zero_gas: 4,
tx_data_non_zero_gas: 68,
copy_gas: 3,
extcodesize_gas: 700,
extcodecopy_base_gas: 700,
... | random_line_split | |
schedule.rs | free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRA... | () -> Schedule {
Self::new(false, false, 21000)
}
/// Schedule for the Homestead-era of the Ethereum main net.
pub fn new_homestead() -> Schedule {
Self::new(true, true, 53000)
}
/// Schedule for the post-EIP-150-era of the Ethereum main net.
pub fn new_post_eip150(max_code_siz... | new_frontier | identifier_name |
schedule.rs | free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRA... | call_gas: 700,
call_stipend: 2300,
call_value_transfer_gas: 9000,
call_new_account_gas: 25000,
suicide_refund_gas: 24000,
memory_gas: 3,
quad_coeff_div: 512,
create_data_gas: 200,
create_data_limit: max_code_size... | {
Schedule {
exceptional_failed_code_deposit: true,
have_delegate_call: true,
stack_limit: 1024,
max_depth: 1024,
tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0],
exp_gas: 10,
exp_byte_gas: if fix_exp { 50 } else { 10 },
s... | identifier_body |
stats.rs | // rpc-perf - RPC Performance Testing
// Copyright 2015 Twitter, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unle... | {
pub start: u64,
pub stop: u64,
pub status: Status,
}
| Stat | identifier_name |
stats.rs | // rpc-perf - RPC Performance Testing
// Copyright 2015 Twitter, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unle... | Hit,
Miss,
Ok,
Closed,
}
#[derive(Clone)]
pub struct Stat {
pub start: u64,
pub stop: u64,
pub status: Status,
} | #[derive(Clone)]
pub enum Status {
Error, | random_line_split |
tagging.py | from django import template | from django.template.loader import render_to_string
from ..models import TaggedItem, Tag
register = template.Library()
@register.assignment_tag
def get_tagged_items_for(object):
'''retrieve tagged items which relative with the specific object.
:syntax: {% get_tagged_items_for <object> as <variable> %}
''... | from django.contrib.contenttypes.models import ContentType | random_line_split |
tagging.py | from django import template
from django.contrib.contenttypes.models import ContentType
from django.template.loader import render_to_string
from ..models import TaggedItem, Tag
register = template.Library()
@register.assignment_tag
def get_tagged_items_for(object):
'''retrieve tagged items which relative with the... | ():
return render_to_string('generic_tagging/head.html')
@register.simple_tag
def render_generic_tagging_component_tag_for(object):
return render_to_string('generic_tagging/component.html', {'object': object})
| render_generic_tagging_head_tag | identifier_name |
tagging.py | from django import template
from django.contrib.contenttypes.models import ContentType
from django.template.loader import render_to_string
from ..models import TaggedItem, Tag
register = template.Library()
@register.assignment_tag
def get_tagged_items_for(object):
'''retrieve tagged items which relative with the... |
@register.simple_tag
def render_generic_tagging_component_tag_for(object):
return render_to_string('generic_tagging/component.html', {'object': object})
| return render_to_string('generic_tagging/head.html') | identifier_body |
user-profile.js | eneratePassword();
}
$pass1.on( 'input' + ' pwupdate', function () {
if ( $pass1.val() === currentPass ) {
return;
}
currentPass = $pass1.val();
$pass1.removeClass( 'short bad good strong' );
showOrHideWeakPasswordCheckbox();
} );
}
function resetToggle( show ) {
$toggleButton
.attr(... | break;
case 4:
$('#pass-strength-result').addClass('strong').html( pwsL10n.strong );
break;
case 5:
$('#pass-strength-result').addClass('short').html( pwsL10n.mismatch );
break;
default:
$('#pass-strength-result').addClass('short').html( pwsL10n['short'] );
}
}
function showOrHide... | {
var pass1 = $('#pass1').val(), strength;
$('#pass-strength-result').removeClass('short bad good strong empty');
if ( ! pass1 ) {
$( '#pass-strength-result' ).addClass( 'empty' ).html( ' ' );
return;
}
strength = wp.passwordStrength.meter( pass1, wp.passwordStrength.userInputDisallowedList(), pa... | identifier_body |
user-profile.js | eneratePassword();
}
$pass1.on( 'input' + ' pwupdate', function () {
if ( $pass1.val() === currentPass ) {
return;
}
currentPass = $pass1.val();
$pass1.removeClass( 'short bad good strong' );
showOrHideWeakPasswordCheckbox();
} );
}
function resetToggle( show ) {
$toggleButton
.attr(... |
/**
* Fix a LastPass mismatch issue, LastPass only changes pass2.
*
* This fixes the issue by copying any changes from the hidden
* pass2 field to the pass1 field, then running check_pass_strength.
*/
$pass2 = $( '#pass2' ).on( 'input', function () {
if ( $pass2.val().length > 0 ) {
$pass1.v... | {
// Password field for the login form.
$pass1 = $( '#user_pass' );
} | conditional_block |
user-profile.js |
// Once zxcvbn loads, passwords strength is known.
$( '#pw-weak-text-label' ).text( __( 'Confirm use of weak password' ) );
}
function bindPass1() {
currentPass = $pass1.val();
if ( 1 === parseInt( $pass1.data( 'reveal' ), 10 ) ) {
generatePassword();
}
$pass1.on( 'input' + ' pwupdate', function ()... | $pass1.attr( 'type', 'text' );
} else {
$toggleButton.trigger( 'click' );
} | random_line_split | |
user-profile.js | eneratePassword();
}
$pass1.on( 'input' + ' pwupdate', function () {
if ( $pass1.val() === currentPass ) {
return;
}
currentPass = $pass1.val();
$pass1.removeClass( 'short bad good strong' );
showOrHideWeakPasswordCheckbox();
} );
}
function resetToggle( show ) {
$toggleButton
.attr(... | () {
var passStrength = $('#pass-strength-result')[0];
if ( passStrength.className ) {
$pass1.addClass( passStrength.className );
if ( $( passStrength ).is( '.short, .bad' ) ) {
if ( ! $weakCheckbox.prop( 'checked' ) ) {
$submitButtons.prop( 'disabled', true );
}
$weakRow.show();
} else {... | showOrHideWeakPasswordCheckbox | identifier_name |
control.py |
the correct value for CROSS_COMPILE.
Args:
boards: Boards object containing selected boards
toolchains: Toolchains object containing available toolchains
Return:
None on success, string error message otherwise
"""
boards = boards.GetSelectedDict()
tc_set = set()
fo... | warnings_as_errors=options.warnings_as_errors,
work_in_output=options.work_in_output)
builder.force_config_on_failure = not options.quick
if make_func: | random_line_split | |
control.py | else:
commits = None
print(GetActionSummary(False, commits, boards_selected,
options))
print('Build directory: %s' % builder.base_dir)
if commits:
for upto in range(0, len(series.commits), options.step):
commit = series.commits[upto]
print(' ', col.C... | """Display a list of actions that we would take, if not a dry run.
Args:
series: Series object
why_selected: Dictionary where each key is a buildman argument
provided by the user, and the value is the list of boards
brought in by that argument. For example, 'arm' mig... | identifier_body | |
control.py | a list of actions that we would take, if not a dry run.
Args:
series: Series object
why_selected: Dictionary where each key is a buildman argument
provided by the user, and the value is the list of boards
brought in by that argument. For example, 'arm' might bring
... |
else:
if has_range:
count, msg = gitutil.CountCommitsInRange(options.git_dir,
options.branch)
else:
count, msg = gitutil.CountCommitsInBranch(options.git_dir,
... | count = 1 | conditional_block |
control.py | (series, why_selected, boards_selected, builder, options,
board_warnings):
"""Display a list of actions that we would take, if not a dry run.
Args:
series: Series object
why_selected: Dictionary where each key is a buildman argument
provided by the user, and the ... | ShowActions | identifier_name | |
test_plot.py | import teneto
import matplotlib.pyplot as plt
def test_sliceplot():
G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'graphlet', 'wu')
fig, ax = plt.subplots(1)
ax = teneto.plot.slice_plot(G, ax)
plt.close(fig)
def test_circleplot():
G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'gr... | G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'contact', 'wd')
fig, ax = plt.subplots(1)
ax = teneto.plot.graphlet_stack_plot(G, ax, q=1)
plt.close(fig) | plt.close(fig)
def test_stackplot(): | random_line_split |
test_plot.py |
import teneto
import matplotlib.pyplot as plt
def | ():
G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'graphlet', 'wu')
fig, ax = plt.subplots(1)
ax = teneto.plot.slice_plot(G, ax)
plt.close(fig)
def test_circleplot():
G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'graphlet', 'wd')
fig, ax = plt.subplots(1)
ax = teneto.plot.... | test_sliceplot | identifier_name |
test_plot.py |
import teneto
import matplotlib.pyplot as plt
def test_sliceplot():
|
def test_circleplot():
G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'graphlet', 'wd')
fig, ax = plt.subplots(1)
ax = teneto.plot.circle_plot(G.mean(axis=-1), ax)
plt.close(fig)
def test_stackplot():
G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'contact', 'wd')
fig, ax = pl... | G = teneto.generatenetwork.rand_binomial([4, 2], 0.5, 'graphlet', 'wu')
fig, ax = plt.subplots(1)
ax = teneto.plot.slice_plot(G, ax)
plt.close(fig) | identifier_body |
pokemon_hunter.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
from geopy.distance import great_circle
from s2sphere import Cell, CellId, LatLng
from pokemongo_bot import inventory
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.item_list import Item
from pokemongo_bot.walkers.polyline_w... | (self):
self.destination = None
self.walker = None
self.search_cell_id = None
self.search_points = []
self.lost_counter = 0
self.no_log_until = 0
self.config_max_distance = self.config.get("max_distance", 2000)
self.config_hunt_all = self.config.get("hunt... | initialize | identifier_name |
pokemon_hunter.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
from geopy.distance import great_circle
from s2sphere import Cell, CellId, LatLng
from pokemongo_bot import inventory
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.item_list import Item
from pokemongo_bot.walkers.polyline_w... |
pokemons.sort(key=lambda p: p["distance"])
return pokemons
def get_worth_pokemons(self, pokemons):
if self.config_hunt_all:
worth_pokemons = pokemons
else:
worth_pokemons = []
if self.config_hunt_vip:
worth_pokemons += [p for p... | pokemon["distance"] = self.get_distance(self.bot.position, p)
pokemon["name"] = inventory.pokemons().name_for(pokemon["pokemon_id"]) | conditional_block |
pokemon_hunter.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
from geopy.distance import great_circle
from s2sphere import Cell, CellId, LatLng
from pokemongo_bot import inventory
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.item_list import Item
from pokemongo_bot.walkers.polyline_w... |
def get_search_points(self, cell_id):
points = []
# For cell level 15
for c in Cell(CellId(cell_id)).subdivide():
for cc in c.subdivide():
latlng = LatLng.from_point(cc.get_center())
point = (latlng.lat().degrees, latlng.lng().degrees)
... | return great_circle(location, (pokemon["latitude"], pokemon["longitude"])).meters | identifier_body |
pokemon_hunter.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
from geopy.distance import great_circle
from s2sphere import Cell, CellId, LatLng
from pokemongo_bot import inventory
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.item_list import Item
from pokemongo_bot.walkers.polyline_w... |
def get_search_points(self, cell_id):
points = []
# For cell level 15
for c in Cell(CellId(cell_id)).subdivide():
for cc in c.subdivide():
latlng = LatLng.from_point(cc.get_center())
point = (latlng.lat().degrees, latlng.lng().degrees)
... | return great_circle(location, (pokemon["latitude"], pokemon["longitude"])).meters | random_line_split |
bench.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 ... |
#[bench]
fn one_pass_short_b_not(b: &mut Bencher) {
let re = regex!(".bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_long_prefix(b: &mut Bencher) {
let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$");
let text = "abcdefghijklmnopqrstuvwxyz";
... | {
let re = regex!("^.bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
} | identifier_body |
bench.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 ... | (n: uint) -> String {
let mut rng = task_rng();
let mut bytes = rng.gen_ascii_chars().map(|n| n as u8).take(n)
.collect::<Vec<u8>>();
for (i, b) in bytes.mut_iter().enumerate() {
if i % 20 == 0 {
*b = '\n' as u8
}
}
String::from_utf8(bytes).unwrap()... | gen_text | identifier_name |
bench.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 ... |
}
String::from_utf8(bytes).unwrap()
}
throughput!(easy0_32, easy0(), 32)
throughput!(easy0_1K, easy0(), 1<<10)
throughput!(easy0_32K, easy0(), 32<<10)
throughput!(easy1_32, easy1(), 32)
throughput!(easy1_1K, easy1(), 1<<10)
throughput!(easy1_32K, easy1(), 32<<10)
throughput!(medium_32, medium(), 32)
through... | {
*b = '\n' as u8
} | conditional_block |
bench.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 ... | let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text.as_slice()));
}
#[bench]
fn one_pass_short_a(b: &mut Bencher) {
let re = regex!("^.bc(d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_a_not(b: &mut Bencher) {
let... | let re = regex!("^.bc(d|e)"); | random_line_split |
macro.rs | #[macro_use]
extern crate double;
// Traits which only return types that implement `Default`.
trait Calculator: Clone {
fn multiply(&self, x: i32, y: i32) -> i32;
}
trait BalanceSheet: Clone {
fn profit(&self, revenue: u32, costs: u32) -> i32;
fn loss(&self, revenue: u32, costs: u32) -> i32;
}
trait Gree... | get_user(i32) -> Result<User, String>,
delete_user(i32) -> Result<(), String>);
impl UserStore for MockUserStore {
mock_method!(get_user(&self, id: i32) -> Result<User, String>);
mock_method!(delete_user(&self, id: i32) -> Result<(), String>);
}
fn main() {
// Test individual return values
let... |
mock_trait_no_default!(
MockUserStore, | random_line_split |
macro.rs | #[macro_use]
extern crate double;
// Traits which only return types that implement `Default`.
trait Calculator: Clone {
fn multiply(&self, x: i32, y: i32) -> i32;
}
trait BalanceSheet: Clone {
fn profit(&self, revenue: u32, costs: u32) -> i32;
fn loss(&self, revenue: u32, costs: u32) -> i32;
}
trait Gree... | () {
// Test individual return values
let mock = MockBalanceSheet::default();
mock.profit.return_value(42);
mock.profit.return_value_for((0, 0), 9001);
let value = mock.profit(10, 20);
assert_eq!(42, value);
mock.profit.has_calls_exactly_in_order(vec!((10, 20)));
let value = mock.profi... | main | identifier_name |
device_user_defined.py | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import QDialog, QVBoxLayout, QPlainTextEdit, QTimer, \
QDialogBut... | self.bbox.setEnabled(False)
QTimer.singleShot(1000, self.device_info)
def device_info(self):
try:
from calibre.devices import device_info
r = step_dialog(self.parent(), _('Device Detection'),
_('Ensure your device is disconnected, then press O... | def __init__(self, parent=None):
QDialog.__init__(self, parent)
self._layout = QVBoxLayout(self)
self.setLayout(self._layout)
self.log = QPlainTextEdit(self)
self._layout.addWidget(self.log)
self.log.setPlainText(_('Getting device information')+'...')
self.copy = ... | identifier_body |
device_user_defined.py | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import QDialog, QVBoxLayout, QPlainTextEdit, QTimer, \
QDialogBut... | (self):
try:
from calibre.devices import device_info
r = step_dialog(self.parent(), _('Device Detection'),
_('Ensure your device is disconnected, then press OK'))
if r:
self.close()
return
before = device_inf... | device_info | identifier_name |
device_user_defined.py | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import QDialog, QVBoxLayout, QPlainTextEdit, QTimer, \
QDialogBut... |
trailer = _(
'Copy these values to the clipboard, paste them into an '
'editor, then enter them into the USER_DEVICE by '
'customizing the device plugin in Preferences->Advanced->Plugins. '
'Remember to also enter the folders w... | res = _('USB Vendor ID (in hex)') + ': ' + \
fmtid(after['device_details'][d][0]) + '\n'
res += _('USB Product ID (in hex)') + ': ' + \
fmtid(after['device_details'][d][1]) + '\n'
res += _('USB Revision ID (in hex)') + ': '... | conditional_block |
device_user_defined.py | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import QDialog, QVBoxLayout, QPlainTextEdit, QTimer, \
QDialogBut... | r = step_dialog(self.parent(), _('Device Detection'),
_('Ensure your device is connected, then press OK'))
if r:
self.close()
return
after = device_info()
new_devices = after['device_set'] - before['device_set']
... | if r:
self.close()
return
before = device_info() | random_line_split |
signal_handler.rs | _metric:expr, $body:ident) => {
#[inline(always)]
extern "C" fn $fn_name(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) {
// Safe because we're just reading some fields from a supposedly valid argument.
let si_signo = unsafe { (*info).si_signo };
let si_code ... | unsafe {
syscall(libc::SYS_kill, process::id(), SIGSEGV);
}
// Call SIGXFSZ signal handler.
assert_eq!(METRICS.signals.sigxfsz.fetch(), 0);
unsafe {
syscall(libc::SYS_kill, process::id(), SIGXFSZ);
}
//... | {
let child = thread::spawn(move || {
assert!(register_signal_handlers().is_ok());
let filter = make_test_seccomp_bpf_filter();
assert!(seccompiler::apply_filter(&filter).is_ok());
assert_eq!(METRICS.seccomp.num_faults.fetch(), 0);
// Call the forbi... | identifier_body |
signal_handler.rs | :expr, $body:ident) => {
#[inline(always)]
extern "C" fn $fn_name(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) {
// Safe because we're just reading some fields from a supposedly valid argument.
let si_signo = unsafe { (*info).si_signo };
let si_code = unsaf... |
// Other signals which might do async unsafe things incompatible with the rest of this
// function are blocked due to the sa_mask used when registering the signal handler.
let syscall = unsafe { *(info as *const i32).offset(SI_OFF_SYSCALL) as usize };
error!(
"Shutting down VM after intercepti... | {
// We received a SIGSYS for a reason other than `bad syscall`.
exit_with_code(FC_EXIT_CODE_UNEXPECTED_ERROR);
} | conditional_block |
signal_handler.rs | _metric:expr, $body:ident) => {
#[inline(always)]
extern "C" fn $fn_name(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) {
// Safe because we're just reading some fields from a supposedly valid argument.
let si_signo = unsafe { (*info).si_signo };
let si_code ... | error!("Received signal {}, code {}.", si_signo, si_code);
}
/// Registers all the required signal handlers.
///
/// Custom handlers are installed for: `SIGBUS`, `SIGSEGV`, `SIGSYS`
/// `SIGXFSZ` `SIGXCPU` `SIGPIPE` `SIGHUP` and `SIGILL`.
pub fn register_signal_handlers() -> utils::errno::Result<()> {
// Call ... | }
METRICS.signals.sigpipe.inc();
| random_line_split |
signal_handler.rs | _metric:expr, $body:ident) => {
#[inline(always)]
extern "C" fn $fn_name(num: c_int, info: *mut siginfo_t, _unused: *mut c_void) {
// Safe because we're just reading some fields from a supposedly valid argument.
let si_signo = unsafe { (*info).si_signo };
let si_code ... | (num: c_int, info: *mut siginfo_t, _unused: *mut c_void) {
// Just record the metric and allow the process to continue, the EPIPE error needs
// to be handled at caller level.
// Safe because we're just reading some fields from a supposedly valid argument.
let si_signo = unsafe { (*info).si_signo };
... | sigpipe_handler | identifier_name |
index.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
module.exports = angular.module('trafficPortal.table.cacheGroupStaticDnsEntries', [])
.controller('TableCacheGroupStaticDnsEntriesController', require('./TableCacheGroupStaticDnsEntriesController')); | * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ | random_line_split |
DragAndDropTest.py | '''
Task Coach - Your friendly task manager
Copyright (C) 2004-2010 Task Coach developers <developers@taskcoach.org>
Task Coach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
... | (self, event):
self.failUnless(event.vetoed)
self.failIf(event.allowed)
def assertEventIsAllowed(self, event):
self.failUnless(event.allowed)
self.failIf(event.vetoed)
def testEventIsVetoedWhenDragBeginsWithoutItem(self):
event = DummyEvent()
se... | assertEventIsVetoed | identifier_name |
DragAndDropTest.py | '''
Task Coach - Your friendly task manager
Copyright (C) 2004-2010 Task Coach developers <developers@taskcoach.org>
Task Coach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
... | self.failUnless(event.allowed)
self.failIf(event.vetoed)
def testEventIsVetoedWhenDragBeginsWithoutItem(self):
event = DummyEvent()
self.treeCtrl.OnBeginDrag(event)
self.assertEventIsVetoed(event)
def testEventIsAllowedWhenDragBeginsWithItem(self):
... | self.failIf(event.allowed)
def assertEventIsAllowed(self, event): | random_line_split |
DragAndDropTest.py | '''
Task Coach - Your friendly task manager
Copyright (C) 2004-2010 Task Coach developers <developers@taskcoach.org>
Task Coach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
... |
def GetItem(self):
return self.item
def Veto(self):
self.vetoed = True
def Allow(self):
self.allowed = True
class TreeCtrlDragAndDropMixinTest(test.wxTestCase):
# pylint: disable-msg=E1101
def setUp(self):
self.treeCtrl = treectr... | self.item = item
self.vetoed = self.allowed = False | identifier_body |
mixer.rs | use std::ptr;
use std::ffi::CStr;
use std::ffi::CString;
use std::cmp::min;
use libc::c_int;
use libc::c_uint;
use libc::c_void;
use format::error::DriverError;
use alsa::device::AlsaDevice;
use alsa::device::create_error;
use alsa::ffi::*;
pub type SndSize = snd_pcm_uframes_t;
pub struct Params {
hw_params: *mut ... |
}
}
| {
return None;
} | conditional_block |
mixer.rs | use std::ptr;
use std::ffi::CStr;
use std::ffi::CString;
use std::cmp::min;
use libc::c_int;
use libc::c_uint;
use libc::c_void;
use format::error::DriverError;
use alsa::device::AlsaDevice;
use alsa::device::create_error;
use alsa::ffi::*;
pub type SndSize = snd_pcm_uframes_t;
pub struct Params {
hw_params: *mut ... |
pub fn format(&self, dev: &AlsaDevice, rate_in: c_uint, channels: c_uint, format: c_int) -> Option<DriverError> {
let pcm = dev.get_pcm();
let mut err = 0;
let mut rate: c_uint = rate_in;
unsafe {
err = snd_pcm_hw_params_set_rate_resample(pcm, self.hw_params, 1);
err = snd_pcm_hw_params_set_access... | {
let pcm = dev.get_pcm();
let mut err = 0;
unsafe {
err = snd_pcm_hw_params_any(pcm, self.hw_params);
}
if err < 0 {
return Some(create_error("snd_pcm_hw_params_any", err));
}
else {
return None;
}
} | identifier_body |
mixer.rs | use std::ptr;
use std::ffi::CStr;
use std::ffi::CString;
use std::cmp::min;
use libc::c_int;
use libc::c_uint;
use libc::c_void;
use format::error::DriverError;
use alsa::device::AlsaDevice;
use alsa::device::create_error;
use alsa::ffi::*;
pub type SndSize = snd_pcm_uframes_t;
pub struct Params {
hw_params: *mut ... | (&self) -> Result<SndSize, DriverError> {
let mut size: snd_pcm_uframes_t = 0;
let mut err = 0;
unsafe {
err = snd_pcm_hw_params_get_buffer_size(self.hw_params, &mut size);
}
if err < 0 {
return Err(create_error("snd_pcm_hw_params_get_buffer_size", err));
}
else {
println!("Buffer size: {}", size... | buffer_size | identifier_name |
mixer.rs | use std::ptr;
use std::ffi::CStr;
use std::ffi::CString;
use std::cmp::min;
use libc::c_int;
use libc::c_uint;
use libc::c_void;
use format::error::DriverError;
use alsa::device::AlsaDevice;
use alsa::device::create_error;
use alsa::ffi::*;
pub type SndSize = snd_pcm_uframes_t;
pub struct Params {
hw_params: *mut ... |
pub fn any(&self, dev: &AlsaDevice) -> Option<DriverError> {
let pcm = dev.get_pcm();
let mut err = 0;
unsafe {
err = snd_pcm_hw_params_any(pcm, self.hw_params);
}
if err < 0 {
return Some(create_error("snd_pcm_hw_params_any", err));
}
else {
return None;
}
}
pub fn format(&self, dev:... | }
} | random_line_split |
plugin.py | the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"... |
def __init__(self):
self.__parent = super(RequestBot, self)
self.__parent.__init__(irc)
self.dailyChecksInterval = conf.supybot.plugins.RequestBot.dailyCheckInterval()
self.stopDailyCheck = conf.supybot.plugins.RequestBot.stopDailyCheck()
self.numberOfChecks = conf.supyb... | threaded = True | random_line_split |
plugin.py | the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"... |
numberOfValidUsers = len(users) - numberOfInvalidUsers
if numberOfValidUsers >= self.numberOfValidUsers:
return "Valid"
else:
return "Invalid"
def _getDailyChecks(self, channel):
with open("plugins/RequestBot/local/dailyChecks.json", "r") as dailyChe... | for nick in invalidNicks:
if user.lower() == nick:
numberOfInvalidUsers += 1 | conditional_block |
plugin.py | the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"... |
def _checkRequesterBan(self, nick):
try:
with open("plugins/RequestBot/local/nickBans.json", "r") as nicks:
banList = json.loads(nicks.read())
if nick.lower() not in banList.keys():
return "Valid"
else:
... | try:
with open("plugins/RequestBot/local/channelBans.json", "r") as bans:
banList = json.loads(bans.read())
if channel.lower() not in banList.keys():
return "Valid"
else:
return "Banned"
except Exception as e:
... | identifier_body |
plugin.py | the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"... | (self, message):
with open("local\log.txt", "a") as logFile:
logFile.write("\n")
logFile.write(message)
def _checkChannelBan(self, channel):
try:
with open("plugins/RequestBot/local/channelBans.json", "r") as bans:
banList = json.loads(bans.re... | _logError | identifier_name |
test_args.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); | # https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing p... | # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# | random_line_split |
test_args.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (kwargs, expected):
assert tftest.parse_args(**kwargs) == expected
def test_var_args():
assert sorted(tftest.parse_args(init_vars={'a': 1, 'b': '["2"]'})) == sorted(
["-backend-config=a=1", '-backend-config=b=["2"]'])
assert sorted(tftest.parse_args(tf_vars={'a': 1, 'b': '["2"]'})) == sorted(
['-var... | test_terragrunt_args | identifier_name |
test_args.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
def test_targets():
assert tftest.parse_args(targets=['one', 'two']) == sorted(
['-target=one', '-target=two'])
| assert sorted(tftest.parse_args(init_vars={'a': 1, 'b': '["2"]'})) == sorted(
["-backend-config=a=1", '-backend-config=b=["2"]'])
assert sorted(tftest.parse_args(tf_vars={'a': 1, 'b': '["2"]'})) == sorted(
['-var', 'b=["2"]', '-var', 'a=1']) | identifier_body |
csvjson.py | #!/usr/bin/env python
import json
import codecs
from csvkit import CSVKitReader
from csvkit.cli import CSVKitUtility, match_column_identifier
from csvkit.exceptions import NonUniqueKeyColumnException
class CSVJSON(CSVKitUtility):
description = 'Convert a CSV file into JSON (or GeoJSON).'
override_flags = ['H... |
for row in rows:
feature = { 'type': 'Feature' }
properties = {}
geoid = None
lat = None
lon = None
for i, c in enumerate(row):
if i == lat_column:
lat = float(c)
... | id_column = None | conditional_block |
csvjson.py | #!/usr/bin/env python
import json
import codecs
from csvkit import CSVKitReader
from csvkit.cli import CSVKitUtility, match_column_identifier
from csvkit.exceptions import NonUniqueKeyColumnException
class | (CSVKitUtility):
description = 'Convert a CSV file into JSON (or GeoJSON).'
override_flags = ['H']
def add_arguments(self):
self.argparser.add_argument('-i', '--indent', dest='indent', type=int, default=None,
help='Indent the output JSON this many spaces. Disabled by default.')
... | CSVJSON | identifier_name |
csvjson.py | #!/usr/bin/env python
import json
import codecs
from csvkit import CSVKitReader
from csvkit.cli import CSVKitUtility, match_column_identifier
from csvkit.exceptions import NonUniqueKeyColumnException
class CSVJSON(CSVKitUtility):
description = 'Convert a CSV file into JSON (or GeoJSON).'
override_flags = ['H... |
def main(self):
"""
Convert CSV to JSON.
"""
if self.args.lat and not self.args.lon:
self.argparser.error('--lon is required whenever --lat is specified.')
if self.args.lon and not self.args.lat:
self.argparser.error('--lat is required whenever --l... | self.argparser.add_argument('-i', '--indent', dest='indent', type=int, default=None,
help='Indent the output JSON this many spaces. Disabled by default.')
self.argparser.add_argument('-k', '--key', dest='key', type=str, default=None,
help='Output JSON as an array of objects keyed by a gi... | identifier_body |
csvjson.py | #!/usr/bin/env python
import json
import codecs
from csvkit import CSVKitReader
from csvkit.cli import CSVKitUtility, match_column_identifier
from csvkit.exceptions import NonUniqueKeyColumnException
class CSVJSON(CSVKitUtility):
description = 'Convert a CSV file into JSON (or GeoJSON).'
override_flags = ['H... | self.argparser.error('--lon is required whenever --lat is specified.')
if self.args.lon and not self.args.lat:
self.argparser.error('--lat is required whenever --lon is specified.')
if self.args.crs and not self.args.lat:
self.argparser.error('--crs is only allowed ... | random_line_split | |
Backgrounding_OnePage.js | #import "../../jasmine-uiautomation.js"
#import "../../jasmine/lib/jasmine-core/jasmine.js"
#import "../../jasmine-uiautomation-reporter.js"
#import "../../helpers/general_helpers.js"
describe("Questions Backgrounding", function() {
var helpers = new EPHelpers();
var expectedFirstVisibleCellName = 'Content ... |
it("displays the same set of questions when re-entering questions section", function() {
helpers.enterQuestions();
helpers.checkThereIsACorrectNumberOfRowsInTheTableView(40);
expect(helpers.getFirstVisibleCellTextForTableView('Questions')).toContain(expectedFirstVisibleCellName);
});... | helpers.checkThereIsACorrectNumberOfRowsInTheTableView(expected_number_of_questions);
expect(helpers.getFirstVisibleCellTextForTableView('Questions')).toContain(expectedFirstVisibleCellName);
}); | random_line_split |
Virtualize.tsx | import * as React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete, {
AutocompleteRenderGroupParams,
autocompleteClasses,
} from '@material-ui/core/Autocomplete';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import ListSubheader from '@material-ui/core/ListSubhe... |
return itemSize;
};
const getHeight = () => {
if (itemCount > 8) {
return 8 * itemSize;
}
return itemData.map(getChildSize).reduce((a, b) => a + b, 0);
};
const gridRef = useResetCache(itemCount);
return (
<div ref={ref}>
<OuterElementContext.Provider value={other}>
... | {
return 48;
} | conditional_block |
Virtualize.tsx | import * as React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete, {
AutocompleteRenderGroupParams,
autocompleteClasses,
} from '@material-ui/core/Autocomplete';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import ListSubheader from '@material-ui/core/ListSubhe... | () {
return (
<Autocomplete
id="virtualize-demo"
sx={{ width: 300 }}
disableListWrap
PopperComponent={StyledPopper}
ListboxComponent={
ListboxComponent as React.ComponentType<React.HTMLAttributes<HTMLElement>>
}
renderGroup={renderGroup}
options={OPTIONS}
... | Virtualize | identifier_name |
Virtualize.tsx | import * as React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete, {
AutocompleteRenderGroupParams,
autocompleteClasses,
} from '@material-ui/core/Autocomplete';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import ListSubheader from '@material-ui/core/ListSubhe... | );
}
| {
return (
<Autocomplete
id="virtualize-demo"
sx={{ width: 300 }}
disableListWrap
PopperComponent={StyledPopper}
ListboxComponent={
ListboxComponent as React.ComponentType<React.HTMLAttributes<HTMLElement>>
}
renderGroup={renderGroup}
options={OPTIONS}
... | identifier_body |
Virtualize.tsx | import * as React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete, {
AutocompleteRenderGroupParams,
autocompleteClasses,
} from '@material-ui/core/Autocomplete';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import ListSubheader from '@material-ui/core/ListSubhe... |
return itemSize;
};
const getHeight = () => {
if (itemCount > 8) {
return 8 * itemSize;
}
return itemData.map(getChildSize).reduce((a, b) => a + b, 0);
};
const gridRef = useResetCache(itemCount);
return (
<div ref={ref}>
<OuterElementContext.Provider value={other}>
... | random_line_split | |
logger.rs | extern crate log4rs;
extern crate log;
extern crate libc;
use std::error::Error;
use indy;
pub struct IndyCliLogger;
impl IndyCliLogger {
pub fn | (path: &str) -> Result<(), String> {
log4rs::init_file(path, Default::default())
.map_err(|err| format!("Cannot init Indy CLI logger: {}", err.description()))?;
indy::logger::set_logger(log::logger())
.map_err(|_| "Cannot init Libindy logger".to_string())
}
}
#[macro_export... | init | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.