Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
8,400 | def expln(x):
""" This continuous function ensures that the values of the array are always positive.
It is ln(x+1)+1 for x >= 0 and exp(x) for x < 0. """
def f(val):
if val < 0:
# exponential function for x < 0
return exp(val)
else:
# natural log funct... | TypeError | dataset/ETHPy150Open pybrain/pybrain/pybrain/tools/functions.py/expln |
8,401 | def explnPrime(x):
""" This function is the first derivative of the expln function (above).
It is needed for the backward pass of the module. """
def f(val):
if val < 0:
# exponential function for x<0
return exp(val)
else:
# linear function for x>=0
... | TypeError | dataset/ETHPy150Open pybrain/pybrain/pybrain/tools/functions.py/explnPrime |
8,402 | def __set__(self, instance, value):
if value is not None and isinstance(value, str):
try:
value = W3CDTF_to_datetime(value)
except __HOLE__:
raise ValueError("Value must be W3C datetime format")
super(W3CDateTime, self).__set__(instance, value) | ValueError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/openpyxl-2.3.0-b2/openpyxl/workbook/properties.py/W3CDateTime.__set__ |
8,403 | def fetch_posts(s, newsgroup, last, cid):
"""Fetch newsgroups posts, using the given nntp object s."""
NUM_POSTS = 10 # we will fetch the last 10 posts (at most)
try:
start = str(int(last) - NUM_POSTS)
_, items = s.xover(start, last)
posts = []
for (article_id, subject, author, _, _, _,
... | UnicodeDecodeError | dataset/ETHPy150Open GoogleCloudPlatform/appengine-sockets-python-java-go/python_socket_demo/main.py/fetch_posts |
8,404 | def _load_function(source):
"""
Returns a function from a module, given a source string of the form:
'module.submodule.subsubmodule.function_name'
"""
module_string, function_string = source.rsplit('.', 1)
modules = [i for i in sys.modules.keys() if 'calliope' in i]
# Check if module a... | ImportError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/_load_function |
8,405 | def plugin_load(name, builtin_module):
try: # First try importing as a third-party module
func = _load_function(name)
except __HOLE__:
# ValueError raised if we got a string without '.',
# which implies a builtin function,
# so we attempt to load from the given module
fu... | ValueError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/plugin_load |
8,406 | def prev(self, t):
"""Using the timesteps set of this model instance, return `t-1`,
even if the set is not continuous.
E.g., if t is [0, 1, 2, 6, 7, 8], model.prev(6) will return 2.
"""
# Create an index to look up t, and save it for later use
try:
# Check i... | AttributeError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model.prev |
8,407 | def get_option(self, option, x=None, default=None,
ignore_inheritance=False):
"""
Retrieves options from model settings for the given tech,
falling back to the default if the option is not defined for the
tech.
If ``x`` is given, will attempt to use location-s... | KeyError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model.get_option |
8,408 | def initialize_parents(self):
o = self.config_model
try:
self.parents = {i: o.techs[i].parent for i in o.techs.keys()
if i != 'defaults'}
except __HOLE__:
tech = inspect.trace()[-1][0].f_locals['i']
if 'parent' not in list(o.techs[t... | KeyError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model.initialize_parents |
8,409 | def initialize_sets(self):
o = self.config_model
d = self.data
path = o.data_path
#
# t: Timesteps set
#
table_t = pd.read_csv(os.path.join(path, 'set_t.csv'), header=None,
index_col=1, parse_dates=[1])
table_t.columns = ['t_i... | KeyError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model.initialize_sets |
8,410 | def read_data(self):
"""
Read parameter data from CSV files, if needed. Data that may be
defined in CSV files is read before generate_model() so that it
only has to be read from disk once, even if generate_model() is
repeatedly called.
Note on indexing: if subset_t is se... | KeyError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model.read_data |
8,411 | def add_constraint(self, constraint, *args, **kwargs):
try:
constraint(self, *args, **kwargs)
# If there is an error in a constraint, make sure to also get
# the index where the error happened and pass that along
except __HOLE__ as e:
index = inspect.trace()[-1][0... | ValueError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model.add_constraint |
8,412 | def _set_t_end(self):
# t_end is the timestep previous to t_start + horizon,
# because the .loc[start:end] slice includes the end
try:
self.t_end = self.prev(int(self.t_start
+ self.config_model.opmode.horizon
/ se... | KeyError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model._set_t_end |
8,413 | def solve(self, warmstart=False):
"""
Args:
warmstart : (default False) re-solve an updated model
instance
Returns: None
"""
m = self.m
cr = self.config_run
solver_kwargs = {}
if not warmstart:
solver_io = ... | ValueError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model.solve |
8,414 | def get_var(self, var, dims=None, standardize_coords=True):
"""
Return output for variable `var` as a pandas.Series (1d),
pandas.Dataframe (2d), or xarray.DataArray (3d and higher).
Args:
var : variable name as string, e.g. 'es_prod'
dims : list of indices as str... | AttributeError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model.get_var |
8,415 | def _get_time_res_sum(self):
m = self.m
time_res = self.data.time_res_series
try: # Try loading time_res_sum from operational mode
time_res_sum = self.data.time_res_sum
except __HOLE__:
time_res_sum = sum(time_res.at[t] for t in m.t)
return time_res_sum | KeyError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model._get_time_res_sum |
8,416 | def save_solution(self, how):
"""Save model solution. ``how`` can be 'netcdf' or 'csv'"""
if 'path' not in self.config_run.output:
self.config_run.output['path'] = 'Output'
logging.warning('`config_run.output.path` not set, using default: `Output`')
# Create output dir,... | OSError | dataset/ETHPy150Open calliope-project/calliope/calliope/core.py/Model.save_solution |
8,417 | def main(self, request_id, path_to_file):
self.repository_info, self.tool = self.initialize_scm_tool(
client_name=self.options.repository_type)
server_url = self.get_server_url(self.repository_info, self.tool)
api_client, api_root = self.get_api(server_url)
request = get_rev... | IOError | dataset/ETHPy150Open reviewboard/rbtools/rbtools/commands/attach.py/Attach.main |
8,418 | def write(self, *args, **kwargs):
if kwargs.get('level', SIPLOG_INFO) < self.level:
return
ltime = kwargs.get('ltime', None)
if ltime == None:
ltime = time()
call_id = kwargs.get('call_id', self.call_id)
obuf = '%s.%.3d/%s/%s: %s\n' % (strftime('%d %b %H:%... | IOError | dataset/ETHPy150Open hgascon/pulsar/pulsar/core/sippy/SipLogger.py/SipLogger.write |
8,419 | def get_user_info(self):
fields = providers.registry \
.by_id(LinkedInProvider.id) \
.get_profile_fields()
url = self.url + ':(%s)' % ','.join(fields)
raw_xml = self.query(url)
if not six.PY3:
raw_xml = raw_xml.encode('utf8')
try:
r... | KeyError | dataset/ETHPy150Open pennersr/django-allauth/allauth/socialaccount/providers/linkedin/views.py/LinkedInAPI.get_user_info |
8,420 | def pairwise(iterable):
"""
Yield pairs of consecutive elements in iterable.
>>> list(pairwise('abcd'))
[('a', 'b'), ('b', 'c'), ('c', 'd')]
"""
iterator = iter(iterable)
try:
a = iterator.next()
except __HOLE__:
return
for b in iterator:
yield a, b
... | StopIteration | dataset/ETHPy150Open SimonSapin/snippets/markov_passwords.py/pairwise |
8,421 | def parse_encoding(fp):
"""Deduce the encoding of a source file from magic comment.
It does this in the same way as the `Python interpreter`__
.. __: https://docs.python.org/3.4/reference/lexical_analysis.html#encoding-declarations
The ``fp`` argument should be a seekable file object.
(From Jeff... | ImportError | dataset/ETHPy150Open python-babel/babel/babel/util.py/parse_encoding |
8,422 | def pop(self, key, default=missing):
try:
value = dict.pop(self, key)
self._keys.remove(key)
return value
except __HOLE__ as e:
if default == missing:
raise e
else:
return default | KeyError | dataset/ETHPy150Open python-babel/babel/babel/util.py/odict.pop |
8,423 | def _GetBenchmarkSpec(benchmark_config, benchmark_name, benchmark_uid):
"""Creates a BenchmarkSpec or loads one from a file.
During the provision stage, creates a BenchmarkSpec from the provided
configuration. During any later stage, loads the BenchmarkSpec that was
created during the provision stage from a fi... | IOError | dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/pkb.py/_GetBenchmarkSpec |
8,424 | def test_instance(self):
'''
Test creating an instance on ProfitBricks
'''
# check if instance with salt installed returned
try:
self.assertIn(
INSTANCE_NAME,
[i.strip() for i in self.run_cloud(
'-p profitbricks-test... | AssertionError | dataset/ETHPy150Open saltstack/salt/tests/integration/cloud/providers/profitbricks.py/ProfitBricksTest.test_instance |
8,425 | def action_logging(user, object_list, action_type, message=None, context=None):
"""
Add ActionLog using a set of parameters.
user:
The user that did the action.
object_list:
A list of objects that should be created the actionlog for.
action_type:
Label of a type of action from the... | TypeError | dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/actionlog/models.py/action_logging |
8,426 | def main(argv=None):
if argv is None:
argv = sys.argv
parser = E.OptionParser(
version="%prog version: $Id$",
usage=globals()["__doc__"])
parser.add_option("-g", "--genome-file", dest="genome_file", type="string",
help="filename with genome [default=%default]... | KeyError | dataset/ETHPy150Open CGATOxford/cgat/scripts/gtf2reads.py/main |
8,427 | @register.tag
def render_form_field(parser, token):
"""
Usage is {% render_form_field form.field_name optional_help_text optional_css_classes %}
- optional_help_text and optional_css_classes are strings
- if optional_help_text is not given, then it is taken from form field object
"""
try:
... | ValueError | dataset/ETHPy150Open Tivix/django-common/django_common/templatetags/custom_tags.py/render_form_field |
8,428 | def test_run__requires_result(self):
suite = unittest.TestSuite()
try:
suite.run()
except __HOLE__:
pass
else:
self.fail("Failed to raise TypeError")
# "Run the tests associated with this suite, collecting the result into
# the test result ob... | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_suite.py/Test_TestSuite.test_run__requires_result |
8,429 | def test_addTest__noniterable(self):
suite = unittest.TestSuite()
try:
suite.addTests(5)
except __HOLE__:
pass
else:
self.fail("Failed to raise TypeError") | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_suite.py/Test_TestSuite.test_addTest__noniterable |
8,430 | def all(user, groupby='week', summary='default', network=False, split_week=False, split_day=False, attributes=True, flatten=False):
"""
Returns a dictionary containing all bandicoot indicators for the user,
as well as reporting variables.
Relevant indicators are defined in the 'individual', and 'spatia... | ValueError | dataset/ETHPy150Open yvesalexandre/bandicoot/bandicoot/utils.py/all |
8,431 | def sequential_join(left_rows, right_rows, header=True):
"""
Join two tables by aligning them horizontally without performing any filtering.
"""
len_left_headers = len(left_rows[0])
len_right_headers = len(right_rows[0])
if header:
output = [left_rows[0] + right_rows[0]]
left_ro... | StopIteration | dataset/ETHPy150Open wireservice/csvkit/csvkit/join.py/sequential_join |
8,432 | def _to_link_header(self, link):
"""
Convert the link tuple to a link header string. Used internally.
"""
try:
bucket, key, tag = link
except __HOLE__:
raise RiakError("Invalid link tuple %s" % link)
tag = tag if tag is not None else bucket
... | ValueError | dataset/ETHPy150Open basho/riak-python-client/riak/codecs/http.py/HttpCodec._to_link_header |
8,433 | @staticmethod
def displayRow( pRow, pDescription, pDepth=0 ):
'''
Print content row for a particular table description and data.
'''
line=""
for column in pDescription.columns:
if column['visible'] == True:
try:
if type(column... | KeyError | dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/pulitools/puliquery/common.py/CustomTable.displayRow |
8,434 | def render(self, data, accepted_media_type=None, renderer_context=None):
self.set_filename(self.basename(data), renderer_context)
fp = data['image']
try:
fp.seek(0, 2)
except __HOLE__:
size = os.path.getsize(fp)
fp = open(fp)
else:
... | AttributeError | dataset/ETHPy150Open bkg/django-spillway/spillway/renderers/gdal.py/BaseGDALRenderer.render |
8,435 | def set_filename(self, name, renderer_context):
type_name = 'attachment; filename=%s' % name
try:
renderer_context['response']['Content-Disposition'] = type_name
except (KeyError, __HOLE__):
pass | TypeError | dataset/ETHPy150Open bkg/django-spillway/spillway/renderers/gdal.py/BaseGDALRenderer.set_filename |
8,436 | def set_response_length(self, length, renderer_context):
try:
renderer_context['response']['Content-Length'] = length
except (__HOLE__, TypeError):
pass | KeyError | dataset/ETHPy150Open bkg/django-spillway/spillway/renderers/gdal.py/BaseGDALRenderer.set_response_length |
8,437 | def render(self, data, accepted_media_type=None, renderer_context=None):
if isinstance(data, dict):
data = [data]
zipname = '%s.%s' % (self.arcdirname, self.format)
self.set_filename(zipname, renderer_context)
fp = tempfile.TemporaryFile(suffix='.%s' % self.format)
wi... | AttributeError | dataset/ETHPy150Open bkg/django-spillway/spillway/renderers/gdal.py/GeoTIFFZipRenderer.render |
8,438 | @classmethod
def split_input(cls, mapper_spec):
shard_count = mapper_spec.shard_count
# Grab the input parameters for the split
params = input_readers._get_params(mapper_spec)
logging.info("Params: %r", params)
db = params['db']
# Unpickle the query
app, mod... | IndexError | dataset/ETHPy150Open potatolondon/djangae/djangae/contrib/mappers/readers.py/DjangoInputReader.split_input |
8,439 | def __init__(self, **kwargs):
View.__init__(self, **kwargs)
# Allow this view to easily switch between feed formats.
format = kwargs.get('format', self.format)
try:
self.feed_type = _FEED_FORMATS[format]
except __HOLE__:
raise ValueError("Unsupported feed... | KeyError | dataset/ETHPy150Open edoburu/django-fluent-blogs/fluent_blogs/views/feeds.py/FeedView.__init__ |
8,440 | def decode(arg, delimiter=None, encodeseq=None):
'''Decode a single argument from the file-system'''
arg = coerce_unicode(arg, _c.FSQ_CHARSET)
new_arg = sep = u''
delimiter, encodeseq = delimiter_encodeseq(
_c.FSQ_DELIMITER if delimiter is None else delimiter,
_c.FSQ_ENCODE if encodeseq ... | ValueError | dataset/ETHPy150Open axialmarket/fsq/fsq/encode.py/decode |
8,441 | def pathsplit(path):
"""Split a /-delimited path into a directory part and a basename.
:param path: The path to split.
:return: Tuple with directory name and basename
"""
try:
(dirname, basename) = path.rsplit("/", 1)
except __HOLE__:
return ("", path)
else:
return (... | ValueError | dataset/ETHPy150Open natestedman/Observatory/observatory/lib/dulwich/index.py/pathsplit |
8,442 | def lastfm_get_tree(self, method, **kwargs):
kwargs.update({
'autocorrect': 1,
self.get_type(): unicode(self).encode('utf-8'),
})
if hasattr(self, 'artist'):
kwargs['artist'] = unicode(self.artist).encode('utf-8')
if hasattr(self, 'album'):
... | IOError | dataset/ETHPy150Open jpic/playlistnow.fm/apps/music/models.py/MusicalEntity.lastfm_get_tree |
8,443 | def test_is_true_failure(self):
try:
assert_that(False).is_true()
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('Expected <True>, but was not.') | AssertionError | dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_bool.py/TestBool.test_is_true_failure |
8,444 | def test_is_false_failure(self):
try:
assert_that(True).is_false()
fail('should have raised error')
except __HOLE__ as ex:
assert_that(str(ex)).is_equal_to('Expected <False>, but was not.') | AssertionError | dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_bool.py/TestBool.test_is_false_failure |
8,445 | def _parse_version(version_string):
version = []
for x in version_string.split('.'):
try:
version.append(int(x))
except __HOLE__:
# x may be of the form dev-1ea1592
version.append(x)
return tuple(version) | ValueError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/utils/fixes.py/_parse_version |
8,446 | def makedirs(name, mode=0o777, exist_ok=False):
"""makedirs(name [, mode=0o777][, exist_ok=False])
Super-mkdir; create a leaf directory and all intermediate ones. Works
like mkdir, except that any intermediate path segment (not just the
rightmost) will be created if it does not exist. ... | OSError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/utils/fixes.py/makedirs |
8,447 | def _validate_multicast_ip_range(self, network_profile):
"""
Validate multicast ip range values.
:param network_profile: network profile object
"""
try:
min_ip, max_ip = (network_profile
['multicast_ip_range'].split('-', 1))
exce... | ValueError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/ml2/drivers/cisco/n1kv/network_profile_service.py/NetworkProfile_db_mixin._validate_multicast_ip_range |
8,448 | def get_decompressed_message():
"""
For upload formats that support it, detect gzip Content-Encoding headers
and de-compress on the fly.
:rtype: str
:returns: The de-compressed request body.
"""
content_encoding = request.headers.get('Content-Encoding', '')
if content_encoding in ['gzi... | IndexError | dataset/ETHPy150Open gtaylor/EVE-Market-Data-Relay/emdr/daemons/gateway/wsgi.py/get_decompressed_message |
8,449 | def parse_and_error_handle(parser, data, upload_format):
"""
Standardized parsing and error handling for parsing. Returns the final
HTTP body to send back to the uploader after parsing, or error messages.
:param callable parser: The parser function to use to parse ``data``.
:param object data: An d... | ValueError | dataset/ETHPy150Open gtaylor/EVE-Market-Data-Relay/emdr/daemons/gateway/wsgi.py/parse_and_error_handle |
8,450 | def load_starting_page(config_data):
"""
Load starting page into the CMS
:param config_data: configuration data
"""
with chdir(config_data.project_directory):
env = deepcopy(dict(os.environ))
env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))
... | OSError | dataset/ETHPy150Open nephila/djangocms-installer/djangocms_installer/django/__init__.py/load_starting_page |
8,451 | def trap_exit_fail(f):
def test_wrapper(*args):
try:
f(*args)
except __HOLE__:
import traceback
print (traceback.format_exc())
assert False
test_wrapper.__name__ = f.__name__
return test_wrapper | SystemExit | dataset/ETHPy150Open hyde/commando/commando/tests/test_commando.py/trap_exit_fail |
8,452 | def trap_exit_pass(f):
def test_wrapper(*args):
try:
print (f.__name__)
f(*args)
except __HOLE__:
pass
test_wrapper.__name__ = f.__name__
return test_wrapper | SystemExit | dataset/ETHPy150Open hyde/commando/commando/tests/test_commando.py/trap_exit_pass |
8,453 | def test_command_version_param():
with patch.object(BasicCommandLine, '_main') as _main:
c = BasicCommandLine()
exception = False
try:
c.parse(['--version'])
assert False
except __HOLE__:
exception = True
assert exception
assert not... | SystemExit | dataset/ETHPy150Open hyde/commando/commando/tests/test_commando.py/test_command_version_param |
8,454 | def test_command_version():
class VersionCommandLine(Application):
@command(description='test', prog='Basic')
@param('--force', action='store_true', dest='force1')
@param('--force2', action='store', dest='force2')
@version('--version', version='%(prog)s 1.0')
def main(self, ... | SystemExit | dataset/ETHPy150Open hyde/commando/commando/tests/test_commando.py/test_command_version |
8,455 | def __new__(self, *args):
obj = super(Matcher, self).__new__(self)
try:
argspec = inspect.getargspec(type(obj).__init__)
except __HOLE__:
return obj
else:
if argspec.varargs or argspec.keywords:
return obj
nargs = len(argspec.... | TypeError | dataset/ETHPy150Open eallik/spinoff/spinoff/util/pattern_matching.py/Matcher.__new__ |
8,456 | def remove_empty_bridges():
try:
interface_mappings = n_utils.parse_mappings(
cfg.CONF.LINUX_BRIDGE.physical_interface_mappings)
except ValueError as e:
LOG.error(_LE("Parsing physical_interface_mappings failed: %s."), e)
sys.exit(1)
LOG.info(_LI("Interface mappings: %s."... | RuntimeError | dataset/ETHPy150Open openstack/neutron/neutron/cmd/linuxbridge_cleanup.py/remove_empty_bridges |
8,457 | def check_gitignore():
# checks .gitignore for .gitver inclusion
try:
gifile = os.path.join(GITIGNOREFILE)
with open(gifile, 'r') as f:
if CFGDIRNAME in f.read():
return True
except __HOLE__:
pass
return False | IOError | dataset/ETHPy150Open manuelbua/gitver/gitver/sanity.py/check_gitignore |
8,458 | def __enter__(self):
try:
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
# Note that this will only work with a CDH release.
# This uses the thrift bindings generated by the Thri... | ImportError | dataset/ETHPy150Open spotify/luigi/luigi/contrib/hive.py/HiveThriftContext.__enter__ |
8,459 | def reorder_data(data, shape, torder):
"""
Reorder raw data from file.
Parameters
----------
data : 2D ndarray
Raw data as ordered in binary file.
shape : tuple of ints
Shape of the NMR data.
torder : {'f', 'r', 'o' of Pytho function}
Trace ordering . See :py:func:`r... | ValueError | dataset/ETHPy150Open jjhelmus/nmrglue/nmrglue/fileio/varian.py/reorder_data |
8,460 | def read_fid(filename, shape=None, torder='flat', as_2d=False,
read_blockhead=False):
"""
Read a Agilent/Varian binary (fid) file.
Parameters
----------
filename : str
Filename of Agilent/Varian binary file (fid) to read.
shape : tuple of ints, optional
Shape of the... | ValueError | dataset/ETHPy150Open jjhelmus/nmrglue/nmrglue/fileio/varian.py/read_fid |
8,461 | def read_fid_ntraces(filename, shape=None, torder='flat', as_2d=False,
read_blockhead=False):
"""
Read a Agilent/Varian binary (fid) file possibility having multiple
traces per block.
Parameters
----------
filename : str
Filename of Agilent/Varian binary file (fid) ... | ValueError | dataset/ETHPy150Open jjhelmus/nmrglue/nmrglue/fileio/varian.py/read_fid_ntraces |
8,462 | def init(config, benchmark):
benchmark.executable = benchmark.tool.executable()
benchmark.tool_version = benchmark.tool.version(benchmark.executable)
try:
processes = subprocess.Popen(['ps', '-eo', 'cmd'], stdout=subprocess.PIPE).communicate()[0]
if len(re.findall("python.*benchmark\.py", u... | OSError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/localexecution.py/init |
8,463 | def execute_benchmark(benchmark, output_handler):
run_sets_executed = 0
logging.debug("I will use %s threads.", benchmark.num_of_threads)
if benchmark.requirements.cpu_model \
or benchmark.requirements.cpu_cores != benchmark.rlimits.get(CORELIMIT, None) \
or benchmark.requirements... | KeyboardInterrupt | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/localexecution.py/execute_benchmark |
8,464 | def run(self):
while not _Worker.working_queue.empty() and not STOPPED_BY_INTERRUPT:
currentRun = _Worker.working_queue.get_nowait()
try:
logging.debug('Executing run "%s"', currentRun.identifier)
self.execute(currentRun)
logging.debug('Fin... | SystemExit | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/localexecution.py/_Worker.run |
8,465 | def execute(self, run):
"""
This function executes the tool with a sourcefile with options.
It also calls functions for output before and after the run.
"""
self.output_handler.output_before_run(run)
benchmark = self.benchmark
memlimit = benchmark.rlimits.get(MEM... | OSError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/localexecution.py/_Worker.execute |
8,466 | def check_numeric(self, value):
"""Cast value to int or float if necessary"""
if not isinstance(value, (int, float)):
try:
value = int(value)
except __HOLE__:
value = float(value)
return value | ValueError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/packages/openpyxl/cell.py/Cell.check_numeric |
8,467 | def set_value_explicit(self, value = None, data_type = TYPE_STRING):
"""Coerce values according to their explicit type"""
type_coercion_map = {
self.TYPE_INLINE: self.check_string,
self.TYPE_STRING: self.check_string,
self.TYPE_FORMULA: unicode,
self.TYPE_... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/packages/openpyxl/cell.py/Cell.set_value_explicit |
8,468 | @staticmethod
def _gen_tuples(list_object):
while True:
try:
key = list_object.pop()
value = list_object.pop()
except __HOLE__:
raise StopIteration
else:
yield key, value | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/ini_manage.py/_Ini._gen_tuples |
8,469 | def itersubclasses(cls, _seen=None):
"""
itersubclasses(cls)
Generator over all subclasses of a given class, in depth first order.
>>> list(itersubclasses(int)) == [bool]
True
>>> class A(object): pass
>>> class B(A): pass
>>> class C(A): pass
>>> class D(B,C): pass
>>> class E... | TypeError | dataset/ETHPy150Open fp7-ofelia/ocf/expedient/src/python/expedient/common/extendable/inheritance.py/itersubclasses |
8,470 | def test_builtin(self):
for name in ('str', 'str.translate', '__builtin__.str',
'__builtin__.str.translate'):
# test low-level function
self.assertIsNotNone(pydoc.locate(name))
# test high-level function
try:
pydoc.render_doc(n... | ImportError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_pydoc.py/TestHelper.test_builtin |
8,471 | def parse_date(self):
# Try as best we can to parse the date into a datetime object. Note:
# this assumes that we never see a timestamp, just the date, in any
# QIF date.
if self.date != "UNKNOWN":
try:
return dateutil.parser.parse(self.date, dayfirst=self.day... | ValueError | dataset/ETHPy150Open wesabe/fixofx/lib/ofxtools/ofx_statement.py/OfxTransaction.parse_date |
8,472 | def write_input(self, SelPackList=False, check=False):
"""
Write the input.
Parameters
----------
SelPackList : False or list of packages
"""
if check:
# run check prior to writing input
self.check(f='{}.chk'.format(self.name),... | TypeError | dataset/ETHPy150Open modflowpy/flopy/flopy/mbase.py/BaseModel.write_input |
8,473 | @property
def api_version(self):
if not hasattr(self, "_api_version"):
_api_version = None
metas = [x for x in self.parsed.findall(".//meta")
if x.get("name", "").lower() == "api-version"]
if metas:
try:
_api_ve... | TypeError | dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/pip/index.py/HTMLPage.api_version |
8,474 | @property
def verifiable(self):
"""
Returns True if this link can be verified after download, False if it
cannot, and None if we cannot determine.
"""
trusted = self.trusted or getattr(self.comes_from, "trusted", None)
if trusted is not None and trusted:
#... | TypeError | dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/pip/index.py/Link.verifiable |
8,475 | def gds_validate_integer_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
fvalue = float(value)
except (__HOLE__, ValueError), exp:
raise_parse_error(node, 'Requires sequence... | TypeError | dataset/ETHPy150Open lsaffre/lino/lino/sandbox/bcss/SSDNRequest.py/GeneratedsSuper.gds_validate_integer_list |
8,476 | def gds_validate_float_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
fvalue = float(value)
except (TypeError, __HOLE__), exp:
raise_parse_error(node, 'Requires sequence of... | ValueError | dataset/ETHPy150Open lsaffre/lino/lino/sandbox/bcss/SSDNRequest.py/GeneratedsSuper.gds_validate_float_list |
8,477 | def gds_validate_double_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
fvalue = float(value)
except (TypeError, __HOLE__), exp:
raise_parse_error(node, 'Requires sequence o... | ValueError | dataset/ETHPy150Open lsaffre/lino/lino/sandbox/bcss/SSDNRequest.py/GeneratedsSuper.gds_validate_double_list |
8,478 | def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'UserID':
UserID_ = child_.text
UserID_ = self.gds_validate_string(UserID_, node, 'UserID')
self.UserID = UserID_
self.validate_t_SSIN(self.UserID) # validate type t_SSIN
... | ValueError | dataset/ETHPy150Open lsaffre/lino/lino/sandbox/bcss/SSDNRequest.py/AuthorizedUserType.buildChildren |
8,479 | def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'ReturnCode':
sval_ = child_.text
try:
ival_ = int(sval_)
except (TypeError, __HOLE__), exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
... | ValueError | dataset/ETHPy150Open lsaffre/lino/lino/sandbox/bcss/SSDNRequest.py/ResultSummary.buildChildren |
8,480 | def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'SSIN':
SSIN_ = child_.text
SSIN_ = self.gds_validate_string(SSIN_, node, 'SSIN')
self.SSIN = SSIN_
self.validate_t_SSIN(self.SSIN) # validate type t_SSIN
elif nodeNa... | TypeError | dataset/ETHPy150Open lsaffre/lino/lino/sandbox/bcss/SSDNRequest.py/InscriptionType.buildChildren |
8,481 | def fetch(self, url):
socket.setdefaulttimeout(self.socket_timeout)
req = Request(url, headers={'User-Agent': self.user_agent})
try:
resp = fetch(req)
except URLError:
return False
except __HOLE__:
return False
except socket.timeout:
... | HTTPError | dataset/ETHPy150Open coleifer/micawber/micawber/providers.py/Provider.fetch |
8,482 | def handle_response(self, response, url):
try:
json_data = json.loads(response)
except InvalidJson as exc:
try:
msg = exc.message
except __HOLE__:
msg = exc.args[0]
raise InvalidResponseException(msg)
if 'url' not i... | AttributeError | dataset/ETHPy150Open coleifer/micawber/micawber/providers.py/Provider.handle_response |
8,483 | def get_db_version(self):
''' Obtain the database schema version.
Return: (negative, text) if error or version 0.0 where schema_version table is missing
(version_int, version_text) if ok
'''
cmd = "SELECT version_int,version,openmano_ver FROM schema_version"
for r... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.get_db_version |
8,484 | def disconnect(self):
'''disconnect from specific data base'''
try:
self.con.close()
del self.con
except mdb.Error, e:
print "Error disconnecting from DB: Error %d: %s" % (e.args[0], e.args[1])
return -1
except __HOLE__, e: #self.con not de... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.disconnect |
8,485 | def new_row(self, table, INSERT, tenant_id=None, add_uuid=False, log=False, created_time=0):
''' Add one row into a table.
Attribute
INSERT: dictionary with the key: value to insert
table: table where to insert
tenant_id: only useful for logs. If provided, logs will ... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.new_row |
8,486 | def update_rows(self, table, UPDATE, WHERE, log=False, modified_time=0):
''' Update one or several rows into a table.
Atributes
UPDATE: dictionary with the key: value to change
table: table where to update
WHERE: dictionary of elements to update
Return: (resul... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.update_rows |
8,487 | def delete_row(self, table, uuid, tenant_id=None, log=True):
for retry_ in range(0,2):
try:
with self.con:
#delete host
self.cur = self.con.cursor()
cmd = "DELETE FROM %s WHERE uuid = '%s'" % (table, uuid)
... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.delete_row |
8,488 | def delete_row_by_dict(self, **sql_dict):
''' Deletes rows from a table.
Attribute sql_dir: dictionary with the following key: value
'FROM': string of table name (Mandatory)
'WHERE': dict of key:values, translated to key=value AND ... (Optional)
'WHERE_NOT': dict of k... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.delete_row_by_dict |
8,489 | def get_rows(self,table,uuid):
'''get row from a table based on uuid'''
for retry_ in range(0,2):
try:
with self.con:
self.cur = self.con.cursor(mdb.cursors.DictCursor)
self.cur.execute("SELECT * FROM " + str(table) +" where uuid='" + s... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.get_rows |
8,490 | def get_table(self, **sql_dict):
''' Obtain rows from a table.
Attribute sql_dir: dictionary with the following key: value
'SELECT': list or tuple of fields to retrieve) (by default all)
'FROM': string of table name (Mandatory)
'WHERE': dict of key:values,... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.get_table |
8,491 | def get_table_by_uuid_name(self, table, uuid_name, error_item_text=None, allow_serveral=False, WHERE_OR={}, WHERE_AND_OR="OR"):
''' Obtain One row from a table based on name or uuid.
Attribute:
table: string of table name
uuid_name: name or uuid. If not uuid format is found, it i... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.get_table_by_uuid_name |
8,492 | def get_uuid(self, uuid):
'''check in the database if this uuid is already present'''
for retry_ in range(0,2):
try:
with self.con:
self.cur = self.con.cursor(mdb.cursors.DictCursor)
self.cur.execute("SELECT * FROM uuids where uuid='" +... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.get_uuid |
8,493 | def new_vnf_as_a_whole(self,nfvo_tenant,vnf_name,vnf_descriptor,VNFCDict):
print "Adding new vnf to the NFVO database"
for retry_ in range(0,2):
created_time = time.time()
try:
with self.con:
myVNFDict = {}
myVN... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.new_vnf_as_a_whole |
8,494 | def new_scenario(self, scenario_dict):
for retry_ in range(0,2):
created_time = time.time()
try:
with self.con:
self.cur = self.con.cursor()
tenant_id = scenario_dict.get('tenant_id')
#scenario
... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.new_scenario |
8,495 | def edit_scenario(self, scenario_dict):
for retry_ in range(0,2):
modified_time = time.time()
try:
with self.con:
self.cur = self.con.cursor()
#check that scenario exist
tenant_id = scenario_dict.get('tenant_id')... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.edit_scenario |
8,496 | def get_scenario(self, scenario_id, tenant_id=None, datacenter_id=None):
'''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name
scenario_id is the uuid or the name if it is not a valid uuid format
if datacenter_id is provided, it supply aditional vim_id fiel... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.get_scenario |
8,497 | def get_uuid_from_name(self, table, name):
'''Searchs in table the name and returns the uuid
'''
for retry_ in range(0,2):
try:
with self.con:
self.cur = self.con.cursor(mdb.cursors.DictCursor)
where_text = "name='" + name +"'"... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.get_uuid_from_name |
8,498 | def delete_scenario(self, scenario_id, tenant_id=None):
'''Deletes a scenario, filtering by one or several of the tenant, uuid or name
scenario_id is the uuid or the name if it is not a valid uuid format
Only one scenario must mutch the filtering or an error is returned
'''
for ... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.delete_scenario |
8,499 | def new_instance_scenario_as_a_whole(self,tenant_id,instance_scenario_name,instance_scenario_description,scenarioDict):
print "Adding new instance scenario to the NFVO database"
for retry_ in range(0,2):
created_time = time.time()
try:
with self.con:
... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.new_instance_scenario_as_a_whole |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.