Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
3,300
def main(self, folder, field_name, value, as_json=False): fields = folder.get_fields() if as_json: try: value = json.loads(value) except ValueError: raise JirafsError( "Value '%s' could not be decoded as JSON." % ( ...
ValueError
dataset/ETHPy150Open coddingtonbear/jirafs/jirafs/commands/setfield.py/Command.main
3,301
def parse_cpp_files(test_directory): """Parse cpp files looking for snippet marks. Args: test_directory: Directory to look for cpp files in. Returns: Tuple of file_list and snippet_list where file_list is a list of files that need to be updated with documentation and snippet_list is a dictionary of ...
IOError
dataset/ETHPy150Open google/fplutil/docs/update_code_snippets.py/parse_cpp_files
3,302
def update_md_files(md_directory, file_list, snippet_list): """Update md files from snippets. Args: md_directory: Directory to look for md files in. snippet_list: Array of snippets to put into the md files. """ for md_file in file_list: path = find_file(md_file, md_directory) if not path: ...
IOError
dataset/ETHPy150Open google/fplutil/docs/update_code_snippets.py/update_md_files
3,303
def create_project(args): print "Creating your project..." project_name = args.name create_dirs = [ project_name, os.path.join(project_name, 'app/bundles'), os.path.join(project_name, 'app/config') ] for d in create_dirs: try: os.makedirs(d) except...
OSError
dataset/ETHPy150Open gengo/decanter/decanter/decanter-admin.py/create_project
3,304
def send_file(self, fp, headers=None, cb=None, num_cb=10, query_args=None, chunked_transfer=False, size=None): """ Upload a file to a key into a bucket on S3. :type fp: file :param fp: The file pointer to upload. The file pointer must point point at ...
IOError
dataset/ETHPy150Open darcyliu/storyboard/boto/s3/key.py/Key.send_file
3,305
def lex(self): # Get lexer for language (use text as fallback) try: if self.language and unicode(self.language).lower() <> 'none': lexer = get_lexer_by_name(self.language.lower(), **self.custom_args ...
ValueError
dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/pygments_code_block_directive.py/DocutilsInterface.lex
3,306
def __iter__(self): """parse code string and yield "clasified" tokens """ try: tokens = self.lex() except __HOLE__: log.info("Pygments lexer not found, using fallback") # TODO: write message to INFO yield ('', self.code) ...
IOError
dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/pygments_code_block_directive.py/DocutilsInterface.__iter__
3,307
def code_block_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """Parse and classify content of a code_block.""" if 'include' in options: try: if 'encoding' in options: encoding = options['en...
IOError
dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/pygments_code_block_directive.py/code_block_directive
3,308
def get_form(self, request, name): try: ret = self.forms[name] except __HOLE__: ret = self.form if isinstance(ret, basestring): return import_string(ret) else: return ret
KeyError
dataset/ETHPy150Open IanLewis/kay/kay/generics/crud.py/CRUDViewGroup.get_form
3,309
def _normalize_query(uri): query = uri.query try: items = urlparse.parse_qsl(query, keep_blank_values=True, strict_parsing=True) except __HOLE__: # If we can't parse the query string, we better preserve it as it was. return query # Python sorts are stable, so preserving relativ...
ValueError
dataset/ETHPy150Open hypothesis/h/h/api/uri.py/_normalize_query
3,310
def apply_updates(self, branch, initial, pin_unpinned, close_stale_prs=False): InitialUpdateClass = self.req_bundle.get_initial_update_class() if initial: # get the list of pending updates try: _, _, _, updates = list( self.req_bundle.get_upd...
IndexError
dataset/ETHPy150Open pyupio/pyup/pyup/bot.py/Bot.apply_updates
3,311
def perspective_persist(self, profile='jcli-prod', scope='all'): try: if scope in ['all', 'groups']: # Persist groups configuration path = '%s/%s.router-groups' % (self.config.store_path, profile) self.log.info('Persisting current Groups configuration ...
IOError
dataset/ETHPy150Open jookies/jasmin/jasmin/routing/router.py/RouterPB.perspective_persist
3,312
def perspective_load(self, profile='jcli-prod', scope='all'): try: if scope in ['all', 'groups']: # Load groups configuration path = '%s/%s.router-groups' % (self.config.store_path, profile) self.log.info('Loading/Activating [%s] profile Groups configu...
IOError
dataset/ETHPy150Open jookies/jasmin/jasmin/routing/router.py/RouterPB.perspective_load
3,313
def test_listrecursion(self): x = [] x.append(x) try: self.dumps(x) except __HOLE__: pass else: self.fail("didn't raise ValueError on list recursion") x = [] y = [x] x.append(y) try: self.dumps(x) ...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_json/test_recursion.py/TestRecursion.test_listrecursion
3,314
def test_dictrecursion(self): x = {} x["test"] = x try: self.dumps(x) except __HOLE__: pass else: self.fail("didn't raise ValueError on dict recursion") x = {} y = {"a": x, "b": x} # ensure that the marker is cleared ...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_json/test_recursion.py/TestRecursion.test_dictrecursion
3,315
def test_defaultrecursion(self): class RecursiveJSONEncoder(self.json.JSONEncoder): recurse = False def default(self, o): if o is JSONTestObject: if self.recurse: return [JSONTestObject] else: ...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_json/test_recursion.py/TestRecursion.test_defaultrecursion
3,316
def __getitem__(self, value): # The type conversion is required here because in templates Django # performs a dictionary lookup before the attribute lokups # (when a dot is encountered). try: value = int(value) except (__HOLE__, ValueError): # A TypeError ...
TypeError
dataset/ETHPy150Open shtalinberg/django-el-pagination/el_pagination/models.py/PageList.__getitem__
3,317
def _after_exec(self, conn, clause, multiparams, params, results): """ SQLAlchemy event hook """ # calculate the query time end_time = time.time() start_time = getattr(conn, '_sqltap_query_start_time', end_time) # get the user's context context = (None if not self.user_c...
AttributeError
dataset/ETHPy150Open inconshreveable/sqltap/sqltap/sqltap.py/ProfilingSession._after_exec
3,318
def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))): download_IERS_A() for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, fn) if not os.path.exists(dest): url = "http://data.astrometry.net/4200/{}"....
OSError
dataset/ETHPy150Open panoptes/POCS/panoptes/utils/data.py/download_all_files
3,319
def _samefile(src, dst): # Macintosh, Unix. if hasattr(os.path,'samefile'): try: return os.path.samefile(src, dst) except __HOLE__: return False # All other platforms: check for same pathname. return (os.path.normcase(os.path.abspath(src)) == os.path....
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/core/files/move.py/_samefile
3,320
def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_overwrite=False): """ Moves a file from one location to another in the safest way possible. First, tries ``os.rename``, which is simple but will break across filesystems. If that fails, streams manually from one file to anothe...
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/core/files/move.py/file_move_safe
3,321
def try_import(*module_names): for module_name in module_names: try: return import_module(module_name) except __HOLE__: continue
ImportError
dataset/ETHPy150Open mbr/flask-appconfig/flask_appconfig/util.py/try_import
3,322
def test_group_protocols(coordinator): # Requires a subscription try: coordinator.group_protocols() except __HOLE__: pass else: assert False, 'Exception not raised when expected' coordinator._subscription.subscribe(topics=['foobar']) assert coordinator.group_protocols() ...
AssertionError
dataset/ETHPy150Open dpkp/kafka-python/test/test_coordinator.py/test_group_protocols
3,323
def test_fetch_committed_offsets(mocker, coordinator): # No partitions, no IO polling mocker.patch.object(coordinator._client, 'poll') assert coordinator.fetch_committed_offsets([]) == {} assert coordinator._client.poll.call_count == 0 # general case -- send offset fetch request, get successful fu...
AssertionError
dataset/ETHPy150Open dpkp/kafka-python/test/test_coordinator.py/test_fetch_committed_offsets
3,324
def test_commit_offsets_sync(mocker, coordinator, offsets): mocker.patch.object(coordinator, 'ensure_coordinator_known') mocker.patch.object(coordinator, '_send_offset_commit_request', return_value=Future().success('fizzbuzz')) cli = coordinator._client mocker.patch.object(cli, '...
AssertionError
dataset/ETHPy150Open dpkp/kafka-python/test/test_coordinator.py/test_commit_offsets_sync
3,325
def fix_uri(self, text): """ Validates a text as URL format, also adjusting necessary stuff for a clearer URL that will be fetched here. Code based on Django source: https://code.djangoproject.com/browser/django/trunk/django/forms/ fields.py?rev=17430#L610 Argum...
ValueError
dataset/ETHPy150Open brunobraga/termsaver/termsaverlib/screen/helper/urlfetcher.py/URLFetcherHelperBase.fix_uri
3,326
def fetch(self, uri): """ Executes the fetch action toward a specified URI. This will also try to avoid unnecessary calls to the Internet by setting the flag `__last_fetched`. If it can not fetch again, it will simply return the `raw` data that was previously created by a previou...
HTTPError
dataset/ETHPy150Open brunobraga/termsaver/termsaverlib/screen/helper/urlfetcher.py/URLFetcherHelperBase.fetch
3,327
def save(self, delete_zip_import=True, *args, **kwargs): """ If a zip file is uploaded, extract any images from it and add them to the gallery, before removing the zip file. """ super(BaseGallery, self).save(*args, **kwargs) if self.zip_import: zip_file = ZipF...
ImportError
dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/galleries/models.py/BaseGallery.save
3,328
@register.filter def field(form, field): try: return form[field] except __HOLE__: return None
KeyError
dataset/ETHPy150Open nyaruka/smartmin/smartmin/templatetags/smartmin.py/field
3,329
def restart(self, site_id, request): filepath = MOD_WSGI_FILES.get(site_id) if filepath: try: os.utime(filepath, None) return True except __HOLE__: return False return False
IOError
dataset/ETHPy150Open ojii/django-server-manager/server_manager/backends/mod_wsgi.py/ModWSGIBackend.restart
3,330
def get_uptime(self, site_id, request): filepath = MOD_WSGI_FILES.get(site_id) if filepath: try: return datetime.fromtimestamp(os.stat(filepath)[-2]) except __HOLE__: return None return None
IOError
dataset/ETHPy150Open ojii/django-server-manager/server_manager/backends/mod_wsgi.py/ModWSGIBackend.get_uptime
3,331
def set_repeated_blocks(parser): """ helper function to initialize the internal variable set on the parser. """ try: parser._repeated_blocks except __HOLE__: parser._repeated_blocks = {}
AttributeError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/repeatedblocks.py/set_repeated_blocks
3,332
@register.tag def repeated_block(parser, token): try: tag_name, block_name = token.split_contents() except __HOLE__: raise template.TemplateSyntaxError( '{0} tag takes only one argument'.format( token.contents.split()[0])) # initialize attribute storing block cont...
ValueError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/repeatedblocks.py/repeated_block
3,333
@register.tag def repeat(parser, token): try: tag_name, block_name = token.split_contents() except ValueError: raise template.TemplateSyntaxError( '{0} tag takes only one argument'.format( token.contents.split()[0])) # try to fetch the stored block try: ...
AttributeError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/repeatedblocks.py/repeat
3,334
def month_number_from_arg(month, error): try: month_number = Months.options[month] except __HOLE__: error( "Months should be e.g. Jan/January or numbers " "in range 1 (January) to 12 (Dec), not %s" % month ) return 1 else: return month_number
KeyError
dataset/ETHPy150Open sahana/eden/modules/ClimateDataPortal/DSL/Check.py/month_number_from_arg
3,335
def month_filter_number_from_arg(month, error): try: month_number = Months.options[month] except __HOLE__: error( "Months should be e.g. PrevDec/PreviousDecember/Jan/January or numbers " "in range 0 (PreviousDecember) to 12 (Dec), not %s" % month ) return ...
KeyError
dataset/ETHPy150Open sahana/eden/modules/ClimateDataPortal/DSL/Check.py/month_filter_number_from_arg
3,336
@check.implementation(To) def To_check(to_date): to_date.errors = [] error = to_date.errors.append year = to_date.year if to_date.month is None: month = 12 else: month = to_date.month if to_date.day is None: day = -1 else: day = to_date.day if not isinstan...
ValueError
dataset/ETHPy150Open sahana/eden/modules/ClimateDataPortal/DSL/Check.py/To_check
3,337
def get_resultspace_environment(result_space_path, base_env=None, quiet=False, cached=True, strict=True): """Get the environemt variables which result from sourcing another catkin workspace's setup files as the string output of `cmake -E environment`. This cmake command is used to be as portable as possible...
IOError
dataset/ETHPy150Open catkin/catkin_tools/catkin_tools/resultspace.py/get_resultspace_environment
3,338
def load_resultspace_environment(result_space_path, base_env=None, cached=True): """Load the environemt variables which result from sourcing another workspace path into this process's environment. :param result_space_path: path to a Catkin result-space whose environment should be loaded, ``str`` :type ...
TypeError
dataset/ETHPy150Open catkin/catkin_tools/catkin_tools/resultspace.py/load_resultspace_environment
3,339
def _CurrentKey(self): """Return the current key. Returns: str, like 'display_name' """ try: return self._current_key[-1] except __HOLE__: if self._current_mode[-1] == 'dict': # e.g. <string>foo</string> without <key>..</key> before it. raise MalformedPlistError('M...
IndexError
dataset/ETHPy150Open google/simian/src/simian/mac/munki/plist.py/ApplePlist._CurrentKey
3,340
def _BinLoadObject(self, ofs=0): """Load an object. Args: ofs: int, offset in binary Returns: any value of object (int, str, etc..) """ pos = ofs if pos in self.__bin: return self.__bin[pos] objtype = ord(self._plist_bin[pos]) >> 4 objarg = ord(self._plist_bin[pos]) ...
KeyError
dataset/ETHPy150Open google/simian/src/simian/mac/munki/plist.py/ApplePlist._BinLoadObject
3,341
def Equal(self, plist, ignore_keys=None): """Checks if a passed plist is the same, ignoring certain keys. Args: plist: ApplePlist object. ignore_keys: optional, sequence, str keys to ignore. Returns: Boolean. True if the plist is the same, False otherwise. Raises: PlistNotParsed...
KeyError
dataset/ETHPy150Open google/simian/src/simian/mac/munki/plist.py/ApplePlist.Equal
3,342
def _test_database_name(self): name = TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME'] try: if self.connection.settings_dict['TEST_NAME']: name = self.connection.settings_dict['TEST_NAME'] except __HOLE__: pass return name
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/oracle/creation.py/DatabaseCreation._test_database_name
3,343
def _test_database_user(self): name = TEST_DATABASE_PREFIX + self.connection.settings_dict['USER'] try: if self.connection.settings_dict['TEST_USER']: name = self.connection.settings_dict['TEST_USER'] except __HOLE__: pass return name
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/oracle/creation.py/DatabaseCreation._test_database_user
3,344
def _test_database_passwd(self): name = PASSWORD try: if self.connection.settings_dict['TEST_PASSWD']: name = self.connection.settings_dict['TEST_PASSWD'] except __HOLE__: pass return name
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/oracle/creation.py/DatabaseCreation._test_database_passwd
3,345
def _test_database_tblspace(self): name = TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME'] try: if self.connection.settings_dict['TEST_TBLSPACE']: name = self.connection.settings_dict['TEST_TBLSPACE'] except __HOLE__: pass return name
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/oracle/creation.py/DatabaseCreation._test_database_tblspace
3,346
def _test_database_tblspace_tmp(self): name = TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME'] + '_temp' try: if self.connection.settings_dict['TEST_TBLSPACE_TMP']: name = self.connection.settings_dict['TEST_TBLSPACE_TMP'] except __HOLE__: pass...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/oracle/creation.py/DatabaseCreation._test_database_tblspace_tmp
3,347
def _restore_bytes(self, formatted_size): if not formatted_size: return 0 m = re.match(r'^(?P<size>\d+(?:\.\d+)?)\s+(?P<units>[a-zA-Z]+)', formatted_size) if not m: return 0 units = m.group('units') try: exponent = ['B', 'KB', 'MB', 'GB', 'TB',...
ValueError
dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/extractor/channel9.py/Channel9IE._restore_bytes
3,348
@flow.StateHandler(next_state="CheckHash") def ReceiveFileHash(self, responses): """Add hash digest to tracker and check with filestore.""" # Support old clients which may not have the new client action in place yet. # TODO(user): Deprecate once all clients have the HashFile action. if not responses....
KeyError
dataset/ETHPy150Open google/grr/grr/lib/flows/general/transfer.py/MultiGetFileMixin.ReceiveFileHash
3,349
@flow.StateHandler() def LoadComponentAfterFlushOldComponent(self, responses): """Load the component.""" request_data = responses.request_data name = request_data["name"] version = request_data["version"] next_state = request_data["next_state"] # Get the component summary. component_urn =...
IOError
dataset/ETHPy150Open google/grr/grr/lib/flows/general/transfer.py/LoadComponentMixin.LoadComponentAfterFlushOldComponent
3,350
def laplacian_spectrum(G, weight='weight'): """Return eigenvalues of the Laplacian of G Parameters ---------- G : graph A NetworkX graph weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each edge ha...
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/linalg/spectrum.py/laplacian_spectrum
3,351
def adjacency_spectrum(G, weight='weight'): """Return eigenvalues of the adjacency matrix of G. Parameters ---------- G : graph A NetworkX graph weight : string or None, optional (default='weight') The edge data key used to compute each value in the matrix. If None, then each...
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/linalg/spectrum.py/adjacency_spectrum
3,352
def list_related(self, request, pk=None, field_name=None): """Fetch related object(s), as if sideloaded (used to support link objects). This method gets mapped to `/<resource>/<pk>/<field_name>/` by DynamicRouter for all DynamicRelationField fields. Generally, this method probab...
ObjectDoesNotExist
dataset/ETHPy150Open AltSchool/dynamic-rest/dynamic_rest/viewsets.py/WithDynamicViewSetMixin.list_related
3,353
def _set_start_end_params(request, query): format_date_for_mongo = lambda x, datetime: datetime.strptime( x, '%y_%m_%d_%H_%M_%S').strftime('%Y-%m-%dT%H:%M:%S') # check for start and end params if 'start' in request.GET or 'end' in request.GET: query = json.loads(query) \ if isin...
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/api/viewsets/xform_viewset.py/_set_start_end_params
3,354
def ScanForFileSystem(self, source_path_spec): """Scans the path specification for a supported file system format. Args: source_path_spec: the source path specification (instance of dfvfs.PathSpec). Returns: The file system path specification (instance of dfvfs.PathSpec...
RuntimeError
dataset/ETHPy150Open log2timeline/dfvfs/dfvfs/helpers/source_scanner.py/SourceScanner.ScanForFileSystem
3,355
def ScanForStorageMediaImage(self, source_path_spec): """Scans the path specification for a supported storage media image format. Args: source_path_spec: the source path specification (instance of dfvfs.PathSpec). Returns: The storage media image path specification (ins...
RuntimeError
dataset/ETHPy150Open log2timeline/dfvfs/dfvfs/helpers/source_scanner.py/SourceScanner.ScanForStorageMediaImage
3,356
def ScanForVolumeSystem(self, source_path_spec): """Scans the path specification for a supported volume system format. Args: source_path_spec: the source path specification (instance of dfvfs.PathSpec). Returns: The volume system path specification (instance of dfvfs.Pa...
IOError
dataset/ETHPy150Open log2timeline/dfvfs/dfvfs/helpers/source_scanner.py/SourceScanner.ScanForVolumeSystem
3,357
def apply_adaptive_noise(computation_graph, cost, variables, num_examples, parameters=None, init_sigma=1e-6, model_cost_coefficient=1.0, seed=Non...
ValueError
dataset/ETHPy150Open rizar/attention-lvcsr/lvsr/graph.py/apply_adaptive_noise
3,358
def serialWriteEvent(self): try: dataToWrite = self.outQueue.pop(0) except __HOLE__: self.writeInProgress = 0 return else: win32file.WriteFile(self._serial.hComPort, dataToWrite, self._overlappedWrite)
IndexError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/_win32serialport.py/SerialPort.serialWriteEvent
3,359
def run_and_read(view, cmd): out, err = subprocess.Popen([cmd], stdout=PIPE, stderr=PIPE, shell=True).communicate() try: return (out or err).decode('utf-8') except __HOLE__: return ''
AttributeError
dataset/ETHPy150Open guillermooo/Vintageous/ex/plat/linux.py/run_and_read
3,360
def _compute_substitution_score(aln1_chars, aln2_chars, substitution_matrix, gap_substitution_score, gap_chars): substitution_score = 0 for aln1_char, aln2_char in product(aln1_chars, aln2_chars): if aln1_char in gap_chars or aln2_char in gap_chars: substi...
KeyError
dataset/ETHPy150Open biocore/scikit-bio/skbio/alignment/_pairwise.py/_compute_substitution_score
3,361
def __init__(self): self.nodes = [] self.metadata = self.config.get('metadata', {}) try: creator = self.metadata['creator'] except __HOLE__: raise UsageError("Must specify creator metadata.") if not creator.isalnum(): raise UsageError( ...
KeyError
dataset/ETHPy150Open ClusterHQ/flocker/admin/acceptance.py/LibcloudRunner.__init__
3,362
def dataset_backend(self): """ Get the storage driver the acceptance testing nodes will use. :return: A ``BackendDescription`` matching the name of the backend chosen by the command-line options. """ configuration = self.dataset_backend_configuration() # Avoi...
ValueError
dataset/ETHPy150Open ClusterHQ/flocker/admin/acceptance.py/CommonOptions.dataset_backend
3,363
def postOptions(self): if self['distribution'] is None: raise UsageError("Distribution required.") if self['config-file'] is not None: config_file = FilePath(self['config-file']) self['config'] = yaml.safe_load(config_file.getContent()) else: self...
AttributeError
dataset/ETHPy150Open ClusterHQ/flocker/admin/acceptance.py/CommonOptions.postOptions
3,364
def _libcloud_runner(self, package_source, dataset_backend, provider, provider_config): """ Run some nodes using ``libcloud``. By default, two nodes are run. This can be overridden by using the ``--number-of-nodes`` command line option. :param PackageS...
TypeError
dataset/ETHPy150Open ClusterHQ/flocker/admin/acceptance.py/CommonOptions._libcloud_runner
3,365
def parse_line(self, line): """ Given a line with an Eliot message, it inserts the hostname and the system name into the message :param line: The line read from the tail output that was identified as an Eliot message """ try: message = json.loads(...
ValueError
dataset/ETHPy150Open ClusterHQ/flocker/admin/acceptance.py/TailFormatter.parse_line
3,366
def journald_json_formatter(output_file): """ Create an output handler which turns journald's export format back into Eliot JSON with extra fields to identify the log origin. """ accumulated = {} # XXX Factoring the parsing code separately from the IO would make this # whole thing nicer. ...
ValueError
dataset/ETHPy150Open ClusterHQ/flocker/admin/acceptance.py/journald_json_formatter
3,367
def read_basic_config(self): """Read basic options from the daemon config file""" self.config_filename = self.options.config_filename cp = ConfigParser.ConfigParser() cp.read([self.config_filename]) self.config_parser = cp try: self.uid, self.gid = get_uid_gi...
ValueError
dataset/ETHPy150Open kiberpipa/Intranet/pipa/ltsp/src/ltsp_usage_monitor/daemon.py/Daemon.read_basic_config
3,368
def start(self): """Initialize and run the daemon""" # The order of the steps below is chosen carefully. # - don't proceed if another instance is already running. self.check_pid() # - start handling signals self.add_signal_handlers() # - create log file and pid fi...
KeyboardInterrupt
dataset/ETHPy150Open kiberpipa/Intranet/pipa/ltsp/src/ltsp_usage_monitor/daemon.py/Daemon.start
3,369
def stop(self): """Stop the running process""" if self.pidfile and os.path.exists(self.pidfile): pid = int(open(self.pidfile).read()) os.kill(pid, signal.SIGTERM) # wait for a moment to see if the process dies for n in range(10): time.sleep...
OSError
dataset/ETHPy150Open kiberpipa/Intranet/pipa/ltsp/src/ltsp_usage_monitor/daemon.py/Daemon.stop
3,370
def set_uid(self): """Drop root privileges""" if self.gid: try: os.setgid(self.gid) except __HOLE__, (code, message): sys.exit("can't setgid(%d): %s, %s" % (self.gid, code, message)) if self.uid: try: ...
OSError
dataset/ETHPy150Open kiberpipa/Intranet/pipa/ltsp/src/ltsp_usage_monitor/daemon.py/Daemon.set_uid
3,371
def chown(self, fn): """Change the ownership of a file to match the daemon uid/gid""" if self.uid or self.gid: uid = self.uid if not uid: uid = os.stat(fn).st_uid gid = self.gid if not gid: gid = os.stat(fn).st_gid ...
OSError
dataset/ETHPy150Open kiberpipa/Intranet/pipa/ltsp/src/ltsp_usage_monitor/daemon.py/Daemon.chown
3,372
def start_logging(self): """Configure the logging module""" try: level = int(self.loglevel) except __HOLE__: level = int(logging.getLevelName(self.loglevel.upper())) handlers = [] if self.logfile: handlers.append(logging.FileHandler(self.logfi...
ValueError
dataset/ETHPy150Open kiberpipa/Intranet/pipa/ltsp/src/ltsp_usage_monitor/daemon.py/Daemon.start_logging
3,373
def check_pid(self): """Check the pid file. Stop using sys.exit() if another instance is already running. If the pid file exists but no other instance is running, delete the pid file. """ if not self.pidfile: return # based on twisted/scripts/twistd.p...
ValueError
dataset/ETHPy150Open kiberpipa/Intranet/pipa/ltsp/src/ltsp_usage_monitor/daemon.py/Daemon.check_pid
3,374
def get_uid_gid(cp, section): """Get a numeric uid/gid from a configuration file. May return an empty uid and gid. """ uid = cp.get(section, 'uid') if uid: try: int(uid) except __HOLE__: # convert user name to uid try: uid = pwd.ge...
ValueError
dataset/ETHPy150Open kiberpipa/Intranet/pipa/ltsp/src/ltsp_usage_monitor/daemon.py/get_uid_gid
3,375
def daemonize(): """Detach from the terminal and continue as a daemon""" # swiped from twisted/scripts/twistd.py # See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16 if os.fork(): # launch child and... os._exit(0) # kill off parent os.setsid() if os.fork(): # launch child a...
OSError
dataset/ETHPy150Open kiberpipa/Intranet/pipa/ltsp/src/ltsp_usage_monitor/daemon.py/daemonize
3,376
def assertListsEqual(self, list1, list2): try: # Python 3.4 self.assertCountEqual(list1, list2) except __HOLE__: # Python 2.7 self.assertItemsEqual(list1, list2)
AttributeError
dataset/ETHPy150Open mwarkentin/django-watchman/tests/test_utils.py/TestWatchman.assertListsEqual
3,377
def show(self): if not self.window: self.init_ui() try: core.showWindow(self.window) except __HOLE__: self.init_ui core.showWindow(self.window) core.window(self.window, edit=True, w=self.width, h=self.height)
RuntimeError
dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/ui.py/PrevisUI.show
3,378
def _deactivate(method): def deactivate(self): try: method(self) finally: try: self.socket.shutdown(SHUT_RDWR) except (EOFError, __HOLE__): pass if not self.is_active: self.socket.close() return deac...
IOError
dataset/ETHPy150Open osrg/ryu/ryu/controller/controller.py/_deactivate
3,379
@_deactivate def _recv_loop(self): buf = bytearray() required_len = ofproto_common.OFP_HEADER_SIZE count = 0 while self.state != DEAD_DISPATCHER: ret = "" try: ret = self.socket.recv(required_len) except SocketTimeout: ...
IOError
dataset/ETHPy150Open osrg/ryu/ryu/controller/controller.py/Datapath._recv_loop
3,380
def _send_loop(self): try: while self.state != DEAD_DISPATCHER: buf = self.send_q.get() self._send_q_sem.release() self.socket.sendall(buf) except SocketTimeout: LOG.debug("Socket timed out while sending data to switch at address %s...
IOError
dataset/ETHPy150Open osrg/ryu/ryu/controller/controller.py/Datapath._send_loop
3,381
def reserve_experiment(self, experiment_id, serialized_client_initial_data, serialized_consumer_data, client_address, core_server_universal_id ): # Put user information in the session self.get_user_information() self._session['experiment_id'] = experiment_id reservation_info = self._s...
ValueError
dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/weblab/core/user_processor.py/UserProcessor.reserve_experiment
3,382
def run_elastalert(self, rule, args): """ Creates an ElastAlert instance and run's over for a specific rule using either real or mock data. """ # Mock configuration. Nothing here is used except run_every conf = {'rules_folder': 'rules', 'run_every': datetime.timedelta(minutes=5),...
KeyError
dataset/ETHPy150Open Yelp/elastalert/elastalert/test_rule.py/MockElastAlerter.run_elastalert
3,383
def port (tokeniser): if not tokeniser.tokens: raise ValueError('a port number is required') value = tokeniser() try: return int(value) except __HOLE__: raise ValueError('"%s" is an invalid port' % value) if value < 0: raise ValueError('the port must positive') if value >= pow(2,16): raise ValueError('...
ValueError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/configuration/parser.py/port
3,384
def asn (tokeniser, value=None): if value is None: if not tokeniser.tokens: raise ValueError('an asn is required') value = tokeniser() try: if value.count('.'): high,low = value.split('.',1) as_number = (int(high) << 16) + int(low) else: as_number = int(value) return ASN(as_number) except __HOL...
ValueError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/configuration/parser.py/asn
3,385
def ip (tokeniser): if not tokeniser.tokens: raise ValueError('an ip address is required') value = tokeniser() try: return IP.create(value) except (__HOLE__,ValueError,socket.error): raise ValueError('"%s" is an invalid IP address' % value)
IndexError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/configuration/parser.py/ip
3,386
def emit(self, record): """Emits logged message by delegating it """ try: formated = self._serializable_record(record) self._delegate_emit(formated) except (KeyboardInterrupt, __HOLE__): raise # This should really catch every other exception! ...
SystemExit
dataset/ETHPy150Open duerrp/pyexperiment/pyexperiment/Logger.py/MPRotLogHandler.emit
3,387
def getOpenIDStore(filestore_path, table_prefix): """ Returns an OpenID association store object based on the database engine chosen for this Django application. * If no database engine is chosen, a filesystem-based store will be used whose path is filestore_path. * If a database engine is c...
KeyboardInterrupt
dataset/ETHPy150Open necaris/python3-openid/examples/djopenid/util.py/getOpenIDStore
3,388
def _parseHeaders(self, header_file): header_file.seek(0) # Remove the status line from the beginning of the input unused_http_status_line = header_file.readline() lines = [line.strip() for line in header_file] # and the blank line from the end empty_line = lines.pop() ...
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/openid/fetchers.py/CurlHTTPFetcher._parseHeaders
3,389
def fetch(self, url, body=None, headers=None): """Perform an HTTP request @raises Exception: Any exception that can be raised by httplib2 @see: C{L{HTTPFetcher.fetch}} """ if body: method = 'POST' else: method = 'GET' # httplib2 doesn't ...
KeyError
dataset/ETHPy150Open CollabQ/CollabQ/openid/fetchers.py/HTTPLib2Fetcher.fetch
3,390
def _get_shift_key(self, ctx): try: return self._shift_keys[ctx._id_obj] except __HOLE__: pass # create the net shift of self and the context's shift set (applying # self to the ctx's shift set so any re-shifted nodes take the values # from the shift set)...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/context.py/ShiftSet._get_shift_key
3,391
def _shift(self, shift_set_, cache_context=True): """ see shift - this is the implementation called from C, split out so other C functions can call this directly """ # if there's nothing to shift return this context if not shift_set_: return self # ch...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/context.py/MDFContext._shift
3,392
def is_shift_of(self, other): """ returns True if this context's shift set is a super-set of the other context's shift set """ try: return self._is_shift_of_cache[other._id_obj] except __HOLE__: pass if self._parent is not (other._parent o...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/context.py/MDFContext.is_shift_of
3,393
def _set_date(self, date): """ implementation for set_date """ # unwrap if necessary if isinstance(date, NowNodeValue): tmp = cython.declare(NowNodeValue) tmp = date date = tmp.value if date == self._now: return # ...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/context.py/MDFContext._set_date
3,394
def _activate(self, prev_ctx=None, thread_id=None): """set self as the current context""" # activate this context if different from the previous context thread_id = thread_id if thread_id is not None else PyThread_get_thread_ident() if prev_ctx is None: try: p...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/context.py/MDFContext._activate
3,395
def _get_calling_node(self, prev_ctx=None): if prev_ctx is None: thread_id = PyThread_get_thread_ident() try: prev_ctx = _current_contexts[thread_id] except __HOLE__: prev_ctx = None if prev_ctx is None: prev_ctx = ...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/context.py/MDFContext._get_calling_node
3,396
def _get_current_context(thread_id=None): """returns the current context during node evaluation""" if thread_id is None: thread_id = PyThread_get_thread_ident() try: ctx = _current_contexts[thread_id] except __HOLE__: ctx = None if ctx is None: raise NoCurrentContext...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/context.py/_get_current_context
3,397
def __init__ (self,logfile=None,loggername=None,level=logging.INFO): # default is to locate loggername from the logfile if avail. if not logfile: #loggername='console' #handler=logging.StreamHandler() #handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"...
IOError
dataset/ETHPy150Open fp7-ofelia/ocf/ofam/src/src/ext/sfa/util/sfalogging.py/_SfaLogger.__init__
3,398
def pygments_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): try: lexer = get_lexer_by_name(arguments[0]) except __HOLE__: # no lexer found - use the text one instead of an exception lexer = TextLexer() # ...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Pygments-1.3.1/external/rst-directive-old.py/pygments_directive
3,399
def item(title, url, children=None, url_as_pattern=True, hint='', alias='', description='', in_menu=True, in_breadcrumbs=True, in_sitetree=True, access_loggedin=False, access_guest=False, access_by_perms=None, perms_mode_all=True, **kwargs): """Dynamically creates and returns a sitetree i...
ValueError
dataset/ETHPy150Open idlesign/django-sitetree/sitetree/utils.py/item