Dataset Viewer
Auto-converted to Parquet Duplicate
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
def run(self): """ Called when the process intializes. """ logger.info('started worker') FULL_NAMESPACE = settings.FULL_NAMESPACE MINI_NAMESPACE = settings.MINI_NAMESPACE MAX_RESOLUTION = settings.MAX_RESOLUTION full_uniques = FULL_NAMESPACE + 'unique_met...
NotImplementedError
dataset/ETHPy150Open etsy/skyline/src/horizon/worker.py/Worker.run
def create_entropies(vmx, m): try: default_signature = vmx.get_method_signature(m, predef_sign = DEFAULT_SIGNATURE).get_string() l = [ default_signature, entropy( vmx.get_method_signature(m, "L4", { "L4" : { "arguments" : ["Landroid"] } } ).get_string() ), entropy( vmx.ge...
KeyError
dataset/ETHPy150Open androguard/androguard/androguard/core/data/data.py/create_entropies
def new_id(self, i, l): try: return l[i] except __HOLE__: l[i] = len(l) return l[i]
KeyError
dataset/ETHPy150Open androguard/androguard/androguard/core/data/data.py/DexViewer.new_id
@property def storage_path(self): try: conan_user_home = os.getenv("CONAN_USER_HOME") if conan_user_home: storage = self.storage["path"] if storage[:2] == "~/": storage = storage[2:] result = os.path.join(conan_user_...
KeyError
dataset/ETHPy150Open conan-io/conan/conans/client/conf/__init__.py/ConanClientConfigParser.storage_path
def run_tests(tests, test_input, timeout = 60, waittime = 0.1): """ Runs all the tests given by directly executing them. If they return with a non-zero exit code, it adds them to the dictionary returned. Keyword arguments: tests -- a list of paths to executable test files test_input -- ...
IOError
dataset/ETHPy150Open gosquadron/squadron/squadron/tests.py/run_tests
def git_version(): def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LA...
OSError
dataset/ETHPy150Open dnlcrl/PyFunt/setup.py/git_version
def setup_package(): # Rewrite the version file every time write_version_py() cmdclass = {} # Figure out whether to add ``*_requires = ['numpy']``. # We don't want to do that unconditionally, because we risk updating # an installed numpy which fails too often. Just if it's not installed, we ...
ImportError
dataset/ETHPy150Open dnlcrl/PyFunt/setup.py/setup_package
def exclude(self, excludes): """Takes a list of node names and removes all nodes and their successors from the graph. :param excludes: list of node names :type excludes: list of string """ if not excludes: return if not isinstance(excludes, (list, tup...
KeyError
dataset/ETHPy150Open thasso/pyjip/jip/pipelines.py/Pipeline.exclude
def download(uri, filename=None, headers=None, redirect_limit=5, **kwargs): """ Get a remote resource and save the content to a local file. If a local file already exists at the download destination, the modification time of that file is sent in the request headers as the `If-Modified-Since` value to pe...
OSError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/packages/httpstream/__init__.py/download
def ReadFile(filename, logger=None): """Read the contents of the file. An optional logger can be specified to emit messages to your favorite logging stream. If specified, then no exception is raised. This is external so that it can be used by third-party applications. Arguments: filename: (unicode) The ...
IOError
dataset/ETHPy150Open google/yapf/yapf/yapflib/yapf_api.py/ReadFile
@view(path=r'^themes/?$') def index(request): order = request.GET.get('order', '') if not order in ['downloads', 'date']: order = 'downloads' nameFilter = request.GET.get('filter', '') try: page = int(request.GET.get('page', '1')) except __HOLE__: page = 1 themes, page,...
ValueError
dataset/ETHPy150Open y-a-r-g/idea-color-themes/backend/views/themes.py/index
def payment_successful_handler(sender, **kwargs): if sender.payment_status == "Completed": try: token = ShoppingToken.objects.get(value=sender.invoice) token.payed = True token.save() except __HOLE__: pass
ObjectDoesNotExist
dataset/ETHPy150Open y-a-r-g/idea-color-themes/backend/views/themes.py/payment_successful_handler
def test_numparser_strict(): parsenumber = numparser(strict=True) assert parsenumber('1') == 1 assert parsenumber('1.0') == 1.0 assert parsenumber(str(maxint + 1)) == maxint + 1 assert parsenumber('3+4j') == 3 + 4j try: parsenumber('aaa') except __HOLE__: pass # expected ...
ValueError
dataset/ETHPy150Open alimanfoo/petl/petl/test/util/test_parsers.py/test_numparser_strict
def test_laxparsers(): p1 = datetimeparser('%Y-%m-%dT%H:%M:%S') try: p1('2002-12-25 00:00:00') except ValueError: pass else: assert False, 'expected exception' p2 = datetimeparser('%Y-%m-%dT%H:%M:%S', strict=False) try: v = p2('2002-12-25 00:00:00') except _...
ValueError
dataset/ETHPy150Open alimanfoo/petl/petl/test/util/test_parsers.py/test_laxparsers
def logout(self, request): try: request.user.auth_token.delete() except (__HOLE__, ObjectDoesNotExist): pass logout(request) return Response({"success": _("Successfully logged out.")}, status=status.HTTP_200_OK)
AttributeError
dataset/ETHPy150Open Tivix/django-rest-auth/rest_auth/views.py/LogoutView.logout
def search_external_subtitles(path, directory=None): """Search for external subtitles from a video `path` and their associated language. Unless `directory` is provided, search will be made in the same directory as the video file. :param str path: path to the video. :param str directory: directory to s...
ValueError
dataset/ETHPy150Open Diaoul/subliminal/subliminal/video.py/search_external_subtitles
def scan_videos(path, subtitles=True, embedded_subtitles=True, subtitles_dir=None): """Scan `path` for videos and their subtitles. :param str path: existing directory path to scan. :param bool subtitles: scan for subtitles with the same name. :param bool embedded_subtitles: scan for embedded subtitles....
ValueError
dataset/ETHPy150Open Diaoul/subliminal/subliminal/video.py/scan_videos
def _ParseQueueYaml(self): """Loads the queue.yaml file and parses it. Returns: None if queue.yaml doesn't exist, otherwise a queueinfo.QueueEntry object populated from the queue.yaml. """ if hasattr(self, 'queue_yaml_parser'): return self.queue_yaml_parser(self._root_path) if...
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/taskqueue/taskqueue_stub.py/TaskQueueServiceStub._ParseQueueYaml
def add_image_info_cb(self, viewer, channel, image_info): """Almost the same as add_image_info(), except that the image may not be loaded in memory. """ chname = channel.name name = image_info.name self.logger.debug("name=%s" % (name)) # Updates of any extant inf...
KeyError
dataset/ETHPy150Open ejeschke/ginga/ginga/misc/plugins/Contents.py/Contents.add_image_info_cb
def asm(chrom, start, end, bamfilename, reffile, kmersize, tmpdir, mutid='null', debug=False): bamfile = pysam.Samfile(bamfilename,'rb') matefile = pysam.Samfile(bamfilename,'rb') readpairs = {} nreads = 0 ndisc = 0 # track discordant reads rquals = [] mquals = [] for read in bamfil...
ValueError
dataset/ETHPy150Open adamewing/bamsurgeon/bamsurgeon/asmregion.py/asm
def circuit_built(self, circuit): """ICircuitListener API""" # older tor versions will have empty build_flags if 'ONEHOP_TUNNEL' in circuit.build_flags: return if circuit.purpose == 'GENERAL': if len(circuit.path) > 0: if circuit.path[0] not in se...
KeyError
dataset/ETHPy150Open meejah/txtorcon/examples/circuit_failure_rates.py/CircuitFailureWatcher.circuit_built
def circuit_failed(self, circuit, kw): """ICircuitListener API""" if kw['REASON'] != 'MEASUREMENT_EXPIRED': return # older tor versions will have empty build_flags if 'ONEHOP_TUNNEL' in circuit.build_flags: return if circuit.purpose == 'GENERAL': ...
KeyError
dataset/ETHPy150Open meejah/txtorcon/examples/circuit_failure_rates.py/CircuitFailureWatcher.circuit_failed
@nif_blueprint.route('/', methods=['POST', 'GET']) def home(): try: params = get_params(request) algo = params.get("algorithm", None) specific_params = current_app.senpy.parameters(algo) logger.debug( "Specific params: %s", json.dumps(specific_params, indent=4)) p...
ValueError
dataset/ETHPy150Open gsi-upm/senpy/senpy/blueprints.py/home
def automoderate(instance, user): ''' Auto moderates given model instance on user. Returns moderation status: 0 - Rejected 1 - Approved ''' try: status = instance.moderated_object.automoderate(user) except __HOLE__: msg = "%s has been registered with Moderation." % instance._...
AttributeError
dataset/ETHPy150Open dominno/django-moderation/moderation/helpers.py/automoderate
def import_moderator(app): ''' Import moderator module and register all models it contains with moderation ''' from django.utils.importlib import import_module import imp try: app_path = import_module(app).__path__ except __HOLE__: return None try: imp.find_modu...
AttributeError
dataset/ETHPy150Open dominno/django-moderation/moderation/helpers.py/import_moderator
def parse_request(self): """Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back...
IndexError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/BaseHTTPRequestHandler.parse_request
def send_error(self, code, message=None): """Send and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the response code. This sends an error response (so it must be called before any out...
KeyError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/BaseHTTPRequestHandler.send_error
def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all cir...
IOError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/SimpleHTTPRequestHandler.send_head
def nobody_uid(): """Internal routine to get nobody's uid""" global nobody if nobody: return nobody try: import pwd except __HOLE__: return -1 try: nobody = pwd.getpwnam('nobody')[2] except KeyError: nobody = 1 + max(x[2] for x in pwd.getpwall()) r...
ImportError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/nobody_uid
def run_cgi(self): """Execute a CGI script.""" path = self.path dir, rest = self.cgi_info i = path.find('/', len(dir) + 1) while i >= 0: nextdir = path[:i] nextrest = path[i+1:] scriptdir = self.translate_path(nextdir) if os.path....
ValueError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/CGIHTTPRequestHandler.run_cgi
def test(HandlerClass = BaseHTTPRequestHandler, ServerClass = HTTPServer, protocol="HTTP/1.0", port=8000): """Test the HTTP request handler class. This runs an HTTP server on port 8000 (or the first command line argument). """ server_address = ('', port) HandlerClass.protocol_version...
KeyboardInterrupt
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/test
def get_object_from_identifier(identifier, valid=None): """ Helper function to resolve an item identifier into a model instance. Raises StoreException if the identifier is invalid or the requested Model could not be found Raises <Model>.DoesNotExist if the object lookup fails ...
ValueError
dataset/ETHPy150Open klipstein/dojango/dojango/data/modelstore/utils.py/get_object_from_identifier
def get_fields_and_servicemethods(bases, attrs, include_bases=True): """ This function was pilfered (and slightly modified) from django/forms/forms.py See the original function for doc and comments. """ fields = [ (field_name, attrs.pop(field_name)) for \ field_name, obj in attrs.items() if ...
AttributeError
dataset/ETHPy150Open klipstein/dojango/dojango/data/modelstore/utils.py/get_fields_and_servicemethods
def GetCaParameters(settings, ca_id=0, omit_server_private_key=False): """Get ca/cert parameters for CA named ca_id. Note, subtle: If no ca_id value is supplied, the default value from settings.CA_ID is used for the ca_id. This value might make the chosen parameters be NOT from the defaults (no prefix on the ...
AttributeError
dataset/ETHPy150Open google/simian/src/simian/auth/util.py/GetCaParameters
def setup_config(config_dir): """ Setup configuration directory. """ config_dir = os.path.abspath(config_dir) if not os.path.isdir(config_dir): try: os.mkdir(config_dir) except OSError as err: print('Polyglot could not create configuration directory.') pri...
OSError
dataset/ETHPy150Open UniversalDevicesInc/Polyglot/polyglot/__main__.py/setup_config
def run_ginkgo(): parser = argparse.ArgumentParser(prog="ginkgo", add_help=False) parser.add_argument("-v", "--version", action="version", version="%(prog)s {}".format(ginkgo.__version__)) parser.add_argument("-h", "--help", action="store_true", help=""" show program's help text and exit ...
RuntimeError
dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/run_ginkgo
def run_ginkgoctl(): parser = argparse.ArgumentParser(prog="ginkgoctl") parser.add_argument("-v", "--version", action="version", version="%(prog)s {}".format(ginkgo.__version__)) parser.add_argument("-p", "--pid", help=""" pid or pidfile to use instead of target """.strip()) pars...
RuntimeError
dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/run_ginkgoctl
def load_class(class_path): if '.' not in class_path: raise RuntimeError("Invalid class path") module_name, class_name = class_path.rsplit('.', 1) try: try: module = runpy.run_module(module_name) except ImportError: module = runpy.run_module(module_name + ".__...
KeyError
dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/load_class
def resolve_target(target): if target.endswith('.py'): if os.path.exists(target): config = ginkgo.settings.load_file(target) try: return config['service'] except __HOLE__: raise RuntimeError( "Configuration does not spec...
KeyError
dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/resolve_target
def start(self, target, daemonize=True): print "Starting process with {}...".format(target) app = setup_process(target, daemonize) try: app.serve_forever() except __HOLE__: pass finally: app.stop()
KeyboardInterrupt
dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/ControlInterface.start
def _validate(self, pid): try: os.kill(pid, 0) return pid except (__HOLE__, TypeError): print "Process is NOT running."
OSError
dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/ControlInterface._validate
def logtail(self, target): try: app = setup_process(target) app.logger.tail_log() except __HOLE__: pass
KeyboardInterrupt
dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/ControlInterface.logtail
def do_reload(self): try: self.config.reload_file() self.logger.load_config() except __HOLE__, e: logger.warn(e)
RuntimeError
dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/Process.do_reload
def make_all(self, profiler=None, input_storage=None, output_storage=None, storage_map=None): # can't import at toplevel because of circular import TODO: # don't do this ugly hacky way of setting the # filter_checks_isfinite from theano.tensor import TensorType # to set...
NotImplementedError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/compile/debugmode.py/_Linker.make_all
def GenerateOutput(target_list, target_dicts, data, params): user_config = params.get('generator_flags', {}).get('config', None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['conf...
KeyboardInterrupt
dataset/ETHPy150Open francelabs/datafari/debian7/elk/kibana/node/lib/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py/GenerateOutput
@staticmethod def load(path, name, cluster): """ Load a node from from the path on disk to the config files, the node name and the cluster the node is part of. """ node_path = os.path.join(path, name) filename = os.path.join(node_path, 'node.conf') with open(f...
KeyError
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.load
def print_process_output(self, name, proc, verbose=False): try: stderr = proc.communicate()[1] except __HOLE__: stderr = '' if len(stderr) > 1: print_("[%s ERROR] %s" % (name, stderr.strip())) # This will return when exprs are found or it timeouts
ValueError
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.print_process_output
def stress(self, stress_options=None, capture_output=False, whitelist=False,**kwargs): if stress_options is None: stress_options = [] else: stress_options = stress_options[:] stress = common.get_stress_bin(self.get_install_dir()) if self.cluster.cassandra_version...
KeyboardInterrupt
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.stress
def shuffle(self, cmd): cdir = self.get_install_dir() shuffle = common.join_bin(cdir, 'bin', 'cassandra-shuffle') host = self.address() args = [shuffle, '-h', host, '-p', str(self.jmx_port)] + [cmd] try: subprocess.call(args) except __HOLE__: pass
KeyboardInterrupt
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.shuffle
def __update_status(self): if self.pid is None: if self.status == Status.UP or self.status == Status.DECOMMISSIONED: self.status = Status.DOWN return old_status = self.status # os.kill on windows doesn't allow us to ping a process if common.is_wi...
OSError
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.__update_status
def _find_pid_on_windows(self): found = False try: import psutil found = psutil.pid_exists(self.pid) except __HOLE__: print_("WARN: psutil not installed. Pid tracking functionality will suffer. See README for details.") cmd = 'tasklist /fi "PID eq ...
ImportError
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node._find_pid_on_windows
def _update_pid(self, process): pidfile = os.path.join(self.get_path(), 'cassandra.pid') start = time.time() while not (os.path.isfile(pidfile) and os.stat(pidfile).st_size > 0): if (time.time() - start > 30.0): print_("Timed out waiting for pidfile to be filled (cur...
IOError
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node._update_pid
def pause(self): try: import psutil p = psutil.Process(self.pid) p.suspend() except __HOLE__: if common.is_win(): print_("WARN: psutil not installed. Pause functionality will not work properly on Windows.") else: ...
ImportError
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.pause
def resume(self): try: import psutil p = psutil.Process(self.pid) p.resume() except __HOLE__: if common.is_win(): print_("WARN: psutil not installed. Resume functionality will not work properly on Windows.") else: ...
ImportError
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.resume
def _get_load_from_info_output(info): load_lines = [s for s in info.split('\n') if s.startswith('Load')] if not len(load_lines) == 1: msg = ('Expected output from `nodetool info` to contain exactly 1 ' 'line starting with "Load". Found:\n') + info raise RuntimeEr...
KeyError
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/_get_load_from_info_output
def _grep_log_for_errors(log): matchings = [] it = iter(log.splitlines()) for line in it: is_error_line = ('ERROR' in line and 'DEBUG' not in line.split('ERROR')[0]) if is_error_line: matchings.append([line]) try: it, peeker = ...
StopIteration
dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/_grep_log_for_errors
def _get__data_sources_names(self): names = [] for name in self.data_sources: try: self.data_sources[name] + 1 names.append(name) except __HOLE__: pass names.sort() return names # Dictionnary mapping the views
TypeError
dataset/ETHPy150Open enthought/mayavi/mayavi/tools/data_wizards/data_source_wizard.py/DataSourceWizard._get__data_sources_names
def _findNode(self, nodeId): try: return self.getDispatchTree().nodes[int(nodeId)] except __HOLE__: raise NodeNotFoundError(nodeId)
KeyError
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/nodes.py/NodesResource._findNode
def iterOnCommands(self): """ Cancel each command in a node hierarchy (command is given by a generator on the node) Each command might be blocked by network pb (or machine swapping) but asynchronous mecanism will allow other request to be treated between each command cancelation. ...
StopIteration
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/nodes.py/NodeStatusResource.iterOnCommands
def put(self, nodeId): data = self.getBodyAsJSON() try: paused = data['paused'] except __HOLE__: raise Http400('Missing entry: "paused".') except TypeError: raise Http400('Missing entry: "paused".') else: nodeId = int(nodeId) ...
KeyError
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/nodes.py/NodePausedResource.put
def put(self, nodeId): ''' | Put a new value for the maxAttempt attribute of a task node | The new maxAttempt value is taken from request body, for instance : "{ maxAttempt : 10 }" :param nodeId: id of the task node to update ''' # Get task object try: ...
KeyError
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/nodes.py/NodeMaxAttemptResource.put
def __getattr__(self, key): try: return self[key] except __HOLE__: raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
KeyError
dataset/ETHPy150Open michaelliao/transwarp/transwarp/utils.py/Dict.__getattr__
def test_options_without_type(self): query = self.session.query(self.Character.name).filter( match({self.Character.name: 0.5, self.Character.info['race']: 0.9}, 'Trillian', options={'boost': 10.0}) ) err = None try: str(query) ...
ValueError
dataset/ETHPy150Open crate/crate-python/src/crate/client/sqlalchemy/tests/match_test.py/SqlAlchemyMatchTest.test_options_without_type
def conv_TimeField(self, model, field, kwargs): def time_only(obj): try: return obj.time() except __HOLE__: return obj kwargs['filters'].append(time_only) return f.DateTimeField(widget=form.DateTimePickerWidget(), ...
AttributeError
dataset/ETHPy150Open syrusakbary/Flask-SuperAdmin/flask_superadmin/model/backends/django/orm.py/AdminModelConverter.conv_TimeField
def conv_DateTimeField(self, model, field, kwargs): def time_only(obj): try: return obj.time() except __HOLE__: return obj kwargs['filters'].append(time_only) return f.DateTimeField(widget=form.DateTimePickerWidget(), ...
AttributeError
dataset/ETHPy150Open syrusakbary/Flask-SuperAdmin/flask_superadmin/model/backends/django/orm.py/AdminModelConverter.conv_DateTimeField
def conv_DateField(self, model, field, kwargs): def time_only(obj): try: return obj.date() except __HOLE__: return obj kwargs['filters'].append(time_only) return f.DateField(widget=form.DatePickerWidget(), **kwargs)
AttributeError
dataset/ETHPy150Open syrusakbary/Flask-SuperAdmin/flask_superadmin/model/backends/django/orm.py/AdminModelConverter.conv_DateField
def conv_USStateField(self, model, field, kwargs): try: from django.contrib.localflavor.us.us_states import STATE_CHOICES except __HOLE__: STATE_CHOICES = [] return f.SelectField(choices=STATE_CHOICES, **kwargs)
ImportError
dataset/ETHPy150Open syrusakbary/Flask-SuperAdmin/flask_superadmin/model/backends/django/orm.py/AdminModelConverter.conv_USStateField
def refresh(self): """ Refresh the screen. """ super(_CursesScreen, self).refresh() try: sys.stdout.flush() except __HOLE__: pass
IOError
dataset/ETHPy150Open peterbrittain/asciimatics/asciimatics/screen.py/_CursesScreen.refresh
def _print_at(self, text, x, y): """ Print string at the required location. :param text: The text string to print. :param x: The x coordinate :param y: The Y coordinate """ # Move the cursor if necessary msg = "" ...
IOError
dataset/ETHPy150Open peterbrittain/asciimatics/asciimatics/screen.py/_CursesScreen._print_at
def refresh(self): """ Refresh the screen. """ # Flush screen buffer to get all updates after doing the common # processing. Exact timing of the signal can interrupt the # flush, raising an EINTR IOError, which we can safely ignore. su...
IOError
dataset/ETHPy150Open peterbrittain/asciimatics/asciimatics/screen.py/_BlessedScreen.refresh
def get_order_for_user_or_404(user, number): try: return queryset_orders_for_user(user).get(number=number) except __HOLE__: raise Http404()
ObjectDoesNotExist
dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/dashboard/orders/views.py/get_order_for_user_or_404
def handle_line_action(self, request, order, action): if action not in self.line_actions: return self.reload_page(error=_("Invalid action")) # Load requested lines line_ids = request.POST.getlist('selected_line') if len(line_ids) == 0: return self.reload_page(err...
ValueError
dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/dashboard/orders/views.py/OrderDetailView.handle_line_action
def delete_note(self, request, order): try: note = order.notes.get(id=request.POST.get('note_id', None)) except __HOLE__: messages.error(request, _("Note cannot be deleted")) else: messages.info(request, _("Note deleted")) note.delete() ret...
ObjectDoesNotExist
dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/dashboard/orders/views.py/OrderDetailView.delete_note
def _populate_port_ha_information(self, context, port, router_id, hags, user_router_id, modified_interfaces): subnet_id = port['fixed_ips'][0]['subnet_id'] try: hag = hags[subnet_id] except __HOLE__: # Oops, the subnet_id was not foun...
KeyError
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/db/l3/ha_db.py/HA_db_mixin._populate_port_ha_information
@gen_test def test_websocket_handler_bad_token(self): """ A bad token should returns a 401 during a websocket connect """ token = 'A'*32 url = 'ws://127.0.0.1:{0}/hook/{1}'.format(self.get_http_port(), token) request = HTTPRequest(url, headers={'Origin': 'http://exam...
HTTPError
dataset/ETHPy150Open saltstack/salt/tests/unit/netapi/rest_tornado/test_handlers.py/TestWebsocketSaltAPIHandler.test_websocket_handler_bad_token
@gen_test def test_cors_origin_single(self): self._app.mod_opts['cors_origin'] = 'http://example.com' response = yield self.http_client.fetch(self.get_url('/login'), method='POST', body=urlencode(self.au...
HTTPError
dataset/ETHPy150Open saltstack/salt/tests/unit/netapi/rest_tornado/test_handlers.py/TestWebsocketSaltAPIHandler.test_cors_origin_single
@workflow def operation_mapping3(ctx, value, **_): def expect_error(func): try: func('test.operation', kwargs={ 'value': value }).get() except __HOLE__, e: assert 'Duplicate' in e.message node1 = list(ctx.get_node('node1').instances)[0] no...
RuntimeError
dataset/ETHPy150Open cloudify-cosmo/cloudify-manager/tests/mock_plugins/mock_workflows/workflows.py/operation_mapping3
def is_superuser_staff_or_in_translators_group(user): if not getattr(settings, 'ROSETTA_REQUIRES_AUTH', True): return True try: if not user.is_authenticated(): return False elif user.is_superuser and user.is_staff: return True else: return user...
AttributeError
dataset/ETHPy150Open mbi/django-rosetta/rosetta/access.py/is_superuser_staff_or_in_translators_group
def can_translate_language(user, langid): try: if not rosetta_settings.ROSETTA_LANGUAGE_GROUPS: return can_translate(user) elif not user.is_authenticated(): return False elif user.is_superuser and user.is_staff: return True else: return...
AttributeError
dataset/ETHPy150Open mbi/django-rosetta/rosetta/access.py/can_translate_language
def create_authn_response(self, identity, in_response_to, destination, sp_entity_id, name_id_policy=None, userid=None, name_id=None, authn=None, issuer=None, sign_response=None, sign_assertion=None, e...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/server.py/Server.create_authn_response
def create_assertion_id_request_response(self, assertion_id, sign=False, **kwargs): """ :param assertion_id: :param sign: :return: """ try: (assertion, to_sign) = self.session_db.get_assertion(assertion_id) ...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/server.py/Server.create_assertion_id_request_response
def clean_out_user(self, name_id): """ Remove all authentication statements that belongs to a user identified by a NameID instance :param name_id: NameID instance :return: The local identifier for the user """ lid = self.ident.find_local_id(name_id) logg...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/server.py/Server.clean_out_user
def cpu_count(): ''' Returns the number of CPUs in the system ''' if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 elif 'bsd' in sys.platform or sys.platform == 'darwin': comm = '/sbi...
ValueError
dataset/ETHPy150Open benoitc/flower/flower/util.py/cpu_count
def extract_text(escaped_html_str): notes = xml.sax.saxutils.unescape(escaped_html_str) try: from PyQt4 import QtGui except __HOLE__: return str(notes) else: fragment = QtGui.QTextDocumentFragment.fromHtml(notes) return str(fragment.toPlainText()) # The queries are old a...
ImportError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/query/__init__.py/extract_text
@defer.inlineCallbacks def on_PUT(self, request, txn_id): try: defer.returnValue( self.txns.get_client_transaction(request, txn_id) ) except __HOLE__: pass response = yield self.on_POST(request) self.txns.store_client_transaction(...
KeyError
dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/RoomCreateRestServlet.on_PUT
@defer.inlineCallbacks def on_PUT(self, request, room_id, event_type, txn_id): try: defer.returnValue( self.txns.get_client_transaction(request, txn_id) ) except __HOLE__: pass response = yield self.on_POST(request, room_id, event_type, tx...
KeyError
dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/RoomSendEventRestServlet.on_PUT
@defer.inlineCallbacks def on_PUT(self, request, room_identifier, txn_id): try: defer.returnValue( self.txns.get_client_transaction(request, txn_id) ) except __HOLE__: pass response = yield self.on_POST(request, room_identifier, txn_id) ...
KeyError
dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/JoinRoomAliasServlet.on_PUT
@defer.inlineCallbacks def on_PUT(self, request, room_id, membership_action, txn_id): try: defer.returnValue( self.txns.get_client_transaction(request, txn_id) ) except __HOLE__: pass response = yield self.on_POST( request, roo...
KeyError
dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/RoomMembershipRestServlet.on_PUT
@defer.inlineCallbacks def on_PUT(self, request, room_id, event_id, txn_id): try: defer.returnValue( self.txns.get_client_transaction(request, txn_id) ) except __HOLE__: pass response = yield self.on_POST(request, room_id, event_id, txn_id...
KeyError
dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/RoomRedactEventRestServlet.on_PUT
def get_connection(self, address): try: return self.connections[address] except __HOLE__: return None
KeyError
dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/connection.py/ConnectionManager.get_connection
def get_or_connect(self, address, authenticator=None): if address in self.connections: return ImmediateFuture(self.connections[address]) else: with self._new_connection_mutex: if address in self._pending_connections: return self._pending_connec...
KeyError
dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/connection.py/ConnectionManager.get_or_connect
def close_connection(self, address, cause): try: connection = self.connections[address] connection.close(cause) except __HOLE__: logging.warn("No connection with %s was found to close.", address) return False
KeyError
dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/connection.py/ConnectionManager.close_connection
def _inner_acquire(self, blocking, timeout): # make sure our election parent node exists if not self.assured_path: self._ensure_path() node = None if self.create_tried: node = self._find_node() else: self.create_tried = True if not no...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/kazoo-2.0/kazoo/recipe/lock.py/Lock._inner_acquire
def _ensure_path(self): result = self.client.ensure_path(self.path) self.assured_path = True if result is True: # node did already exist data, _ = self.client.get(self.path) try: leases = int(data.decode('utf-8')) except (ValueError...
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/kazoo-2.0/kazoo/recipe/lock.py/Semaphore._ensure_path
def get_partition_names(self, model): current = model._partition_manager.current_partition_key next = model._partition_manager.next_partition_key current_only = self.options.get('current_only') next_only = self.options.get('next_only') if current_only and next_only: ...
IndexError
dataset/ETHPy150Open danfairs/django-parting/parting/management/commands/ensure_partition.py/Command.get_partition_names
def get_model(self): try: model = self.args[0] except IndexError: raise CommandError(u'Please supply at least one partitioned model') try: module_name, model_name = model.rsplit('.', 1) except ValueError: raise CommandError('Bad model name...
AttributeError
dataset/ETHPy150Open danfairs/django-parting/parting/management/commands/ensure_partition.py/Command.get_model
@logging_level.setter def logging_level(self, value): if value is None: value = self._default_logging_level if type(value) is str: try: level = _levelNames[value.upper()] except KeyError: raise ValueError('Unrecognized logging level...
ValueError
dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/searchcommands/search_command.py/SearchCommand.logging_level
@property def search_results_info(self): """ Returns the search results info for this command invocation or None. The search results info object is created from the search results info file associated with the command invocation. Splunk does not pass the location of this file by def...
ValueError
dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/searchcommands/search_command.py/SearchCommand.search_results_info
def process(self, args=argv, input_file=stdin, output_file=stdout): """ Processes search results as specified by command arguments. :param args: Sequence of command arguments :param input_file: Pipeline input file :param output_file: Pipeline output file """ self.logger...
SystemExit
dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/searchcommands/search_command.py/SearchCommand.process
def create_transformer_classes(transformer_spec, config_globals, increment_id): """Create an importer and exporter class from a transformer spec. Args: transformer_spec: A bulkloader_parser.TransformerEntry. config_globals: Dict to use to reference globals for code in the config. increment_id: Method I...
NameError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/bulkload/bulkloader_config.py/create_transformer_classes
End of preview. Expand in Data Studio

CuBERT ETH150 Open Benchmarks

This is an unofficial HuggingFace upload of the CuBERT ETH150 Open Benchmarks. This dataset was released along with Learning and Evaluating Contextual Embedding of Source Code.


Benchmarks and Fine-Tuned Models

Here we describe the 6 Python benchmarks we created. All 6 benchmarks were derived from ETH Py150 Open. All examples are stored as sharded text files. Each text line corresponds to a separate example encoded as a JSON object. For each dataset, we release separate training/validation/testing splits along the same boundaries that ETH Py150 Open splits its files to the corresponding splits. The fine-tuned models are the checkpoints of each model with the highest validation accuracy.

  1. Function-docstring classification. Combinations of functions with their correct or incorrect documentation string, used to train a classifier that can tell which pairs go together. The JSON fields are:
    • function: string, the source code of a function as text
    • docstring: string, the documentation string for that function. Note that the string is unquoted. To be able to properly tokenize it with the CuBERT tokenizers, you have to wrap it in quotes first. For example, in Python, use string_to_tokenize = f'"""{docstring}"""'.
    • label: string, one of (“Incorrect”, “Correct”), the label of the example.
    • info: string, an unformatted description of how the example was constructed, including the source dataset (always “ETHPy150Open”), the repository and filepath, the function name and, for “Incorrect” examples, the function whose docstring was substituted.
  2. Exception classification. Combinations of functions where one exception type has been masked, along with a label indicating the masked exception type. The JSON fields are:
    • function: string, the source code of a function as text, in which one exception type has been replaced with the special token “__HOLE__”
    • label: string, one of (ValueError, KeyError, AttributeError, TypeError, OSError, IOError, ImportError, IndexError, DoesNotExist, KeyboardInterrupt, StopIteration, AssertionError, SystemExit, RuntimeError, HTTPError, UnicodeDecodeError, NotImplementedError, ValidationError, ObjectDoesNotExist, NameError, None), the masked exception type. Note that None never occurs in the data and will be removed in a future release.
    • info: string, an unformatted description of how the example was constructed, including the source dataset (always “ETHPy150Open”), the repository and filepath, and the fully-qualified function name.
  3. Variable-misuse classification. Combinations of functions where one use of a variable may have been replaced with another variable defined in the same context, along with a label indicating if this bug-injection has occurred. The JSON fields are:
    • function: string, the source code of a function as text.
    • label: string, one of (“Correct”, “Variable misuse”) indicating if this is a buggy or bug-free example.
    • info: string, an unformatted description of how the example was constructed, including the source dataset (always “ETHPy150Open”), the repository and filepath, the function, and whether the example is bugfree (marked “original”) or the variable substitution that has occurred (e.g., “correct_variable” → “incorrect_variable”).
  4. Swapped-operand classification. Combinations of functions where one use binary operator’s arguments have been swapped, to create a buggy example, or left undisturbed, along with a label indicating if this bug-injection has occurred. The JSON fields are:
    • function: string, the source code of a function as text.
    • label: string, one of (“Correct”, “Swapped operands”) indicating if this is a buggy or bug-free example.
    • info: string, an unformatted description of how the example was constructed, including the source dataset (always “ETHPy150Open”), the repository and filepath, the function, and whether the example is bugfree (marked “original”) or the operand swap has occurred (e.g., “swapped operands of not in”).
  5. Wrong-binary-operator classification. Combinations of functions where one binary operator has been swapped with another, to create a buggy example, or left undisturbed, along with a label indicating if this bug-injection has occurred. The JSON fields are:
    • function: string, the source code of a function as text.
    • label: string, one of (“Correct”, “Wrong binary operator”) indicating if this is a buggy or bug-free example.
    • info: string, an unformatted description of how the example was constructed, including the source dataset (always “ETHPy150Open”), the repository and filepath, the function, and whether the example is bugfree (marked “original”) or the operator replacement has occurred (e.g., “==-> !=”).
  6. Variable-misuse localization and repair. Combinations of functions where one use of a variable may have been replaced with another variable defined in the same context, along with information that can be used to localize and repair the bug, as well as the location of the bug if such a bug exists. The JSON fields are:
    • function: a list of strings, the source code of a function, tokenized with the vocabulary from item b. Note that, unlike other task datasets, this dataset gives a tokenized function, rather than the code as a single string.
    • target_mask: a list of integers (0 or 1). If the integer at some position is 1, then the token at the corresponding position of the function token list is a correct repair for the introduced bug. If a variable has been split into multiple tokens, only the first subtoken is marked in this mask. If the example is bug-free, all integers are 0.
    • error_location_mask: a list of integers (0 or 1). If the integer at some position is 1, then there is a variable-misuse bug at the corresponding location of the tokenized function. In a bug-free example, the first integer is 1. There is exactly one integer set to 1 for all examples. If a variable has been split into multiple tokens, only the first subtoken is marked in this mask.
    • candidate_mask: a list of integers (0 or 1). If the integer at some position is 1, then the variable starting at that position in the tokenized function is a candidate to consider when repairing a bug. Candidates are all variables defined in the function parameters or via variable declarations in the function. If a variable has been split into multiple tokens, only the first subtoken is marked in this mask, for each candidate.
    • provenance: string, an unformatted description of how the example was constructed, including the source dataset (always “ETHPy150Open”), the repository and filepath, the function, and whether the example is bugfree (marked “original”) or the buggy/repair token positions and variables (e.g., “16/18 kwargsself”). 16 is the position of the introduced error, 18 is the location of the repair.

Citation

@inproceedings{cubert,
author    = {Aditya Kanade and
             Petros Maniatis and
             Gogul Balakrishnan and
             Kensen Shi},
title     = {Learning and evaluating contextual embedding of source code},
booktitle = {Proceedings of the 37th International Conference on Machine Learning,
               {ICML} 2020, 12-18 July 2020},
series    = {Proceedings of Machine Learning Research},
publisher = {{PMLR}},
year      = {2020},
}
Downloads last month
52

Models trained or fine-tuned on claudios/cubert_ETHPy150Open

Paper for claudios/cubert_ETHPy150Open