================================================================================ Example 1 ================================================================================ Target: pcpid = config['PROPERTY_CONSTRAINT_PID'] Prediction: return cls.get_distinct_value_props(sparql_endpoint_url) def get_distinct_value_props(cls, sparql_endpoint_url='https://query.wikidata.org/sparql'): """ On ================================================================================ Example 2 ================================================================================ Target: is_check_by_dropping_pawn = self.was_check_by_dropping_pawn(move) Prediction: if is_suicide: return True else: return False def is_check_by_dropping_pawn(self, move): ''' Checks if the given move would move would leave the king in check or put it into check ================================================================================ Example 3 ================================================================================ Target: self))) Prediction: self) - 1)) self.pop() break return self def setScope(self, scope): """ Set scope scope = 1 -> only one scope (global) """ self.append(NameScopeItem(scope)) ================================================================================ Example 4 ================================================================================ Target: return content Prediction: return content def _get_content(self, data, key): """ get the content from the data :param data: contains the data from the provider :type data: dict :rtype: string """ content = data.get ================================================================================ Example 5 ================================================================================ Target: nodes = [ndict[i] for i in range(self.nnodes)[::-1]] Prediction: if feature is not None: ndict[feature] = self.get_node_values(feature, show_root=True, show_tips=True) else: ndict[self.get_node_name(feature)] = self.get_node_ ================================================================================ Example 6 ================================================================================ Target: finally: Prediction: finally: for key, val in old_environment.items(): del os.environ[key] def _os_encode(val): if isinstance(val, bytes): return val.encode('utf-8') elif isinstance(val, ================================================================================ Example 7 ================================================================================ Target: 'utf-8' Prediction: 'utf-8' return json.dumps(obj, **kwargs) def json_loads(obj, # type: Any **kwargs # type: Any ): # type: (...) -> Any """ Force use of unicode. """ ================================================================================ Example 8 ================================================================================ Target: module = self.load(self.fpath) Prediction: self._confs = uwsgiconf.get_configurations() return self._confs def get_configurations(self): """Get configurations from uwsgiconf module.""" if self._confs is None: return None return ================================================================================ Example 9 ================================================================================ Target: statement.execute(self.sensor_graph, self._scope_stack) Prediction: statement.compile(model) # Create a scope for the root scope root = RootScope(self.sensor_graph, allocator) self._scope_stack.append(root) # Create a scope for the root scope root = RootScope(self. ================================================================================ Example 10 ================================================================================ Target: if os.environ.get('INFLUXDB_PASSWORD'): Prediction: # because it's used by the Python process. _base_tags = base_tags or base_tags or _base_tags if _base_tags is None: _base_tags = {} if _base_url is None: _base_url ================================================================================ Example 11 ================================================================================ Target: if max_connections > 1 and range_get_content_md5 is None: Prediction: if max_connections > 1: file_size = self._get_file_size(share_name, directory_name, file_name, start_range=start_range, end_range=end_range, range_get_content_ ================================================================================ Example 12 ================================================================================ Target: 35' Prediction: 35' ) else: params['until'] = utils.timestamp_to_datetime(until) if follow is None: return self._get_logs(container, stream, params) if follow is True: return self._get_logs ================================================================================ Example 13 ================================================================================ Target: _set_mongodb_host_val('password', MONGODB_DEFAULT_PWD, Prediction: _set_mongodb_host_val('password', MONGODB_DEFAULT_PASSWORD, mongodb_host, mongodb_defaults) _set_mongodb_host_val('dbname', MONGODB_DEFAULT_DB, mong ================================================================================ Example 14 ================================================================================ Target: append((w.x, w.y)) Prediction: append(w) return Polygon(points) def view_indexes(self, done): '''return a list of indexes for the waypoints''' indexes = [] for idx in self.view_indexes(done): indexes.append( ================================================================================ Example 15 ================================================================================ Target: NotImplementedError: Prediction: ue_exception: pass return self.storage.tag(alt, use_size, **attrs) def _get_dimensions(self, alt='', use_size=None, **attrs): """ Return the dimensions of the image. :param ================================================================================ Example 16 ================================================================================ Target: status, headers, data = self._request('GET', url) Prediction: return self.get_response(url, 'text') def search_index(self, index, query, **params): """ Performs a search query. """ if index is None: index = 'search' options = {} ================================================================================ Example 17 ================================================================================ Target: pop("allow_empty", False): Prediction: get('allow_empty'): return [message.strip() for message in message.splitlines() if message.strip()] if not message.strip(): return [message.strip() for message in message.splitlines() if message.strip()] ================================================================================ Example 18 ================================================================================ Target: centiseconds = 0 Prediction: microsecond = local.tm_usec self.microsecond_fraction = local.tm_usec / 1000000000.0 self.microsecond_offset = utils.gmtoffset_from_tm(tm, local) self._initialized = True ================================================================================ Example 19 ================================================================================ Target: if not isinstance(value, models.Model): Prediction: if isinstance(value, models.Model): # If it is, then we need to serialize the model if value.meta.get('pk') is not None: # Get the model's primary key pk = value.meta.get('pk') # ================================================================================ Example 20 ================================================================================ Target: data = self.queue.pop() Prediction: record = self.queue.pop() # Get the next record from the queue next_record = self.queue.pop() # Get the next record from the data queue next_record = next_record.next() # Get the next record from the data ================================================================================ Example 21 ================================================================================ Target: (w, h) = image_shape(thumb) Prediction: x = (self.x() + self.w() / 2) y = (self.y() + self.h() / 2) if x < 0 or y < 0 or x > self.w() or y > self.h(): return # find ================================================================================ Example 22 ================================================================================ Target: try: Prediction: if self.status_data_cite_mds_mds_mds_mds_mds_mds_mds_mds_mds_mds_mds_mds_mds_mds_mds_mds_mds_mds ================================================================================ Example 23 ================================================================================ Target: data['results']) Prediction: data['results']), ])) def get_course_list(data, request): """ Get list of all courses in the course catalog. Arguments: data (dict): Dictionary containing course catalog courses. request (HttpRequest): Current request object. ================================================================================ Example 24 ================================================================================ Target: if (await get_auth(args[-1])) is None: Prediction: try: return await func(*args) except HTTPForbidden as e: raise web.HTTPForbidden(e.message) return wrapper ================================================================================ Example 25 ================================================================================ Target: gene_name) Prediction: gene_name) return self.coregenomes def coregenomes(self): """ Return a list of core genes """ corefile = os.path.join(self.reffilepath, self.analysistype, 'Escherichia', ================================================================================ Example 26 ================================================================================ Target: device = next(d for d in cls._instances[cls._class_group].values() Prediction: if cls is None: return None if cls is None or cls.is_bridge: return None if cls.is_bridge: return None if cls.is_bridge and cls.is_bridge.is_visible ================================================================================ Example 27 ================================================================================ Target: = self.path Prediction: ia_resource_id = resource["resourceId"] if client is not None: query_params["client"] = client return self.set_policy(resource, query_params=query_params) def set_policy(self, resource, query_params=None ================================================================================ Example 28 ================================================================================ Target: 1] Prediction: 1] for prop in props.get("CH", []): mol.atom(prop[0]).mass = prop[1] for prop in props.get("CH2", []): mol.atom(prop[0]).mass = prop[1] for ================================================================================ Example 29 ================================================================================ Target: analyzer.get_analysis_definition() Prediction: analyzer.get_definition() if not definition: continue analysis[analyzer_name] = definition return analysis def get_analyzer_definition(self, analyzer_name): ''' :param analyzer_name: the name of the analyzer ================================================================================ Example 30 ================================================================================ Target: init_from_checkpoint(ckpt_dir, variable_map) Prediction: init_from_checkpoint(reader, ckpt_dir) tf.logging.info("Initializing variables from %s", ckpt_dir) tf.logging.info("Model dir: %s", model_dir) tf.logging.info("Model name ================================================================================ Example 31 ================================================================================ Target: kwargs Prediction: def _get_platform_name(platform): """ Given a platform name, return the platform name. """ if platform == 'win32': return 'win32' elif platform == 'posix': return 'posix' ================================================================================ Example 32 ================================================================================ Target: = coords.galcencyl_to_XYZ(\ Prediction: ia= coords.galcencyl_to_XYZ(\ thiso[0,:],thiso[3,:]-obs.phi(*args,**kwargs), nu.zeros_like(thiso[0]), Xsun=obs.R(*args,** ================================================================================ Example 33 ================================================================================ Target: objt = '"' + obj + '"' Prediction: objt = obj.strip() else: objt = obj # if object is a string, we need to make it a curie if objt == '': objt = 'rdf:type' # if object is a number, we ================================================================================ Example 34 ================================================================================ Target: encoded_string Prediction: ustrlen(encoded_string) def _EncodeBytes(self, bytes): """Encodes a byte array in the preferred encoding. Returns: bytes: encoded byte array. """ try: encoded_bytes = bytes.encode( self._ ================================================================================ Example 35 ================================================================================ Target: str(self.resolve_option("query")) Prediction: icalendar.Query(self.resolve_option("query")) if icalendar.Query(self.resolve_option("query")): return icalendar.Query(self.resolve_option("query")) else: return icalendar.Query(self.resolve ================================================================================ Example 36 ================================================================================ Target: rows_slice) Prediction: slice_slice) slice_slice = slice_queue.get() for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_slice ================================================================================ Example 37 ================================================================================ Target: try: Prediction: if creator is not None: if status == FileStatus.created: if status == FileStatus.created_by: flags |= FileFlags.created_by else: flags |= FileFlags.created_by_and_modified else: flags ================================================================================ Example 38 ================================================================================ Target: setThirdStateChecked(value, ids, dpth + 1, key) Prediction: if isinstance(value, dict): #print "DICT: ", value if 'children' in value and type(value['children']) is list and len(value['children']) > 0: children = value['children'] number_of_possible_checked ================================================================================ Example 39 ================================================================================ Target: Entry Prediction: ical_entry from zinnia.models.tag import Tag tags = Tag.objects.filter(published=True).order_by('-id') return tags @register_tag def tags_published_by_user(name=None): """ ================================================================================ Example 40 ================================================================================ Target: version, target.os_code_name) Prediction: version, target.get('os', None)) if version: statuses.append( { 'name': target.get('name'), 'version': version, 'status': 'Affected' }) status[pkg ================================================================================ Example 41 ================================================================================ Target: = mod_peer_func(trustee) Prediction: iapp_name = 'trusted_device_iapp' mod_peer_func iapp_name = 'trusted_device_iapp_func' trust_device = self.get_trust_device(truster) if trust_device is None: ================================================================================ Example 42 ================================================================================ Target: for i in xrange(1, len(items)+1): Prediction: # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/list-params.html # https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ListTagsForResource.html # https://docs.aws ================================================================================ Example 43 ================================================================================ Target: if stage_minor: Prediction: if stage_minor_sep: stage_minor = stage_minor.split('.')[0] else: stage_minor = '' if stage_minor_sep: stage_minor = stage_minor.split('.')[0] else: ================================================================================ Example 44 ================================================================================ Target: casts' % tmdb_id) Prediction: cast' % tmdb_id) year = get_on_tmdb(u'/movie/%d/year' % tmdb_id) genres = get_on_tmdb(u'/movie/%d/genres' % tmdb_id) ================================================================================ Example 45 ================================================================================ Target: driver.find_element(by=by, value=selector) Prediction: return driver.find_element_by(selector).is_present() except NoSuchElementException: return False def is_element_present_by_css(driver, selector, by=By.CSS_SELECTOR): """ Returns whether the specified element ================================================================================ Example 46 ================================================================================ Target: else: Prediction: elif input.startswith(b'\ufeff'): # Decode the six-byte sequence 0xff FE FF. return '\u00ff', 6 elif input.startswith(b'\u20ac'): # Decode the six-byte sequence 0 ================================================================================ Example 47 ================================================================================ Target: init)() Prediction: init)() # run the worker function if it is given if args.worker: with redirect_stdout(sys.stderr): look_up(args.worker)() # run the finish function if it is given if args.finish: with ================================================================================ Example 48 ================================================================================ Target: print( Prediction: self.log.error('Error loading inventory from cache: %s' % e) return False self.log.info('Loaded inventory from cache') return True def load_inventory_from_file(self): ''' Loads inventory from file. ''' ================================================================================ Example 49 ================================================================================ Target: else: Prediction: else: self.__enqueue(self) def __dealloc__(self): """Deallocate the object.""" self.__dequeue() self.__dealloc_object() def __dealloc_object(self): """Deallocate the object.""" ================================================================================ Example 50 ================================================================================ Target: if child.tail is not None: Prediction: if child.text: result += child.text return result def node_text_list(node): """Needed for things like abstracts which have internal tags (see PMID:27822475)""" if node.text_list: ================================================================================ Example 51 ================================================================================ Target: return [word.lower() for word in phrase if word.lower() not in stopwords] Prediction: return [word for word in phrase if word not in stopwords] def _get_stopwords(phrase): """Get the stopwords from a list of words""" stopwords = [word for word in phrase if word not in stopwords] return stopwords ================================================================================ Example 52 ================================================================================ Target: pkg.parse_version(online_version) Prediction: online_version if recent: print('Updates available!') print('Updates available!') print('Updates available!') print('Updates available!') print('Updates available!') print('Updates available!') ================================================================================ Example 53 ================================================================================ Target: from .viscera import Origin # Lazy. Prediction: from . import MAASClient if insecure: from . import MAASClientInsecure client = MAASClient(url, apikey) return client def connect_to_maas(url, apikey=None, insecure=False): """Connect ================================================================================ Example 54 ================================================================================ Target: reversed(list(leonardo_page.request_processors.values())): Prediction: erc_request_processors: try: fn(request) except: pass # apply filters for fn in erc_filters: try: fn(request) except: pass # apply session middleware ================================================================================ Example 55 ================================================================================ Target: "for computing the PSD. Gates are applied " Prediction: "for PSD.") gate_group.add_argument("--psd-overwhitened", action="store_true", help="Overwhiten data first, then apply the " "gates specified in --psd-gate. Overwhit ================================================================================ Example 56 ================================================================================ Target: except (TypeError, IndexError): Prediction: except ValueError: # if all(isinstance(x, MultiIndex) for x in other): # raise # else: # raise # # if all(isinstance(x, MultiIndex) for x in other): # ================================================================================ Example 57 ================================================================================ Target: 1*self.mesh.velocities.for_computations[:,2] Prediction: self._populate_rv(dataset, **kwargs) rv_cols = self._populate_rv(dataset, **kwargs) # We need to fill all the flux-related columns so that we can weigh each # triangle's rv by its flux in the requested passband. ================================================================================ Example 58 ================================================================================ Target: level Prediction: level def get_env_var(name): '''get the environment variable for the given name''' return os.environ.get(name) def get_env_var_list(name): '''get the environment variable list for the given name''' ================================================================================ Example 59 ================================================================================ Target: else: Prediction: else: model = self._model self.model_name = model.name self.model_version = model.version self.model_version_string = model.version_string self.model_version_date = model.version_date ================================================================================ Example 60 ================================================================================ Target: level]) Prediction: level]) except KeyError: # Unknown level return set() def get_level_methods_by_name(self, level, name): """ Returns the methods to call for the given level of report :param level: The level of report ================================================================================ Example 61 ================================================================================ Target: return ret Prediction: return ret def reshape_like(a, b): """Reshapes a to match the shape of b in all but the last dimension.""" ret = tf.reshape(a, tf.concat([tf.shape(b)[:-1], tf.shape(a ================================================================================ Example 62 ================================================================================ Target: ): Prediction: ast3, # type: Node ast4, # type: Node ast5, # type: Node ast6, # type: Node ast7, # type: Node ast8, # type: Node ast9, ================================================================================ Example 63 ================================================================================ Target: df Prediction: #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ ================================================================================ Example 64 ================================================================================ Target: ' for immediate snapshot cancellation' % volume_id) Prediction: ' as cancelled.' % volume_id) else: click.echo('File volume with id %s has been marked as cancelled.' % volume_id) return True @click.command() @click.argument('volume_id', required=True) @ ================================================================================ Example 65 ================================================================================ Target: of tuples Prediction: ### test_data = self._read_data(test_set) if format is None: format = self.DEFAULT_FORMAT else: format = format or self.DEFAULT_FORMAT if format == "csv": data = self._read_ ================================================================================ Example 66 ================================================================================ Target: next_states[index] = result[len(result) - 1][0]; Prediction: if result == 0: next_states[index] = 0; else: next_states[index] = result; return next_states; def _calculate_states(self, solution, t, step, ================================================================================ Example 67 ================================================================================ Target: 0., 1./self.f, 10./self.f]) Prediction: 0, 1, 10]) # The mle is the maximum likelihood estimate of the signal fraction mle = self.mle # The parabola is the parabola that is the maximum likelihood estimate of the signal fraction parabola = self.parabola ================================================================================ Example 68 ================================================================================ Target: designspace.filename = name Prediction: designspace_file = open(name, "w") # add master styles to designspace file for master in self.masters: master.add_style(self.font.master_styles) # add master styles to designspace file for master in self ================================================================================ Example 69 ================================================================================ Target: bool, Prediction: liveform.LiveForm( makeRemover(i), [liveform.Parameter( 's3lected', liveform.RADIO_INPUT, liveform.LiveForm( makeRemover(i ================================================================================ Example 70 ================================================================================ Target: client_id=self.client_id)) Prediction: self.client), user=user, password=password) try: token = session.get_token(self.client) except OAuth2Error as e: raise TokenCreateError(e) return token def generate_ ================================================================================ Example 71 ================================================================================ Target: try: Prediction: return False try: other_next = next(other_it) except StopIteration: return False if not approx_eq(val_next, other_next, atol): return False if not approx_eq(val ================================================================================ Example 72 ================================================================================ Target: except Exception as e: Prediction: except: logger_start.error("Error reading LiPD file: {}".format(file)) continue logger_start.info("Finished reading LiPD files") logger_start.info("Finished writing LiPD files") return _d def ================================================================================ Example 73 ================================================================================ Target: return pressure.reshape(altitude.shape) Prediction: return pressure def prof_temperature(altitude, z_coef=(1.94170e-9, -5.14580e-7, 4.57018e-5, -1.55620e-3, -4.61994e-2, ================================================================================ Example 74 ================================================================================ Target: "FD": "Floating Point Double (8 bytes)", Prediction: "FR": "Floating Point Double (8 bytes)", "GA": "General Attribute", "GS": "General String", "GT": "General Time", "H": "Humanoid", "I": "Integer", "J": " ================================================================================ Example 75 ================================================================================ Target: = 'number_value': Prediction: 'kind': return google.protobuf.FieldDescriptorProto.Kind.value_descriptor.EnumValueDescriptorProto.value_descriptor.EnumValueDescriptorProto.value_descriptor.EnumValueDescriptorProto.value_descriptor.EnumValueDescriptorProto.value_descriptor.EnumValueDescriptorProto.value_descriptor ================================================================================ Example 76 ================================================================================ Target: headers = get_headers(profile) Prediction: if url.startswith('https://api.github.com/repos/'): url = url[len('https://api.github.com/repos/'):] if url.startswith('https://api.github.com/users/'): url = url ================================================================================ Example 77 ================================================================================ Target: parent = parent.parent Prediction: parent = parent.parent if parent.name not in ('register', ): return False return True def is_templatetags_module_valid_function(node): """Suppress warnings for valid functions in templatetags module.""" ================================================================================ Example 78 ================================================================================ Target: name = model.name Prediction: name = self.name if not name: name = self.name_short if not name: name = self.name_long if not name: name = self.name_full if not name: name = self.name ================================================================================ Example 79 ================================================================================ Target: inference_time) Prediction: it) current_model['mean'].append(inference_time) current_model['stddev'].append(inference_time) current_model['name'] = model current_model['iters'] = iters current_model['mean'] = ================================================================================ Example 80 ================================================================================ Target: InputMode.INSERT Prediction: irc_mode get_app().vi_state.input_mode_buffer.set_state(irc_mode) # Go to insert mode. get_app().vi_state.input_mode = irc_mode get_app().vi_state.input ================================================================================ Example 81 ================================================================================ Target: output) Prediction: output) logger.info("Build complete.") def run_configure(self, mandatory=False): """Run 'configure' and return the result. The result is a string containing the name of the compiler, the name of the compiler's library, the compiler ================================================================================ Example 82 ================================================================================ Target: value Prediction: ivalue else: if _type == "bool": return value == "True" elif _type == "int": return value == 1 elif _type == "float": return value == 1.0 elif _type == "list": ================================================================================ Example 83 ================================================================================ Target: tables) Prediction: ustr(self.database)) # Get table data rows = [] for table in tables: rows.append(self._get_table_data(table, source, commands)) return dict(rows) def _get_table_data(self, table ================================================================================ Example 84 ================================================================================ Target: t2 in arg_types: Prediction: ia1 in arg_types: for ia2 in arg_types: if not (t1 == ia1 and t1 == ia2): continue if not (t1 == ia1 and t2 == ia2): continue ================================================================================ Example 85 ================================================================================ Target: == 1: Prediction: ia 64: header = "\n".join(( "P7", "MAXVAL %i" % self.maxval, "\n".join("TUPLTYPE %s" % unicode(i) for i in self.tupltypes), "ENDH ================================================================================ Example 86 ================================================================================ Target: partial(worker, model), args)) Prediction: _gene_deletion_worker, _reaction_deletion_worker, entity )) results.set_index('ids', inplace=True) results.columns = ['ids'] results.sort_values('growth', ascending=True) ================================================================================ Example 87 ================================================================================ Target: qstim.setEditor(template['testtype']) Prediction: return stim, qstim def loadFromFile(file, stim=None): """Initialized this stimulus from a saved *file* :param file: file from a previously stored stimulus via :class:`templateDoc` :type file: str """ stim ================================================================================ Example 88 ================================================================================ Target: source: Prediction: ., target: raise ValueError("target must be a list or a comma separated list of targets") if not SCons.Util.is_List(source): source = [source] if not SCons.Util.is_List(args): args = [ ================================================================================ Example 89 ================================================================================ Target: if dtype == np.int8: Prediction: if dtype == 'float32': dtype = np.float32 elif dtype == 'float64': dtype = np.float64 else: raise ValueError('dtype must be float32 or float64') if batch_size is None: ================================================================================ Example 90 ================================================================================ Target: as_view=handler.as_view) Prediction: handler) def generic_api_view_factory(injector): """Create DRF generic class-based API view factory from injector class.""" handler = create_handler(GenericAPIViewFactory, injector) apply_http_methods(handler, injector) ================================================================================ Example 91 ================================================================================ Target: self.safe_exceptions: Prediction: erts_errors: print(e) else: print('Error: %s' % e) else: if self.last_cmd: self.last_cmd = tokens else: print('No previous command.') ================================================================================ Example 92 ================================================================================ Target: indexdir / "cumindex.hdf" Prediction: path + "COISS_2999_index.hdf" df = pd.read_hdf(path, "df") return df def read_cumulative_iss_index_with_date_index(): "Read in the whole cumulative index and return data ================================================================================ Example 93 ================================================================================ Target: getConstant('general__enableCronTasks'): Prediction: Series.objects.filter(status=Series.STATUS_OPEN).exists(): return else: return False def updateSeriesRegistrationStatus(self): ''' Update the status of the series that are currently open for registration ''' self.status ================================================================================ Example 94 ================================================================================ Target: error() Prediction: error(errno.ECONNRESET) return value def _write_socket(self, data): """ Writes data to socket. :param data: Data to write :return: True if data was written """ if not data ================================================================================ Example 95 ================================================================================ Target: for name, value in term_dict.items(): Prediction: if term_dict: term_strings.append(term_dict) if escape: term_strings.append('%s%s' % (escape, term_strings)) return self.search(term_strings) def search_with_additional_ ================================================================================ Example 96 ================================================================================ Target: logger.debug('Application returned None ' Prediction: return self.handle_error(env, data) else: return self.handle_response(env, response) except webob.HTTPException: return self.handle_error(env, data) except Exception: return self.handle_error ================================================================================ Example 97 ================================================================================ Target: key = (type_module, type_name) Prediction: if type_name == 'dtype': return format_dtype(self, type_module, type_name, func) elif type_name == 'float': return format_float(self, type_module, type_name, func) elif type_ ================================================================================ Example 98 ================================================================================ Target: self.draw_footer_status() Prediction: self.header.draw(self.statuses) self.header.draw(self.selected) self.header.draw(self.full_redraw_statuses) self.header.draw(self.full_redraw_statuses_selected) ================================================================================ Example 99 ================================================================================ Target: ax=None, Prediction: fontsize=None, fontname='Helvetica', fontsize_h=12, fontname_h='Helvetica', fontsize_v=12, fontname_v='Helvetica', fontsize_h_v= ================================================================================ Example 100 ================================================================================ Target: == self._type_time: Prediction: ~~ self.subtype: value = self.input_type.get_python() elif self.input_type.get_python() == self.subtype.get_python(): value = self.input_type.get_python() else: # ================================================================================ Example 101 ================================================================================ Target: elif isinstance(value, list): Prediction: else: raise TypeError("Expected a Document or DocumentList, got %s" % type(value)) def wrap_list(value): """ Wraps the given value in a DocumentList as applicable. """ if isinstance(value, DocumentList ================================================================================ Example 102 ================================================================================ Target: expanded = expand_variable_dicts(aligned) Prediction: if explicit_coords is not None: explicit_coords = set(explicit_coords) else: explicit_coords = None if explicit_coords is not None: explicit_coords = set(explicit_co ================================================================================ Example 103 ================================================================================ Target: if command in help_topics: Prediction: if verbose: print(" %s: %s" % (command, func)) if has_help_func: cmds_doc.append(func) cmds_undoc.append(func) cmds_cats[command] = func ================================================================================ Example 104 ================================================================================ Target: app_path Prediction: ustrime(app_path) def _get_server_url(url): ''' Extract the server URL from a Bokeh server URL Args: url (str) : Returns: str ''' server_url = urlparse(url ================================================================================ Example 105 ================================================================================ Target: } Prediction: } self.application_2_add.append(application) self.save() else: self.application_2_add.append(application) return application def remove_application(self, application): """ remove an application from ================================================================================ Example 106 ================================================================================ Target: 'stdout'] Prediction: 0] def upgrade_all(name, version=None, source=None, force=False, pre_versions=False, install_args=None, override_args=False, force_x86=False, ================================================================================ Example 107 ================================================================================ Target: else: Prediction: else: params += ["--variant", in_file, "--output", tx_recal, "--tranches-file", tx_tranches, "--rscript-file", tx_plot_file] broad_runner.run(params, tx_recal, ================================================================================ Example 108 ================================================================================ Target: ) Prediction: ) return True def fire_failed_msisdn_lookup_with_identity(self, to_identity): """ Fires a webhook in the event of a None to_addr. """ payload = {"to_identity": to_identity ================================================================================ Example 109 ================================================================================ Target: return os.path.basename(full_path) Prediction: return full_path return None def get_notebook_path(kernel_id): """ Return the full path of the jupyter notebook. """ kernel_id = re.search('kernel-(.*).json', ipy ================================================================================ Example 110 ================================================================================ Target: = VkInstance_T() Prediction: iaDevice = c_uint64() pDevice = c_uint64() pDevice = c_uint64() pDevice = c_uint64() pDevice = c_uint64() pDevice = c_uint64() pDevice = c ================================================================================ Example 111 ================================================================================ Target: chunksize=chunksize) Prediction: chunksize=chunksize) def read_query(self, query_string, index_col=None, coerce_float=True, parse_dates=None, columns=None, schema=None, chunksize=None): """Read ================================================================================ Example 112 ================================================================================ Target: else: Prediction: else: return data def has_multiple_timesteps(data): """Check if data has multiple timesteps.""" if not data.has_index: return False return len(data.index) > 1 def has_consistent_ ================================================================================ Example 113 ================================================================================ Target: bin_width) Prediction: mmin + self.bin_width) return mag, beta, moment_rate def get_mfd_rate(self, slip, area, shear_modulus=30.0): ''' Calculates activity rate on the fault :param float slip: ================================================================================ Example 114 ================================================================================ Target: '//', 1)[1]).replace('.', r'\.'))) Prediction: '.')[0]), re.I), # OSS Path # - oss:/// # - oss://.oss-.aliyuncs.com/ # - oss://.oss-< ================================================================================ Example 115 ================================================================================ Target: if request.status_code == 200: Prediction: return request.status_code == 200 ================================================================================ Example 116 ================================================================================ Target: sys.exit(0) Prediction: sys.exit(0) except OSError as err: sys.stderr.write("Second fork failed: {0} ({1})\n".format(err.errno, err.strerror)) sys.exit(1) # decouple from parent environment ================================================================================ Example 117 ================================================================================ Target: c.fetchone() Prediction: c.fetchone() if row: return row[0] else: raise ValueError("No primary text for %s" % item_url) def get_secondary_text(self, item_url): """ Retrieve the secondary text for the ================================================================================ Example 118 ================================================================================ Target: try: Prediction: if k in atom_uniparc_keys: uparc_id_1 = atom_uniparc_keys[k] uparc_id_2 = atom_uniparc_keys[k] else: uparc_id_1 = None ================================================================================ Example 119 ================================================================================ Target: else: Prediction: else: return False except Exception as e: print('error', e) return False def launch_app_with_timeout(app_path, params=[], time_before_kill_app=15): """ start an app with a ================================================================================ Example 120 ================================================================================ Target: data Prediction: irc_client.replace_namespaced_stateful_set_scale_with_http_info(data, **kwargs) # noqa: E501 def replace_namespaced_stateful_set_scale_with_http_info(self, name, namespace, body, ** ================================================================================ Example 121 ================================================================================ Target: else: Prediction: else: body_json[key] = value # Add in parameters from the body. for key, value in method_parameters.iteritems(): if key in body_json: body_json[key] = value + body_json[key] ================================================================================ Example 122 ================================================================================ Target: combinations_map = {} Prediction: for i in range(self.n_outputs): available.add(i) available.remove(self.n_outputs) available.add(self.n_outputs) available.remove(self.n_outputs) available.add(self. ================================================================================ Example 123 ================================================================================ Target: 'LINKS %s' % r_server) Prediction: r_server.get_server_name()) else: self.send(mask) return self.get_links() def get_links(self): """ Get LINKS information. Optional arguments: * r_server=None - ================================================================================ Example 124 ================================================================================ Target: return session Prediction: def init_db_test(drop_all=False): """Initialize the database, optionally dropping existing tables.""" if drop_all: Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) ================================================================================ Example 125 ================================================================================ Target: **filter_settings) Prediction: filter_name, filters_settings) filter_set.append(filter_item) else: filter_set = self._filters[filter_name] if filter_set: filter_set.append(filters_settings) else: ================================================================================ Example 126 ================================================================================ Target: = True Prediction: ~~= True else: d[col[0]] = False elif col[0] in ["present", "tried_storage"]: if row[idx] == 0: d[col[0]] = False elif row[idx] == 1 ================================================================================ Example 127 ================================================================================ Target: "IBAN": account.iban, Prediction: "type": "transfer", "recipient_name": recipient_name, "amount": amount, "account_name": account_name, "reason": reason, "endtoend_id": endtoend_id, } ================================================================================ Example 128 ================================================================================ Target: builder.add_permute(name, axes, input_name, output_name) Prediction: if axes: axes = [axes] if param['type'] == 'convolutional': conv_type = 'conv' elif param['type'] == 'maxpool': conv_type = 'maxpool' elif param['type'] == ' ================================================================================ Example 129 ================================================================================ Target: 13: '%s:21' % main_head, Prediction: 13: '%s:20' % main_head, 14: '%s:21' % main_head, 15: '%s:22' % main_head, 16: '%s:23' % main_head, 17: '%s:24' ================================================================================ Example 130 ================================================================================ Target: counter_type = self._property_counter_types.get(property_name) Prediction: if property_raw_value is not None: formatted_wmi_object[property_name] = property_raw_value return formatted_wmi_object def _format_property_values(self, previous, current): """ Format WMI ================================================================================ Example 131 ================================================================================ Target: maximum = validators.numeric(maximum, Prediction: maximum = validators.numeric(maximum, allow_empty = True) if minimum is None and maximum is None: raise ValueError('minimum and maximum cannot both be None') if minimum is None and maximum is None: raise ValueError('minimum and maximum ================================================================================ Example 132 ================================================================================ Target: self.recurse(i, *args) Prediction: recurse(i, *args) return self def __str__(self): return 'Hypercat(%s)' % self.name class Hypercat(Hypercat): """A hypercat is a hypercat.""" def __init__(self, name, ================================================================================ Example 133 ================================================================================ Target: return exp_dict Prediction: self.logger.info(" Created experiment directory %s", exp_dir) return exp_dict def _experiment(self, **kwargs): """ Get the next experiment id from the experiment list Parameters ---------- **kwargs Keyword ================================================================================ Example 134 ================================================================================ Target: extensions = [ Prediction: if overwrite: req.overwrite() return self.create_signed_pair(req, ca_name, cert_type, bits, years, alt_names, serial) def create_signed_pair(self, req, ca_name, cert ================================================================================ Example 135 ================================================================================ Target: otc * np.cos(self.ang) Prediction: c * self.w * self.otc2a * np.cos(self.ang) num2b = self.c * self.w * self.otc2b * np.cos(self.ang) num2 = num2a + num2b ================================================================================ Example 136 ================================================================================ Target: lat_lon): Prediction: prop, compare, extreme, val): if prop in bounds: return True else: return False return bound_check def _get_bounds(self, prop, compare, extreme, val): """Get bounds for a property.""" if prop ================================================================================ Example 137 ================================================================================ Target: fcf_map_name_key = ET.SubElement(fcoe_fcf_map, "fcf-map-name") Prediction: fcoe_fcf_map_name_key = ET.SubElement(fcoe_fcf_map, "fcoe-fcf-map-name") fcoe_fcf_map_name_key.text = kwargs.pop('fcoe_fcf_ ================================================================================ Example 138 ================================================================================ Target: self Prediction: # -------------------------------------------------------------------- # _keep_positive_counts() # -------------------------------------------------------------------- # -------------------------------------------------------------------- # _keep_positive_counts() # -------------------------------------------------------------------- def _keep_positive_counts(self): '''Internal method to strip elements with a negative or ================================================================================ Example 139 ================================================================================ Target: jconf) Prediction: ]) return pickledRDD def saveAsNewAPIHadoopFile(self, path, outputFormatClass, keyClass=None, valueClass=None, keyConverter=None, valueConverter=None, conf=None): """ Output a Python RDD ================================================================================ Example 140 ================================================================================ Target: thisDict["name"] = values[0].strip() Prediction: thisDict["name"] = values[0] thisDict["raDeg"] = values[1] thisDict["decDeg"] = values[2] thisDict["z"] = values[3] else: thisDict["name"] = values[0 ================================================================================ Example 141 ================================================================================ Target: self._Tij = np.array(Tij) Prediction: self.transition_matrix = self.transition_matrix.copy() self.transition_matrix.update(Tij) # update transition matrix by reference self.transition_matrix = self.transition_matrix.copy() self.transition_matrix.update(Pi) ================================================================================ Example 142 ================================================================================ Target: None): Prediction: labels, ax=ax, names=names, latex_names=latex_names): plt.plot(xres[idx], varied_data[idx], 'o', label=labels[idx], color=c[idx], linewidth=2 ================================================================================ Example 143 ================================================================================ Target: record.set_content_length() Prediction: record.compute_length(payload_offset) self._params.length = record.length self._params.checksums = record.checksums def _set_content_length(self, record, payload_offset=None): '''Set the content length.''' ================================================================================ Example 144 ================================================================================ Target: 1) Prediction: ]) if onet: if onet: if not kwargs.get('use_physical'): kwargs['use_physical']= True kwargs['physical_scale']= thiso.shape[0] else: kwargs['use_physical'] ================================================================================ Example 145 ================================================================================ Target: expr) Prediction: expr) if self.storagehandler.storage[str(self.resolve_option("storage_name"))] is None: return "Storage handler does not exist!" if self.storagehandler.storage[str(self.resolve_option("storage_name"))] is not None ================================================================================ Example 146 ================================================================================ Target: if model_list: Prediction: if model_list: site_models[app_config.get_app_label()] = model_list return site_models def get_model_list(self, model_name): """Returns a list of models by model name. """ ================================================================================ Example 147 ================================================================================ Target: None: Prediction: ublox.web.WebSocket: """ Add a WebSocket connection to the given path. :param path: The path to the WebSocket connection. :param endpoint: The endpoint to connect to. :param view_func: The view function to call when the ================================================================================ Example 148 ================================================================================ Target: try: Prediction: try: klass = klass() except Exception as e: logger.error("Error loading job module %s: '%s'", mod_name, e) return return klass def get_job_class(klass_str): ================================================================================ Example 149 ================================================================================ Target: False Prediction: ~~value if value.lower().strip() in trues: return value return value def is_number(value): """Evaluate a value for numberness >>> is_number(1) True >>> is_number(1.0) ================================================================================ Example 150 ================================================================================ Target: result = self.library.Cli_Disconnect(self.pointer) Prediction: self.client.disconnect() logger.info("disconnected snap7 client") def _get_snap_id(self): """ get the snap id of a client. """ snap_id = self.client.get_snap_id() ================================================================================ Example 151 ================================================================================ Target: context in list(self._key_by_context): Prediction: ia in self._connections: ia.close() finally: self._lock.release() def _get_connection(self, ia): """ Return a connection object for the given ia. """ self._lock.acquire ================================================================================ Example 152 ================================================================================ Target: value, kind = struct.unpack('>ifb', fd.read(9)) Prediction: ival = struct.unpack(">i", fd.read(4))[0] self.tracks[row] = ival return self def get_tracks(self): """Return the tracks""" return self.tracks def get_tracks_by ================================================================================ Example 153 ================================================================================ Target: else: Prediction: else: return '[&B] %s%s' % (self.root.newick(),suffix) def __str__(self): return self.newick() def __repr__(self): return self.newick() def __eq ================================================================================ Example 154 ================================================================================ Target: (num_bytes,) = FIELD_U16.unpack_from(buf) Prediction: buf = buf[:FIELD_U16.size] return buf[0] def decode_int(f): """Decode a buffer length from a 2-byte unsigned int then read the subsequent bytes. Parameters ---------- f: file ================================================================================ Example 155 ================================================================================ Target: if not fields: Prediction: request['session'] = session request['fields'] = fields return request.execute() ================================================================================ Example 156 ================================================================================ Target: is_bit_set = lambda b: self.value & (1 << (b - 1)) > 0 Prediction: except ValueError: raise InvalidMessageError( 'Invalid message: %s' % data) def _parse_message_from_file(self, data): """ Parses the raw message from a file. :param data: message data ================================================================================ Example 157 ================================================================================ Target: port) Prediction: port) waiting_url = server_url + waiting_msg nonres_url = server_url + nonres_msg waiting_url += '?timeout=%s' % timeout nonres_url += '?timeout=%s' % timeout wait ================================================================================ Example 158 ================================================================================ Target: return chem Prediction: return chem def get_cell_chemistry(self): ''' Get cell chemistry ''' length = self.bus.read_byte_data(self.address, 0x79) chem = [] for n in range(length): chem.append( ================================================================================ Example 159 ================================================================================ Target: confirm( Prediction: echo("Sending public key type='{}' keyid='{}'".format(kind, keyid)) cmd_ssh.send_public_key(pubkey) else: click.echo("Sending public key type='{}' keyid='{}'".format( ================================================================================ Example 160 ================================================================================ Target: layers if layer_filter(x)] Prediction: ].filter(layer_filter) if not valid_layers: return None if color is not None: color = Image.fromarray(color) else: color = Image.new('RGB', (0, 0, 0), color) if ================================================================================ Example 161 ================================================================================ Target: else: Prediction: else: return [self.get_3_tuple(obj,default) for o in obj] def get_3_tuple(self,obj,default=None): """Return 3-tuple from sequence of a sequence, sequence - it is mapped to ================================================================================ Example 162 ================================================================================ Target: 4]) Prediction: 1:]) else: # If we're at the end of a line, we need to check the next line. if token[0] == '\n': self.check_physical(token[1:]) else: # Otherwise, we need to ================================================================================ Example 163 ================================================================================ Target: dep_transf_cbs=repeat(dep_tr) if dep_tr is not None else None, Prediction: dep_transf=list(zip(list(map(dep_tr[0], dep)), list(map(dep_tr[1], dep)) if dep_tr is not None else None), indep_transf=((ind ================================================================================ Example 164 ================================================================================ Target: for threshold, color in threshold_list: Prediction: # Loop through the threshold list and find the color that is closest to the # threshold value for threshold_list_item in threshold_list: threshold_value = threshold_list_item[0] threshold_value_color = threshold_list_item[1] ================================================================================ Example 165 ================================================================================ Target: filter = [ Prediction: return minID, maxID def get_max_id_by_name(self, object_type, role, name): """Get the highest used ID by name.""" if object_type == 'user': objectclass = 'posixAccount' ld ================================================================================ Example 166 ================================================================================ Target: orig_request.Copy() Prediction: ue_client_action_request.get(request_client_id) if request is None: res.append(orig_request) continue request.client_id = client_id request.request_type = orig_request.request_type ================================================================================ Example 167 ================================================================================ Target: exclude_ops Prediction: i["operation"] == "transfer" and i["amount"] > 0 and i["fee"] > 0 and i["fee"] < 0.01 ): cnt += 1 break if cnt > 0: break # R ================================================================================ Example 168 ================================================================================ Target: ) Prediction: ) ) except azurearm.exceptions.AzureError as e: if e.status_code == 404: return result else: raise except azurearm.exceptions.AzureError as e: if e.status_ ================================================================================ Example 169 ================================================================================ Target: 'newcommand', Prediction: tex_source, '\\newcommand', '', '', '', '', '', '', '', '', '', '', '', '', '', ================================================================================ Example 170 ================================================================================ Target: r2_id) Prediction: r2_id) # Cleanup job.fileStore.deleteGlobalFile(r1_id) job.fileStore.deleteGlobalFile(r2_id) return inputs def cutadapt_fastq(job, inputs, r1_id, ================================================================================ Example 171 ================================================================================ Target: 1]: Prediction: 0]: self.__neighbors = self.__neighbors[:, :k_neighbors] # Update the perplexity self.perplexity = new_perplexity # Update the affinity matrix self.update_affinity(self.__neighbors ================================================================================ Example 172 ================================================================================ Target: else: Prediction: else: raise Warning('The IBM Watson API requires credentials that should be passed as "username" and "password" in "synth_args"') return self.watson_api.synthesize(params) def watson_request_text(text, synth_args): ================================================================================ Example 173 ================================================================================ Target: pix0] Prediction: pix0] if i == self.ndim - 1: idx += [npix1] return idx def get_offsets_from_pixels(self, pix): """Get offset of the first pixel in each dimension in the local coordinate system ================================================================================ Example 174 ================================================================================ Target: '_unique' Prediction: '_UNIQUE' if not connection.has_index(index_name): connection.create_index(index_name) return connection.get_index(index_name) def _get_index_name(table_name, column_names): ================================================================================ Example 175 ================================================================================ Target: rel) Prediction: rel, type="atom", title=sibling.title, description=sibling.description, feed=sibling.feed, atom_feed=sibling.atom_feed) else: rel ================================================================================ Example 176 ================================================================================ Target: reuse=reuse): Prediction: reuse=reuse): if trainable_initial_states: initial_states = tf.get_variable( 'initial_states', [n_hidden, n_hidden, n_hidden], initializer=tf.contrib.layers.xavier_initializer( ================================================================================ Example 177 ================================================================================ Target: return (day, month, year) Prediction: return year, month, day def get_year(soup): """ Get the year from child tags """ year = node_text(raw_parser.year(soup)) return year def get_month(soup): ================================================================================ Example 178 ================================================================================ Target: stream_stats[stream] = stream.read_stats() Prediction: stream_stats[stream.index] = stream.stats_captions return stream_stats def read_stream_stats_by_stream(self, stream_index): """ :param stream_index: stream index. :return: dictionary {stream index ================================================================================ Example 179 ================================================================================ Target: if by_time is not None: Prediction: for group in factor_data.index.levels: grouper.append(group) grouper.append(factor_data.loc[factor_data.index.get_level_values(group) == group, 'IC']) if by_time is not ================================================================================ Example 180 ================================================================================ Target: eids = dstore['losses_by_event']['eid'] Prediction: arr = dstore['losses_by_event'].value[['event_id', 'rup_id', 'year']] writer.save(arr.copy().view(dtlist), dest) return dest def export_losses_by_event_by_ ================================================================================ Example 181 ================================================================================ Target: req Prediction: ue.api_request(req) def api_request_for_request(request, *args, **kwargs): """ Create an API request for a request. `request_type` is the request type (string). This is used to look up a plugin ================================================================================ Example 182 ================================================================================ Target: self.miss = self.miss + 1 Prediction: return 0 else: return memo_dict.get(self.method_name, 0) def __getitem__(self, key): """ Returns the value of the computed key. """ return self.count(key) def __contains__( ================================================================================ Example 183 ================================================================================ Target: services = [services] Prediction: services = [services] return { 'auth': services, 'auth_url': services + [services + 'auth'], 'auth_url_prefix': services + [services + 'auth_url'], 'auth_url_suffix': services + [services ================================================================================ Example 184 ================================================================================ Target: '__iter__'): Prediction: ia_getitem): return x[0][ia_getitem(x[0])] else: return x[0] else: return x def _locations_mirror(x): """ Mirrors the points in a list ================================================================================ Example 185 ================================================================================ Target: Rs_angle = Rs / self.D_d / const.arcsec # Rs in arcsec Prediction: theta_Rs = self.nfw_physical2angle(rho0, r200) return theta_Rs def nfw_physical3angle(self, M, c): """ converts the physical mass and concentration parameter of an NFW profile into the lensing ================================================================================ Example 186 ================================================================================ Target: self.work_list.remove(global_state) Prediction: return global_state return super_strategy.get_strategic_global_state() def _is_covered(self, global_state: GlobalState) -> bool: """ Returns true if global_state is covered by the work list. """ ================================================================================ Example 187 ================================================================================ Target: startswith('www.'), Prediction: startswith('ftp://'), str_.startswith('file://'), str_.startswith('file:///'), str_.startswith('file:///'), str_.startswith('file:///'), str_.startswith('file:// ================================================================================ Example 188 ================================================================================ Target: 'code_list': code_list, Prediction: 'code_list': code_list, 'subtype_list': subtype_list, 'query_processor': query_processor } return self._send_unsubscribe_req(kargs) def _check_subscribe_param(self, code_ ================================================================================ Example 189 ================================================================================ Target: 'aux': Prediction: '_aux': aux_params[name] = v.as_in_context(ctx) return mx.model.load_checkpoint(params, name=name, ctx=ctx, **arg_params) def load_checkpoint(params, ctx=None): ================================================================================ Example 190 ================================================================================ Target: 0] Prediction: 0] def predict_text_spacy(stoi, model, text): """Do the actual prediction on the text using the spacy model and mapping files passed """ # prefix text with tokens: # xbos: beginning of sentence # ================================================================================ Example 191 ================================================================================ Target: unstemmed = match.group(0) Prediction: token = match.group(0) # Get the stemmed token. token_stemmed = stem.stem(token) # Get the token type. token_type = token_stemmed.group(1) # Get the token value. ================================================================================ Example 192 ================================================================================ Target: cfg_dir: Prediction: user_defined_files: filenames.append(self.user_defined_files) # look for user defined files if self.user_defined_files_and_configs: filenames.append(self.user_defined_files_and_ ================================================================================ Example 193 ================================================================================ Target: if self.bit_length() == 1: Prediction: return toType elif isinstance(sigOrVal, Value): return sigOrVal else: raise TypeError("Unsupported type for conversion: %s" % (toType,)) def convertBits(self, sigOrVal, toType): ================================================================================ Example 194 ================================================================================ Target: for. Prediction: :return: A list of non-zero bits """ if index < 0: return [0] if index >= self.numBuckets: return [0] if index < self.numBuckets - 1: return [self.num ================================================================================ Example 195 ================================================================================ Target: self.do_save(fp) Prediction: self.settings['storage']['state_separator'] = self.state_separator self.settings['storage']['state'] = self.state self.settings['storage']['state_separator'] = self.state_separator self.settings['storage']['state'] = self.state ================================================================================ Example 196 ================================================================================ Target: ii, jj = self.pairs().T Prediction: if metric == 'l2': return l2_distance(coords) elif metric == 'euclidean': return euclidean_distance(coords) elif metric == 'cosine': return cosine_distance(coords) elif metric == ================================================================================ Example 197 ================================================================================ Target: elif self._ack: # MP_JOIN-ACK Prediction: elif self._ack: # MP_JOIN-ACK return self._read_join_ack(bits, size, kind) elif self._ack_ack: # MP_JOIN-ACK-ACK return self._read_join_ack_ack(bits ================================================================================ Example 198 ================================================================================ Target: pattern_string = pattern_string.replace(r"\{type\}", action_cgp).replace( Prediction: # Capturing group patterns action_cgp_position = r"({type}|{scope}|{subject})" scope_cgp_position = r"({scope}|{subject})" subject_cgp_position = r"({subject})" # Capt ================================================================================ Example 199 ================================================================================ Target: data.value Prediction: ustrlen(data.value) def trace_region_get(self): """Retrieves a list of available trace regions. Args: self (JLink): the ``JLink`` instance. Returns: List of available trace regions. """ ================================================================================ Example 200 ================================================================================ Target: kwargs['_return_http_data_only'] = True Prediction: kwargs.setdefault('allow_empty_response', True) kwargs.setdefault('processor', 'payment_transaction_processor') return cls.update_payment_transaction_by_id_with_processor(payment_transaction_id, payment_transaction, **kwargs) ================================================================================ Example 201 ================================================================================ Target: rec.content.scheduled_times] Prediction: ical.parse(rec.entry.value, rec.entry.entry_type, rec.entry.entry_id) if rec.entry.entry_type == 'time'] return times def _get_times_for_search( ================================================================================ Example 202 ================================================================================ Target: "components": ",".join(components)} Prediction: "zip_data": zip_data, "components": components } response = self.client.post( self.api_url, query_params=query_params, validate=self.validate_params ) if response ================================================================================ Example 203 ================================================================================ Target: raise TypeError("password can only be an instance of type basestring") Prediction: raise ValueError("password must be a string") if not password: raise ValueError("password must be set") if not password.lower(): raise ValueError("password must be lower case") if not password.isdigit(): raise ValueError(" ================================================================================ Example 204 ================================================================================ Target: batchSystems.singleMachine import SingleMachineBatchSystem Prediction: resource.resource import Resource resource = Resource(userScript) self._batchSystem.addResource(resource) userScript = resource.getUserScript() return userScript def _setupAutoDeployment(self, userScript=None): """ Determine ================================================================================ Example 205 ================================================================================ Target: return np.maximum(np.abs(activation) - threshold, 0.) * np.sign(activation) Prediction: threshold = np.array([0.0, 0.0, 0.0]) elif thresholdType == 'absoluteHard': threshold = np.array([0.0, 0.0, 0.0]) elif thresholdType == 'relativeHard': threshold = np ================================================================================ Example 206 ================================================================================ Target: node, name, offset) Prediction: node, name, offset) def _get_scope_lookup(self, node, name, offset=0): """Lookup where the given name is assigned. :param node: The node to look for assignments up to. Any assignments after the given node are ignored. ================================================================================ Example 207 ================================================================================ Target: return output Prediction: else: return output def pretty_print_graphql_mutation(query, use_four_spaces=True): """Take a GraphQL mutation, pretty print it, and return it.""" # Use our custom visitor, which fixes directive argument order # to ================================================================================ Example 208 ================================================================================ Target: container=blob_file.group("container"), Prediction: content_type=blob_file.group("content_type"), content_encoding=blob_file.group("content_encoding"), content_disposition=blob_file.group("content_disposition"), content_language=blob_file.group ================================================================================ Example 209 ================================================================================ Target: elif ext in ['.pkl', '.p', '.pickle', '.pk']: Prediction: elif ext in ['.csv', '.tsv', '.txt']: df = pd.read_csv(filepath, **kwargs) elif ext in ['.xls', '.xlsx']: df = pd.read_excel(filepath, **kwargs ================================================================================ Example 210 ================================================================================ Target: raise Full Prediction: raise Full self.not_full.wait() self.not_full.release() return else: if self._qsize() == self.maxsize: raise Full elif timeout is None: while self._qsize() ================================================================================ Example 211 ================================================================================ Target: df = pd.read_csv(file_name, sep='\t', header=0).iloc[:,1:] Prediction: df = pd.read_tsv(file_name, sep=',', header=0).iloc[:,1:] elif file_extension=='.txt': df = pd.read_csv(file_name, sep=',', header=0).iloc[:, ================================================================================ Example 212 ================================================================================ Target: websocket.close() Prediction: websocket.close() self.websocket = None def _on_disconnect(self, event): """ Called when the connection is closed. """ self.logger.debug('Connection closed...') if self.auto_reconnect: ================================================================================ Example 213 ================================================================================ Target: x10_unitcode) Prediction: x10_device_id) elif self._is_x20: dev_id = 'x20{}{:02d}'.format(self.x20_housecode, self.x20_device_id) elif self._is_x30 ================================================================================ Example 214 ================================================================================ Target: for event in self._events: Prediction: self._notify_all() # notify all watchers that the check was changed self._notify() return value def set_value(self, value: Optional[bool]): """Sets current status of a check :param value: ``True`` (healthy ================================================================================ Example 215 ================================================================================ Target: if method: Prediction: if method is None: return self.execute_http_request(bot) return method(self.request_url, self.request_headers, self.request_body) def execute_http_request(self, bot): """ Use this method if ================================================================================ Example 216 ================================================================================ Target: 0) Prediction: ]) if retcode: ret = __opts__.get('retcode', retcode) if ret: ret = ret.strip() if retcode == 0: return ret else: return ret.replace('\n', ' ') ================================================================================ Example 217 ================================================================================ Target: to_save) Prediction: jid, to_save) else: mdb.jobs.insert_one(jid, to_save) if minions is not None: mdb.minions.insert_one(jid, minions) if conn: conn ================================================================================ Example 218 ================================================================================ Target: in param_list: Prediction: ia, param_list_ia in zip(param_list, param_list_ia): if normalize: ret_vector.append(param.normalize()) else: ret_vector.append(param.normalize()) if ia == 0: ================================================================================ Example 219 ================================================================================ Target: raise errors.PathSpecError( Prediction: raise PathSpecError("path specification must have a parent") if not path_spec.IsValid(): raise PathSpecError("path specification must be valid") if not path_spec.IsValidName(): raise PathSpecError("path specification must be valid name") ================================================================================ Example 220 ================================================================================ Target: f, 'r') Prediction: f, 'rb') fh.seek(0) fh.write(tmp_file.read()) fh.close() os.rename(f, f) finally: os.remove(tmp_file.name) tmp_file ================================================================================ Example 221 ================================================================================ Target: closed.FIELD_DATE = 'closed_at' Prediction: if self.closed: closed.es_url = self.es_url closed.es_index = self.es_index closed.es_interval = self.interval else: closed.es_url = self.es_url closed. ================================================================================ Example 222 ================================================================================ Target: a copy of Parameter '%s' on ctx %s via data() " \ Prediction: ith parameter on a different " "context than the one it was initialized on.") if ctx is None: ctx = self._ctx return self._ndarray_to_ndarray(ctx, self._stype, self._ndarray_shape) def _ ================================================================================ Example 223 ================================================================================ Target: return ret Prediction: return ret def get_security_group_by_name(self, name): ''' Get a security group by name ''' nt_ks = self.compute_conn security_group = nt_ks.security_groups.get(name) ================================================================================ Example 224 ================================================================================ Target: return self._provider_session.get_comments_for_reference_on_date(reference_id, from_, to) Prediction: return self._lookup_session.get_comments_for_reference_on_date( reference_id, from_, to ) # Implemented from azosid template for - # osid.relationship.RelationshipLookupSession.get_relationships_for_ ================================================================================ Example 225 ================================================================================ Target: else: Prediction: else: d = Directory(name, total or len(entries), entries) doc[root] = d entries = [] else: name = line[:-1] if entries: d = Directory(name, total or len(entries), ================================================================================ Example 226 ================================================================================ Target: n += 1 Prediction: out += prop + '(' + trans(REPL[e][1:-1]) + ')' else: out += prop + '(' + trans(e) + ')' n += 1 return out return trans(REPL[new]) def ================================================================================ Example 227 ================================================================================ Target: _trigger_repoint Prediction: size, callback=self.on_destination_repoint) self.destination.set_pos(self.pos) self.destination.set_size(self.size) self.destination.set_callback(self.on_destination_repoint) ================================================================================ Example 228 ================================================================================ Target: registry, insecure_registry=kwargs.get('insecure_registry')) Prediction: registry) if image_name: image_name = image_name.decode('utf-8') else: image_name = self.get_image_name(config_id) if image_name: image = self.get_image( ================================================================================ Example 229 ================================================================================ Target: return Prediction: return plugin_conf = self.spec.plugin_conf.value plugin_conf_path = self.spec.plugin_conf_path.value if not plugin_conf and not plugin_conf_path: logger.info('Removing %s because plugin_ ================================================================================ Example 230 ================================================================================ Target: conn.delete_affinity_group(kwargs['name']) Prediction: conn.delete_affinity_group(kwargs) except SaltCloudException as e: raise SaltCloudSystemExit( 'Error deleting affinity group: %s' % e.message ) def delete_affinity_group_by_name(kwargs=None, conn ================================================================================ Example 231 ================================================================================ Target: else: Prediction: return output[0] def get_lineage(self, tax_id): """ Returns lineage FIXME: expand return lineage to include custom 'below' ranks built when get_lineage is caled """ s = select([self. ================================================================================ Example 232 ================================================================================ Target: for name, _i in GRAVITIES.items(): Prediction: if i not in ['none', 'basic', 'compensated', 'tree']: raise ValueError("Gravity module '%s' not found" % i) return i def _gravity(self): """ Get or set the gravity module. ================================================================================ Example 233 ================================================================================ Target: for i, core_sems in enumerate(doc_core_sems): Prediction: for i, doc in enumerate(docs): for j, all_concept in enumerate(all_concepts): doc_core_semantics = doc_core_semantics[doc] all_concepts_semantics = all_concepts_semantics[all_ ================================================================================ Example 234 ================================================================================ Target: if f: Prediction: else: power *= 2 period += 1 tortise_value = tortise.next() hare_value = hare.next() yield tortise_value yield hare_value yield tortise_value yield hare ================================================================================ Example 235 ================================================================================ Target: _read_certificates() Prediction: certificate = self._session_context.certificate self.certificate_type = self._session_context.certificate_type self.certificate_serial = self._session_context.certificate_serial self.certificate_issuer = self._session_context ================================================================================ Example 236 ================================================================================ Target: return f Prediction: return wrapper return decorator def _intent_prompts(self, intent_name): """Returns a dictionary of intent_name -> intent_prompts. The intent_prompts dictionary is a dictionary of intent_name -> intent_prompts. The intent ================================================================================ Example 237 ================================================================================ Target: render_template('doxygen.txt.tpl', mapping, out_path=output_path) Prediction: if iotile.description: mapping['description'] = iotile.description if iotile.keywords: mapping['keywords'] = iotile.keywords if iotile.license: mapping['license'] = iotile.license ================================================================================ Example 238 ================================================================================ Target: timeout} Prediction: timeout} return self.list_queues_async(kwargs) def list_queues_async(self, kwargs): ''' Returns a generator to list the queues. The generator will lazily follow the continuation tokens returned by the service and stop ================================================================================ Example 239 ================================================================================ Target: raise ParseThisError("To many types provided for conversion for '{}'." Prediction: raise ParseThisError("too many types for conversion") for type_name, type_type in types: if type_type not in defaults: raise ParseThisError("type %s not in defaults" % type_name) if len(func_args) != ================================================================================ Example 240 ================================================================================ Target: 2] == "?": Prediction: 2] == "?": fus2_range = fus_args[2] else: fus2_range = f'"{prefix}2_{fus_args[2].value}"' if fus_args[3] == "?": ================================================================================ Example 241 ================================================================================ Target: slug) & Prediction: slug) and (TabPost2Tag.tag_id == kind) ).order_by( TabPost2Tag.post_id, TabPost2Tag.tag_id, TabPost2Tag.tag_name, TabPost2Tag. ================================================================================ Example 242 ================================================================================ Target: return output Prediction: return output def get_raw_headers(self): """ Return a list of all raw headers """ output = [] for i in self.message.get_all("received", []): output.append(decode_header_part(i ================================================================================ Example 243 ================================================================================ Target: if include_self: Prediction: if include_self: path_ids = np.concatenate(path_ids, axis=0) return path_ids def _get_paths_from_polygons(self, polygons): """ Given a list of polygons, find ================================================================================ Example 244 ================================================================================ Target: update_func() Prediction: else: thread._updated = update_func() end = time.time() if end - start > 0.1: thread.resume() def make_update_loop(thread, update_func): """ Makes a run loop which calls an ================================================================================ Example 245 ================================================================================ Target: def carveRest(s, sep): Prediction: for i in range(len(split)): if i == 0: args.append(rest) kwargs["key"+str(i)] = rest else: args.append(rest) kwargs["key"+str(i)] = split[i+ ================================================================================ Example 246 ================================================================================ Target: msg) Prediction: irc.msg.WARNING, msg) self._sendMsg('warning', irc.msg.WARNING, msg) self._sendMsg('warning', irc.msg.WARNING, msg) self._sendMsg('warning', irc.msg.WARNING, msg) ================================================================================ Example 247 ================================================================================ Target: return self._constructor(rdd, rekeyed=rekeyed, shape=shape, split=split).__finalize__(self) Prediction: return rdd, shape def _rekeyed(self): """ Rekey the input array. Returns ------- RDD """ self._rekeyed = True # rekey the input array if self._rekey ================================================================================ Example 248 ================================================================================ Target: mapper: Prediction: ustr_to_int_map(f): r = r + mapper[f_i] if r < 0: raise ValueError("Invalid permission flag: %s" % f) return r def int_flags_to_str(flags, m ================================================================================ Example 249 ================================================================================ Target: ':')[0] Prediction: ',') payload['vlans-enabled'] = True #if vlans_setting is not None: # payload['vlans-enabled'] = True # if vlans_setting.startswith('enabled') or vlans_setting.startswith(' ================================================================================ Example 250 ================================================================================ Target: return callback(config) Prediction: if callback is not None: callback(fwdl_cmd_msg) output.text = kwargs.pop('output', fwdl_cmd_msg.text) output.text_content_type = kwargs.pop('output_content_type', 'text ================================================================================ Example 251 ================================================================================ Target: LOGGER.debug('record: %s', record) Prediction: records.append(record) return records def _list_records_by_zone(self, zone_id, name=None, content=None): """List all records for the hosted zone.""" records = [] paginator = RecordSetPaginator( ================================================================================ Example 252 ================================================================================ Target: self.position = max(self.position + pos, 0) Prediction: raise ValueError("Seek to negative position") self.position = min(max(pos, 0), self.size) elif whence == os.SEEK_END: if pos > self.size: raise ValueError("Seek past end of file") ================================================================================ Example 253 ================================================================================ Target: [] Prediction: [] for i in range(len(data)): words.append(data[i]) if zone is not None: zone.write(addr, words) else: zone.write(addr, words) return len(words) def ================================================================================ Example 254 ================================================================================ Target: else: Prediction: else: self.set_cell(row, col, updated_grid[row][col]) class Grid(object): """ Grid class for the grid. """ def __init__(self, grid_width, grid_height, grid_cells): ================================================================================ Example 255 ================================================================================ Target: AttributeError: Prediction: ustring: pass return utcnow() def utcnow_utc(utcnow): """Overridable version of utcnow.""" if utcnow.override_time: try: return utcnow.override_time ================================================================================ Example 256 ================================================================================ Target: for filename in filenames: Prediction: # Process FILE if len(filenames) > 1: print_err("Usage: rm [-f] FILE") return # Process DIRECTORY if len(filenames) > 1: print_err("Usage: rm [-r] DIRECT ================================================================================ Example 257 ================================================================================ Target: if local_filepath_override: Prediction: if local_filepath_override: local_filepath = local_filepath_override return global_config, local_config def get_configs( config_filepath, local_filepath_override='', ): """go and ================================================================================ Example 258 ================================================================================ Target: audit") Prediction: audit") h.Allow("aff4:/audit/*") # Namespace for the default user. h.Allow("aff4:/default") h.Allow("aff4:/default/*") # Namespace for the default group. h.Allow ================================================================================ Example 259 ================================================================================ Target: and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): Prediction: and new_parsed.scheme == 'https' and new_parsed.port in (80, None)): return True return False def _strip_auth_header(self, url, auth_header): """Remove the Authorization header from a URL. ================================================================================ Example 260 ================================================================================ Target: 0: Prediction: 001: print "Bhf = ", Bhf print "Bh = ", Bh print "E0 = ", E0 print "E = ", E print "E0 = ", E0 print "E = ", E print "E0 = ================================================================================ Example 261 ================================================================================ Target: print 'Executing: %s' % command Prediction: return True def to_pdf(filename, command): """A helper function for to_pdf. Should not be used directly.""" if filename[-4:] in ['.pdf', '.png']: filename = filename[:-4] try: f = ================================================================================ Example 262 ================================================================================ Target: default_team Prediction: ia.Team(attributes) teams[team] = team return teams def get_team(self, team_id): """Get team by id.""" return self._header.lobby.teams[team_id] def get_team_ ================================================================================ Example 263 ================================================================================ Target: else: Prediction: else: raise ValueError('Unknown API version "{}"'.format(api_version)) return OperationClass(self._client, self._config, self._serialize, self._deserialize) def list_gallery_images(self): """Instance depends on the API version ================================================================================ Example 264 ================================================================================ Target: preconditions = [group for group in preconditions if len(group) > 0] Prediction: if not precondition_group: return [] # Filter precondition groups that are not "require else" blocks if not (isinstance(precondition_group, list) and not isinstance(precondition_group[0], list)): return [] # Filter pre ================================================================================ Example 265 ================================================================================ Target: ty, w - (x + indent), th) Prediction: y + 6, w - x + indent, h - y + indent) self._dateTimeGrid[key] = ((r, 0), rect) # create the date grid for date time options ================================================================================ Example 266 ================================================================================ Target: raw_fitness_ - penalty Prediction: metric.fitness(penalty) def _get_fitness(self, parsimony_coefficient=None): """Get the penalized fitness of the program. Parameters ---------- parsimony_coefficient : float, optional If automatic parsimony is being ================================================================================ Example 267 ================================================================================ Target: aa] += wt Prediction: aa] = 0 else: cnt[aa] += 1 return cnt def col_counts_by_type(col, type_names=None, gap_chars='-.'): """Absolute counts of each residue type in a single column.""" ================================================================================ Example 268 ================================================================================ Target: generateFileNodeDocuments() Prediction: generateFileNodeDocuments() self.generateDirectoryNodeDocuments() # generate the actual RST documents self.generateNodeDocuments() def generateNodeDocuments(self): ''' Generates all of the reStructuredText documents related to types parsed by Doxygen ================================================================================ Example 269 ================================================================================ Target: type == ContractParameterType.Boolean: Prediction: ue.IsContractParameter(type): return ContractParameter(type, value=ue.GetContractParameter(type)) elif ue.IsContractParameter(type, item): return ContractParameter(type, value=ue.GetContractParameter(type, item)) else: ================================================================================ Example 270 ================================================================================ Target: np.frombuffer(self.data, dtype=np.int8)\ Prediction: self.single_compamp_data() single_compamp_data.append(first_header) single_compamp_data.append(self.compamp_data()) single_compamp_data.append(self.compamp_data_2()) ================================================================================ Example 271 ================================================================================ Target: {'map': map_dict}, 'POST', url) Prediction: url, map_dict) if code != 200: raise AmbienteNaoExisteError(code, name) else: return None def get_rule(self, name, id_env, contents, blocks_id): """ Get an ================================================================================ Example 272 ================================================================================ Target: continue Prediction: continue if tag == 'xpath': ns = nslookup.get(ns, ns) if ns: getattr(self, 'parse_%s' % ns)(child, e, nslookup.get(ns, ns)) ================================================================================ Example 273 ================================================================================ Target: ]) Prediction: ]) return table ================================================================================ Example 274 ================================================================================ Target: else: Prediction: return container.objects_by_offset(start) def _get_container(self, start): """ Find the container for the given region. :param start: :return: """ container = self.get_container(start) ================================================================================ Example 275 ================================================================================ Target: return _STATE.RUNNING Prediction: return _STATE.STARTING if isfile(file_stop) or isfile(file_start): return _STATE.STOPPED raise Exception('Invalid wallet name: %s' % wallet_name) @staticmethod def _get_state(wal ================================================================================ Example 276 ================================================================================ Target: True Prediction: ### True def _check_release_done_processing(release): """Moves a release candidate to reviewing if all runs are done.""" if release.status != models.Release.PROCESSING: # NOTE: This statement also guards for situations where the user has ================================================================================ Example 277 ================================================================================ Target: self.index Prediction: xt.get_index(self.parent) return leader_name + "/" + leader_index else: return self.name def _get_name_scope(self, pathname): """ Returns name scope of the pathname. """ ================================================================================ Example 278 ================================================================================ Target: h0 Prediction: hk_1 + hk_2 hk_2 = hk_1 + hk_3 hk_3 = hk_1 + hk_4 hk_4 = hk_1 + hk_5 hk_5 = hk_1 ================================================================================ Example 279 ================================================================================ Target: keys = reversed(sorted(keys)) Prediction: for key in keys: if key not in self.items: items.pop(key) return items def __contains__(self, key): """ Check if the item with the specified key is in the collection. :param key: The key ================================================================================ Example 280 ================================================================================ Target: _, _, _parseable = self.line.partition("+") Prediction: self.name = self.line[len("{0}+".format(self.vcs)):] else: self.name = self.line return self.name def get_url_for_branch(self): # type: () -> STRING ================================================================================ Example 281 ================================================================================ Target: loglevel, Prediction: loglevel, retries=retries, fail_on_empty_before=False, note=note, debug_command=debug_command, pause_point_on_fail=pause_point_on_fail, nonewline=none ================================================================================ Example 282 ================================================================================ Target: init_ = init Prediction: init_ = init fini_ = fini # Extract arguments for arg in argv_: if arg in state.args: if arg in state.args[0]: main_ = arg else: argc_ = 1 ================================================================================ Example 283 ================================================================================ Target: if not isinstance(claims, Mapping): Prediction: return claims def get_verified_claims(token): """Returns the decoded claims with verification of any kind. Args: token (str): A signed JWT to decode the headers from. Returns: dict: The dict representation of the token claims. ================================================================================ Example 284 ================================================================================ Target: 'retcode'] != 0: Prediction: 0].strip() == '0': # This is a native list subcommand, so we can't use the # ``--porcelain`` option. return {} else: # This is a native list subcommand, so we can use the # `` ================================================================================ Example 285 ================================================================================ Target: self.full_path = request.get_full_path() Prediction: full_path = request.path_info # get url from full_path url = full_path.split('/')[-1] # get url from request url = request.path_info # get url from full_path url = full_ ================================================================================ Example 286 ================================================================================ Target: elif len(matching_repos) != 1: Prediction: return Repository(name, matching_repos) def get_configured_vcs_repo(name): """ Get a repository defined by the user in a configuration file. :param name: The name of the repository (a string). :returns: A ================================================================================ Example 287 ================================================================================ Target: the Message " Prediction: ###fedora.messages' entry point" % ( message.name, message.name ) ) message.register(cls) def load_message_classes_from_file(filename): """Load the 'fedora.messages' entry points from a ================================================================================ Example 288 ================================================================================ Target: 'link_id': self.submission.fullname, Prediction: 'comments': self._comments_by_id(self.count)} return self._fetch_comments(data) def _fetch_comments(self, data): """Fetch and return the comments for a MoreComments object.""" if not self._comments: if ================================================================================ Example 289 ================================================================================ Target: res Prediction: # return self.store # return res # return self.subStores # return res # return self.store # return res # return res # return res # return res # return res # return res ================================================================================ Example 290 ================================================================================ Target: if nh_int: Prediction: # nh_source_proc_nr = viastr.group('procnr') # nh_source_proc_nr = viastr.group('procnr') # nh_source_proc_nr = viastr.group('procnr ================================================================================ Example 291 ================================================================================ Target: for epi, eparr in enumerate(extparams): Prediction: for epi, eparr in enumerate(extparams): extparams[epi] = eparr[sigind] # update delta and go to the top of the loop delta = nottoodimind - nottoobrightind # final sigclipped ================================================================================ Example 292 ================================================================================ Target: if req: Prediction: return req.read() def get_user_info_by_channel(tokens, channel): '''获取用户的部分信息. 比如头像, 用户名, 自我介绍, 粉丝数 ================================================================================ Example 293 ================================================================================ Target: if num_of_slices is not None and slice_pos is not None and slice_start is None and slice_end is None: Prediction: if num_of_slices is None: num_of_slices = self.num_of_slices if slice_pos is None: slice_pos = self.slice_pos if slice_start is None: slice_ ================================================================================ Example 294 ================================================================================ Target: 'clk_p'] Prediction: 0].get('clk_p') self.clk_n = ts_d.attrs[0].get('clk_n') self.clk_d = ts_d.attrs[0].get('clk_d') self.clk_a = ts_a. ================================================================================ Example 295 ================================================================================ Target: = None Prediction: ia = pygame.mouse.get_pos() the_p.x = the_p.x + the_p.width / 2 the_p.y = the_p.y + the_p.height / 2 the_p.x = the_p ================================================================================ Example 296 ================================================================================ Target: time.sleep(delay) Prediction: break return self.target_temperature class TemperatureControl(object): """A temperature control class. This class is used to control the temperature of a thermostat. The class is designed to be used with a thermostat that has a temperature sensor. ================================================================================ Example 297 ================================================================================ Target: count = self._process_value(count, 'int') Prediction: count = self._process_value(count, 'count') if work: self._work_accounts(wallet, count) return self._accounts_create(wallet, count) def accounts_delete(self, wallet, count, work=True ================================================================================ Example 298 ================================================================================ Target: while shp.tell() < self.shpLength: Prediction: self.shp = shp self.shp.seek(0,2) self.shpLength = self.shp.tell() self.shp = self.shp.read() self.shp.seek(0,2) ================================================================================ Example 299 ================================================================================ Target: finally: Prediction: wave_output.close() except IOError as e: print('Error writing WAV file: %s' % e) return wave_output def write_wav_to_file(self, filename): """Write this sample to a WAV file ================================================================================ Example 300 ================================================================================ Target: masters] Prediction: masters] for master in masters: self._syndics[master] = self._spawn_syndics_for_master(master) def _spawn_syndics_for_master(self, master): ''' Spawn all ================================================================================ Example 301 ================================================================================ Target: plt.annotate(txt, (rate_rest[i], rate_group[i])) Prediction: ax.annotate(txt, (0, 0), xy=(0, 0), xytext=(0, 0), textcoords='offset points', arrowprops=dict(arrowstyle='->', connectionstyle='arc3')) else: for i, txt in ================================================================================ Example 302 ================================================================================ Target: self.connection.dynamizer, data)) Prediction: self.connection.dynamizer, data)) self.connection.dynamizer.flush() def _to_put(self, data): """ Put data into Dynamo """ self.connection.dynamizer.put(data) def _to_delete ================================================================================ Example 303 ================================================================================ Target: 0], Prediction: 0], products=pybel_lists[1], node_data=pybel_lists[2]) return rxn_node_data def _assemble_reaction(self, stmt): """Example: p(HGNC:HK1) => rx ================================================================================ Example 304 ================================================================================ Target: self.p['ranges'] Prediction: self.p['ranges'] if key in keys: return ranges[key] else: return ranges[key] = { 'start': self.p['start'], 'end': self.p['end'], 'name': key, ================================================================================ Example 305 ================================================================================ Target: isfile(target) is False: Prediction: isfile(target): self.sections.append(self.section_names.append(filename)) self.section_names.append(filename) self.section_names.append(filename) self.section_names.append(filename) self.section ================================================================================ Example 306 ================================================================================ Target: np.zeros = zeros Prediction: np.zeros = zeros np.ones = ones np.nan = nan np.nanmax = nanmax np.nanargmax = nanargmax np.nanargmin = nanargmin np.nanargmin_like = nanarg ================================================================================ Example 307 ================================================================================ Target: r = self.request( Prediction: if not self.is_valid_object(oid): raise GeneralException('Object ID "%s" is not valid.' % oid) if not self.is_valid_name(name): raise GeneralException('New object name "%s" is not valid.' % name ================================================================================ Example 308 ================================================================================ Target: return period_std / np.sqrt(conversion_factor) Prediction: return pd.DataFrame( { 'period_std': period_std, 'base_period': base_period, 'period_len': period_len, 'conversion_factor': conversion_factor } ) def std_ ================================================================================ Example 309 ================================================================================ Target: if not np.isfinite (upper): Prediction: if not np.isfinite (upper): raise ValueError ('"upper" argument must be finite number; got %r' % upper) if not np.isfinite (lower + upper): raise ValueError ('"lower" + "upper" argument must be finite number; ================================================================================ Example 310 ================================================================================ Target: if t is None: Prediction: if t is None: t = self._t else: t = self._t nd_iter = iter(nodes_nbrs) for n in nd_iter: self._pred[n] = t self._succ[n ================================================================================ Example 311 ================================================================================ Target: axis=1)).flatten() # all that flows out Prediction: axis=1)).flatten() # all that flows out outfluxes = outfluxes.astype(int) outfluxes = outfluxes.astype(int) outfluxes = outfluxes.astype(int) outfluxes = ================================================================================ Example 312 ================================================================================ Target: 4: Prediction: ia_version_len: return v if v[0] == '-': return '-'.join(map(str, v)) return v def get_version_info(version=None): """ Return full version info. For example ================================================================================ Example 313 ================================================================================ Target: not in self._reaction_set Prediction: # for other_reaction in reactions for other_reaction in reactions if other_reaction not in self._reaction_set): self._database.remove_compound(compound) # Remove compound from compound_set if it is referenced # ================================================================================ Example 314 ================================================================================ Target: 1 - x Prediction: x if epos == 0: return 0 elif epos == 1: return 1 elif epos == 2: return 2 elif epos == 3: return 3 elif epos == 4: return 4 elif ================================================================================ Example 315 ================================================================================ Target: resource_copy( Prediction: destination.mkdir(name) else: destination.mkdir(resource_name) for name in resource_listdir(*args): destination.mkdir(name) return resource_copy(package_or_requirement, resource_name, destination) def ================================================================================ Example 316 ================================================================================ Target: raise Prediction: raise ex if es_response.hits: return es_response.hits if not es_response.hits: return { "took": 0, "total": 0, "errors": [], "hits": [] ================================================================================ Example 317 ================================================================================ Target: get_stp_mst_detail, "output") Prediction: config, "output") output.set("port_id", self.get_stp_mst_detail_output_port_id()) output.set("designated_port_id", self.get_stp_mst_detail_output_designated_port ================================================================================ Example 318 ================================================================================ Target: axis.') Prediction: ith axis') def get_depth_bounds(self): """Depth at grid interfaces (m) :return: Bounds of axis ``'depth'`` if availible in the process's domains. :rtype: array :raises: : ================================================================================ Example 319 ================================================================================ Target: payload = {"jsonrpc": "2.0", Prediction: return salt.utils.get_list(list_name) def get_ip_address_list_by_name(list_name): ''' Retrieves a specific IP address list by name. list_name(str): The name of the specific policy IP ================================================================================ Example 320 ================================================================================ Target: shp = (3,) + mesh.lons.shape Prediction: shp = (3, 2) + mesh.lons.shape arr = numpy.zeros((3, shp, 4), F32) for i, lons in enumerate(mesh.lons): for j, lat in enumerate(lons): ================================================================================ Example 321 ================================================================================ Target: return Prediction: self.last_send_time = time.time() self.send_message(self.current_request.id) self.last_send_time = time.time() self.send_message(self.current_request.id) self.last ================================================================================ Example 322 ================================================================================ Target: self.set_cookies(self.current_cookies) Prediction: self.driver.set_window_size(self.driver_args.window_size) self.driver.set_window_position(self.driver_args.window_position) self.driver.set_window_size(self.driver_args.window_size ================================================================================ Example 323 ================================================================================ Target: else: Prediction: else: self.add_q(Q(version_end_date__isnull=False, version_end_date__gt=time)) return self def _querytime_filter_added(self): """ Add the query time ================================================================================ Example 324 ================================================================================ Target: ).get("error"): Prediction: status=200)["name"] == "Bugzilla": return "Bugzilla" else: info_out( "Bugzilla is not installed, please install it first:\n" "https://bugzilla.mozilla.org/install.html\n" ================================================================================ Example 325 ================================================================================ Target: new_settings_json = self._settings_request() Prediction: new_setting_json = self._setting_request() _LOGGER.debug("Setting Refresh Response: %s", new_setting_json) # Update device settings new_settings_json = self._settings_request() _LOGGER.debug ================================================================================ Example 326 ================================================================================ Target: while cur_idx[0] > 0: Prediction: # The first row is the index of the first element in the # path. # The second row is the index of the last element in the # path. # The third row is the index of the first element in the # path. # The fourth ================================================================================ Example 327 ================================================================================ Target: self.bitlen), Prediction: self.bitlen), PrimitiveType.KIND_FLOAT: 'float', PrimitiveType.KIND_DOUBLE: 'double', PrimitiveType.KIND_CHAR: 'char', PrimitiveType.KIND_STRING: 'string', ================================================================================ Example 328 ================================================================================ Target: parent, Mapping): Prediction: obj, MutableSequence): raise OutOfRange(obj) parent, obj = parent, obj except: raise if parent is None: parent = doc if obj is None: obj = doc if parent is None: ================================================================================ Example 329 ================================================================================ Target: else: Prediction: if not parsed.path: parsed = parsed._replace(path=u'') if not parsed.query: parsed = parsed._replace(query=u'') if not parsed.fragment: parsed = parsed._replace(fragment=u' ================================================================================ Example 330 ================================================================================ Target: NotImplementedError('Parser class not specified') Prediction: ue4.ConfigurationError('Configuration is missing a parser.') parser = self.parser try: native = parser.parse(native) except ue4.ConfigurationError: raise ue4.ConfigurationError('Configuration is invalid.') return native ================================================================================ Example 331 ================================================================================ Target: logger.warning("WP_API_AUTH_TOKEN not found in settings. Only public APIs are available.") Prediction: headers = { "Authorization": "Bearer {}".format(settings.WP_API_AUTH_TOKEN) } else: headers = { "Authorization": "Bearer {}".format(settings.WP_API_AUTH_TOKEN) ================================================================================ Example 332 ================================================================================ Target: meth_line_start_len = len(inst_str) + 1 + len(meth_str) Prediction: init_parts_len = len(meth_str) + 1 # Length of the line to the end of the method name init_parts_len_end = init_parts_len + 1 # Length of the line to the end of the method name init_ ================================================================================ Example 333 ================================================================================ Target: else: Prediction: word_chars_append(next_char) continue else: word_chars_append(next_char) word_chars_append(c) return word_chars_append def split_on_word(inp_str, sep_ ================================================================================ Example 334 ================================================================================ Target: = self._accessor.get_root_aggregate(attribute.attr_type) Prediction: ia = self._accessor.get_aggregate_attribute_value(attr_val) if acc is not None: prx = acc else: prx = self._accessor.get_attribute_value(attr_val) return prx ================================================================================ Example 335 ================================================================================ Target: p in enumerate(self.params): Prediction: point in enumerate(self.points): if i == 0: final_points.append(point) else: final_points.append(self.points[i - 1]) if query is not None: query = self.query_to_sql ================================================================================ Example 336 ================================================================================ Target: except FileNotFoundError: Prediction: stay_alive = False # Displays the overview self.flush_overview() self.screen.keypad(False) self.screen.nodelay(-1) curses.cbreak() curses.noecho() cur ================================================================================ Example 337 ================================================================================ Target: IndexError: Prediction: ia.errors.InvalidDataError: pass else: table[row_idx]['status'] = self.status table[row_idx]['timestamp'] = self.timestamp table[row_idx]['data'] = self.data table[row_idx ================================================================================ Example 338 ================================================================================ Target: return partition_state Prediction: except (KeyError, ValueError): raise ValueError("Topic-partition does not exist.") return partition_state def _fetch_partition_state_with_topic_id(self, topic_id, partition_id): """Fetch partition-state for given topic ================================================================================ Example 339 ================================================================================ Target: current_path = self.MULTI_PATH.format(self.user.name, current_name) Prediction: if not self.request_json: return self.request_json(current_name, new_name) else: return self.request_json(current_name, new_name, *args, **kwargs) def request_json(self, current_ ================================================================================ Example 340 ================================================================================ Target: _assert_started() Prediction: delay(amount, pid, method, *args) return class _Process(object): """A process object. This class is used to represent a process in the context of a :class:`~twisted.internet.process.Process`. :iv ================================================================================ Example 341 ================================================================================ Target: relation_predicate Prediction: edge_predicate(relation_predicate) def build_relation_predicate(relations: Iterable) -> EdgePredicate: """Build an edge predicate that passes for edges with the given relation.""" if not isinstance(relations, Iterable): raise TypeError ================================================================================ Example 342 ================================================================================ Target: account_id) + "/users" Prediction: account_id) return self._api.users.create(user=user, pseudonym=self._canvas_pseudonym, email=self._canvas_email, password=self._canvas_password, is_admin=True, ================================================================================ Example 343 ================================================================================ Target: mpstate.logfile_raw = open(logpath_telem_raw, mode=mode) Prediction: if opts.append_log: mpstate.append_log(logpath_telem) if opts.continue_mode: mpstate.continue_mode(logpath_telem) return mpstate.logfile def open_telemetry_logs ================================================================================ Example 344 ================================================================================ Target: np.ndarray, Index, ABCSeries) Prediction: datetime.datetime, datetime.timedelta)) and dt.microsecond > 0): return dt.days * 24 * 3600 + dt.seconds / 3600 + dt.microseconds / 1000000 else: return dt.days * 24 * 3600 + dt.seconds ================================================================================ Example 345 ================================================================================ Target: in file_types: Prediction: ~~ file_types: out += " type = \"gcp\"\n" if "http" ~~ file_types: out += " type = \"http\"\n" if "s3" ~~ file_types: out += " ================================================================================ Example 346 ================================================================================ Target: not node.is_always_running(): Prediction: ###node.status == "running": return True return False def _get_node_status(self, node): """ Get the node status """ return node.status def _get_node_status_by_name(self, ================================================================================ Example 347 ================================================================================ Target: 'dra': 0., 'ddec': 0.} Prediction: 'L7': 'L7', 'L8': 'L8', 'L9': 'L9', 'L10': 'L10', 'L11': 'L11', 'L12': 'L12', 'L ================================================================================ Example 348 ================================================================================ Target: "key": key} Prediction: "key": key} if work: payload["work"] = True try: self._send_rpc(payload) except nano.rpc.RPCException as e: raise nano.rpc.RPCException(e) return wallet def wallet ================================================================================ Example 349 ================================================================================ Target: self.default_args.tc_proxy_host, self.default_args.tc_proxy_port Prediction: self.default_args.tc_proxy_tc, self.default_args.tc_proxy_addr)) else: self.log.info(u'Proxy Server (TC): {}:{}.'.format( self.default_args.tc_proxy_tc ================================================================================ Example 350 ================================================================================ Target: f_mbap = struct.pack('>HHHB', self.__hd_tr_id, tx_hd_pr_id, Prediction: tx_hd_data = f_body[tx_hd_length:] tx_hd_data = self.__hd_tr_id + tx_hd_data tx_hd_data = self.__hd_tr_id + tx_hd_data tx_hd ================================================================================ Example 351 ================================================================================ Target: 'inc_sph_along_free_sph_path_max_dia': fields[2]} Prediction: 'inc_sph_max_rad': fields[2], 'free_sph_max_rad': fields[3], 'inc_sph_min_rad': fields[4], 'free_sph_min_rad': fields ================================================================================ Example 352 ================================================================================ Target: try: Prediction: sftp_client.put(local_path, remote_path) sftp_client.close() def copy_file_to_local(self, local_path, remote_path): """scp the local file to local folder. :param local_ ================================================================================ Example 353 ================================================================================ Target: action Prediction: ia.select_action(action) def select_action_with_greedy(self, q_values): """Return the selected action The selected action follows the Greedy Policy with probability (1 - epsilon) or return the BoltzmannQPolicy with probability epsilon ================================================================================ Example 354 ================================================================================ Target: self._file_system = None Prediction: self._file_system.Close() class _FileSystem(object): """A file-like object that supports the file-system interface.""" def __init__(self, file_system): """Initializes the file-like object.""" self._file_system ================================================================================ Example 355 ================================================================================ Target: self.shall_resume, Prediction: irc_config.get("crawler_daemonize"), "%s" % irc_config.get("crawler_daemonize"), "%s" % irc_config.get("crawler_daemonize"), "%s" ================================================================================ Example 356 ================================================================================ Target: node = self._path[0][2] Prediction: return self._find_eq(key, default) def _find_lt(self, key): """Find the first key-value pair with key *key* and return its value. If the key was not found, return *default*. If no default was provided, ================================================================================ Example 357 ================================================================================ Target: parent_id = parent_obj.id Prediction: # Update public(go2obj p2cs) p2cs.add(parent_obj.id) # Update private(goids_seen) goids_seen.add(parent_obj.id) # Update go2obj with parent alt_ids ================================================================================ Example 358 ================================================================================ Target: r = urllib2.urlopen(url) Prediction: if suffix is None: suffix = '.' if suffix == '': suffix = '' if not os.path.exists(url): return url if suffix == '': suffix = '' if suffix == '.': suffix = ================================================================================ Example 359 ================================================================================ Target: out_vals = np.vectorize(func)(vals.astype(complex)) Prediction: return np.dot(pieces, func(vals)) def _perp_eigendecompose(matrix: np.ndarray, rtol: float = 1e-5, atol: float = 1e-8) -> np.ndarray: """ ================================================================================ Example 360 ================================================================================ Target: map(score_cast_func, it))) Prediction: zip(*it))) def zset_score_pairs_withscores(response, **options): """ If ``withscores`` is specified in the options, return the response as a list of (value, score, score) pairs """ if not response ================================================================================ Example 361 ================================================================================ Target: set_segs_names() Prediction: write_segments() def detect_branchings(self): """Detect branchings and partition the data into corresponding segments. Detect all branchings up to `n_branchings`. Writes ------ segs : np.ndarray Array of dimension ================================================================================ Example 362 ================================================================================ Target: break Prediction: pass return commands def get_command_list(self, args): """ We have to code the key names for each depth. This method scans for each level and returns a list of the command arguments. """ commands = [] for i in itert ================================================================================ Example 363 ================================================================================ Target: data, tf.float32), Prediction: data, dtype=tf.float32), summary_metadata=summary_metadata, description=description) def _scalar_summary_to_tensor(scalar_summary, name, data, step, description=None): """Write a scalar summary. ================================================================================ Example 364 ================================================================================ Target: self._topology.max_cluster_time()), Prediction: self._pool.opts.socket_options), _time() - start) except socket.error: raise ConnectionFailure(self._pool.opts.metadata, self._pool.opts.socket_options) except OperationFailure: ================================================================================ Example 365 ================================================================================ Target: help="Do not deduplicate [default: deduplicate]") Prediction: help="Remove duplicates from the input") p.add_option("--scaffold_size", default=0, type="int", help="Scaffold size (default: 0)") p.add_option("--scaffold_cov", default=0 ================================================================================ Example 366 ================================================================================ Target: ET.SubElement(permit, "permit-list") Prediction: ET.SubElement(permit, "permit-list") permit_list.text = kwargs.pop('permit_list') mac_type = ET.SubElement(permit_list, "mac-type") mac_type.text = kwargs ================================================================================ Example 367 ================================================================================ Target: geo=geometry(residue) Prediction: geo = residue.get_geometry() if geo is None: raise ValueError("residue is not a geometry object") if len(geo.coords) != 3: raise ValueError("residue is not a geometry object") if len(geo. ================================================================================ Example 368 ================================================================================ Target: maplesat: Prediction: formula is None: return if self.formula.is_formula: return self.formula if self.formula.is_formula_list: return self.formula_list if self.formula.is_formula_list_list: return self ================================================================================ Example 369 ================================================================================ Target: if type(sort_by) == str: Prediction: if type(sort_by) == str: if sort_by not in const.sort_by: raise ValueError('invalid sort_by') else: payload['sortBy'] = sort_by else: raise TypeError('sort_by ================================================================================ Example 370 ================================================================================ Target: # T.T = inv(T) Prediction: ### degrees degree=degree) def custom_to_pmrapmdec(pmphi1,pmphi2,phi1,phi2,T=None,degree=False): """ NAME: custom_to_pmrapmdec PUR ================================================================================ Example 371 ================================================================================ Target: 'int') Prediction: np.float32) def _get_sparse_pixel_centres(self, mask, unmasked_sparse_grid_pixel_centres): """The 1D index mappings between the unmasked sparse grid and masked sparse grid.""" return mapping_util ================================================================================ Example 372 ================================================================================ Target: %s>%s' % (el.tag, extra) Prediction: %s>' % (el.tag, extra) def start_tag(el): """ The text representation of a start tag for a tag. Includes leading whitespace when appropriate. """ if el.tail and start_whitespace_re.search( ================================================================================ Example 373 ================================================================================ Target: _initialized: Prediction: is_iso_path(iso_path): raise ValueError("iso_path must be a valid ISO path") if not self.is_joliet_path(iso_path): raise ValueError("iso_path must be a valid Joliet path") ================================================================================ Example 374 ================================================================================ Target: # run at foreground Prediction: ### daemon.start() else: daemon.stop() daemon.join() if args.foreground: daemon.kill() daemon.join() return daemon if __name__ == '__main__ ================================================================================ Example 375 ================================================================================ Target: x1 = _RgbWheel[i+1] Prediction: x1 = _RgbWheel[i + 1] x2 = _RgbWheel[i + 2] x3 = _RgbWheel[i + 3] x4 = _RgbWheel[i + 4] x5 = ================================================================================ Example 376 ================================================================================ Target: }) Prediction: 'error-code': "YANGDynClass.INVALID_TYPE", 'error-string': "Invalid type for intf_ldp_sync"}) return t def _set_intf_ldp_sync_no(self, v, load=False): ================================================================================ Example 377 ================================================================================ Target: == {}".format(kdk_sum)) Prediction: ==== {0}".format(kraus_ops)) def _check_kraus_ops_with_normalization(n, kraus_ops): """ Verify that the Kraus operators are of the correct shape and satisfy the correct normalization. : ================================================================================ Example 378 ================================================================================ Target: tick_interval, Prediction: tick_interval, minor_tick_interval=minor_tick_interval, xlabel_fmt='%s %s' % (xlabel, ylabel), tick_labelsize=tick_labelsize, show=show, fname=fname, **kwargs) ================================================================================ Example 379 ================================================================================ Target: AdsVersion(ads_version)) Prediction: ustr2str(ads_version.version)) def adsSyncReadDeviceInfoReq(port, address): # type: (int, AmsAddr) -> Tuple[str, AdsVersion] """Read the name and the version number of the ADS-server. ================================================================================ Example 380 ================================================================================ Target: 'Prefix']) Prediction: 0]) else: prefixes.append(page['Prefix']) return prefixes def list_objects(self, bucket_name, prefix='', delimiter='', page_size=None, max_items=None): """ Lists objects in ================================================================================ Example 381 ================================================================================ Target: = i+1 Prediction: ~~= s1[i] for j in range(1, n+1): row[j] ~~= s2[p+j] p += j table.append(row) return table def align(s1, s2, ================================================================================ Example 382 ================================================================================ Target: test_format Prediction: ### format_specifier def _format_with_same_month(format_specifier): """ Return a version of `format_specifier` that renders a date assuming it has the same month as another date. Usually this means ommitting the month. ================================================================================ Example 383 ================================================================================ Target: if email: Prediction: if email: query = query.filter_by(email=email) return query.all() def user_list(username, email): """ Find a list of users with username and email :param username: :param email: ================================================================================ Example 384 ================================================================================ Target: if array is None or not array: Prediction: return ChosenInlineResult( self._chosen_inline_result_dict, self._chosen_inline_result_dict.get('chosen_inline_result_id', None), self._chosen_inline_result_dict.get('chosen ================================================================================ Example 385 ================================================================================ Target: if 'LEONARDO' in key: Prediction: if key.startswith('__') and key.endswith('_'): return True return False def _is_leonardo_module_conf(whatever): '''check if is leonardo module conf''' # check if is python module ================================================================================ Example 386 ================================================================================ Target: >> 2) & 0x3F Prediction: ~~ 0x03) & 0x1F b = (pix[2] ~~ 0x03) & 0x1F return (r, g, b) def _pack_rgb(self, pix): """ Internal. Encodes python list [ ================================================================================ Example 387 ================================================================================ Target: kw.values()) Prediction: (*args,kw)) return self.cursor.lastrowid def update(self,*args,**kw): """Update a record in the database Parameters can be positional or keyword arguments. If positional they must be in the same order as in the create() method ================================================================================ Example 388 ================================================================================ Target: file=output_file) Prediction: file=output_file) if self._args and self._args.verbose >= 2: print('{level:>7} | {arithmetic intensity:>5.2} FLOP/B | {0!s:>15} |' ' {bandwidth ================================================================================ Example 389 ================================================================================ Target: help='Enable overwriting model files') Prediction: help=('Force import of all compounds.')) parser.add_argument('--verbose', action='store_true', help=('Print progress information.')) parser.add_argument('--no-progress', action='store_true', help=('Do not ================================================================================ Example 390 ================================================================================ Target: module = importlib.machinery.SourceFileLoader(name, filename).load_module() Prediction: module = imp.load_module(name, filename, loader=imp.get_loader()) # Load the functions. functions = {} for name in module.__dict__.keys(): if name.startswith('__'): continue func = getattr ================================================================================ Example 391 ================================================================================ Target: for i, band in enumerate(self.bands): Prediction: bands = self.rasterio.read_bands(self.rasterio.band_size) except Exception as e: print(e) return None return bands def _write_bands(self, bands): """ Writes a band with ================================================================================ Example 392 ================================================================================ Target: ddoc_search_info = self.r_session.get( Prediction: return self.db.get_design_info(ddoc=self.ddoc, search_index=search_index) def search_index_info(self, search_index): """ Retrieves information about a specified search index within the design document, ================================================================================ Example 393 ================================================================================ Target: append(request_handler_chain) Prediction: append(request_handler_chain) def _add_request_handler_chain(self, request_handler_chain): # type: (GenericRequestHandlerChain) -> None """Adds a request handler chain to the list of request handler chains. :param request_ ================================================================================ Example 394 ================================================================================ Target: refresh_pillar() Prediction: return ret def sync_pillar_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None): ''' .. versionadded:: 2015.8.11,2016.3.2 Sync pillar ================================================================================ Example 395 ================================================================================ Target: return None Prediction: return None def find_global_id(self, name_id): """ Only find persistent IDs :param name_id: :return: """ try: return self.db[name_id.text] except Key ================================================================================ Example 396 ================================================================================ Target: content_type is not None: Prediction: content: request.headers["Content-Type"] = "application/json" request.headers["X-Tincan-State"] = state.content return self.send_request(request) def delete_state(self, state): """Delete a state ================================================================================ Example 397 ================================================================================ Target: remaining = 0 Prediction: remaining -= len(part) if len(self._parts) == 0: raise StopIteration return part_generator(n) return part_generator(n) def peek(self, n): """ ================================================================================ Example 398 ================================================================================ Target: CLIError(usage) Prediction: erc20_error('Invalid certificate or key') if ca: if not all([cert, key]): raise CLIError(usage) if not (cert or key): raise CLIError(usage) if not (cert and key): raise CLIError ================================================================================ Example 399 ================================================================================ Target: an instance of ' Prediction: ia instance of ' 'BaseField.') self.fields.append(field) def add_field_from_dict(self, field_dict): """Add a field from a dictionary. :param field_dict: Dictionary of fields to add ================================================================================ Example 400 ================================================================================ Target: if loader is None or name == '__main__': Prediction: if loader is None: return None return loader.path def _get_module_path(name): """Returns the path to the module containing the named module or None if the path could not be identified (e.g., if ``name == " ================================================================================ Example 401 ================================================================================ Target: o) Prediction: uexec.getenforce_command_exists()) return o def get_selinux_status(): """ get SELinux status of host :return: string, one of Enforced, Permissive, Disabled """ getenforce ================================================================================ Example 402 ================================================================================ Target: ymin = ymin_ if setup.ymin is None else setup.ymin Prediction: xmin, xmax, ymin_, ymax, xspan, yspan = calc_max_min(ss, 1) xmin, xmax, ymin_, ymax, xspan, yspan = calc_max_min(ss, 2) xmin, ================================================================================ Example 403 ================================================================================ Target: args[0] Prediction: args[0] else: self._depth = 0 return self def __str__(self): return "Depth: %s" % self.depth def __repr__(self): return self.__str__() def __eq__(self ================================================================================ Example 404 ================================================================================ Target: feed(new_data) Prediction: append(new_data) self.buffer.append(self.get_line()) self.buffer.append(self.get_line()) self.buffer.append(self.get_line()) self.buffer.append(self.get_line()) ================================================================================ Example 405 ================================================================================ Target: else: Prediction: else: speech.speak("Removing " + file + ".") subprocess.call(["rm", "-f", file]) def removeDir(dir): """remove a directory""" if "y" in speech.question("Are you sure you want ================================================================================ Example 406 ================================================================================ Target: metrics['elapsed'] = self.elapsed() Prediction: for metric in self.metrics: metrics[metric.name] = metric.value epoch_time = time.time() epoch_data = self.epoch_dataframe.append(epoch_time, metrics) self.epoch_dataframe ================================================================================ Example 407 ================================================================================ Target: try: Prediction: return XViewProfile.fromString(strdata) else: return XViewProfile() def fromString(strdata): """ Generates profile data from the inputed string data. :param strdata | ================================================================================ Example 408 ================================================================================ Target: delta_x = self._libinput.libinput_event_gesture_get_dx_unaccelerated( Prediction: ================================================================================ Example 409 ================================================================================ Target: qs Prediction: ubl.query_set(self.name, qs) def get_queryset(self): """ Returns the queryset. """ return ubl.query_set(self.name, self.all()) def get_model(self): ================================================================================ Example 410 ================================================================================ Target: if 'kind' in kwargs.keys(): Prediction: return self.get_parameters(kwargs) def get_parameters(self, **kwargs): """ Get parameters from the context :parameter str context: name of the context (optional) :parameter **kwargs: any other tags to do the filter (except ================================================================================ Example 411 ================================================================================ Target: if DataParser.has_pheno: Prediction: if DataParser.has_parents: pheno = int(words[pheno_col]) if DataParser.has_fid: pheno = int(words[pheno_col]) if DataParser.has_fid: pheno = ================================================================================ Example 412 ================================================================================ Target: try: Prediction: self.config['level'] = logging.DEBUG self.config['propagate'] = False self.config['format'] = '%(asctime)s: %(levelname)s: %(message)s' self.config['datefmt'] = '%Y ================================================================================ Example 413 ================================================================================ Target: self.count Prediction: urn.Uniform(self.count) c.add(value) self.count += 1 class UniformSampleWithCount(UniformSample): """A sample with a count.""" def __init__(self, count): super(UniformSampleWithCount, self). ================================================================================ Example 414 ================================================================================ Target: if hasattr(settings, 'SPECTATOR_SLUG_ALPHABET'): Prediction: return slugged_model(value, alphabet, salt) def generate_slug(value): "A copy of spectator.core.models.SluggedModelMixin._generate_slug()" alphabet = 'abcdefghijkmnopqrstuvw ================================================================================ Example 415 ================================================================================ Target: if not encrypted_string: Prediction: return json.dumps(json_encoded, cls=self.encrypt_type) + encrypted_string def encrypt_fields_with_key(self, document, fieldspec, key): """ Encrypt a document using the registered encryption providers. :param ================================================================================ Example 416 ================================================================================ Target: self.number_of_threads): Prediction: self.num_workers): self.queue.put(self._kill_worker_threads()) time.sleep(0.1) def _kill_worker_threads(self): """This function coerces the consumer/worker threads to kill themselves. ================================================================================ Example 417 ================================================================================ Target: BAD_LIST = [['ilm-scale', BAD_DAMP], ['ilm-off', BAD_DAMP], ['ilm-z-0', Prediction: glbl_dmp = 0.3 if a == 0 else 3e-2 glbl_dmp = 0.3 if a == 0 else 3e-2 glbl_dmp = 0.3 if a == 0 else 3e-2 glbl_ ================================================================================ Example 418 ================================================================================ Target: = PluginOptions(defaults) Prediction: ia_options = plugin_args.add_mutually_exclusive_group( "ia_options", defaults) plugin.options ia_options.add_argument("--ia_options", action="store_true") plugin.options ia_options.add_ ================================================================================ Example 419 ================================================================================ Target: self.clock.time = max(0.5, value) Prediction: def seek_to(self, value): """ Seek to the specified time. Parameters ---------- value : str or int The time to seek to. Can be any of the following formats: >>> 15.4 -> 15.4 # seconds >>> ================================================================================ Example 420 ================================================================================ Target: log.info("setting a coroutine incoming local hook callback") Prediction: if coro is None: return handler if coro is 1: return handler if coro is 2: return handler raise ValueError("unknown coroutine type") def local_outgoing_hook(handler=None, coro= ================================================================================ Example 421 ================================================================================ Target: bottom = sub_area[0][0] + sub_area[1][0] Prediction: bottom = sub_area[0][1] left = sub_area[1][0] right = sub_area[1][1] if data_matches and data_and_metadata.metadata.get("top_left", None) is not None: ================================================================================ Example 422 ================================================================================ Target: for (regexp, retvalue) in regexp_list: Prediction: count += 1 return result def expect_list_with_timeout(self, connection, regexp_list, timeout=10): ''' Expect a list of expressions @param connection: Connection to the host @type connection: L{Connection} ================================================================================ Example 423 ================================================================================ Target: protocol = u'https' if request.is_secure() else u"http" Prediction: url = request.GET.get('url', '') if url: url = url.split('?', 1)[0] if url.startswith('http'): url = url[2:] if url.startswith('https'): url ================================================================================ Example 424 ================================================================================ Target: infd = gzip.open(modelfile) Prediction: # Read the model file with open(modelfile, 'rb') as f: modelfile_data = f.read() # Read the model table modelfile_data = np.load(modelfile_data) # Convert the model ================================================================================ Example 425 ================================================================================ Target: component = closed_components[i] Prediction: component = closed_components[i] # print "component ",component # print "component eigenvalues ",component.eigvals # print "component eigenvalues ",component.eigvals[0] # print "component eigenvalues ",component.eigvals[1] ================================================================================ Example 426 ================================================================================ Target: = get_vnetwork_dvpgs Prediction: = ET.SubElement(get_vnetwork_dvpgs, "config") get_vnetwork_dvpgs.set("name", "vnetwork_dvpgs") get_vnetwork_dvpgs.set("value", "1") get_ ================================================================================ Example 427 ================================================================================ Target: bp Prediction: ================================================================================ Example 428 ================================================================================ Target: filename Prediction: ustr(filename) self.module = self.stream.get_module() self.module.parse(self.stream, self.filename) return self.module def parse_module(self, module): """Parse the given module and return its Module object.""" ================================================================================ Example 429 ================================================================================ Target: in _ANSI_CODES: Prediction: iax in tokenize.generate_tokens(text): if token.startswith('^'): text = text.replace(token, '^') if token.startswith('^'): text = text.replace(token, '^') return text ================================================================================ Example 430 ================================================================================ Target: abbr=True), Prediction: self.company_type_id) ) def company_type(self) -> str: # noqa: A003 """Get the type of company. :return: Type of company. """ return self.company_type_id def ================================================================================ Example 431 ================================================================================ Target: is None: Prediction: ia None: predictor = self._predictor else: predictor = predictor.clone() # if predictor is None, then we are fitting the predictor # and we should use the predictor's predictions if predictor is None: predictor.fit( ================================================================================ Example 432 ================================================================================ Target: self.settings[u"initial_presence"] Prediction: irc.presence.get_presence(self.me, self.peer) if presence: self.send_message(presence.get_nickname()) self.send_message(presence.get_nickname()) self.send_message(pres ================================================================================ Example 433 ================================================================================ Target: if should_forward: Prediction: if should_forward: # send the packet send_msg["data"] = convert_pkt_to_json(pk) send_msg["created"] = rnow() send_msg["source"] = SOURCE send_msg["data"] = ================================================================================ Example 434 ================================================================================ Target: raise problems.InvalidMapping(field) Prediction: raise DuplicateMapping(filename, new_mapping) new_mapping[field] = filename class _Mapping(object): """A mapping class that can be used to add a mapping to a file. This class is used to add a mapping to a file. It is ================================================================================ Example 435 ================================================================================ Target: r = a Prediction: # # x**a * exp(-x) / Gamma(a) = # # a * x**a * exp(-x) / Gamma(a) = # # a * x**a * exp(-x) / Gamma(a ================================================================================ Example 436 ================================================================================ Target: p = Parser() Prediction: if s.startswith('{'): s = s[1:] if s.startswith('{') and s.endswith('}') and s.startswith('{') and s.endswith('}'): s = s[1:-1] ================================================================================ Example 437 ================================================================================ Target: variant_obj=variant_obj, Prediction: user_obj=user_obj, variant_obj=variant_obj, variant_link=variant_link, criteria=criteria) return variant_link def variant_acmg_post(store, institute_id, case_name, variant ================================================================================ Example 438 ================================================================================ Target: processed into Edges") Prediction: ============") if jsonl_flag: nanopub_cnt = nanopub_cnt + 1 if nanopub_cnt % 100 == 0: timer.track(f"{nanopub_cnt} JSON Lines ============") if yaml_flag: ================================================================================ Example 439 ================================================================================ Target: ) Prediction: ) if id_format is None: return None return id_format def _get_id_format_from_name(self, name): """ Return the id regex from the name""" id_format = gf.safe_get( ================================================================================ Example 440 ================================================================================ Target: for groups in chemgroups: Prediction: for group, count in groups.items(): group_counts[group] = count r = [] q = [] for group, count in group_counts.items(): r.append(count) q.append(count) ================================================================================ Example 441 ================================================================================ Target: fields: Prediction: ue_param_fields: return fields if not fields: return fields if fields[0] == 'fields': return fields[1:] if fields[0] == '_type': return fields[1:] if fields[0] == ================================================================================ Example 442 ================================================================================ Target: 1) Prediction: ###) # Check if we have to start a new row if i > 0 and i % ncol == 0: html += " \n" html += " \n" return html def _get_packages(self, ================================================================================ Example 443 ================================================================================ Target: += 0xdc00 Prediction: ~~ 0x2028 return val def _escape_surrogate_escape(error): """ Simulate the Python 3 ``surrogateescape`` handler, but for Python 2 only. """ chars = error.object[error.start:error.end] ================================================================================ Example 444 ================================================================================ Target: match in enumerate(self.regex.finditer(text)): Prediction: token in enumerate(text): if token_class is not None: tokens[token_class(token)] = i else: tokens[token] = i return tokens def _tokenize_with_whitespace(self, text, token_class ================================================================================ Example 445 ================================================================================ Target: self.changed_keys_requiring_restart.add(config_key) Prediction: self.restart_required = True elif config_key in self.config.keys_requiring_refresh: self.refresh_required = True elif config_key in self.config.keys_requiring_save: self.save_required = True ================================================================================ Example 446 ================================================================================ Target: defaults):]): Prediction: defaults) + 1:]): parser.add_argument("--%s-%s-%s-%s" % (prefix, cfgkey, i, arg), dest="%s_%s_%s_%s" % (prefix, cfgkey, i, arg), ================================================================================ Example 447 ================================================================================ Target: 0] << 8 | buf_h[1]) & 0xFFFC Prediction: 0] << 8 | buf_h[1]) & 0xFFFC self._humidity = self._calc_humidity(humid) else: self._ok = False self.log_error("Bad reading: %s", buf_t) return ================================================================================ Example 448 ================================================================================ Target: 'bindings', {'members': [publisher], 'role': 'roles/pubsub.publisher'}) Prediction: 'bindings', { 'role': 'roles/pubsub.publisher', 'members': [publisher], } ) else: policy.setdefault( 'bindings', { 'role': ' ================================================================================ Example 449 ================================================================================ Target: worker_pid_file = open(worker_pid_path, 'r') Prediction: worker.start() except Exception as e: self.logger.error("Failed to start worker: %s", e) return None return worker def stop_worker(self): """Stop the worker process.""" if not self.include_rq ================================================================================ Example 450 ================================================================================ Target: } " Prediction: }. " "This is not a valid line number".format(linenum)) if NL in line_without_newline: self._warn("Newline character at line {}. " "This is not a valid line number".format(linenum)) ================================================================================ Example 451 ================================================================================ Target: slot Prediction: ### slot return -1 def set_bp(self, slot, bp): """ Sets a hardware breakpoint. @type slot: int @param slot: Slot (debug register) to set breakpoint. @param bp: Breakpoint ================================================================================ Example 452 ================================================================================ Target: def stem_tokens(tokens): Prediction: tfidf = TfidfVectorizer(min_df=1, stop_words='english', remove_punctuation_map=remove_punctuation_map) tfidf.fit(a) tfidf.transform(b) tf ================================================================================ Example 453 ================================================================================ Target: THỔ", Prediction: ƠIỀN THỔ", "M6": "LƯƠNG TRẠCH LỰU MỘC", "K6": "KIM PHONG KIM", "H7": "PHÚ TRẠCH H ================================================================================ Example 454 ================================================================================ Target: if not progressbar: Prediction: if progressbar is not None: raise ValueError("progressbar is not supported") # create a context manager to keep track of the upload with contextlib.closing(upload_context): # create a file object file_obj = open(file_path, ================================================================================ Example 455 ================================================================================ Target: L_onehot[i, j, k - 1] = 1 Prediction: L_onehot[i, j] = 1 else: L_onehot[i, j] = 0 return L_onehot def label_matrix_to_one_hot(L, k=None): """Converts a 2D [ ================================================================================ Example 456 ================================================================================ Target: dict(parser.get_wf_extensions()) Prediction: self.get_extensions() if extensions: self.extensions = extensions self.xml.update(self.description, self.title, self.extensions) self.set_xml_link(self.xml) def get_xml_link(self): ================================================================================ Example 457 ================================================================================ Target: '', Prediction: '', 'cmd': cmd_kw, 'cmd_kwargs': cmd_kw, 'cmd_ret': cmd_kw, 'cmd_ret_kwargs': cmd_kw, 'cmd_timeout': timeout, 'cmd_timeout_kwargs': cmd ================================================================================ Example 458 ================================================================================ Target: ret Prediction: ireq_to_jids(ret) def get_jids_by_instance(instance_id): ''' Return a list of all job ids for a given instance_id ''' query = '''SELECT jid FROM {keyspace}.jids WHERE j ================================================================================ Example 459 ================================================================================ Target: plate_stock_table Prediction: 【plate_stock_table】 def get_stock_list(self, plate_code): """ 获取股票列表 :param plate_code: 板块代码, string, 例如,”SH.BK ================================================================================ Example 460 ================================================================================ Target: self.fig.canvas.draw_idle() Prediction: elif event.key == 'v': # clears all the regions for patch in self.region_patches: patch.remove() self.region_patches = [] elif event.key == 'w': # clears all the regions for ================================================================================ Example 461 ================================================================================ Target: CertificateSigningRequestBuilder() Prediction: CertificateSigningRequest( private_key_bytes, subject_name, fqdn_list, issuer=subject_name, notBefore=datetime.utcnow(), notAfter=datetime.utcnow() + datetime.timedelta ================================================================================ Example 462 ================================================================================ Target: edge_color = matplotlib.colors.to_rgba('black', alpha=1.0) Prediction: face_color = matplotlib.colors.to_rgba('red', alpha=density_scale) ax.set_facecolor(face_color) ax.set_edgecolor(face_color) ax.set_edgecolor(matplotlib.colors ================================================================================ Example 463 ================================================================================ Target: '-').replace(u'‐', u'-') Prediction: '―').replace(u'―', '―').replace(u'―', '―').replace(u'―', '―') text = text.replace(u'\', u'\').replace(u'\', u'\').replace(u' ================================================================================ Example 464 ================================================================================ Target: item) Prediction: item) db.commit() def _add_to(self, db, index, item): """ Add `item` to `db` at `index`. Note: This function is inverse to :meth:`._remove_from`. Args: ================================================================================ Example 465 ================================================================================ Target: return instance._listeners[change['name']][change['mode']] Prediction: return instance._listeners[change['name']] return [] def _get_listeners_for_change(instance, change): """Gets listeners of changed Property on a HasProperties instance""" if ( change['mode'] not in listeners_disabled._ ================================================================================ Example 466 ================================================================================ Target: from_, Prediction: ualrFrom_, 'to': ualrTo_, 'status_callback': values.unset, 'status_callback_method': values.unset, 'status_callback_event': values.unset, 'timeout': values ================================================================================ Example 467 ================================================================================ Target: raise Prediction: raise ActionError(message) else: raise ActionError(message) def check_action_error(keywords, action_error): """Checks an exception for given keywords and raises a new ``ActionError`` with the desired message if the keywords are found. ================================================================================ Example 468 ================================================================================ Target: if piper in self: Prediction: return self._piper_or_id(piper) except DaggerError as e: if forgive: raise else: return False except: return False def _piper_or_id(self, piper): ================================================================================ Example 469 ================================================================================ Target: for item in items: Prediction: for item in items: if item is None: continue if isinstance(item, (list, tuple)): data_items.append(item) else: data_items.append(item) return data_items def remove_all ================================================================================ Example 470 ================================================================================ Target: rows Prediction: irecords = [entry['_source'] for entry in rows] def _get_timestamp_filer(self): """ Get the timestamp filter for the search request """ if self._index.get_type() == "elasticsearch": return self ================================================================================ Example 471 ================================================================================ Target: out_dir=out_dir, tags=tags).create_node() Prediction: tags=tags, rank=rank, files=files, out_dir=out_dir) node.set_tags(tags) node.set_rank(rank) node.set_files(files) node.set_ ================================================================================ Example 472 ================================================================================ Target: upper = self._compile_expression(upper_expr, scope) Prediction: upper = self._compile_expression(upper_expr, scope) bounds[name] = (lower, upper) return bounds return bounds def compile_action_bound_constraints(self, state: Sequence[tf.Tensor]) -> D ================================================================================ Example 473 ================================================================================ Target: if abs(d_new_from - d_new_to) < tol: Prediction: if d_new_from == 0.0 and d_new_to == 0.0: d_new_from = 0.0 d_new_to = 0.0 if d_new_from == 0.0 and d_new_to == 0 ================================================================================ Example 474 ================================================================================ Target: is self.__default_project_node: Prediction: ### is not None and parent_node.is_authoring_node(): return True return False def is_authoring_node_or_directory(self, node): """ Returns if given Node is an authoring node or directory. :param node ================================================================================ Example 475 ================================================================================ Target: ) Prediction: ) if kmip_version == enums.KMIPVersion.KMIP_1_0: self._signature_key_information.write( local_stream, kmip_version=kmip_version ) if kmip_version == ================================================================================ Example 476 ================================================================================ Target: uri_path=self.base_uri + '/cards/' + card_id Prediction: card_id=card_id, **query_params ) return Card(card_json) def get_card_by_id(self, card_id, **query_params): ''' Get a Card for a given card id. Returns ================================================================================ Example 477 ================================================================================ Target: plpy) Prediction: portal_type, modified, replace_map) # add to map replace_map[new_subcol_ident] = minor # update minor version td['new']['minor'] = minor # update minor version td[' ================================================================================ Example 478 ================================================================================ Target: if target.dead: Prediction: if not isinstance(exception, compat.greenlet): raise TypeError("can only schedule exceptions for greenlets") if not isinstance(exception, compat.greenlet): raise TypeError("can only schedule exceptions for greenlets") if not isinstance(exception, compat.green ================================================================================ Example 479 ================================================================================ Target: 1)) Prediction: xtlPngSize[0]), varOldThrMax=tplPngSize[0]) vecYdgr = rmp_rng(vecY, varExtYmin, varExtYmax, varOldThrMin=0.0, varOld ================================================================================ Example 480 ================================================================================ Target: render_context)) Prediction: render_context)) return fragment def _render_child_fragment(self, child, context, child_id): """ Render a child fragment. """ fragment = self.runtime.get_block(child_id) fragment.content = self ================================================================================ Example 481 ================================================================================ Target: cmd.append('{0}@{1}'.format(user, host)) Prediction: if runas: cmd.append('--runas') cmd.append('rabbitmq') cmd.append('--host=%s' % host) cmd.append('--user=%s' % user) cmd.append('--password=%s' % ================================================================================ Example 482 ================================================================================ Target: out += hex(self.g)[2:] Prediction: out += hex(self.g)[2:] if self.a == 0: out += "00" else: out += hex(self.a)[2:] return out def to_hex(self): """ Converts to Hex """ ================================================================================ Example 483 ================================================================================ Target: payload) Prediction: payload) return tempfile.mkstemp()[0] def write_payload_file(payload=None, objectInput=None): """ This function writes a base64 payload or file object on disk. Args: payload (string): payload in base64 ================================================================================ Example 484 ================================================================================ Target: Si += v @ v.T Prediction: v = v.reshape(n_features, 1) Si[m, x] = v.mean(axis=0) Sw[cl, cl] = Si return Sw def calculate_within_class_scatter_matrix(X, y): ================================================================================ Example 485 ================================================================================ Target: [] Prediction: [] for node in start_nodes: if node not in dependencies: continue if node not in dependencies[node]: continue retval.append(node) return retval def _get_node_order(node, dependencies): """ ================================================================================ Example 486 ================================================================================ Target: ".format(label, price) Prediction: This is not a valid price for this product." .format(price, price)) if not isfinite(label): raise BadOrderParameters( msg="Attempted to place an order with a {} label " "of {}. This is not a valid label ================================================================================ Example 487 ================================================================================ Target: return False Prediction: else: return False else: return False def CheckEmail(self, email, checkTypo=False): '''Checks a Single email if it is correct''' contents = email.split('@') if len(contents) == 2: ================================================================================ Example 488 ================================================================================ Target: if not isinstance(var, list): Prediction: if not isinstance(var, list): var = [var] return var def make_list_of_terms(var, num_terms=1): """ Make a variable a list of terms if it is not already If variable is not a list it will ================================================================================ Example 489 ================================================================================ Target: atan2(float(cobj.luv_v), float(cobj.luv_u)) Prediction: sqrt(math.pow(cobj.luv_h, 2.0) + math.pow(cobj.luv_v, 2.0)) lch_s = math.sqrt(math.pow(cobj.luv_s, 2.0) + math ================================================================================ Example 490 ================================================================================ Target: name=name, args=colString)) Prediction: name=name, args=colString)) except Exception as e: print(e) return False return True def create_index(dbcon, name, columns): """ Create an index in the database. :param dbcon: database ================================================================================ Example 491 ================================================================================ Target: if extension: Prediction: if extension == '.py': py_files.append(f) else: # If we don't have an extension, or if we don't have a .py extension, # then we don't want to add us to the list if not extension: ================================================================================ Example 492 ================================================================================ Target: self.user_id, Prediction: ustring(self.userid), 'orgid': ustring(self.orgid), 'destid': ustring(self.destid), 'destpath': ustring(self.destpath), 'destfile': ustring(self ================================================================================ Example 493 ================================================================================ Target: None Prediction: ### TODO: return None ### ================================================================================ Example 494 ================================================================================ Target: token_version, Prediction: auth_context['user_type'], _user_type, _from) else: raise Exception('Unknown token version') def get_password(self): """Get a password formatted for a specific token version.""" _from = self.auth_context['from'] ================================================================================ Example 495 ================================================================================ Target: kw['exception_level_filters'] = exception_level_filters Prediction: exception_level_filters = sorted(exception_level_filters) if len(exception_level_filters) > 1: raise RollbarException( 'Multiple exception level filters specified. ' 'Please specify only one.', exception_level_filters, ================================================================================ Example 496 ================================================================================ Target: nattable='\n'.join(self.nat), Prediction: mangle=self.mangle, mangle_type='iptables-restore', mangle_name='iptables-restore', mangle_value='iptables-restore', mangle ================================================================================ Example 497 ================================================================================ Target: ('Ask again later.', 'eq/3'), Prediction: ('I don't know.', 'eq/2'), ('I don't know.', 'eq/2'), ('I don't know.', 'eq/2'), ('I don't know.', 'eq/2'), ('I don't know.', 'eq/2'), ================================================================================ Example 498 ================================================================================ Target: False Prediction: self.table = tbl self.table.set_color(self.table.get_color()) self.table.set_font(self.table.get_font()) self.table.set_font_size(self.table.get_font_size ================================================================================ Example 499 ================================================================================ Target: None: Prediction: ### f.read(size) else: f.read(size) return f.read() def readlines(self, filename, binary_mode=False, size=None, offset=None): """Reads contents of a file to a list ================================================================================ Example 500 ================================================================================ Target: return callback(config) Prediction: if callback: return self._send_event(callback, kwargs) return self._send_event(state, kwargs) def system_monitor_cid_card_alert_state_changed(self, **kwargs): """Auto Generated Code """ ================================================================================ Example 501 ================================================================================ Target: if name: Prediction: return ans def is_binary(obj, name=None): """ returns True if object is binary-like """ try: # python2 ans = isinstance(obj, basestring) except NameError: # python3 ================================================================================ Example 502 ================================================================================ Target: Append(-1, "&Some notes", "") Prediction: Append(wx.ID_ABOUT, "About") menu_help.Append(wx.ID_HELP, "Help") self.menubar.Append(menu_about, "&About") self.menubar.Append(menu_help, "& ================================================================================ Example 503 ================================================================================ Target: self.batch_size, self.flags, self.read_concern, Prediction: self.skip, self.limit_str, self.sort, self.sort_str, self.fields_str, self.ntoskip_str, self.limit_str_str, self.sort_str_str, self.fields_str_str, ================================================================================ Example 504 ================================================================================ Target: disp.shape[1:] != (self._supercell.get_number_of_atoms(), 3)): Prediction: disp.shape[0] != self.supercells or disp.shape[1] != self.natoms or disp.shape[2] != self.natom): raise ValueError('Displacements must be a 3D array of displacements.') return ================================================================================ Example 505 ================================================================================ Target: alerts_on = True Prediction: profile = 'default' if not obj_type: obj_type = 'default' if not obj_type: obj_type = 'default' if not profile: profile = 'default' if not obj_type: obj ================================================================================ Example 506 ================================================================================ Target: i_type = type(i.get()) Prediction: yield i pool.join(raise_error=True) def parallel_map_async(func, iterable, args=None, kwargs=None, workers=None): """Map func on a list using gevent greenlets. :param func: function applied ================================================================================ Example 507 ================================================================================ Target: _logger.error( Prediction: self.logger.error("-" * 40, file=sys.stderr) self.logger.error("-" * 40, file=sys.stderr) self.logger.error("-" * 40, file=sys.stderr) self.logger.error("-" * 40 ================================================================================ Example 508 ================================================================================ Target: alleles.append(int(allele)) Prediction: alleles.append(allele) if len(markers) > 0: marker_name = markers[0] allele_number = alleles[0] is_perfect = False has_perfect_match = False for marker in markers[ ================================================================================ Example 509 ================================================================================ Target: set() Prediction: set() self.abort_run.set() self.stop_run.set() self.abort_run.set() self.stop_run.set() self.abort_run.set() self.stop_run.set ================================================================================ Example 510 ================================================================================ Target: if transformer.max_payload is not None: Prediction: if transformer.max_parallel_transforms is not None: config['MaxParallelTransforms'] = transformer.max_parallel_transforms if transformer.max_parallel_transforms_per_job is not None: config['MaxParallelTransformsPerJob'] ================================================================================ Example 511 ================================================================================ Target: obj: Prediction: ~~obj: return i raise ValueError("No such item") def _rindex_from_sequence(sequence: Sequence[T], obj: T) -> int: """ Return zero-based index in the sequence of the last item whose value is equal to obj ================================================================================ Example 512 ================================================================================ Target: self.numTries = 0 Prediction: self.retry = 0 # The number of times we have tried to generate a valid encoding self.retryCount = 0 # The number of times we have tried to generate a valid encoding self.retryCountCount = 0 # The number of times we ================================================================================ Example 513 ================================================================================ Target: print Prediction: mainPos = mainPos + 1 mainLen = mainLen + 1 if mainLen > mainPos: mainLen = mainPos if mainLen > 0: mainLen = mainLen - 1 if mainLen > 0: mainLen = main ================================================================================ Example 514 ================================================================================ Target: xmin, xmax, zmin, zmax, rpha) Prediction: xmin, xmax, zmin, zmax, rmag) return self def set_area_to_sip_signature_with_frequencies(self, xmin, xmax, zmin, zmax, spectrum): """Parameterize the eit instance ================================================================================ Example 515 ================================================================================ Target: value = self.data.get(section, {}).get(name, default) Prediction: if name == 'config': section = 'config' else: section = 'config.%s' % name if section in self.config_files: value = self.config_files[section] if value is None: # Third: ================================================================================ Example 516 ================================================================================ Target: in_p=[frontend_name]) Prediction: frontend_name) return plug_in_modules def _call(self, method, *args, **kwargs): """Calls a method on the backend. This method is called by the backend when it needs to perform a particular action. ================================================================================ Example 517 ================================================================================ Target: 0: continue Prediction: 0: continue if cycle_is[0] == 0: continue if cycle_is[0] == 1: continue if cycle_is[0] == 2: continue if cycle_is[0] == 3: ================================================================================ Example 518 ================================================================================ Target: setCursorPosition(*self.cursorPos) Prediction: setCursor(self.markerPos[0], self.markerPos[1]) self.qteWidget.setMark(self.markerPos[0], self.markerPos[1]) self.qteWidget.setMark(self.markerPos[0], self.cursorPos ================================================================================ Example 519 ================================================================================ Target: {} Prediction: { 'y_pred': y_pred, 'y_pred_std': np.std(y_pred), 'y_pred_std_std': np.std(y_pred), 'y_pred_std_std_std': np.std ================================================================================ Example 520 ================================================================================ Target: __extract_directory( Prediction: extract(destination) def extract_all(self, destination): """Extracts all the contents of the archive to the specifed directory. Args: destination (str): Path to an empty directory to extract the files to. """ if os ================================================================================ Example 521 ================================================================================ Target: _build_array() Prediction: json elif self.json['sys']['type'] == 'Object': return SyncObject( self.json, default_locale=self.default_locale, localized=True ) else: return self.json def get ================================================================================ Example 522 ================================================================================ Target: _list_datasets(uri, quiet, verbose) Prediction: _list_item_items(uri, quiet, verbose) def _list_item_items(uri, quiet, verbose): """List items in a dataset. If the URI is a dataset the items in the dataset will be listed. It is not possible to list ================================================================================ Example 523 ================================================================================ Target: 'decimalValues'] = \ Prediction: self.my_osid_object_form.id] = None self.my_osid_object_form._my_map[self.my_osid_object_form.id] = None self.my_osid_object_form._my_map[ ================================================================================ Example 524 ================================================================================ Target: install_monitor(self._monitor) Prediction: add_monitor(self._monitor) def _get_monitor_stat_func(self, monitor_pattern: str, monitor_stat_func_name: str): """ Returns the name of the monitor statistics function. :param monitor_pattern: Pattern string. ================================================================================ Example 525 ================================================================================ Target: yield OffsetCommitResponse(topic, partition, error) Prediction: if error: raise ValueError('Invalid partition: %s' % error) if partition == 0: continue if partition == 1: continue if partition == 2: continue if partition == 3: continue if partition == ================================================================================ Example 526 ================================================================================ Target: else: Prediction: else: return sum(map(lambda g: g.intensities_from_grid(grid), []) def intensities_of_galaxies_from_masked_grid(masked_grid, galaxies): """Compute the intensities of a list of galaxies ================================================================================ Example 527 ================================================================================ Target: prompt=DEFAULT_COLOR_PROMPT, Prediction: underline=DEFAULT_COLOR_UNDERLINE, strikethrough=DEFAULT_COLOR_STRIKETHROUGH, underline_color=DEFAULT_COLOR_UNDERLINE_COLOR, strikethrough_color=DEFAULT_COLOR_STRIKETHROUGH ================================================================================ Example 528 ================================================================================ Target: docker.Client.") Prediction: ###client") if not isinstance(repository_tag, str): raise TypeError("repository_tag needs to be of type ###str") if not isinstance(docker_file, str): raise TypeError("docker_file needs to be of type ###str") ================================================================================ Example 529 ================================================================================ Target: else: Prediction: elif isinstance(b[key], dict) and isinstance(a[key], dict): merge_dict(a[key], b[key], path + [str(key)]) else: raise TypeError("dict keys must be strings or dicts") return a ================================================================================ Example 530 ================================================================================ Target: median_diff/2.0] Prediction: iaxis[0] for iaxis in self.x] bin_edges = np.array(bin_edges) bin_edges = np.array(bin_edges) / np.array(self.x.shape[0]) bin_edges = np ================================================================================ Example 531 ================================================================================ Target: self.canvas.unsetMapTool(self.pan_tool) Prediction: self.rectangle_map_tool.set_color(QtGui.QColor(QtGui.QColor.fromRgb(0, 0, 0))) self.rectangle_map_tool.set_size(QtGui.QSize(100, 100)) self ================================================================================ Example 532 ================================================================================ Target: full.cross_entropy( Prediction: labels, name=name, loss_weight=loss_weight, per_example_weights=per_example_weights) else: # If we don't have labels, we don't need to do anything. return SoftmaxResult(input_. ================================================================================ Example 533 ================================================================================ Target: oldvalue: Prediction: oldvalue: raise ValidateError("Cannot set the same value twice") elif value != oldvalue: raise ValidateError("Cannot set the same value") elif value == oldvalue: raise ValidateError("Cannot set the same value twice") elif value ================================================================================ Example 534 ================================================================================ Target: ) Prediction: ) return diff_result def words_diff(before_words, after_words): '''Diff the words in two strings. This is intended for use in diffing prose and other forms of text where line breaks have little semantic value. Parameters ================================================================================ Example 535 ================================================================================ Target: check_error(r) Prediction: data = r.json() return data def get_upload_spec(self): """doc: http://open.youku.com/docs/doc?id=91 """ url = 'https://openapi.youku.com/v2/ ================================================================================ Example 536 ================================================================================ Target: ckan_portal = RemoteCKAN(portal_url, apikey=apikey) Prediction: if identifier is None: identifier = catalog.get_identifier() if label is None: label = catalog.get_label() if apikey is None: apikey = catalog.get_apikey() if identifier is None: identifier = ================================================================================ Example 537 ================================================================================ Target: SparseTensor, tf.compat.v1.SparseTensorValue)): Prediction: SparseTensor, tf.SparseTensor, tf.SparseTensor, tf.SparseTensor, tf.SparseTensor, tf.SparseTensor, tf.SparseTensor, tf.SparseTensor, tf.SparseTensor, tf.SparseTensor, ================================================================================ Example 538 ================================================================================ Target: n)] Prediction: n)] def partition_with_replacement(lst, n): """ Divide list into n equal parts """ q, r = divmod(len(lst), n) indices = [q*i + min(i, r) for i in x ================================================================================ Example 539 ================================================================================ Target: return result[-1] Prediction: else: return result.close # 定义一个函数,用于判断是否是正负的 def is_negative(self): """判断是否是负""" return self.close < ================================================================================ Example 540 ================================================================================ Target: self.rc("display :@/%s" % " or ".join(water_selection)) Prediction: self.rc("~display :HOH") self.rc("~display :HOH") self.rc("~display :HOH") self.rc("~display :HOH") self.rc("~display :HOH") self.rc ================================================================================ Example 541 ================================================================================ Target: try: Prediction: if not isinstance(address, (str, int)): raise ValueError("address must be a string or an integer") if not isinstance(address, (tuple, list)): raise ValueError("address must be a string or an integer or a tuple") if not isinstance( ================================================================================ Example 542 ================================================================================ Target: return '{0}/{1}'.format( Prediction: return self.entity_mixins.Entity.path(self.entity_mixins.Entity.refresh) elif which == 'external_usergroups': return self.entity_mixins.Entity.path(self.entity_mixins.Entity.external_usergroups) ================================================================================ Example 543 ================================================================================ Target: sval = list(map(self.toString, self.value, len(self.value)*[1])) Prediction: if cl: return self.dpar_cl(cl) else: return self.dpar_py(cl=cl) def dpar_cl(self, cl=1): """Return dpar-style CL version of code. Default ================================================================================ Example 544 ================================================================================ Target: func: Prediction: uevent.is_webhook_event(func): return if uevent.is_webhook_event(func, 'all'): return if uevent.is_webhook_event(func, 'event'): return if ue ================================================================================ Example 545 ================================================================================ Target: return build_response Prediction: return build_response def build_image_in_privileged_container_from_dockerfile(build_image, source, image, parent_registry, target_registries, dont_pull_base_image, **kwargs): ================================================================================ Example 546 ================================================================================ Target: self).deconstruct() Prediction: self).deconstruct() if name == '__init__': return name, path, args, kwargs elif name == 'get_value': return self.get_value() elif name == 'set_value': return self.set_value( ================================================================================ Example 547 ================================================================================ Target: if "floordiv" in name: # (PR 9308) Prediction: result = result.astype('float64', copy=False) else: # GH 7325 # if we have a fill of inf, then sign it correctly # (GH 6178 and PR 9308) signs = y if name.startswith ================================================================================ Example 548 ================================================================================ Target: data = self._slice(view) Prediction: bbox = self.bbox_to_view(shape_obj) bbox = bbox.view(view) # mask out the pixels not in the bbox mask = mask.view(view) # cut out the bbox return mask. ================================================================================ Example 549 ================================================================================ Target: VarDecl(p[1]) Prediction: get_type_declaration(p[0]) p[1] = self.asttypes.get_initializer_declaration(p[1]) else: raise SyntaxError("invalid declaration") def p_variable_declaration_list(self, p ================================================================================ Example 550 ================================================================================ Target: in patterns) Prediction: ia pattern in patterns) return _trace_filter def trace_filter (patterns): """Add given patterns to trace filter set or clear set if patterns is None.""" if patterns is None: _trace_filter.clear() else: ================================================================================ Example 551 ================================================================================ Target: print location Prediction: else: print "Corrijo WSDL ...", location, location = location.replace("http://", "https://").replace(":80", ":443") self.client.services['LumService']['ports']['LumEndPoint']['location'] = location ================================================================================ Example 552 ================================================================================ Target: dirname)) Prediction: dirname)) def list_files(dir_pathname, recursive=True, topdown=True, followlinks=False): """ Enlists all the files in the specified directory, optionally recursively. :param dir_pathname: The directory to traverse. ================================================================================ Example 553 ================================================================================ Target: ) Prediction: ) return None return module def _check_module_attrs(self, node, module, module_names): """check that module_names (list of string) are accessible through the given module """ assert isinstance(module, astroid. ================================================================================ Example 554 ================================================================================ Target: if max_width > self.list.width(): Prediction: results.append(text_item) if line_number is not None: text_item += " ({0:} {1:})".format(self.line_count[index], _("lines")) results.append(text_item) ================================================================================ Example 555 ================================================================================ Target: except AttributeError: Prediction: value.prepare_to_store(fh, prepare) fh.write(prepare) except KeyError: pass except: pass except: pass fh.close() except: pass def load ================================================================================ Example 556 ================================================================================ Target: app) Prediction: app) def _get_gateway_app(self, full_path): """Read WSGI app/Gateway path string and import application module.""" mod_path, _, app_path = full_path.partition(':') app = getattr(import_ ================================================================================ Example 557 ================================================================================ Target: 'levels must be a positive integer, but got {}'.format(levels)) Prediction: "levels must be an integer between 1 and %d" % levels ) if not (isinstance(min_val, int) and min_val > 0): raise ValueError( "min_val must be an integer between 0 and %d" % min_ ================================================================================ Example 558 ================================================================================ Target: 'available error codes (with a list of ' Prediction: 'errors. For example: --ignore=D101,D2') add_check('--convention', metavar='', default=None, help='choose the basic list of checked errors by ' 'specifying which errors to check for (with a ================================================================================ Example 559 ================================================================================ Target: ) Prediction: status=self.STATUS_CONFIRMED, ) return confirmation def generate_key(self, email_address): "Generate a unique key for the given email address" return self.generate_key(email_address.email, self.generate_key ================================================================================ Example 560 ================================================================================ Target: return json.dumps(values) Prediction: return json.dumps(values, indent=4, separators=(',', ': ')) def as_json(self): """Return the key as JSON.""" return json.dumps(self.as_dict(), indent=4, separators=(',', ': ' ================================================================================ Example 561 ================================================================================ Target: self.PlanetaryRadius = self.configGet("float", "numerical2D", "PlanetaryRadius", optional=True) Prediction: self.lonlat = self.configGet("string", "numerical2D", "lonlat", optional=True) self.latlon = self.latlon.replace(" ", "") self.lonlat = self.lonlat.replace(" ", "") self.lat ================================================================================ Example 562 ================================================================================ Target: scripts_dir) Prediction: daemon_name='powerline') set_up_powerline_vim() set_up_powerline_bash() set_up_powerline_tmux() set_up_powerline_i3() set_up_powerline_vim ================================================================================ Example 563 ================================================================================ Target: _helpers._to_bytes(private_key_password) Prediction: ustr(private_key_password) private_key_bytes = pkcs12_key_from_der(private_key_bytes, private_key_password) return pem_encode(private_key_bytes) def pkcs12_key_from ================================================================================ Example 564 ================================================================================ Target: checkbox = widget[0].get('checkbox', False) Prediction: return True return False def getRejectionReasons(self): """Return a list of all the rejection reasons for the rejection workflow """ widget = self.getRejectionReasons() if len(widget) > 0: return widget ================================================================================ Example 565 ================================================================================ Target: return max((np.linalg.norm(AX), np.linalg.norm(self.cnst_B(Y)), Prediction: else: self._nrm_cnst_c = self.cnst_c() # Avoid computing the norm of the value returned by cnst_A() # more than once if not hasattr(self, '_nrm_cnst_A'): ================================================================================ Example 566 ================================================================================ Target: scriptable, callback) Prediction: callback=callback) self.threads[script] = thread thread.start() return thread def run_script(self, scriptable, script, callback=None): """Run the script and add it to the list of threads.""" if scriptable in ================================================================================ Example 567 ================================================================================ Target: response = self._post('v2', 'accounts', account_id, 'transactions', data=params) Prediction: params['currency'] = self.currency params['amount'] = self.amount params['account_id'] = account_id return self.request('POST', self.url, params) def send_transfer(self, account_id, amount, currency, ** ================================================================================ Example 568 ================================================================================ Target: pages, Prediction: ., 'page_languages': page_languages, 'page_id': page_id, }, context_instance=RequestContext(request)) def sub_menu_page(request, page_id): """Render the children of the requested page with the ================================================================================ Example 569 ================================================================================ Target: nvmlLib Prediction: iret iret = fn() _nvmlCheckReturn(iret) # # Initialize the GPUs # # This method is called by the NVML library when it is first loaded. # # The GPUs are initialized in the following order: ================================================================================ Example 570 ================================================================================ Target: FileNotFoundError, PermissionError): Prediction: ValueError, IOError): return elements.error("Bit for Bit", "File named " + fname + " has no suitable match!") # Check the data if not model_data.has_bit_for_bit(bench_data): return ================================================================================ Example 571 ================================================================================ Target: slug = slugify('%s-%s' % ( Prediction: for receiver, response in responses: if response is False: logger.debug( 'Skipping MEP %s', mep_json['Name']['full']) return if response['Status'] == 'OK': changed = True logger. ================================================================================ Example 572 ================================================================================ Target: return Prediction: raise AttributeError('Django >= 1.10 requires the "refresh_from_db" method to be implemented.') def _refresh_from_db(self): """ Django >= 1.10: patch refreshing deferred fields. Crucial for only/defer to work. ================================================================================ Example 573 ================================================================================ Target: self.positive_prob_prior) Prediction: self.negative_features, self.negative_labels, self.positive_labels, self.positive_features, self.negative_features, self.negative_labels, self.positive_labels, ================================================================================ Example 574 ================================================================================ Target: (-1)**(~obs.value['voiced'])) Prediction: sr) # Create a list of lists of observations observations = [] for time in times: observations.append([]) for frequency in freqs: observations[time].append( []) for obs in annotation ================================================================================ Example 575 ================================================================================ Target: VerificationException( Prediction: iaas_exceptions.VerificationException( "Signing Certificate does not contain the DNS name " "of the domain to be verified") class VerificationException(Exception): """Exception raised when a certificate is not valid.""" pass class _ValidateCert ================================================================================ Example 576 ================================================================================ Target: Get("cpe") or [None] Prediction: Get("cpe") or [None] if os_name and cpe: if os_name is None: os_name = [] os_name.append(os_name) cpe.append(cpe) if artifact is None: ================================================================================ Example 577 ================================================================================ Target: == "TITLE": Prediction: ia "title": titles.append(child.name) return titles def _get_vcard_children(self): """ :rtype: list(list(str)) """ children = [] for child in self.vcard ================================================================================ Example 578 ================================================================================ Target: alias.build(builder) Prediction: alias.build(builder) if self.specify: builder.end("CodeListItem", params) return builder.end() def build_xml(self, builder): """Build XML by appending to builder""" params = dict(Coded ================================================================================ Example 579 ================================================================================ Target: self._from_temp_dataset(ds) Prediction: xt.array(ds, name=self.name, dtype=self.dtype, shape=self.shape, compute=self.compute, **kwargs) return new def _to_temp_dataset(self): """Return a ================================================================================ Example 580 ================================================================================ Target: result['name'] Prediction: ustr(result['name']) self.description = ustr(result['description']) self.status = result['status'] self.ip_address = result['ip_address'] self.mac_address = result['mac_address'] self.dhcp_ ================================================================================ Example 581 ================================================================================ Target: if not self.terminate(force): Prediction: self.close() else: self.wait() self.closed = True def wait(self): """Wait for the child to terminate. This is a blocking call.""" if self.closed: raise RuntimeError("Child is already closed") ================================================================================ Example 582 ================================================================================ Target: in dep_dict: Prediction: ia in dep_dict.values(): if len(item) > 1: ties.append(item) return ties def get_dependencies(G): """ Returns a list of all dependencies of a graph. """ # we are going to ================================================================================ Example 583 ================================================================================ Target: else: Prediction: else: url = url_search_num % vars() # Prepare the URL of the next request. if pause: url += '&pause=' + str(pause) # Prepare the URL of the last request. if stop: ================================================================================ Example 584 ================================================================================ Target: options = handle_default_options(options) Prediction: if options.settings: parser.error("--settings is not supported") if options.pythonpath: parser.error("--pythonpath is not supported") if options.help: parser.error("--help is not supported") if options.version ================================================================================ Example 585 ================================================================================ Target: raise MissingCorpusError(msg) Prediction: raise ValueError(msg) else: return w_td_c def load_from_file(self, loc, file_name): '''Load a pickled model from a file.''' try: w_td_c = pickle. ================================================================================ Example 586 ================================================================================ Target: _value) Prediction: value) def __str__(self): """ Return the string representation :rtype : str """ return self.value def __repr__(self): """ Return the string representation :rtype : str """ ================================================================================ Example 587 ================================================================================ Target: return True Prediction: resp = await self._send(self.srp.verify3(), 'verify3') if resp[0:32] == 'atv_public_secret': return True else: return False async def verify_authed_with_public_key ================================================================================ Example 588 ================================================================================ Target: ): Prediction: proxy): raise OperationFailed( 'ObjectiveBankSearchSession does not support objective bank search.' ) return self.get_objective_bank_search_session(proxy) def get_objective_bank_search_session(self, proxy): ================================================================================ Example 589 ================================================================================ Target: delete() Prediction: revoke() return True def revoke_permission(self, role, name): """ revoke authorization of a group """ if not self.has_permission(role, name): return True targetGroup = AuthGroup.objects(role=role, creator ================================================================================ Example 590 ================================================================================ Target: else: Prediction: elif button == 'Cancel': return None else: return button def save_zip(self): """Parameters for saving zip backups""" with gui.FlexForm(self.title, auto_size_text=True, default_element_size ================================================================================ Example 591 ================================================================================ Target: e) Prediction: e) return False return True def prompt_4_overwrite(filename, force_write): """ Prompts user to overwrite file if it already exists :param filename: :param force_write: :return: """ ================================================================================ Example 592 ================================================================================ Target: cache_valid = os.path.exists(col_org_file_check) and os.path.exists(col_values_file_check) Prediction: if not os.path.exists(col_org_file_check): os.makedirs(col_org_file_check) if not os.path.exists(col_values_file_check): os.makedirs(col_values_file ================================================================================ Example 593 ================================================================================ Target: M = self.flat() Prediction: if mtx is None: return None if isinstance(mtx, QuTiP.Qobj): return mtx.type == "super" else: return mtx.type == "covariance" def _get_superop_from_ ================================================================================ Example 594 ================================================================================ Target: '' Prediction: item.get_object().get_field(field_name) row[field_name] = item.get_object().get_field(field_name) row[field_name] = item.get_object().get_field(field_name) row ================================================================================ Example 595 ================================================================================ Target: TypeError: Prediction: erc20.errors.JSONDecodeError: raise ValueError("Invalid JSON") class HasProperties(object): """ A class that represents a property of an instance. """ def __init__(self, value): self.value = value def ================================================================================ Example 596 ================================================================================ Target: kwargs) Prediction: kwargs) return data def read_namespaced_stateful_set_status_with_http_info(self, name, namespace, **kwargs): """ read status of the specified StatefulSet with HTTP info This method makes a synchronous HTTP request by default. ================================================================================ Example 597 ================================================================================ Target: return True Prediction: return True def set_language_description(self, language_description): """ Sets the language description. :param language_description: Language description. :type language_description: str :return: Method success. :rtype: bool ================================================================================ Example 598 ================================================================================ Target: calibration_path.mkdir(parents=True, exist_ok=True) Prediction: calibration_path.create_dir() if not os.path.exists(calibration_path): os.makedirs(calibration_path) if not os.path.exists(calibration_path + 'tipLength.txt'): os.m ================================================================================ Example 599 ================================================================================ Target: investment_term) Prediction: self._investment_term) return self._investment_term def _get_investment_term(self): """ This is the investment term in months. This might change to a relative delta.""" return self._investment_term def _ ================================================================================ Example 600 ================================================================================ Target: ascii_uppercase: Prediction: ascii_lowercase: if c in urls: return urls[c] else: urls = ["0-9" + start + "0-9" + end] for c in string.ascii_lowercase: if c in ur ================================================================================ Example 601 ================================================================================ Target: prompt = colors.prompt + self.templates[name] + colors.normal Prediction: if name=='out': prompt = self.prompt_out else: prompt = self.prompt_in # Render the prompt if name=='out': self.render_out(prompt, fmtargs) else: self ================================================================================ Example 602 ================================================================================ Target: if not (cutoff_value == -999 and cutoff_value_perc == -999): Prediction: if not (pass_int_interval or pass_int_interval_perc): if not (pass_sigma or pass_sigma_perc): pars['pass_or_fail'] = 'fail' pars['fail_list'].append("int_sigma") ================================================================================ Example 603 ================================================================================ Target: False Prediction: irc_role(role, color) else: return irc_role(role, color) def create_device_role(role, color): ''' .. versionadded:: 2019.2.0 Create a device role role String of ================================================================================ Example 604 ================================================================================ Target: raise Prediction: raise NoLoopbackAvailableError() # Fill volume with logical volumes for l in volume.info['volume_group'].split('\n'): volume.info['volume_group'] = l.strip() volume.info['volume_name'] = l.strip() ================================================================================ Example 605 ================================================================================ Target: client_factory else None Prediction: irc_client_factory else client_factory(command_args) return op(client, name, **kwargs) return _command_handler def _get_op_handler(self, operation): """ Returns the op handler for the given operation """ if not isinstance ================================================================================ Example 606 ================================================================================ Target: match.start(0):match.end(0)], match.end(0) Prediction: match.end():], match.end() def accept_line(buf, pos): """Skip whitespace at the current buffer position.""" match = re_line.match(buf, pos) if not match: return None, pos return buf[match ================================================================================ Example 607 ================================================================================ Target: unbounded_typevar(TC, G) Prediction: match(TC) and match(G) ) or match(G) ) return scrutinee(tc) def _lookup_type(self, TC: type, G: type) -> TypeClass: ''' Find ================================================================================ Example 608 ================================================================================ Target: return fn Prediction: return register = decorator(register) register(on) @register def on_change(cls, event, handler_func=None): """ Registers a handler function whenever an instance of the model emits the given event. ================================================================================ Example 609 ================================================================================ Target: parameter_type == "known_class": Prediction: ivalue_type is None: # if no value_type is required, return the parameter as is return value elif ivalue_type == "str": # if string is required, convert to a string try: value = value.strip() ================================================================================ Example 610 ================================================================================ Target: if not self._connection: Prediction: if read_only: self._connection.execute('PRAGMA read_only=1') self._connection.execute('PRAGMA writable=1') self._connection.execute('PRAGMA journal_mode=wal') self._connection.execute(' ================================================================================ Example 611 ================================================================================ Target: element.send_keys(Keys.CONTROL + 'a') Prediction: #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== #============================================================================== ================================================================================ Example 612 ================================================================================ Target: target = m.group(1) Prediction: return m.group(1) def _help_end_re.search(line): """Return the first non-whitespace character after the end of a line.""" return line.rstrip(line.rfind('\n') + 1) def _ ================================================================================ Example 613 ================================================================================ Target: aux = 1. / (1. + step) Prediction: sma = self.sma + step step = -step return sma, step def update_sma(self, step): """ Update the semimajor axis length. Parameters ---------- step : float The current step ================================================================================ Example 614 ================================================================================ Target: with self.graph.as_default(): Prediction: # Get the initial state initial_state = self._cell.initial_state() initial_state = initial_state.as_list() # Get the states states = self._cell.states() states = states.as_list() # Get ================================================================================ Example 615 ================================================================================ Target: else: Prediction: elif exception_type == self._EXCEPTION_TYPE_REMOVE: return False else: raise ValueError("Unknown exception type: %s" % exception_type) return self.is_active(date) def is_active(self, date): ================================================================================ Example 616 ================================================================================ Target: indent Prediction: indent return '\n'.join([indent, self.name, self.description, self.category, self.version, self.author, self.license, self.url, self.summary, self.description, self.category, self.version, self.author, self.license, self ================================================================================ Example 617 ================================================================================ Target: weights = weights.where(np.isfinite(data)) Prediction: masked_data = self.mask_var(data, lon_cyclic=lon_cyclic, lon_str=lon_str, lat_str=lat_str, mask=mask) masked_data = masked_data[masked_data. ================================================================================ Example 618 ================================================================================ Target: strip()] Prediction: strip()] comment_lines = [i.strip() for i in comment_text.split("\n") if i.strip()] code_lines = [i.strip() for i in code_text.split("\n") if i.strip()] return docstr ================================================================================ Example 619 ================================================================================ Target: Y = yfit*SpringPotnl Prediction: fig = plt.figure() ax = fig.add_subplot(111) ax.plot(z, yfit, 'r-', label='Dynamical Potential') ax.plot(z, density, 'b-', label='Steady State ================================================================================ Example 620 ================================================================================ Target: profile: Prediction: profile: stopwatch.sw.profile = True stopwatch.sw.trace = True stopwatch.sw.enabled = True stopwatch.sw.profile_trace = True stopwatch.sw.trace_trace = True stopwatch.sw.enabled ================================================================================ Example 621 ================================================================================ Target: _output) Prediction: output_dim) self._input = layer.compute_tensor(self.input_dim) self._output_shape = layer.compute_shape(self._output) self._input_shape = layer.compute_shape(self._input) self._output_ ================================================================================ Example 622 ================================================================================ Target: new_metadata_factory = CSRMatrixFactory() Prediction: return self.categories_as_metadata() def categories_as_metadata(self): ''' Returns a TermDocMatrix which is identical to self except the metadata values are now identical to the categories present. :return: TermDocMatrix ''' return ================================================================================ Example 623 ================================================================================ Target: )) Prediction: 0)) def transformMesh(self, transformation): """ Apply this transformation to the actor's transformation, not to the polygonal `mesh`, which is reset. :param transformation: ``vtkTransform`` or ``vtkMatrix4x4`` object. ================================================================================ Example 624 ================================================================================ Target: ) Prediction: ) def get_organisation_information_by_id(self, id): ''' Get information fot this organisation by id. Returns a dictionary of values. ''' return self.fetch_json( uri_path=self.base_uri, ================================================================================ Example 625 ================================================================================ Target: in keys_to_delete: Prediction: ia in keys_to_delete: for v in feed_map[ia]: if v.name not in node_names: feed_map[ia].remove(v) return feed_map def _prune_graph_def(meta_graph, ================================================================================ Example 626 ================================================================================ Target: index}L)' Prediction: index})'.format( array=array, index=index) return weld_obj.weld_template(weld_template, obj_id, weld_obj) def weld_iloc_float(array, index): """Retrieves the ================================================================================ Example 627 ================================================================================ Target: = { Prediction: = self.to_json() return { 'action': 'update', 'storage': 'storage', 'body': body, } def to_json(self): """ Return a JSON representation of the object. U ================================================================================ Example 628 ================================================================================ Target: ) Prediction: ) if DEBUG: return view(view, *view_args, **view_kwargs) return view(view, *view_args, **view_kwargs) @secure(view) def slack_chat(request): """Send a message to the ================================================================================ Example 629 ================================================================================ Target: sys.stdout, sys.stderr = None, None Prediction: sys.stdout = _temp1 sys.stderr = _temp2 else: # On non-Windows platforms: redirect standard inputs _temp1, _temp2 = sys.stdin, sys.stdout sys.stdin = _temp1 sys ================================================================================ Example 630 ================================================================================ Target: _prop = (scope or '') + prop Prediction: if prop == '__name__': return if prop == '__module__': return if prop == '__doc__': return if prop == '__class__': return if prop == '__init__': return ================================================================================ Example 631 ================================================================================ Target: dist_name, dist_hash) Prediction: dist_hash, dist_name) def _add_dist_zip(self, dist_path, dist_name): """Add a distribution from a zip file. :param dist_path: The path to the zip file. :param dist_name: The name ================================================================================ Example 632 ================================================================================ Target: datacenter_id, volume_id), Prediction: datacenter_id, volume_id), data, datacenter_id=datacenter_id, volume_id=volume_id, name=name, description=description, headers=self.headers, body=body ================================================================================ Example 633 ================================================================================ Target: else: Prediction: else: return _keys def _get_keys(self): """ Return a list of keys. Either all keys or only keys of a specific type :return: If typ is undefined all the keys as a dictionary otherwise the appropriate keys in a ================================================================================ Example 634 ================================================================================ Target: else: Prediction: else: a = [[0, 1, 2], [2, 3, 4]] if rhofile: a = [a, a, a] else: a = [0, 0, 0] return a def readin_ ================================================================================ Example 635 ================================================================================ Target: ( Prediction: "Displaying %s" % info.name else: message = "Displaying %s" % info.name else: message = "Displaying %s" % info.name if display_handle is None: display_handle = port ================================================================================ Example 636 ================================================================================ Target: label.setMinimumWidth(width) Prediction: label.setFixedWidth(width) def harmonizeLabelsTextHeight(labels, height=None): """ Sets the the maximum height of the labels If height is None, the maximum height is calculated using labelsMaxTextHeight() """ if height is None: ================================================================================ Example 637 ================================================================================ Target: for gff_object in d[(gff_start, gff_end)] Prediction: for gff_object in d[(gff_start, gff_end)] if not (gff_start <= gff_end or gff_start >= gff_end)] def get_coverage(self, seqid, start, end, overlap=True ================================================================================ Example 638 ================================================================================ Target: ) Prediction: ) if exclude and exclude != ALL_FIELDS: raise TypeError( 'The `exclude` option must be a list or tuple or "__all__". ' 'Got %s.' % type(exclude).__name__ ) if fields ================================================================================ Example 639 ================================================================================ Target: break Prediction: break class Query(object): """ A query object. """ def __init__(self, query_string, query_type='all', **kwargs): self.query_string = query_string self.query_type = query_type ================================================================================ Example 640 ================================================================================ Target: 'errorHandler'](e) Prediction: e.args[0]] = e.args[1] else: raise return None def _execCommand(Argv, collect_missing): """Executes the given task with parameters. Args: Argv: A string containing the command ================================================================================ Example 641 ================================================================================ Target: ) as client: Prediction: self.memcached_host, self.memcached_port) as client: client.delete_all_keys() class Rez(object): """Rez is a python package manager for memcached. Rez is a python package manager for memcached. It is ================================================================================ Example 642 ================================================================================ Target: pending, self._pending = self._pending, None Prediction: self._pending = [] def _on_connection_done(self, reason): """ Mark the protocol as failed and fail all pending operations. """ self._failed = reason self._pending = [] def _on_connection_error(self ================================================================================ Example 643 ================================================================================ Target: _verify_version(connection) Prediction: connect(connection) if connection.state == self.__class__.cached_state: return connection raise interface.ConnectionError('{} not connected'.format(self)) def disconnect(self): """Disconnect from the first available interface.""" self.disconnect_ ================================================================================ Example 644 ================================================================================ Target: }) Prediction: 'error-code': -1}) return t def _get_filter(self, v, load=False): """ Getter method for filter, mapped from YANG variable /interface_vlan/interface/vlan/ip/arp/inspection/filter ================================================================================ Example 645 ================================================================================ Target: else: Prediction: else: a_min = 0.0 if a_min > 0.0: return True else: return False def _get_vertex_colors(self): """ Returns the vertex colors for the current object. Returns ================================================================================ Example 646 ================================================================================ Target: master_process = BackgroundProcess.objects.filter(parent_process__isnull=True, Prediction: # start the scheduler self.start_daemon() # start the scheduler self.start_daemon() # start the scheduler self.start_daemon() # start the scheduler self.start_ ================================================================================ Example 647 ================================================================================ Target: in custom_types: Prediction: ia_type(interface): return interface # Create a new registry for the interface. registry = registry_factory(interface) # Register factories for the interface. for factory in registry.factory_registry: factory.register(interface) # Return the ================================================================================ Example 648 ================================================================================ Target: extra_args) Prediction: extra_args) return args def solc_arguments(libraries=None, combined='bin,abi', optimize=True, extra_args=None): """ Build the arguments to call the solc binary. """ args = [ '--comb ================================================================================ Example 649 ================================================================================ Target: get_user_token( Prediction: ue_login(self, user) def do_login(self, user): """ Login with the user. The user is authenticated by the token, and the user is logged in. """ # never allow insecure login self.check_secure ================================================================================ Example 650 ================================================================================ Target: (self.address_string(), Prediction: (self.__class__.__name__, format, *args)) sys.stderr.flush() class NullHandler(logging.Handler): """A handler that does nothing. This handler is useful if you want to write to stderr but don't want to log messages ================================================================================ Example 651 ================================================================================ Target: if not os.path.isfile(file_name): Prediction: with open(file_name, 'r') as f: data = json.load(f) return data def load_json_array(file_name, default=None): """ Deserialized into a Python array ================================================================================ Example 652 ================================================================================ Target: pitches[idx[:, 0], idx[:, 1]] = ((idx[:, 0] + shift[idx[:, 0], idx[:, 1]]) Prediction: pitches[idx] = S[idx] mags[idx] = S[idx] # Store the local max of the magnitude pitches[idx] = np.max(mags[idx]) # Store the local max of the pitch pitches ================================================================================ Example 653 ================================================================================ Target: fcoe_intf_rbridge_id = ET.SubElement(input, "fcoe-intf-rbridge-id") Prediction: input.set("type", "rbridge") input.set("id", "fcoe_rbridge_id") input.set("name", "fcoe_rbridge_name") input.set("description", "fcoe_rbridge_description") ================================================================================ Example 654 ================================================================================ Target: token = connect_mtd Prediction: return token if token["bearer"] == "": return token if token["bearer"] == "bearer": return token if token["bearer"] == "bearer": return token if token["bearer"] == "bearer ================================================================================ Example 655 ================================================================================ Target: try: Prediction: return response.json() def _response_json(self, response, json=True): """Parses the HTTP response as a the cloudstack value. It throws an exception if the server didn't answer with a 200. """ if json: content ================================================================================ Example 656 ================================================================================ Target: None: Prediction: ###: now = datetime.utcnow() else: now = datetime.utcnow() # get the tweet tweet = raw_tweet.split('\n')[0] # get the source source = source.split(' ================================================================================ Example 657 ================================================================================ Target: add_option_group(group) Prediction: add_option('-u', '--username', help=msg['username']) parser.add_option('-p', '--password', help=msg['password']) parser.add_option('-c', '--client', help=msg['client']) parser.add ================================================================================ Example 658 ================================================================================ Target: cPickle.dump(dict(zip(varnames, atIndices(outOf, varnames))), Prediction: if outOf is not None: f.write(outOf) f.close() for var in varnames: if var in outOf: f.write(var) f.close() f.close() except IOError ================================================================================ Example 659 ================================================================================ Target: if ssl and self.ssl_connect_string: Prediction: if connect_string: self.ssl = ssl.wrap_socket(connect_string, ssl.DO_NOT_REUSE_CERT_NAME, ssl.DO_NOT_REUSE_CERT_PATH, ssl ================================================================================ Example 660 ================================================================================ Target: if r.status_code == 200: Prediction: r.content_type = 'application/json' r.content = json.dumps(self.extract_coverage(container)) return r def extract_coverage_report(self, container: Container) -> FileLineSet: """ Extract ================================================================================ Example 661 ================================================================================ Target: self.display.add_extension_event(code, newevt) Prediction: if name is not None: newevt.name = name if isinstance(evt, ExtensionEvent): newevt.evt = evt else: newevt.evt = evt if isinstance(evt, ExtensionEvent): ================================================================================ Example 662 ================================================================================ Target: ) Prediction: ) elif pooling_convention == 'valid': node = onnx.helper.make_node( pooling_convention, input_nodes, # input [name], name=name ) else: raise Attribute ================================================================================ Example 663 ================================================================================ Target: self.remove_cols_mode = False Prediction: self.update_mode() # exit col_remove_mode self.exit_col_remove_mode() def exit_col_remove_mode(self, event): """ go back from 'remove cols' mode to normal """ ================================================================================ Example 664 ================================================================================ Target: res = _recompress_archive(archive, verbosity=verbosity, interactive=interactive) Prediction: try: archive_path = util.get_archive_path(archive) if not os.path.exists(archive_path): util.log_error("Could not find %s" % (archive,)) return False if verbosity >= 0: ================================================================================ Example 665 ================================================================================ Target: text) Prediction: text) def _construct_prompt(self, id_prefix, lines): """Constructs a prompt for the given id_prefix and lines. """ text = [] for line in lines: if isinstance(line, str): text.append( ================================================================================ Example 666 ================================================================================ Target: inc_session_id=True, callback_function=callback_function_param) Prediction: { 'app_id': self.app_id, 'app_name': self.app_name, 'app_version': self.app_version, 'app_version_name': self.app_version_name, 'app_version ================================================================================ Example 667 ================================================================================ Target: serializer_class = getattr(module, parts[-1]) Prediction: if not module: raise Exception( "Can not load serializer '%s'" % serializer_class + ' before binding or without specifying full path') return serializer_class def _get_serializer_class(self): """Get the class ================================================================================ Example 668 ================================================================================ Target: 677698777895', Prediction: d4a9d9f7b9c6', version='5.0-preview.1', route_values=route_values, query_parameters=query_parameters, response_type='DefinitionProperties') return self._des ================================================================================ Example 669 ================================================================================ Target: i = 0 Prediction: if object_handle is None: raise LdtpServerException('Object not found') if iterations < 0: iterations = 0 else: iterations = iterations + 1 self.scrollbar_up(window_name, object_name, iterations ================================================================================ Example 670 ================================================================================ Target: length = inputs.shape[1] Prediction: length = inputs.shape[1] if valid_length is not None: length = valid_length.shape[0] if states is not None: states = [states] if len(states) == 0: states = [None] * ================================================================================ Example 671 ================================================================================ Target: raise RuntimeError("File %s doesn't exist!" % filename) Prediction: else: return yaml_load(filename) def load_from_file(filename): """"Load yaml file with specific include loader.""" if os.path.isfile(filename): with open(filename) as handle: return yaml_load( ================================================================================ Example 672 ================================================================================ Target: prs_show = prs.add_parser('show', Prediction: if not prs: return if not isinstance(prs, argparse.ArgumentParser): raise TypeError("Expected argument parser object") if not isinstance(prs.formatter, argparse.ArgumentDefaultsHelpFormatter): raise TypeError("Expected argument formatter ================================================================================ Example 673 ================================================================================ Target: uid] = info Prediction: uid] = info return info def _get_index(self, uid, action, success, idxs=_marker): """Returns the index of the instance in the pool, or None if it is not in the pool. """ info = self. ================================================================================ Example 674 ================================================================================ Target: ApplicationGatewaysOperations as OperationClass Prediction: ApplicationGatewaysOperations as OperationClass elif api_version == '2017-08-01': from .v2017_08_01.operations import ApplicationGatewaysOperations as OperationClass elif api_version == '2017-09-01': from . ================================================================================ Example 675 ================================================================================ Target: return proc Prediction: return proc def by_style(self, style_key, style_value): """Return a processor for a "complex" style value. Parameters ---------- style_key : str A style key. style_value : bool or str ================================================================================ Example 676 ================================================================================ Target: self.sessions.keys()): Prediction: self.sessions.values()): if sck.is_stopped(): self.sessions.pop(sck) self.sessions.pop(sck.socket) self.sessions.pop(sck.socket.family) self ================================================================================ Example 677 ================================================================================ Target: abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag('a'))) Prediction: abbreviation_tag = team('td[data-stat="school_abbreviation"]') return (name_tag, abbreviation_tag) def _get_rank(self, rank): """ Retrieve the rank's name and abbreviation. ================================================================================ Example 678 ================================================================================ Target: if direction == 'magic3': Prediction: if direction == 'magic3': return 'magic3' elif direction == 'magic2': return 'magic2' else: return 'magic3' def convert_meas(direction, Rec): """ converts measurments tables ================================================================================ Example 679 ================================================================================ Target: else: Prediction: return new # reproject if point is feasible if np.allclose(equalities.dot(p), self.problem.b, rtol=self.feasibility_tol, atol=self.feasibility_tol): new = self.reproject( ================================================================================ Example 680 ================================================================================ Target: list): Prediction: dict): clan = data for key, value in data.items(): if key == 'name': clan.name = value elif key == 'description': clan.description = value elif key == 'image': clan. ================================================================================ Example 681 ================================================================================ Target: df[choice_col].sum() Prediction: irel_df[choice_col].shape[0] if num_obs != num_choices: raise ValueError("Total number of observed choices does not match " "total number of observations. " "The number of observed choices is " "{} and ================================================================================ Example 682 ================================================================================ Target: 0]+1, Prediction: 0], top_left[1]:bottom_right[1], top_left[2]:bottom_right[2] + 1] return region_sum def get_region_from_x(self, x): """Get region around a location ================================================================================ Example 683 ================================================================================ Target: elif isinstance(self, TopicNode): Prediction: elif isinstance(self, ChannelNode.PresetNode): return format_presets.CHANNEL_THUMBNAIL_PRESET elif isinstance(self, ChannelNode.PresetNode.PresetNode): return format_presets.CHANNEL_THUMBNAIL ================================================================================ Example 684 ================================================================================ Target: '%s' doesn't exist.", export_type) Prediction: 文件 %s not found.", template_file) logging.warning("Template 文件 %s not found.", output_file) raise ValueError("Template 文件 %s not found.", template_file) def flatten_colors(colors): """Flatten a list of ================================================================================ Example 685 ================================================================================ Target: return lines Prediction: return lines def file_writelines(filename,lines): """Write a file and close it. Returns the file source using writelines().""" fobj = open(filename,'w'); fobj.writelines(lines) fobj.close() ================================================================================ Example 686 ================================================================================ Target: else: Prediction: return cls(**args) def _from_corpus(cls, corpus): """Initialize a Corpus object from a json dictionary.""" args = {} if 'corpora' in corpus: args['corpora'] = [ Corpus._from ================================================================================ Example 687 ================================================================================ Target: max_batch_size=max_batch_size or receive_client._prefetch, timeout=timeout) Prediction: timeout=timeout, max_batch_size=max_batch_size, debug=debug, **kwargs) def receive_messages_batch(source, auth=None, max_batch_size=None, timeout=0, debug=False, **kwargs): ================================================================================ Example 688 ================================================================================ Target: stop_id, lat=lat, lng=lng, name=name) Prediction: stop_id) stop.lat = lat stop.lng = lng stop.name = name return stop def AddStop(self, lat, lng, name, stop_id=None): """Add a stop to this schedule. ================================================================================ Example 689 ================================================================================ Target: print(rl) Prediction: print "Collecting word %s" % w.raw if rl.count > 0: yield rl else: break return [] def get_sentences(sent, stopwords): """ iterator for getting the sentences ================================================================================ Example 690 ================================================================================ Target: break_on_hyphens=False) Prediction: width=self.config_header_width, break_long_words=True) fp.write(text) def _AddFooter(self, fp): """Create a file footer in the config. Args: fp: int, a ================================================================================ Example 691 ================================================================================ Target: startswith('OLYMPUS'): Prediction: startswith('Olympus'): if note.values[0:7] == [78, 105, 107, 111, 110, 0, 1]: logger.debug("Looks like a type 1 Olympus MakerNote.") self.dump_ifd(note.field_offset ================================================================================ Example 692 ================================================================================ Target: self.__class__(explicit=tagging.get('explicit'), implicit=tagging.get('implicit')) Prediction: ia.copy(self) new_obj.tag = tagging return new_obj def _tag_explicit(self, tag): """ Tag an object with a specific tag number :param tag: A integer tag number. Only used when tagging ================================================================================ Example 693 ================================================================================ Target: = LoadedDrivers.getDefaultDriver() Prediction: idd = driver_list.get(name) if(driver idd is None): return redirectUnauthorized() return driver_status(driver idd) def driver_status(driver_id): # noqa: E501 """Retrieve the status of ================================================================================ Example 694 ================================================================================ Target: data) Prediction: data) def _get_callback(self, text, data=None): """ Returns a callback for the given `text` and `data`. If `data` is omitted, the given `text` will be used as `data`. In any case `data ================================================================================ Example 695 ================================================================================ Target: frame_info = inspect.getouterframes(inspect.currentframe())[1] Prediction: print(message) self.elapsed_time = time.time() - self.start_time self.start_time = time.time() if self.elapsed_time > 0: self.print_time() else: self. ================================================================================ Example 696 ================================================================================ Target: ret['result'] = False Prediction: ret['result'] = False ret['comment'] = 'Multiple identity pools found for {0}'.format(r['identity_pools']) return ret if not identity_pools: ret['result'] = False ret['comment'] = 'Identity pools ================================================================================ Example 697 ================================================================================ Target: fmt Prediction: fmt + " " + self.occur + " " + self.rng_children() class Choice(Node): """A choice node.""" def __init__(self, rng_children, rng_options, rng_occur, rng_text): ================================================================================ Example 698 ================================================================================ Target: if (score is None) and (default is not None): Prediction: if pipe is not None: pipe.zrem(self.key, self._pickle(member), score) return score def _pickle(self, member): """ Return a pickle of the member. """ return pickle. ================================================================================ Example 699 ================================================================================ Target: log['make_channel'] Prediction: logging.getLogger('channel') llog.setLevel(logging.DEBUG) llog.setLevel(logging.INFO) llog.setLevel(logging.WARNING) llog.setLevel(logging.ERROR) llog.setLevel(logging ================================================================================ Example 700 ================================================================================ Target: doctype=doc.doctype, Prediction: docfilehash=dochash, docfilehash_type=dochash_type, docfilehash_type_str=dochash_type_str, docfilehash_type_str_lower=dochash_type_str_lower, docfilehash ================================================================================ Example 701 ================================================================================ Target: return callback(evpn_activate, handler='get_config') Prediction: evpn_activate.find('.//*activate').set('operation', 'get') if kwargs.pop('callback', None): evpn_activate.find('.//*activate').set('operation', 'callback') return evpn_activate def evpn_ ================================================================================ Example 702 ================================================================================ Target: 5 Prediction: 1000 def calc_regenerated_by_user(self, lastvotetime): ''' Uses math formula to calculate the amount of steem power that would have been regenerated given a certain datetime object ''' delta = datetime.utcnow() - ================================================================================ Example 703 ================================================================================ Target: tuple[1]) + " " Prediction: tuple[1]) + "," + str(tuple[2]) + "," + str(tuple[3]) + "," + str(tuple[4]) + "," + str(tuple[5]) + "," + str(tuple[6]) + "," + str(tuple[7]) + "," + str(tuple ================================================================================ Example 704 ================================================================================ Target: for loggerName in logging.Logger.manager.loggerDict: Prediction: logging.getLogger('').propagate = False logging.getLogger('').propagate = False logging.getLogger('').propagate = False logging.getLogger('').propagate = False logging.getLogger('').propagate = False logging.get ================================================================================ Example 705 ================================================================================ Target: self.adjacency_method, Prediction: copy=copy, **kwds) return self.adjacency_matrix def compute_distance(self, dist_matrix, copy=False, **kwargs): """ This function will compute the distance matrix. In order to ================================================================================ Example 706 ================================================================================ Target: self.new2old) Prediction: self.modelstandardfunctions) return lines def doit(self): """Do the actual work of the model class.""" self.model = Model() self.model.load(self.modelfile) self.model.set_data(self.modelfile ================================================================================ Example 707 ================================================================================ Target: confirm=confirm) Prediction: confirm=confirm) def create_app_multi_region(regional_options, app_name, src_dir, publish=False, set_default=False, billTo=None, try_versions=None, try_update=True, confirm=True): ================================================================================ Example 708 ================================================================================ Target: return selected Prediction: print("\t{}: {}".format(offset, selected)) return selected def get_input(prompt, choices): """ Asks for a single choice out of multiple items. Given those items, and a prompt to ask the user with """ ================================================================================ Example 709 ================================================================================ Target: 'RABC': self.RABC Prediction: 'RABC': self.RABC, 'stock_vol': self.stock_vol[-1], } return re.format(self.stock_name, self.stock_no, self.stock_date, self.stock_price, self.stock_ ================================================================================ Example 710 ================================================================================ Target: tags Prediction: irc.parse_tags(tags) def get_tags(self): """*The list of tags associated with this taskpaper object* **Usage:** .. project and task objects can have associated tags. To get a list of tags assigned to an object use: ================================================================================ Example 711 ================================================================================ Target: for key, row in zip(column, self.rows): Prediction: for row in column: index[row[column]] = index.get(row[column], 0) + 1 return index def _get_column(self, column_or_label): """Return a column from a list of rows corresponding to each value. ================================================================================ Example 712 ================================================================================ Target: param import ParamConcatenation Prediction: import _utils from .. import _utils_helpers from .. import _utils_helpers_helpers from .. import _utils_helpers_helpers_helpers from .. import _utils_helpers_helpers_helpers_helpers from ================================================================================ Example 713 ================================================================================ Target: if ImageURL is not None or ImageURL != '': Prediction: if KakaoButtons is not None or KakaoButtons != '': req['buttons'] = KakaoButtons if AdsYN is not None or AdsYN != '': req['adsYN'] = AdsYN if UserID is ================================================================================ Example 714 ================================================================================ Target: if tdiff > timedelta(hours=2): Prediction: if isinstance(tdiff, timedelta): tdiff = tdiff.to_timedelta() return tdiff.to_timedelta() def timetest(tdiff): """ NOTE do NOT use "interval" or ticks are misaligned! ================================================================================ Example 715 ================================================================================ Target: *(-0.4*mag) Prediction: mag return Ftot/len(mags) def fluxfrac(*mags): """Returns fraction of total flux in first argument, assuming all are magnitudes. """ Ftot = 0 for mag in mags: Ftot += 10*mag ================================================================================ Example 716 ================================================================================ Target: () { Prediction: ~~ (e) { // Update the preview pane $preview.html(e.data); // Update the image $pimg.attr('src', e.data); // Update the crop box $boundx = e.x; $bound ================================================================================ Example 717 ================================================================================ Target: dataType == 'data': Prediction: dataType == 'integer': return combo.setCurrentIndex(combo.findText(value)) else: return combo.setCurrentIndex(combo.findText(value)) ================================================================================ Example 718 ================================================================================ Target: handler_class(mailhost='127.0.0.1', Prediction: ialkivi.EmailHandler(self.filename, when='midnight') handler.setLevel(level) elif handler_class == logging.handlers.RotatingFileHandler: handler = handler_class(self.filename, when='midnight') handler.set ================================================================================ Example 719 ================================================================================ Target: if 'token' not in refresh_data: Prediction: if refresh_data['error'] != 'OK': return False if refresh_data['token'] is None: return True return self._request_token_from_token(refresh_data['token']) def _request_token_from_token(self ================================================================================ Example 720 ================================================================================ Target: 'master' if master else 'slave', Prediction: irc_domain_type, 'name': domain, 'owner': self.owner, 'owner_email': self.owner_email, 'owner_name': self.owner_name, 'owner_url': self.owner_url, ' ================================================================================ Example 721 ================================================================================ Target: if in_place and api_object: Prediction: if in_place: api_object.inplace_reload() return api_object return wrapped ================================================================================ Example 722 ================================================================================ Target: 'app_id'] for app in data['applications']] + \ Prediction: 0] for app in data["applications"]] except requests.exceptions.RequestException: return [] def get_possible_app_ids_for_device(device_id): """ Returns all possible app ids for a given device id. """ try: ================================================================================ Example 723 ================================================================================ Target: message) Prediction: message, self.transport) self.transport.push_message(message) self.transport.start() def _initialize_messages_queues(self, chain_state: ChainState): """Initialize all the message queues with the transport. Note: ================================================================================ Example 724 ================================================================================ Target: raise ValidationError( Prediction: raise ValueError("keys not in data") def validate(self, *args, **kwargs): """Validate data received from the caller. This method is called by the `clean()` method of your event. """ for key in self.data.keys(): ================================================================================ Example 725 ================================================================================ Target: universal_worker, pool_args(func, sequence, args)) Prediction: func, sequence, **args) pool.close() pool.join() return result return simple_parallel def parallel_fn(f): """Simple wrapper function, returning a parallel version of the given function f. The function f must have one argument ================================================================================ Example 726 ================================================================================ Target: return True Prediction: gmail_quote[0].parent.remove(gmail_quote[0]) gmail_quote[0].parent.remove(gmail_quote[0]) gmail_quote[0].parent.remove(gmail_quote[0]) gmail_quote[0].parent.remove ================================================================================ Example 727 ================================================================================ Target: timeout: Prediction: ~~ timeout_string: raise Exception("Timeout check failed") else: break # If we are in the "execute-command-logfile" folder, we will check the log file if tmp_log: if os.path.exists(log_file ================================================================================ Example 728 ================================================================================ Target: parsed) Prediction: parsed) continue elif old_current_type == self.current_type: self.current_type = old_current_type self.list_delim_re.match(text, i) break elif old_current_type == self. ================================================================================ Example 729 ================================================================================ Target: if min_pt.shape != (space.ndim,): Prediction: if min_pt is None: min_pt = min_pt * 0.75 if max_pt is None: max_pt = max_pt * 0.25 if min_pt < max_pt: raise ValueError("min_pt and ================================================================================ Example 730 ================================================================================ Target: tf.logging.info("Wrote out %d references for this WET", num_refs_in_wet) Prediction: return num_refs, num_refs_in_wet def _make_example_from_record(wet_record): """Convert a WET record to an example.""" example = cc_utils.wet_example_from_record(wet_record ================================================================================ Example 731 ================================================================================ Target: _validate_table_name() Prediction: source = gspread.open(self.source) self.credentials = ServiceAccountCredentials.from_json_keyfile_name( self.credentials_json_keyfile_name, self.credentials_json_private_key_file_name) ================================================================================ Example 732 ================================================================================ Target: ) Prediction: ) host.act_depend_of_me_with_daddy.append( (service.uuid, ['d', 'x', 's', 'f'], '', True) ) host.act_depend_of_me_with_daddy_with ================================================================================ Example 733 ================================================================================ Target: hparams.batch_size = 4 Prediction: hparams.num_filters = 256 hparams.dropout_prob = 0.5 hparams.num_layers = 2 hparams.num_blocks = 2 hparams.num_heads = 8 hparams.dropout_prob = 0. ================================================================================ Example 734 ================================================================================ Target: not available" % name) Prediction: 不存在" % name) def get_backend(name): """Returns the backend by name or raises KeyError""" for backend in _BACKENDS: if backend.NAME == name: return backend raise KeyError("Backend %r 不 ================================================================================ Example 735 ================================================================================ Target: decode=False, delete=False) Prediction: ustrlen(key)) key_file = os.path.join(self.tempdir, key_file) key_file = os.path.join(self.tempdir, "encrypted_%s" % id_attr) key_file = os.path ================================================================================ Example 736 ================================================================================ Target: _saved Prediction: ### ================================================================================ Example 737 ================================================================================ Target: len(text)] Prediction: 0] non_code_blocks = [m for m in self.non_code_pattern.finditer(text)] # determine the non code blocks non_code_blocks_starts = [0] + [m.end() for m in non_code_blocks ================================================================================ Example 738 ================================================================================ Target: types.Message, types.MessageService, types.MessageEmpty)) Prediction: telethon.tl.custom.message.Message, telethon.tl.custom.message.Message.Message, telethon.tl.custom.message.Message.Message.Message, telethon.tl.custom.message.Message.Message.Message, tele ================================================================================ Example 739 ================================================================================ Target: fracarray.append(w+prev) Prediction: for i in range(len(weights)): if fracarray[i] < prev: prev = fracarray[i] fracarray.append(weights[i]) return min(fracarray) def get_weighted_random_index(self, ================================================================================ Example 740 ================================================================================ Target: else: Prediction: elif ident in PB_SPECIAL_HANDLING_UNKNOWN: return ["UnknownPB{0}".format(ident)] elif ident in PB_SPECIAL_HANDLING_UNKNOWN_UNKNOWN: return ["UnknownPB{0}".format(ident)] ================================================================================ Example 741 ================================================================================ Target: False Prediction: ### False return True def validate_ip_address(ip_address): """ Check if the supplied IP address is valid :param ip_address: The IP address :return: True if the IP address is valid, False if not """ ================================================================================ Example 742 ================================================================================ Target: 'format.input' Prediction: 'format.input' PARAM_FORMAT_VALUE = 'format.value' PARAM_FORMAT_VALUE_TYPE = 'format.value.type' PARAM_FORMAT_VALUE_TYPE_MAP = { 'int': 'int', 'float': 'float', ================================================================================ Example 743 ================================================================================ Target: if out == 'success': Prediction: out.run() return out def delete_service_by_name(name, restart=True): ''' Delete an existing service CLI Example: .. code-block:: bash salt '*' firewalld.delete_service my_service ================================================================================ Example 744 ================================================================================ Target: '/>\n', Prediction: ' \n', ' y0: NumEqual += 1 ================================================================================ Example 752 ================================================================================ Target: of %s", tweet_id) Prediction: ====> %s" % tweet_id) retweets = self.get_retweets(tweet_id) log.info("retweets ====> %s" % retweets) return retweets def get_retweets( ================================================================================ Example 753 ================================================================================ Target: != expected_size: Prediction: ia 64 bit: print(' => {0}'.format(file_size), end=' ', file=sys.stderr) else: print(' => {0}'.format(file_size), end=' ', file=sys.stderr) if expected_size != file ================================================================================ Example 754 ================================================================================ Target: 'GZIP_CONTENT_TYPES', Prediction: 'BAKERY_GZIP_WHITELIST', [ 'application/x-gzip', 'application/x-gzip-compressed', 'application/x-gzip-compressed-with-gzip', 'application/ ================================================================================ Example 755 ================================================================================ Target: indices[q < qsep] = False Prediction: constraints.append(indices & (q > qsep)) indices = np.where(indices) return funcs, constraints, indices def PorodGuinierMulti(q, A, *alphasRgs): """Empirical multi-part Porod- ================================================================================ Example 756 ================================================================================ Target: "simpleFaultGeometry" in node.tag Prediction: iaas_node.get_node_type() == 'simple_fault_geometry' trace = iaas_node.get_trace() return trace def node_to_simple_fault_geometry_node(node): """ Reads a simple fault ================================================================================ Example 757 ================================================================================ Target: setattr(cls, key, True) Prediction: if recurse: for key in cls.__dict__.keys(): if key.startswith(key + '_'): cls.__dict__[key] = cls._loadAddons(key) else: cls.__dict__[key] ================================================================================ Example 758 ================================================================================ Target: ]) Prediction: ]) def __build_duration_for_id(self, id): """Returns the total duration for a specific build""" return self.get_build_duration(id) def get_build_duration(self, id): """Returns the total build duration ================================================================================ Example 759 ================================================================================ Target: dtype = np.array(peek).dtype Prediction: if dtype is None: dtype = np.dtype(it.next()) else: dtype = np.dtype(it.next()) else: peek, it = iterpeek(it, sample) if dtype is None: ================================================================================ Example 760 ================================================================================ Target: if not email_dispatched: Prediction: return self.get_messages() def get_messages(self): """Returns all messages. Use in unit tests for example:: with mail.get_messages() as outbox: response = app.test_client.get("/email-sending-view/") ================================================================================ Example 761 ================================================================================ Target: 'pi_zoom'): Prediction: '_zoom_pinch_cb'): bd._zoom_pinch_cb(self, fitsimage, event) else: self.fv.zoom_pinch_cb(fitsimage, event) def zoom_pan_cb(self, fitsimage, event): ================================================================================ Example 762 ================================================================================ Target: message_fd = self.descriptors.message_to_fd[name] Prediction: # Message defined in another file # TODO: This is a hack to support the old behavior of # import_message_from_file. # See https://github.com/google/protobuf/issues/1265 # (https://code.google. ================================================================================ Example 763 ================================================================================ Target: if leftright == LEFT: Prediction: # if we are at the end of the chain, we are done if i == len(endpoints) - 1: break # if we are at the start of the chain, we are done elif i == 0: break # if we are at ================================================================================ Example 764 ================================================================================ Target: log.exception("Failed to parse JSON message %s", request_str) Prediction: pass def _read_message(self): """Read a message from the rfile.""" try: message = json.loads(self._rfile.readline()) except ValueError: return None return message def _write_ ================================================================================ Example 765 ================================================================================ Target: kh = opts.khmer_home Prediction: if len(fastq) == 0: sys.exit(not p.print_help()) if len(fastq) == 1: fastq = fastq[0] if len(fastq) == 1: fastq = fastq[0 ================================================================================ Example 766 ================================================================================ Target: name, self.experiment_name Prediction: name, new_name, ) self.channel_manager.rename_channel(name, new_name) def delete_channel(self, name): '''Deletes a channel. Parameters ---------- name: str name ================================================================================ Example 767 ================================================================================ Target: self.autocomplete() Prediction: # If we have a settings file, parse it. if settings.settings_path: settings_path = os.path.abspath(settings.settings_path) settings_path = os.path.normpath(settings_path) settings_path = ================================================================================ Example 768 ================================================================================ Target: dropIn=False,role=role).exclude( Prediction: cancelled=False,role=role).count() return count def numRegisteredForEvent(self, event): ''' Accepts an Event object and returns the number of registrations of that event. ''' return self.eventregistration_set.filter ================================================================================ Example 769 ================================================================================ Target: return name.strip() Prediction: return name def get_version(self): """ Get the version for this extension, can be an empty string """ version = self._info['version'] if version.strip() == '': version = self._info['hduname'] ================================================================================ Example 770 ================================================================================ Target: ), Prediction: ) ) ) def dprint_list(name, val): """Debug print name and val.""" from pprint import pformat print( '% 5s: %s' % ( name, '\n '.join ================================================================================ Example 771 ================================================================================ Target: output Prediction: #endregion #region -- Convolutions #endregion #region -- Convolution #endregion #region -- Convolution #endregion #region -- Convolution #endregion #region -- Convolution #endregion #region ================================================================================ Example 772 ================================================================================ Target: raise ValueError("optimization portion of filename does not start " Prediction: raise ValueError('expected optimization to start with ' '``_OPT``') pycache = optimization[1] else: raise ValueError('expected 2 or 3 dots in ' '{!r}'.format(pycache_filename)) return py ================================================================================ Example 773 ================================================================================ Target: return self._datatable_options Prediction: # Convert the columns to a list of tuples. columns_list = [tuple(column) for column in columns] # Convert the columns_list to a list of tuples. columns_list_list = [tuple(column) for column in columns_list] ================================================================================ Example 774 ================================================================================ Target: 0.0 Prediction: ustask.get_delta() except: delta = 0 deferredFns = [] deferredFns.append(deferredFns.pop()) deferredFns.append(deferredFns.pop()) deferredFns.append ================================================================================ Example 775 ================================================================================ Target: except AttributeError: Prediction: except AttributeError: return False def safe_getattr(obj, name): """Attempt to getattr but catch AttributeErrors.""" try: getattr(obj, name) return True except AttributeError: return False def safe ================================================================================ Example 776 ================================================================================ Target: if validation_set == 'auto': Prediction: validation_dataset = _extensions._drawing_classifier_prepare_data( validation_set, feature) else: validation_dataset = _extensions._drawing_classifier_prepare_data( validation_set, feature) if validation_dataset is ================================================================================ Example 777 ================================================================================ Target: _raise_i2c_status_code_error_if_failure(status) Prediction: if status != 0: raise I2CError(status) return True def i2c_master_read(self, i2c_address, data, flags=I2C_NO_FLAGS): """Make an I2C read access. ================================================================================ Example 778 ================================================================================ Target: Client): Prediction: irc.Client): self.create_task(self._async_connect) def stop(self) -> None: """ Stop monitoring the base unit. """ self._shutdown = True # Stop listening (if server) / Close connection (if ================================================================================ Example 779 ================================================================================ Target: for currentFile in sorted( files ): Prediction: files += glob.glob( os.path.join( sourceDir, "src", "*.cpp" ) ) files += glob.glob( os.path.join( sourceDir, "src", "*.cc" ) ) files += glob.glob( os.path.join ================================================================================ Example 780 ================================================================================ Target: sm) Prediction: sm['BLOCK']) return C def load_final(self, C, streams): """Load the final values for parameters and Wilson coefficients from one or several files. `streams` should be a tuple of file-like objects strings.""" d = {} ================================================================================ Example 781 ================================================================================ Target: raise _BGPInvalidDataException(err) Prediction: raise BGP4Error(err) if length < _BGP_CAPABILITY_MAX_SIZE: err = " ({}".format(length) + " is < _BGP_CAPABILITY_MAX_SIZE " err += "({})).".format(_B ================================================================================ Example 782 ================================================================================ Target: return df_conf, populations, ser_correct, fraction_correct Prediction: ser_correct = pd.Series(data=ser_correct, index=all_cols) populations['ser_correct'] = ser_correct return populations def _get_correct_series(self, y_info): ''' Get correct series ''' a = ================================================================================ Example 783 ================================================================================ Target: self.__dict__.items(): Prediction: ustr.items(): if key in self.embeds: data[key] = value return data class Webhook(object): """ webhook data class :param name: name of webhook :param description: description of webhook ================================================================================ Example 784 ================================================================================ Target: process_cores=process_cores, debug=debug) Prediction: process_cores=process_cores, debug=debug) def lag_calc_with_template(self, stream, pre_processed, shift_len=0.2, min_cc=0.4, horizontal_chans=['E', 'N', '1 ================================================================================ Example 785 ================================================================================ Target: padded: Prediction: total: data += bytearray(struct.pack(' self._gbest.pbest.fitness): self._g ================================================================================ Example 788 ================================================================================ Target: res = requests.post(ndex_service_url, json=params) Prediction: res = requests.post(ndex_service_url, params, headers=headers) if is_json: return json.dumps(res.json()) else: return res.text def get_ndex_service_url(ndex_ ================================================================================ Example 789 ================================================================================ Target: return Prediction: return # Save the wisdom file with open(wisdomfile, 'w') as f: f.write('\n'.join(wisdom)) def get_wisdom(wisdomfile): """ Get the wisdom file from ================================================================================ Example 790 ================================================================================ Target: content_settings, metadata, validate_content, progress_callback, Prediction: urn=self.urn, metadata=metadata, content_settings=content_settings, validate_content=validate_content, progress_callback=progress_callback, max_connections=max_connections, timeout=timeout) def create_file_from_stream(self, share ================================================================================ Example 791 ================================================================================ Target: self.reward_line = reward_lines[0] Prediction: reward_lines.set_xlabel('Time (hours)') reward_lines.set_ylabel('Earnings ($)') reward_lines.grid(True) # State and action plots. state_lines = state_axis.plot( ================================================================================ Example 792 ================================================================================ Target: p[0] = ContextPath(p[1]) Prediction: p[0] = p[1][0] + p[1][1] return p def p_ctx_coords(self, p): """ ctx_coords : ctx_path, ctx_coords""" if len(p[1]) == ================================================================================ Example 793 ================================================================================ Target: display_name = event_values.get('display_name', 'N/A') Prediction: display_name = event_values.get('display_name', 'N/A') event_identifier = event_values.get('uuid', 'N/A') parser_chain = event_values.get('parser', 'N/A') error_message = ================================================================================ Example 794 ================================================================================ Target: else: Prediction: download_file(file_path, resource) return files def get_metadata(self, dataset_identifier, content_type="json"): ''' Get metadata associated with a dataset. ''' metadata = self.get_metadata_from_dataset( ================================================================================ Example 795 ================================================================================ Target: } Prediction: } headers.update(self.headers) headers.update(self.headers_for_logstore) headers.update(self.headers_for_consumer_group) headers.update(self.headers_for_project) headers.update(self ================================================================================ Example 796 ================================================================================ Target: return real_path Prediction: return real_path def get_container_path(self, path): """ provide absolute path within the container :param path: path with container :return: str """ if path.startswith("/"): path = path[ ================================================================================ Example 797 ================================================================================ Target: return default Prediction: return default else: return self.data.get(identifier) def get_by_name(self, name): """Get a layer by name. Get a particular layer in the Overlay. Args: name: Name of the layer to ================================================================================ Example 798 ================================================================================ Target: -----') Prediction: ') print('') print('Uploading images') print('--------') print('') print('') print('') print('') print('') print('') print('') print('') print(' ================================================================================ Example 799 ================================================================================ Target: ids.add(config['sub_array_id']) Prediction: if config['scheduling_block'] == 'scheduling_block_1': ids.add(key) return ids def get_sub_array_ids_by_name(name): """Return list of sub-array Id's currently known to SDP""" ================================================================================ Example 800 ================================================================================ Target: else: Prediction: else: raise ValueError("Invalid file mode spec: %s" % spec) if fd is None: fd = os.open(path, new_mode) else: fd = os.open(path, new_mode, fd) fd ================================================================================ Example 801 ================================================================================ Target: startdate Prediction: calc_start.startdate calc_end = calc_start.enddate else: calc_start = start calc_end = end calc_intervals.add(calc_start, calc_end) calc_intervals.add( ================================================================================ Example 802 ================================================================================ Target: else: Prediction: elif closest_samp_num and (closest_samp_num == closest_samp_num_next and smallest_samp_diff_next < smallest_samp_diff): # The current reference sample is the closest to the # next ================================================================================ Example 803 ================================================================================ Target: url = '/scans/%s/stop' % self.scan_id Prediction: timeout = self.timeout # # Stop the scan # try: self.scan_id = self.scan_id.stop() except Exception as e: # # If the timeout is exceeded, an exception is raised ================================================================================ Example 804 ================================================================================ Target: components = xdot_parser.parse_xdot_data( node._ldraw_ ) Prediction: return canvas def _component_default(self): """ Returns the default component for the graph. """ return self.graph.default_component() def _component_add(self, component): """ Adds a component to the graph. """ ================================================================================ Example 805 ================================================================================ Target: return False, err_msg Prediction: raise Error(err_msg) # Enqueue the message if rids is not None: for remote in rids: if remote not in self.outBoxes: self.outBoxes[remote] = self.outBoxes[remote] + ================================================================================ Example 806 ================================================================================ Target: xyref = sorted(xyref) # sort by x, then y Prediction: xi = xyref[idx][0] yi = xyref[idx][1] # Compute the bilinear interpolation result = np.zeros((4, 4, 4)) result[0, :, :] = xyref[0][0 ================================================================================ Example 807 ================================================================================ Target: plug_name] = self._make_plug_descriptor(plug_type) Prediction: plug_type] = plug_value self._plug_descriptors_by_name[plug_name] = plug_value def get_plug_name(self, plug_type): """Returns the name of the plug for the given plug type. This is ================================================================================ Example 808 ================================================================================ Target: value = 0 Prediction: return None return value def delivered_image_width(self): """ :return: The image width of the data component. """ try: if self._part: value = self._part.delivered_image_width ================================================================================ Example 809 ================================================================================ Target: cls.TTY_ENV_TMPL.format(fd_id), '0')) for fd_id in STDIO_DESCRIPTORS Prediction: env.get('STDIN', ''), '0')) for env in env.items() ) def isatty_from_env(cls, env): """Determine whether remote file descriptors are tty capable using std nailgunned env variables. :param dict ================================================================================ Example 810 ================================================================================ Target: reply_to_message_id, Prediction: reply_to_message_id, reply_markup=reply_markup, **kwargs ) ) # send message try: message = bot.send_message(chat_id, text, parse_mode=parse_mode, disable ================================================================================ Example 811 ================================================================================ Target: ).strip() Prediction: ) # generate the JS function js_function = self.js_function_generator(template_function) # generate the JS function code js_function_code = self.js_function_generator_code(js_function) # generate the JS function ================================================================================ Example 812 ================================================================================ Target: ]) Prediction: and line.endswith('...') ]) def _safe_output_with_args(line): ''' Looks for rabbitmqctl warning, or general formatting, strings that aren't intended to be parsed as output. Returns a boolean whether the line ================================================================================ Example 813 ================================================================================ Target: data_2) Prediction: ., data_2, threshold) return self._matchBlocks(blocked_pairs, generator) def _matchBlocks(self, blocked_pairs, generator): """ Match blocks of records in the data_1 and data_2 dictionaries. Arguments: ================================================================================ Example 814 ================================================================================ Target: srs) Prediction: srs) service.srs.add(srs) service.srs.add(srs) service.srs.add(srs) service.srs.add(srs) service.srs.add(srs) ================================================================================ Example 815 ================================================================================ Target: '//xhtml:body', namespaces=HTML_DOCUMENT_NAMESPACES) Prediction: '//body[@id="book-body"]/div[1]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2 ================================================================================ Example 816 ================================================================================ Target: SMA_INI_FILE) Prediction: CONFIG_FILE) parser.add_argument('--log-dir', default=LOG_DIR) parser.add_argument('--log-file', default=LOG_FILE) parser.add_argument('--log-level', default=LOG_LEVEL) parser ================================================================================ Example 817 ================================================================================ Target: else: Prediction: else: return VirtualEnv() def get_project_venv_dir(): """ Get the project-level virtualenv directory. :return: ``str`` """ venv_dir = os.path.join(os.path.dirname ================================================================================ Example 818 ================================================================================ Target: self._pages[uri] = Page(uri=uri, path=path) Prediction: self._pages[uri] = Page(uri, path) def _get_page(self, uri): """Get page content.""" return self._pages[uri] def _get_page_by_uri(self, uri): """Get page content ================================================================================ Example 819 ================================================================================ Target: try: Prediction: raise ValueError("Invalid literal text: {}".format(literal_text)) return bits def _get_parts_of_format_spec(resolved_string, literal_texts, format_specs): """ Inner function of reverse_format, returns the resolved ================================================================================ Example 820 ================================================================================ Target: return host_names Prediction: return host_names def get_urls_from_hostnames(hostnames): ''' Takes a StringCounter of normalized hostnames and parses their URLs N.B. this assumes that absolute URLs will begin with http:// in order to accurately ================================================================================ Example 821 ================================================================================ Target: else: Prediction: else: return False def node_less(node1, node2): '''node_less High-level api: Evaluate whether two nodes are less than or equal to each other. Parameters ---------- node1 : `Element` A ================================================================================ Example 822 ================================================================================ Target: return str(EnterpriseCustomerCatalog.objects.get(pk=catalog_id).enterprise_customer.uuid) Prediction: enterprise_customer_id = enterprise_customer_catalog_id.get(catalog_id) except: return None return enterprise_customer_id def get_enterprise_customer_from_catalog_id_and_customer_id(catalog_id, ================================================================================ Example 823 ================================================================================ Target: terms.operand, builder)], Prediction: terms.lhs, builder), build_node(table, terms.rhs, builder)], return_type ) if isinstance(terms, CmpOp): return builder.make_function( cmp_ops[terms.op], ================================================================================ Example 824 ================================================================================ Target: stderr=workunit.output('stderr')) Prediction: stderr=workunit.output('stderr'), suppress=self.get_options().suppress) return 0 def checkstyle_py(self, interpreter, sources): """Iterate over sources and run checker on each file. Files can be ================================================================================ Example 825 ================================================================================ Target: temp_key.update(ast.literal_eval(key)) Prediction: key = key.get('data', {}) # Allow key to be either a string describing a dict or a dict. elif type(key) == dict: key = key.get('data', {}) # Allow key to be either a string describing a dict or ================================================================================ Example 826 ================================================================================ Target: root_dir) Prediction: root_dir) self.logger.info(" Creating data directory %s", data_dir) if not osp.exists(data_dir): os.makedirs(data_dir) self.logger.info(" Creating project directory %s", project ================================================================================ Example 827 ================================================================================ Target: if key_node.value == attribute: Prediction: if key_node.name == attribute: key_node.name = new_name break else: raise AttributeError("Attribute '%s' not found in %s" % ( attribute, self.yaml_node.value)) def get_mapping ================================================================================ Example 828 ================================================================================ Target: return 'yum' Prediction: return 'rpm' elif any(['fedora' in distro, 'suse' in distro]) is True: return 'dnf' elif any(['arch' in distro, 'gentoo' in distro]) is True: return 'pkg' ================================================================================ Example 829 ================================================================================ Target: processed_block = self.__des_crypt(block, crypt_type) Prediction: processed_block = self.__des_crypt(block, crypt_type) result.append(processed_block) i += 8 return result def __String_to_BitList(self, data): """Convert a string to a list of bits""" ================================================================================ Example 830 ================================================================================ Target: = None Prediction: ia = kwargs.get('author_name', '') author_name_per = kwargs.get('author_name_per', 0) author_name_per = kwargs.get('author_name_per', 0) author_name_per = kwargs ================================================================================ Example 831 ================================================================================ Target: self.get_name(name_case), Prediction: dataset, cols_defs=cols_defs, ) def to_bigquery_ddl(self, name_case=DdlParseBase.NAME_CASE.original): """ Generate BigQuery CREATE TABLE statements :param name_case ================================================================================ Example 832 ================================================================================ Target: main(argv) Prediction: xt.gpp(argv) def main(): """Main function for running the previewing command.""" parser = argparse.ArgumentParser(description='Run the previewing command') parser.add_argument('-i', '--input', type=str, help='Input ================================================================================ Example 833 ================================================================================ Target: if isinstance(secret, six.text_type) else Prediction: if secret is not None else None ) def _find_passwords(self, service, username): """Find passwords for the service """ items = self._find_passwords_for_service(service, username) if not items: ================================================================================ Example 834 ================================================================================ Target: id_ambiente Prediction: id_ambiente healthcheck_map['match_list'] = match_list healthcheck_map['expect_string'] = expect_string healthcheck_map['healthcheck_expect'] = healthcheck_map return healthcheck_map def add_health ================================================================================ Example 835 ================================================================================ Target: idx in range(n_eps): Prediction: ith_exp in expparams: risk[ith_exp] = np.zeros(n_eps) return risk # for models whose outcome number changes with experiment, we # take the easy way out and for-loop over experiments n_eps = ================================================================================ Example 836 ================================================================================ Target: else: Prediction: search_start_idx = idx else: # Encoding same as R out_bytes.append(chr(length_value)) out_bytes.append(in_bytes[search_start_idx:idx]) search_start_idx = idx + ================================================================================ Example 837 ================================================================================ Target: return Prediction: return self.client.disconnect() def get_device_info(self): """Get device information """ if self.client is None: return self.client.get_device_info() def get_device_info_ ================================================================================ Example 838 ================================================================================ Target: self._auth.options.headers.update({'Cookie': 'SID="%s"' % self._SID}) Prediction: self._search.set_options(headers={'Cookie': 'WOS_SID="%s"' % self._SID}) self._search.set_options(headers={'Cookie': 'WOS_WOS_SID="%s"' % self._SID}) self._ ================================================================================ Example 839 ================================================================================ Target: for addr in path] for path in paths) Prediction: for addr in paths if addr not in self._bb_by_addr]) def all_simple_bb_paths_with_predecessors(self, start_address, end_address): """Return a list of path between start and end address. """ bb ================================================================================ Example 840 ================================================================================ Target: if 'disqus_identifier' in self.options: Prediction: return self.config.get('disqus_identifier') def get_disqus_url(self): """Validate and returns disqus_url option value. :returns: disqus_url config value. :rtype: str ================================================================================ Example 841 ================================================================================ Target: 1 Prediction: 1 lento3 = pos_a[0] - pos_b[0] + 1 return strd + lento5 + lento3 def _position_in_feature(pos_a, pos_b): """return distance to 3' and 5' ================================================================================ Example 842 ================================================================================ Target: ((bb_top, bb_left), (bb_bottom, bb_right)) Prediction: ia.bbox(bb_top, bb_left, bb_bottom, bb_right) def get_bbox(self): """Returns ((top, left), (bottom, right)) of bounding box A bounding box is the smallest rectangle that contains all selections. ================================================================================ Example 843 ================================================================================ Target: table Prediction: # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- ================================================================================ Example 844 ================================================================================ Target: complete_options = " ".join(complete_arguments) Prediction: complete_options = complete_arguments if not use_defaults: complete_options += ' -o default' if not shell: shell = 'bash' if not shell.lower().startswith('tcsh'): shell = 'tcsh' ================================================================================ Example 845 ================================================================================ Target: 1) Prediction: ireplace=separator, nullable_idx=nullable_idx) if len(pair) == 1: return pair[0] else: return [pair[0]] def split_list(list_string, separator, nullable_idx=1): ================================================================================ Example 846 ================================================================================ Target: pipe.returncode, output.read() Prediction: irec, output.read() def run_command_with_env(cmd, env=None, max_timeout=None): """ Run command and return its return status code and its output """ arglist = cmd.split() output = os. ================================================================================ Example 847 ================================================================================ Target: return fig Prediction: return fig def _finalise_figure(fig, **kwargs): """ Finalise the figure and return the figure. """ fig.set_size_inches(fig.dpi_scale_factor * kwargs.get('figsize', (10 ================================================================================ Example 848 ================================================================================ Target: exists(self.paths["readme"]): Prediction: exists(self.report["roles"][role]["state"]) and \ os.path.exists(self.report["roles"][role]["state"] + ".json"): self.report["roles"][role]["state"] = "ok" ================================================================================ Example 849 ================================================================================ Target: event_abi=event_abi, Prediction: token_network_address, channel_identifier, event_name, event_abi, from_block, to_block ) return event_filter_params def get_filter_args_for_specific_event_from_channel_and_block( token_ ================================================================================ Example 850 ================================================================================ Target: updateTime Prediction: updateTime v.updateTimeMask = _v.updateTimeMask v.updateTimeMask = _v.updateTimeMask v.updateTime = _v.updateTime v.updateTimeMask = _v.updateTimeMask v.updateTimeMask = ================================================================================ Example 851 ================================================================================ Target: assert existing_object.name == params[0] Prediction: retval = existing_object return retval elif version == 3: input_params = summaryLine.split() if len(input_params) != 25: print input_params raise TypeError('Expected 25 columns, {0} given'.format( ================================================================================ Example 852 ================================================================================ Target: if type(c) in [list,tuple]: Prediction: if m is None: m = c if y is None: y = c if k is None: k = c return cmyk_to_cmy(c, m, y, k) def cmyk_to_ ================================================================================ Example 853 ================================================================================ Target: ) Prediction: attrs=attrs, **kwargs ) except Exception as e: raise Exception("Error creating table: %s" % e) return ret def _parse_global_index(self, gindex, attrs): """ Parse a global index """ ================================================================================ Example 854 ================================================================================ Target: start_target = start Prediction: start_target = start if end is not None: end_inf = False if end is not None: end_target = pytz.UTC.localize(pd.Timestamp.max) end_inf = True else: end ================================================================================ Example 855 ================================================================================ Target: if bay_number: Prediction: if bay_number is not None: uri += "/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/{}/ ================================================================================ Example 856 ================================================================================ Target: my_dict Prediction: my_dict def fetch_config_from_file(filename): """Fetch the Configuration schema information Finds the schema file, loads the file and reads the JSON, then converts to a dictionary that is returned """ # This trick gets the directory of *this ================================================================================ Example 857 ================================================================================ Target: = ["gurobi", "cplex"] Prediction: ia_order = ["glpk", "cplex", "gurobi"] if mip: mip_order.append("mip") if qp: qp_order.append("qp") if mip and qp: qp_ ================================================================================ Example 858 ================================================================================ Target: address Prediction: ustr(address) return self.client.post( '/v1/servers/{}/storage/attach', body=body, headers=self.headers, ) def detach_storage(self, server, storage, storage_type, address): ================================================================================ Example 859 ================================================================================ Target: continue Prediction: continue funcs.append(item) return funcs def get_workflow_info_by_name(func_list, name): """Return function info, go through lists recursively.""" funcs = [] for item in func_list: ================================================================================ Example 860 ================================================================================ Target: if "error" in resp: Prediction: if resp.status_code != 200: raise ValueError("Registration failed with status code %d" % resp.status_code) return resp.json() def unregister(self): """Unregisters the current user from the database.""" if self. ================================================================================ Example 861 ================================================================================ Target: return self._probs_i1d(gmvs_curve), numpy.zeros_like(gmvs_curve), idxs Prediction: return gmvs_curve, idxs > self.imls[0] def _get_interpolated_probabilities(self, gmvs): """ :param gmvs: array of intensity measure levels :returns: (inter ================================================================================ Example 862 ================================================================================ Target: "outline" : self._outline Prediction: "isMap" : self._isMap, "isFeature" : self._isFeature, "isPolygon" : self._isPolygon, "isLineString" : self._isLineString, "isMultiPolygon" : self._isMulti ================================================================================ Example 863 ================================================================================ Target: strip().strip("'") for line in fh if \ Prediction: strip() for line in fh] except ValueError: print('Unable to open version file: %s' % verfile) sys.exit(1) return version def main(): '''Main function''' print('\n\n\n ================================================================================ Example 864 ================================================================================ Target: qq.com/cgi-bin/user/tag/get", Prediction: qq.com/cgi-bin/user/get_users_by_tag", data={"tag_id": tag_id, "next_open_id": next_open_id}, headers={"Authorization": "Bearer {}".format(self.get_access ================================================================================ Example 865 ================================================================================ Target: copy.deepcopy(self._raw_data) Prediction: self._raw_data def _parse_json_file(self, file_path): """Process Json file data :@param file_path :@type file_path: string :@throws IOError """ if file_path == '' ================================================================================ Example 866 ================================================================================ Target: arg = bytes2str(arg) Prediction: arg = str(arg) else: arg = pformat_xml(arg) elif isinstance(arg, int): arg = str(arg) elif isinstance(arg, float): arg = str(arg) elif isinstance(arg, bool ================================================================================ Example 867 ================================================================================ Target: record Prediction: irecords logging.info('Applying _name_include generator: ' 'ignoring any sequences with names that do not match ' + filter_regex + '.') yield irecords def name_exclude(records, filter_regex): ================================================================================ Example 868 ================================================================================ Target: cls.DoesNotExist: Prediction: ial_model.DoesNotExist: return cls.objects.create(*args, **kwargs), True class UserProfile(User): user = models.OneToOneField(User, on_delete=models.CASCADE) is_staff = models. ================================================================================ Example 869 ================================================================================ Target: -p), uplaces) * 10**p Prediction: p), uplaces) * 10**p if use_exponent: return '%g' % (rdh + rdl) return '%g' % (rdh + rdl) def repvals(self, method): """Return (main, dhigh ================================================================================ Example 870 ================================================================================ Target: += [row] Prediction: iare = [row[0], row[1], row[2]] table.append(row[3]) return table def get_table_from_csv(filename='ssg_report_aarons_returns.csv', delimiter=',', dos=False ================================================================================ Example 871 ================================================================================ Target: mechanism in actual_mechanisms} Prediction: mechanism in actual_mechanisms} return { 'actual_causes': actual_causes, 'actual_effects': actual_effects, 'actual_mechanisms': actual_mechanisms, 'next_state': next_state, ================================================================================ Example 872 ================================================================================ Target: dirname, sub_dir) Prediction: dirname, sub_dir) if not os.path.exists(submission_path): continue submission_file = open(submission_path, 'rb') submissions = [] for line in submission_file: line = line.strip() ================================================================================ Example 873 ================================================================================ Target: is None: Prediction: ia_string: if type_string is None: type_string = get_type_string(data) if type_string is None: raise ValueError("type_string must be set") if type_string == 'string_array': if ================================================================================ Example 874 ================================================================================ Target: resource = cls.post( Prediction: return cls.calculate(order_id, body) @staticmethod def calculate_refund(order_id, shipping=None, refund_line_items=None): """ Calculates refund transactions based on line items and shipping. When you ================================================================================ Example 875 ================================================================================ Target: out[n] = ynnm(n, m) Prediction: for i in range(n): tmp1 = np.exp(-(n-i)*(n-i)*L/2.0) tmp2 = np.exp(-(n-i)*(n-i)*L/2.0) tmp3 = np.exp ================================================================================ Example 876 ================================================================================ Target: current_key_index = i Prediction: uid_strings_fp.append(key['uid']) uid_string_fp2key[key['uid']] = key['key_id'] if uid_strings_fp: print("UID strings: %s" % uid_strings_fp) print ================================================================================ Example 877 ================================================================================ Target: 'code': code, Prediction: 'code': code, 'opts': opts, 'params': params }) return self.session.run(rqst) def get_completions(self, code: str, opts: dict = None) -> Iterable[str]: ''' ================================================================================ Example 878 ================================================================================ Target: dst) Prediction: dst) except OSError: pass def _get_file_contents(src, dst): """ Read the contents of a file (in an atomic fashion when possible). :param src: The pathname of the source file (a string). ================================================================================ Example 879 ================================================================================ Target: x = self.sum(axis=1) * 0.5 Prediction: else: return mono(self) def mono_sum(self, other): """ Return the sum of the channels of this instance and the other instance. If the instance is already mono, this is a no-op. """ if self. ================================================================================ Example 880 ================================================================================ Target: try: Prediction: if k in old._handlers: old._handlers[k]() #: Rerun any write expressions which should trigger #: any dependent reads for k in engine._handlers.keys(): if k in new._handlers: new._hand ================================================================================ Example 881 ================================================================================ Target: constraints=''), Prediction: constraints=''), spOverlapThreshold=dict( description="""The threshold for the overlap between the active output coincidences and the input. The overlap amounts for each coincidence are sorted from highest to lowest. """, accessMode='Read', data ================================================================================ Example 882 ================================================================================ Target: if side_by_side: Prediction: ax = fig.add_subplot(1, 1, 1) if fignum is None: fignum = 1.0 if colors is None: colors = ['#f00'] if side_by_side: ax.set ================================================================================ Example 883 ================================================================================ Target: resp.raise_if_err() Prediction: if resp.status_code == 200: ret = resp.content return ret def get_lun_info(self, lun_id): """ get the info of the LUN :param lun_id: the LUN id : ================================================================================ Example 884 ================================================================================ Target: None: Prediction: ###: varstring = '{}{}'.format(varstring, properties) self.varstring = varstring self.index = index return varstring def get_varstring(self): """ Get the variable string for the given *sort* ================================================================================ Example 885 ================================================================================ Target: yield obj Prediction: yield name def _iter_module_subclasses(package, module_name, base_cls): """inspect all modules in this directory for subclasses of inherit from ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/ ================================================================================ Example 886 ================================================================================ Target: else: Prediction: if kwargs.pop('normed',False): kwargs['d3']= 'Enorm' if kwargs.pop('normed',False): kwargs['d4']= 'Enorm' if kwargs.pop('normed',False): ================================================================================ Example 887 ================================================================================ Target: self.market_definition.get('bspReconciled'), Prediction: self.market_definition.get('bspReconciled'), 'bspDelayed': self.market_definition.get('bspDelayed'), 'bspDelayedBy': self.market_definition.get('bspDelayedBy'), ================================================================================ Example 888 ================================================================================ Target: if fieldlist: Prediction: if fieldlist: for field in fieldlist: if field.creation_counter == field.field_count: return field field_order[field.creation_counter] = field.field_name # if fields were specified, but not in the order specified ================================================================================ Example 889 ================================================================================ Target: "Received deep context for unknown fields: %r (known=%r)" % ( Prediction: "Duplicate declaration keys: %s" % ", ".join(extra_context_keys)) self.declarations = values self.contexts = dict(zip(self.contexts, values)) def split(self, key): """Split a declaration key ================================================================================ Example 890 ================================================================================ Target: != bytes: Prediction: ia str: value = value.decode('utf-8') else: value = value.encode('utf-8') return value def _send_bytes(self,value): """ Convert a single bytes object to a string. """ ================================================================================ Example 891 ================================================================================ Target: notify(CacheObjectCreatedEvent(cached_item, self)) Prediction: self.set(CachableItem, cached_item) self.mapper.save(cached_item) self.session.flush() return cached_item return _cachedItem def get(self, CachableItem): """Returns cached ================================================================================ Example 892 ================================================================================ Target: except ValueError: Prediction: except IndexError: continue if pkgname not in locked_pkgs: locked_pkgs.append(pkgname) return locked_pkgs def _lockcmd(subcmd, pkgname=None, **kwargs): ''' Helper function ================================================================================ Example 893 ================================================================================ Target: item = csvsource.items().next() Prediction: return csvsource.first() except: return None class CSVSource(object): """A CSV source that can be used to read a CSV file""" def __init__(self, source, factory, key): self.source = source self. ================================================================================ Example 894 ================================================================================ Target: pass Prediction: pass class _LoggingHandler(logging.Handler): ''' Handler that logs to a file. ''' def emit(self, record): ''' Write a log record to the file. ''' with open(self._file, 'a') as f: f ================================================================================ Example 895 ================================================================================ Target: return df Prediction: return df def _get_time_series_data(self, name, column): """ Get time series data from filtered table data. Parameters ---------- name : str Component name. column : str Component field with timevarying data. ================================================================================ Example 896 ================================================================================ Target: config Prediction: irc_config.get_config(config) def get_collector_settings(self): """ Returns the collector settings """ config = super(SoftInterruptCollector, self).get_collector_settings() config.update({ ' ================================================================================ Example 897 ================================================================================ Target: sub_len = rec_headers.total_len Prediction: if content_type: content_type = content_type.split(';')[0] if length: length = int(length) if uri: uri = uri.split('?')[0] if uri: uri = uri ================================================================================ Example 898 ================================================================================ Target: if node.token != 'BOUNDLIST': Prediction: if node.is_bound(): return cls.make_node(SymbolBOUNDLIST(), *args) if node.is_bound_list(): return cls.make_node(SymbolBOUNDLIST(), *args) if node.is_bound_ ================================================================================ Example 899 ================================================================================ Target: abs(startVisibleCol - currentCol) > self._MAX_SIZE: Prediction: abs(startVisibleCol - currentVisibleCol) > self._MAX_SIZE: return cursors.append((startLine, startVisibleCol)) if self._end is not None: endLine, endVisibleCol = self._end if abs(endLine - ================================================================================ Example 900 ================================================================================ Target: vn = widgets.Text(value=self.description, description=self.name, disabled=True) Prediction: import pandas as pd from IPython.display import display from IPython.display import HTML if duration is None: duration = period # Start data fetch if duration is not None: start_data_fetch(duration) # ================================================================================ Example 901 ================================================================================ Target: for _ in range(1000): Prediction: env.set_command(command) env.set_command_timeout(command) env.set_command_timeout_interval(command) env.set_command_timeout_interval_multiplier(command) env.set_command_timeout_interval ================================================================================ Example 902 ================================================================================ Target: not in volumes: Prediction: ~~ volume_id: fixed_issues.append(issue) return fixed_issues def process_fixed_issues_for_volume(self, volume, volume_audit_issue): """Provided a list of volumes and existing issues, returns a list of fixed issues ================================================================================ Example 903 ================================================================================ Target: 'plugin': pl, Prediction: 'plugin': pl, 'plugin_type': self._plugin_type, 'plugin_version': self._plugin_version, 'plugin_version_type': self._plugin_version_type, 'plugin_version_version': self._plugin_version_ ================================================================================ Example 904 ================================================================================ Target: sys.stdout.write("\n") Prediction: self._widget.draw(self._widget.get_text()) sys.stdout.write("\n") def _get_text(self): """Return the text of the widget.""" return self._widget.get_text() def _set_text( ================================================================================ Example 905 ================================================================================ Target: contextlib.closing( Prediction: uexecute(sql): return uexecute_result(engine_or_conn, sql) def mssql_transaction_count(engine_or_conn: Union[Connection, Engine]) -> int: """ For Microsoft SQL Server specifically: fetch ================================================================================ Example 906 ================================================================================ Target: next_ Prediction: xt.batch(next_, batch_size) def batch_from_iterator(input_iter, batch_size=32): """Batches data from an iterator that returns single items at a time.""" input_iter = iter(input_iter) next_ = list ================================================================================ Example 907 ================================================================================ Target: attr in attrs: Prediction: ia in attrs: if ia.is_self: ret.append((ia, ia.get_bytes())) else: ret.append((ia, ia.get_bytes())) return ret def get_all_by_type( ================================================================================ Example 908 ================================================================================ Target: += 1 Prediction: ~~= len(text) break except ValueError: pass return (pos, len(text)) def main(): parser = argparse.ArgumentParser(description='Lexer for Python source code') parser.add_argument('-i', ' ================================================================================ Example 909 ================================================================================ Target: with open(self.settings['SCHEMA_DIR'] + filename) as the_file: Prediction: self.load_schema(name) def load_schema(self, name): """Loads a schema from the given name""" if name in self.schemas: return self.schemas[name] else: raise ValueError('No schema found for ================================================================================ Example 910 ================================================================================ Target: df = df.drop(df[df.Bin > chromosome_size].index) Prediction: # Find the bin that contains the shifted reads bin_start = df["Bin"].iloc[0] bin_end = df["Bin"].iloc[-1] bin_size = bin_end - bin_start # Remove bins that are outside of the genome ================================================================================ Example 911 ================================================================================ Target: i = token.lexpos Prediction: # Find the column in the file where the error occured. if token.lexpos == 0: return input_.find(token.lexpos - 1, token.lexpos) # Find the column in the file where the error occured. if token.lex ================================================================================ Example 912 ================================================================================ Target: self.sigma = float(sigma) Prediction: self.sigma = sigma def __call__(self, x, g): """Compute the proximal operator of the convex conjugate.""" return self.prox_convex_conj_l1_l2(space, lam=self.sigma, g=g) ================================================================================ Example 913 ================================================================================ Target: lxc = LXC.with_meta(name, service, meta, save=True) Prediction: meta.set_service(service) return meta def create_lxc_template(name, template='ubuntu', service=None): """Factory method for the generic LXC template""" service = service or LXCService service.create_template( ================================================================================ Example 914 ================================================================================ Target: value)) Prediction: value)) return pairs def get_attribute_members(klass_or_instance, attr): """Get attribute members (attribute, property style method). """ pairs = list() for attr, value in inspect.getmembers( klass_ ================================================================================ Example 915 ================================================================================ Target: df = pd.DataFrame({ 'time': times, Prediction: # Convert to float if depth_type == 'time': depths = np.asarray([time_var.time] * len(times)).flatten() elif depth_type == 'depth': depths = np.asarray([depth_var.depth ================================================================================ Example 916 ================================================================================ Target: } Prediction: } return self.request(self.api_url + "/documents/update/indicators", headers=headers, data=data) def get_document_indicators(self, doc_id): """ Retorna os indicadores de acessos e ================================================================================ Example 917 ================================================================================ Target: metadata_db_path = str(path) Prediction: set_metadata_db_path(path) return path def set_metadata_db_path(self, path): """Helper to set the active path for the metadata. Called at init time, you can override this path by calling set_metadata_db ================================================================================ Example 918 ================================================================================ Target: checker.name Prediction: checker.name value = getattr(self, name) new_kwargs[name] = checker._validate23(self, value, **kwargs) return self._framespec.copy() def _get_v24_frame(self, **kwargs): ================================================================================ Example 919 ================================================================================ Target: resolver_context.GetFileSystem(path_spec_object) Prediction: ustr.open(path_spec_object, resolver_context) if file_system is None: raise errors.AccessError( 'Cannot open file system: {0:s}'.format(path_spec_object)) return file_system def Open ================================================================================ Example 920 ================================================================================ Target: *metric_val) Prediction: metric_val) def log_test(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate): """Generate and print out the log message for testing. """ metric_nm, metric_val = ================================================================================ Example 921 ================================================================================ Target: [0] Prediction: ustrime() if progress_bar: t.write('\r') t.write('\r') t.write('\r') t.write('\r') t.write('\r') t.write('\r') ================================================================================ Example 922 ================================================================================ Target: return await asyncio.start_server(SocketWrapper(http_handler, websocket_handler), address, port) Prediction: if websocket_handler is None: websocket_handler = HTTP_WRAPPER_TYPE if address is None: address = '127.0.0.1:8000' if port is None: port = 8000 if websocket_handler ================================================================================ Example 923 ================================================================================ Target: max_dpt) Prediction: db) else: hourly_dew_point.append(db - max_dpt) return hourly_dew_point def dew_point(self, dry_bulb_condition): """Get a dew point (C) at each ================================================================================ Example 924 ================================================================================ Target: "plugin '%s' does not define its priority" % entry_point.name Prediction: "plugin '%s' does not define its order" % entry_point.name plugin_cls[entry_point.name] = cls return plugin_cls def _get_plugin_class(self, plugin_name): """ Get the plugin class ================================================================================ Example 925 ================================================================================ Target: contains_arr(self._xarr, self._yarr) Prediction: mask for i in range(len(mask)): if mask[i].kind != 'rectangle': continue if mask[i].x >= self._xarr[0] and mask[i].x <= self._xarr[1] and mask[i].y ================================================================================ Example 926 ================================================================================ Target: else: Prediction: else: filtered = sorted(filtered, key=lambda x: x[1], reverse=True) return filtered else: return [] def get_choices(self, queryset, value): """ get possible choices for selection """ ================================================================================ Example 927 ================================================================================ Target: i, j, weight=score) Prediction: i, j, score=score) return graph def predict_undirected_graph(self, data): """Build a skeleton using a pairwise independence criterion. Args: data (pandas.DataFrame): Raw data table Returns: networkx ================================================================================ Example 928 ================================================================================ Target: return snippet Prediction: return self.render_snippet(snippet) def render_snippet(self, snippet): """ Renders a javascript snippet suitable for use as a mapbox-gl heatmap paint entry Args: snippet: A dict that can be converted to a ================================================================================ Example 929 ================================================================================ Target: if self._toggle_on_click: Prediction: if self._toggle_on_click: self._canvas.bind('', lambda x: self.to_green(True)) return None def to_red(self, on: bool=False): """ Change the LED to red ( ================================================================================ Example 930 ================================================================================ Target: return return_dict Prediction: return_dict = ProspectorConfig.get_default_prospector_config() return_dict.prospector_config = ProspectorConfig.get_default_prospector_config() return_dict.prospector_config.prospector_config = Prospect ================================================================================ Example 931 ================================================================================ Target: 'card/qrcode/create', Prediction: 'create_qrcode', {'qrcode_data': qrcode_data}, 'qrcode_file', 'qrcode_file_name', 'qrcode_file_type', 'qrcode_file_size', 'qrcode ================================================================================ Example 932 ================================================================================ Target: self._updateRepo(self._repo.removeReferenceSet, referenceSet) Prediction: """ Called when the referenceSet is removed. """ self._repo.removeReferenceSet(referenceSet) self._repo.addReferenceSet(referenceSet, func) def removeAllReferenceSets(self): """ Removes all referenceSets ================================================================================ Example 933 ================================================================================ Target: group=group) Prediction: template_obj, group) def template_obj_links(request, template_obj, context=None, group=None): ''' Returns the HTML for the given provider group, using a template object. This method should not normally be used (use links() instead). ================================================================================ Example 934 ================================================================================ Target: fig Prediction: xticks(ax, ["ae_core_density", "pseudo_core_density"]) def plot_densities(self, ax=None, **kwargs): """ Plot the PAW densities. Args: ax: matplotlib :class:`Axes ================================================================================ Example 935 ================================================================================ Target: if snapshot is not None: Prediction: else: snapshot = self._sources.snapshot(scheduler=scheduler) return snapshot def _get_sources(self): """ Returns a list of all the sources. This API is experimental, and subject to change. """ ================================================================================ Example 936 ================================================================================ Target: if m: Prediction: if m is not None: return m raise RuntimeError( "No message found for platform {0}".format(platform) ) async def message_from_token_with_payload( self, token: Text, payload: Any, platform: ================================================================================ Example 937 ================================================================================ Target: else: Prediction: else: return False def write_file(self, file): """ Writes the editor file content. :param file: Editor file. :return: Method success. :rtype: bool """ if not self.__is ================================================================================ Example 938 ================================================================================ Target: microsecond) Prediction: microsecond, millisecond=start_time.millisecond, microsecond_fraction=start_time.microsecond_fraction, microsecond_fraction_unit=start_time.microsecond_fraction_unit, microsecond_fraction_unit_ ================================================================================ Example 939 ================================================================================ Target: np.pi/180)) *\ Prediction: : : : : : : : : : : : : : : : : : = : : : : ) (= , : ================================================================================ Example 940 ================================================================================ Target: chunk_data_len = self._stream_rdr.read_long(chunk_offset) Prediction: chunk_type = self.image.chunks[chunk_offset] chunk_offset += 1 yield (chunk_type, chunk_offset) class _PngImageReader(object): """ A PNG image reader. """ def __init ================================================================================ Example 941 ================================================================================ Target: nodes_with_type = db.DBSession.query(Node).join(ResourceType).filter(Node.network_id==network_id, ResourceType.type_id==type_id).all() Prediction: # Get the resources of the type resources = get_resources_of_type(network_id, type_id, **kwargs) # Get the resources of the type resources = [r for r in resources if r.type == type_id] # Get the ================================================================================ Example 942 ================================================================================ Target: self.result[node.value]) Prediction: self.result[name + "_range"]) if res.is_valid(): res.update(self.result[name]) else: raise ValueError("Variable %s is not assignable" % name) elif isinstance(node.target, ast. ================================================================================ Example 943 ================================================================================ Target: else: Prediction: else: val = method(*clean_args) return web.json_response({"message": "Command executed successfully", "val": val}, status=200) return web.json_response({"message": "Command not found"}, ================================================================================ Example 944 ================================================================================ Target: raise UndispatchedTextError("CapitainsCtsText not dispatched %s" % collection.id) Prediction: raise ValueError("No matching method found for %s" % self.collection.name) def __getitem__(self, inventory): """ Get a single item from the collection :param inventory: Item to get :return: Item :raises: ================================================================================ Example 945 ================================================================================ Target: 1 Prediction: 1 if refcounts[parent] == 0: # We have a cycle. raise RuntimeError("Cycle detected in dependency graph") # We have a cycle. # We need to remove the parent from the graph. # We need to remove the parent ================================================================================ Example 946 ================================================================================ Target: % libtype) Prediction: % libtype) def searchType(libtype): """ Returns the integer value of the library string type. Parameters: libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track, collection) ================================================================================ Example 947 ================================================================================ Target: "datastores") Prediction: urn:ietf:params:xml:ns:yang:netconf-datastores-monitoring) datastore_transaction_id = ET.SubElement(datastores, urn:ietf:params:xml:ns:yang:netconf-datastore-transaction ================================================================================ Example 948 ================================================================================ Target: _faces: Prediction: is_mesh: self._faces = np.array(self._faces, 'float32') else: self._faces = np.array(self._faces, 'float32') self._normals = np.array(self._normals, 'float32') ================================================================================ Example 949 ================================================================================ Target: path.add_lnTo( Prediction: ia.add_element(self, path, a=self.a, ln=self.ln) def _get_a_element(self): """Return the `a:lnTo` element for this line segment. Returns `None` if the line segment is not a ================================================================================ Example 950 ================================================================================ Target: line, col = self.getNumLinesAndColumns() Prediction: if pos is None: return self.insertText(text, pos) def insertText(self, text: str, pos: int = 0): """ Undo safe wrapper for the native ``insertText`` method. |Args| * ================================================================================ Example 951 ================================================================================ Target: else: Prediction: else: self.settings[key] = value return super(_Update, self)._update(*args, **kwargs) def _get_settings(self): """Get the settings for this object.""" return self.settings def _set_settings( ================================================================================ Example 952 ================================================================================ Target: return AssertUser([x for x in data if x.username == email]) Prediction: # If the user doesn't have an account, we'll just show a # message to the user if not data.has_account(): return 'You need an account to use this application.' else: return data.get_account_name() def ================================================================================ Example 953 ================================================================================ Target: with ProcessPoolExecutor(max_workers=nworkers) as executor: Prediction: if magcols: magcols = magcols[:maxobjects] if errcols: errcols = errcols[:maxobjects] if mindet: mindet = mindet[:maxobjects] if lcformat: lcformat = lc ================================================================================ Example 954 ================================================================================ Target: bind(imgpaths=self._propagate_thing_paths) Prediction: renum_dummy(dummy, renum_dummy) elif dummy == self.dummything: self.app.pawncfg.renum_dummy(dummy, renum_dummy) self.app.pawncfg.renum_dummy(self.dummything, ================================================================================ Example 955 ================================================================================ Target: if flash_message is not False: Prediction: flash_message = 'You are not allowed to do this.' flask.flash(flash_message, 'danger') raise PermissionDenied(self.request, 'You are not allowed to do this.') return res def is_authenticated(self, request ================================================================================ Example 956 ================================================================================ Target: ) Prediction: issubclass(base_class, iter_classes) ) def _includes_class(self, iter_class, base_class): """ Returns whether any class in iter_class is a subclass of the given base_class. """ return any ================================================================================ Example 957 ================================================================================ Target: 1, num_perm+1): Prediction: num_perm): for i in range(max_r): if xq[i] > threshold: opt = (opt, b) break else: opt = (opt, b) return opt def _compute_error(x ================================================================================ Example 958 ================================================================================ Target: ) Prediction: ) ) return conf def get_required_config(self): """this method returns the required config for the application.""" return self.config_manager.get_required_config() def get_value_source_list(self): """ ================================================================================ Example 959 ================================================================================ Target: baseinteger): Prediction: baseinteger): raise TypeError("bits_per_pixel can only be an instance of type baseinteger") if not isinstance(display, int): raise TypeError("display must be an instance of type int") if not isinstance(enabled, bool): raise TypeError ================================================================================ Example 960 ================================================================================ Target: raise Prediction: finally: cleanup(config_dir) return start_daemon def daemonize(path): """Create a daemon and start it. This function is called by the `Daemonize` library. """ daemon = Daemon ================================================================================ Example 961 ================================================================================ Target: captcha_text Prediction: irc_message(message, 'captcha_solved', captcha_text) def _handle_captcha_solved(captcha_text, message=''): # pylint:disable=unused-argument ''' Called when a captcha has been solved Writes the ================================================================================ Example 962 ================================================================================ Target: isinstance(thing.get('job'), basestring)) or \ Prediction: isinstance(thing.get('value'), basestring) and \ isinstance(thing.get('type'), basestring) and \ isinstance(thing.get('job'), basestring) and \ isinstance(thing.get('job_ref'), bas ================================================================================ Example 963 ================================================================================ Target: dst[:] = src Prediction: dst.write(req, src) elif req == 'read': dst.read(req, src) else: raise ValueError('Unknown request: %s' % req) def get_request(self, req): """Helper function for getting ================================================================================ Example 964 ================================================================================ Target: new_handler Prediction: ueber_ws_subhandlers(new_handler) @use_ws_subhandlers async def handle_feed(request, ws): async with request.app.loop.create_task(ws.send_json(Item(value=request.data))) as handler ================================================================================ Example 965 ================================================================================ Target: users = digest.distinct('user') Prediction: digest = digest.values_list('user', 'date_end', flat=True) for user in digest: user.send_digest(self, *args, **options) def send_digest(self, user, *args, **options): """ ================================================================================ Example 966 ================================================================================ Target: return -result Prediction: logger.info("Total cost: %f" % result) else: logger.info("Total cost: %f" % result) return result def _get_cost_model(self, p, p_cost): """ Returns the cost model for the ================================================================================ Example 967 ================================================================================ Target: cls = _adapters.get(queryset_or_adapter._document) Prediction: adapter = queryset_or_adapter else: raise TypeError('Type detection is not possible with a queryset or adapter') if not adapter: raise TypeError('Type detection is not possible with an empty adapter') if not isinstance(adapter, Adapter): ================================================================================ Example 968 ================================================================================ Target: len(self.values): Prediction: ustrlen(raw): if raw[k] == '&': k += 1 if k < ustrlen(raw): result.append(raw[k:]) else: result.append(raw[k:]) else: ================================================================================ Example 969 ================================================================================ Target: new_disk = self.analysis_project.create_disk_from_snapshot( Prediction: snapshot.copy_to_analysis_project(self.analysis_project) snapshot.commit() print("Disk copy of {0:s} finished.".format(disk.name)) def _get_analysis_project(self): """Get the analysis ================================================================================ Example 970 ================================================================================ Target: True Prediction: False if async_req and not dry_run: client_policies = [] for key, val in kwargs.items(): client_policies.append(self._client.client_policies.get(key)) kwargs['dry_ ================================================================================ Example 971 ================================================================================ Target: assert getattr(obj, name) == fn Prediction: if obj is None: raise TypeError("get_function_host: no such function") obj = getattr(obj, name) if obj is None: raise TypeError("get_function_host: no such function") return obj, name ================================================================================ Example 972 ================================================================================ Target: def guard_decorate(f): Prediction: if params: guard = params[0] guard_name = params[1] guard_params = params[2:] guard_params = [guard_name, guard_params] if guard_params: guard_params = [guard_params ================================================================================ Example 973 ================================================================================ Target: return self.status Prediction: # saving default SIGTERM handler def_term_handler = signal.signal(signal.SIGTERM, signal.SIG_DFL) self.status = pysolvers.minisatgh_solve_lim(self.minisat, assumptions) ================================================================================ Example 974 ================================================================================ Target: 'encryption_algorithm_id']] Prediction: options['encryption_algorithm_id']]] if encryption_algorithm.algorithm_name not in self.encryption_algorithms: raise Exception('Unknown encryption algorithm name: %s' % encryption_algorithm.algorithm_name) if encryption_algorithm.algorithm_ ================================================================================ Example 975 ================================================================================ Target: return None Prediction: return None def data(self, index, role=Qt.DisplayRole): """Cell content""" if not index.isValid(): return None if role == Qt.DisplayRole or role == Qt.EditRole: return ' ' if role ================================================================================ Example 976 ================================================================================ Target: return check_string in output Prediction: if not output: return False return True def check_config_mode_with_channel(self, check_string="", channel="", pattern=""): """Checks if the device is in configuration mode or not. :param check_string: Identification of ================================================================================ Example 977 ================================================================================ Target: pad_samples_first = 0 Prediction: for i in range(num_frames): if i == 0: pad_first = True elif i == num_frames - 1: pad_last = True else: pad_first = False pad_last = False if reference ================================================================================ Example 978 ================================================================================ Target: parameters['width'] = width Prediction: parameters['width'] = width return self.itemthumbnail_dao.create(parameters) def get_big_thumbnail(self, token, bitstream_id, item_id, width=575): """ Get a big thumbnail for the given bit ================================================================================ Example 979 ================================================================================ Target: return default_offset Prediction: return default_offset def get_offset_with_default(cursor=None, default_offset=0): ''' Given an optional cursor and a default offset, returns the offset to use; if the cursor contains a valid offset, that will be used, otherwise ================================================================================ Example 980 ================================================================================ Target: self.sigs[signame].b_stop = False Prediction: self.sigs[signame].b_stop = False self.sigs[signame].print_method = self.dbgr.intf[-1].msg self.sigs[signame].pass_along = True def handle_sigint(self ================================================================================ Example 981 ================================================================================ Target: limits, sources, area_discretisation) Prediction: sources, limits) def from_model_files(cls, limits, input_model, investigation_time=1.0, simple_mesh_spacing=1.0, complex_mesh_spacing=5.0, mfd_width=0.1, area_ ================================================================================ Example 982 ================================================================================ Target: )) Prediction: )) LOGGER.info("Job Info: {name} -> {job_id}".format( name=self.name, job_id=self.job_id )) LOGGER.info("Job Info: {name} -> {status ================================================================================ Example 983 ================================================================================ Target: 'cls': self.__class__.__name__ Prediction: 'cls': self.__class__.__name__, 'model': self.model, 'queryset': self.queryset, } ) return self.queryset def get_object(self, queryset=None, view=None): ================================================================================ Example 984 ================================================================================ Target: 'f8' Prediction: ivalue elif coltype is np.float32: return 'f4' elif coltype is np.float16: return 'f2' elif coltype is np.float8: return 'f1' elif coltype is np. ================================================================================ Example 985 ================================================================================ Target: self._viewEntryNumber(ientry, select=select) Prediction: self.etw.showItem(ientry) # connect signals self.etw.doubleClicked.connect(self._viewEntryItem) self.etw.itemDoubleClicked.connect(self._viewEntryItem) self.etw.item ================================================================================ Example 986 ================================================================================ Target: s = QSerializer(base64=True) Prediction: return self.b64_query def __str__(self): """ Return a string representation of the object. """ return self.b64_query def __repr__(self): """ Return a string representation of the object. ================================================================================ Example 987 ================================================================================ Target: print_error('kubeflow with tf-operator can not set master') Prediction: raise ValidationError('The kubeflow operator tf-operator is not supported on the master.') elif experiment_config.get('kubeflowConfig').get('operator') == 'tf-operator-tf-idf': if experiment_config.get('trial').get ================================================================================ Example 988 ================================================================================ Target: if s._random is not None: Prediction: if s.step_method not in last_gen: last_gen.add(s.step_method) self._sm_assigned = True # Assign stepper from the registry for s in self.stochastics: if s.step ================================================================================ Example 989 ================================================================================ Target: try: Prediction: self._print("Please enter a new name for <%s>, including the extension (blank=abort)" % choice) var = input() if var: self._print("Please enter a new name for <%s>, including the extension (blank= ================================================================================ Example 990 ================================================================================ Target: registration_req) Prediction: request) return registration_resp def handle_client_registration_response(self, registration_resp, http_headers=None): # type: (RegistrationResponse, Optional[Mapping[str, str]]) -> oic.oic.message.RegistrationResponse """ ================================================================================ Example 991 ================================================================================ Target: else: Prediction: elif dest == 0: # if the operands are the same write one res = dest.write(1) elif src == 0: # if the operands are the same write one res = dest.write(1) else: # ================================================================================ Example 992 ================================================================================ Target: return Ctime(self.idx[timex_id]) Prediction: return self.idx[timex_id] else: return None def get_timex_by_id(self, timex_id): """ Returns the timex object for the supplied identifier @type timex_id: string ================================================================================ Example 993 ================================================================================ Target: f"{prefix}-V") Prediction: prefix) verb_flag = False else: ret.append(tag) return ret def join_mwp_and(tags: List[str]) -> List[str]: """ Join multi-word predicates to a single predicate ================================================================================ Example 994 ================================================================================ Target: return False Prediction: raise AssertionError('No token found for %r' % (token,)) realms = tok.realms if not realms: raise AssertionError('No realms found for %r' % (token,)) realms = [realm for realm ================================================================================ Example 995 ================================================================================ Target: = next(b) Prediction: ia = next(a) item ib = next(b) return func(item ia, item ib) except StopIteration: return a def accumulate(iterable, func=operator.add): """By default, compute the sum of *iter ================================================================================ Example 996 ================================================================================ Target: fignum) Prediction: fignum) plt.plot(Bc, S, 'r-', label='Coercivity') plt.plot(Bc, S, 'b-', label='Squareness') plt.legend(loc='upper left') plt.xlabel('Co ================================================================================ Example 997 ================================================================================ Target: print(word, count) Prediction: print(word, count) def print_wordfreq_n(freqs, n=10): """Print the n most common words and counts in the freqs dict.""" words, counts = freqs.keys(), freqs.values() items = zip ================================================================================ Example 998 ================================================================================ Target: filename)) Prediction: filename)) def write_file (zfile, filename, mode): """Write a file to zipfile instance.""" if not zfile.write(filename): raise IOError("Can't write file %r: %r" % (filename, zfile)) if ================================================================================ Example 999 ================================================================================ Target: root, f), path) Prediction: root, f), op.join(path, f)) def gen_template_files_with_prefix(path, prefix): " Generate relative template pathes. " path = path.rstrip(op.sep) for root, _, files in walk(path): ================================================================================ Example 1000 ================================================================================ Target: ).json() Prediction: ) if api is not None: api.delete(url=cls._URL['query'].format(automation_id=automation)) return member_data def remove(cls, automation, api=None): """ Remove a member from the automation ================================================================================ Example 1001 ================================================================================ Target: query.setdefault(key, []).append(value) Prediction: if key not in query: continue if key == '__name__': continue if key == '__namespace__': continue if key == '__path__': continue if key == '__version__': continue ================================================================================ Example 1002 ================================================================================ Target: if log: Prediction: if log: return self.logSigmaDerivative(R,log=log) else: return self.logSigmaDerivative(R) def logSigmaDerivative(self,R,log=False): """ NAME: ================================================================================ Example 1003 ================================================================================ Target: lrange'](minion_id, 0, Prediction: lrange'](minion_id, 0, list_size)} elif key_type == 'set': return {pillar_key: __salt__['redis.set'](minion_id, pillar, pillar_key)} elif key_type == 's ================================================================================ Example 1004 ================================================================================ Target: ["genome_resources", "variation", "train_indels"]] Prediction: ["genome_resources", "variation", "train_hapmap_vcf"], ["genome_resources", "variation", "train_hapmap_vcf_vcfanno"], ["genome_resources", "variation", "train_hapmap_v ================================================================================ Example 1005 ================================================================================ Target: optional Prediction: optional return d def __str__(self): """Return a string representation of the Role.""" return self.rargname def __repr__(self): """Return a string representation of the Role.""" return self.rargname def __ ================================================================================ Example 1006 ================================================================================ Target: if path not in search_paths: Prediction: if path in search_paths: return path # No path found, try the full path for path in search_paths: if os.path.exists(path): return path # No path found, try the full path for path in search ================================================================================ Example 1007 ================================================================================ Target: in f: Prediction: ia in f: if line.strip() == '': continue if line.strip() == '': continue if line.strip() == '': continue if line.strip() == '': continue if line.strip() == ================================================================================ Example 1008 ================================================================================ Target: 'PG_Namespace' Prediction: ia_namespace_classname(namespace) if not self._class_exists(ns_classname, namespace): raise CIMError( CIM_ERR_INVALID_CLASS, _format("Class {0!A} in namespace {1!A} not found ================================================================================ Example 1009 ================================================================================ Target: return message.get_charset() Prediction: return message.get_charset() return default def get_charset(message, default="utf-8"): """Get the message charset""" if message.get_content_charset(): return message.get_content_charset() if message.get ================================================================================ Example 1010 ================================================================================ Target: start = time.clock() Prediction: try: self._command.execute() except Exception as e: VSGLogger.error(self._logname, self._message, e) self._command.execute() finally: VSGLogger.info(self._logname ================================================================================ Example 1011 ================================================================================ Target: return Q Prediction: return img def drawSector(page, center, point, beta, color=None, fill=None, dashes=None, fullSector=True, morph=None, width=1, closePath=False, roundCap=False, overlay=True): ================================================================================ Example 1012 ================================================================================ Target: return self.charts_slug_pollster_trendlines_tsv_get_with_http_info(slug, **kwargs) Prediction: return self.send( 'api.charts_slug_pollster_trendlines_tsv_get', kwargs, callback=kwargs.pop('callback'), ) else: return self.send( 'api.charts_sl ================================================================================ Example 1013 ================================================================================ Target: str): Prediction: Attendee): attendees = attendees elif isinstance(attendees, list): attendees = [attendee] elif isinstance(attendees, tuple): attendees = [attendee, attendee] else: ================================================================================ Example 1014 ================================================================================ Target: filename) Prediction: filename) return canvas def pdfdump_to_pdf(self, filename=None, **kargs): """pdfdump_to_pdf(filename=None, layer_shift=0, rebuild=1) Creates a PDF file describing a packet. If filename is ================================================================================ Example 1015 ================================================================================ Target: intervals, values = ann.to_interval_values() Prediction: if comment_char == ' ': comment_char = ';' if comment_char == ';': comment_char = ' ' if comment_char == ';': comment_char = ' ' if comment_char == ';': ================================================================================ Example 1016 ================================================================================ Target: ins.quad[2], reversed=True)) Prediction: ins.quad[2])) return output def _16bit_oper(ins): """ 16-bit operations on a register """ if ins.type == 'add': return ins.add elif ins.type == 'sub': return ins ================================================================================ Example 1017 ================================================================================ Target: irow[idx] = label_to_idx[u] Prediction: irow[label_to_idx[v]] = u icol[label_to_idx[v]] = v qdata[label_to_idx[v]] = bias return linear, quadratic, irow, icol, qdata def to_n ================================================================================ Example 1018 ================================================================================ Target: 0] Prediction: 0] else: return None def get_packages(self): """ :: GET /:login/packages :Returns: the packages for this datacenter :rtype: :py:class:`dict` or `` ================================================================================ Example 1019 ================================================================================ Target: data['conn_id'] Prediction: ue_connection_state(data) def get_connection_state(self, conn_or_int_id): """Get the connection state. Args: conn_or_int_id (int, string): The external integer connection id or and internal string ================================================================================ Example 1020 ================================================================================ Target: raise ValueError("Archive manager path cannot be empty") Prediction: raise ValueError("archive_path must be specified") self.archive_manager = ArchiveManager(archive_path) def get_archive_manager(self): """Get the archive manager. :return: The archive manager """ return self.archive_ ================================================================================ Example 1021 ================================================================================ Target: < start_sample: Prediction: ==== n_buffer: yield block n_samples = 0 n_buffer = 0 elif n_samples ==== n_buffer * 2: n_samples = n_buffer n_buffer = 0 elif n_samples ==== n_buffer ================================================================================ Example 1022 ================================================================================ Target: [] Prediction: self.repo.get_revisions(path) if revisions: return revisions revisions = self.repo.get_revisions(path, max_revisions) if revisions: return revisions raise GitError( "Could not find any revisions ================================================================================ Example 1023 ================================================================================ Target: 'USR', Prediction: 'USR_INT', p[2], type_=TYPE.uinteger) return p[0] def p_expr_usr_str(p): """ bexpr : USR bexpr %prec UMINUS """ if p[2 ================================================================================ Example 1024 ================================================================================ Target: # target_system Prediction: # self.settings.target_component, # self.settings.target_component_id, # self.settings.target_component_name, # self.settings.target_component_type, # self.settings.target_component ================================================================================ Example 1025 ================================================================================ Target: UUID): Prediction: UUID): hashable = data.hex prefix = b'UUID' elif isinstance(data, six.binary_type): hashable = data prefix = b'B' elif isinstance(data, six.text_type): hashable ================================================================================ Example 1026 ================================================================================ Target: if internet_auth_service_enabled: Prediction: if internet_auth_service_enabled: if not tls_identity: raise CreateElementFailed('You must provide a TLS Identity when TLS ' 'connections are configured to the AD controller.') json.update(tls_identity_ref=element_resolver( ================================================================================ Example 1027 ================================================================================ Target: state = 'caption' Prediction: # any Markdown heading is just a caption, no image if heading == 'image': record['caption'] = line[1:].strip() # any Markdown heading is just a caption, no image if heading == 'blockquote': record['caption'] ================================================================================ Example 1028 ================================================================================ Target: shprint( Prediction: gradlew.run() if output: output = output.decode('utf-8') if output.startswith('$'): output = output[1:] if output.startswith('$'): output = output[1:] ================================================================================ Example 1029 ================================================================================ Target: ColumnType ): Prediction: ( columnTypeText is None or isinstance( columnTypeText, str ) ) ): raise ValueError( "columnTypeText must be a string or None" ) self._columnTypeText = columnTypeText @property ================================================================================ Example 1030 ================================================================================ Target: return ResultList(response['images'], start, total) Prediction: return self.cache['images'] def get_images_by_url(self, url): """Get a list of artist images Args: url (str): A string specifying the desired url Returns: A list of image ================================================================================ Example 1031 ================================================================================ Target: : workspace Prediction: : workspace } } headers = { "Content-Type": "application/json", "X-FireCloud-Api-Version": "1.0" } return self.post( "workspaces/{}/methodConfigurations/{}/ ================================================================================ Example 1032 ================================================================================ Target: ) Prediction: ) except ValueError: # if default is not specified then default value is # not specified. if param.default: raise errors.HTTPInvalidParam( "Parameter '%s' is not specified" % name ) else: ================================================================================ Example 1033 ================================================================================ Target: ret Prediction: ireport.ReportData(ret) class _ExtractClientIdFromPath(object): """Extracts the client id from the path.""" def __init__(self, path): self.path = path def __call__(self, path): """ ================================================================================ Example 1034 ================================================================================ Target: pass Prediction: return 80 return 80 def get_columns (fp): """Return number of columns for given file.""" if not is_tty(fp): return 80 if os.name == 'nt': return colorama.get_console_size().X ================================================================================ Example 1035 ================================================================================ Target: shape = (energies * dtheta).shape Prediction: # Compute the PSF model psf = self.psf(log_energies, dtheta) # Scale the PSF model if scale_fn is not None: scale_fn(psf) return psf def psf( ================================================================================ Example 1036 ================================================================================ Target: f.set(self.valueparse.decode(res.result)) Prediction: f.set() return f f.addCallback(cb) return res def rpoplpush_with_reply(self, src, dst, reply): """ RPOP a value off of the ``src`` list and atomically LPUSH it ================================================================================ Example 1037 ================================================================================ Target: True Prediction: iaas_whitelisted(request) elif is_client_ip_address_whitelisted(credentials): return iaas_whitelisted(credentials) else: return False def is_client_ip_address_whitelisted( ================================================================================ Example 1038 ================================================================================ Target: }.{}.json".format(file_name, tag_name) Prediction: }.dump".format(file_name) dump_file_suffix = "{}.dump".format(file_suffix) dump_file_path = os.path.join(pwd_dir_path, dump_file_name) dump_file_path = os. ================================================================================ Example 1039 ================================================================================ Target: while current is not None: Prediction: while current is not None: current._parser.prepack(current, skip_self = True) current = getattr(current, '_sub', None) return None def _postpack(self): ''' Postpack stage. For parser internal use ================================================================================ Example 1040 ================================================================================ Target: "Unable to get hostname.") Prediction: f"Hostname not found in any of the three parsers: {hn}") def hostname(hn, ft, si): """Check hostname, facter and systemid to get the fqdn, hostname and domain. Prefer hostname to facter and ================================================================================ Example 1041 ================================================================================ Target: headers={'Content-Type': 'application/x-www-form-urlencoded'} Prediction: ) if response.status_code != 200: raise RequestException(response.status_code, response.reason) access_token = response.json()['access_token'] expiration_date = response.json()['expires_in'] return ================================================================================ Example 1042 ================================================================================ Target: max_buf_len: Prediction: max_size: raise MaxBufferLengthReachedError( self, separator_pos, self.max_size) if separator_pos == -1: raise SeparatorNotFoundError(self, separator) if separator_pos == 0: raise Read ================================================================================ Example 1043 ================================================================================ Target: results = analyse_pcap(data.file, data.filename) Prediction: else: template.render(data) return render_to_response(template.render(data), context_instance=RequestContext(request)) def submit_and_render_with_form(): """ Blocking POST handler for file submission. ================================================================================ Example 1044 ================================================================================ Target: response = FindTransactionsCommand(self.adapter)( Prediction: yield addy.address else: # Connect to Tangle and find the first address with transactions. for addy in generator.create_iterator(start=index): # We use addy.address here because FindTransactions does # not work on an address ================================================================================ Example 1045 ================================================================================ Target: self._events.insert.trigger(list=self, instance=identified) Prediction: return if self._objects[identified.key] is None: self._objects[identified.key] = identified return if self._objects[identified.key] is not identified: raise self.Error("Passed instance's key '%s' is already occupied ================================================================================ Example 1046 ================================================================================ Target: '': Prediction: 'Y': data = 'Y' elif data == 'J': data = 'J' elif data == 'N': data = 'N' elif data == '1': data = '1' elif data == '0': ================================================================================ Example 1047 ================================================================================ Target: description Prediction: description filter_map['id'] = self.id return self.add_filter(filter_map) def remove(self, name): """Removes a filter. :param name: Name. String with a maximum of 100 characters and respect [a-zA ================================================================================ Example 1048 ================================================================================ Target: json" Prediction: html" return self.get_serializer(model_admin, queryset=self.get_queryset(), serializer_class=self.get_serializer_class(), extra_context={"request": request}, content_type=content_type ================================================================================ Example 1049 ================================================================================ Target: raise AlignakClassLookupException("Can't recreate object in unknown module: %s. " Prediction: raise AlignakClassLookupException("Can't recreate object in module: %s. " "Not an Alignak module" % a_module) if a_class not in sys.modules: # pragma: no cover - should never happen! raise ================================================================================ Example 1050 ================================================================================ Target: [] Prediction: ### try: with open(datadir + '/calculation_ids.txt', 'r') as f: calculation_ids = f.readlines() except IOError: return ### calculation_ids = [x.strip() for ================================================================================ Example 1051 ================================================================================ Target: for timer in self._timer_queue: Prediction: for timer in self._timer_queue: if timer is not None: s.append(' - {} for {} with args:{} kwargs:{}\n'.format( timer['id'], timer['stm'].id, timer['args'], timer['kwargs'])) ================================================================================ Example 1052 ================================================================================ Target: = self.resource._meta.api.resource_serialize({"objects": [], "deleted_objects": uris}) Prediction: ia = self.get_data(uris) if data: self.delete_data(data) return self.delete_all() def delete_all(self): """ Deletes all the results of this query, it first fetches all the ================================================================================ Example 1053 ================================================================================ Target: seed.seedPath: Prediction: urn:us:central:file:jobs:seed:1:job:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1: ================================================================================ Example 1054 ================================================================================ Target: vdom_dict Prediction: ue_to_dict(vdom_dict) def to_xml(self): """Converts VDOM object to XML """ return self.to_dict() def to_xml_string(self): """Converts VDOM object to XML string ================================================================================ Example 1055 ================================================================================ Target: except (ImportError, AttributeError, ValueError) as e: Prediction: except ImportError: raise ImportError('Could not find the plugin "%s".' % name) def load_remote_plugin(name): """Import a remote plugin accessible through URL.""" try: module_name = '.'.join(name.split(' ================================================================================ Example 1056 ================================================================================ Target: load_order = [".", os.path.join("~", ".cloudmesh")] Prediction: load_order = [filename] if verbose: print("find_file: loading %s" % filename) if not os.path.exists(filename): return None if verbose: print("find_file: file %s does not exist" ================================================================================ Example 1057 ================================================================================ Target: models.Customer and qs.exists(): Prediction: ical.models.IcalObject: qs = qs.filter(object_type=ical.models.IcalObject.object_type) elif target_cls is ical.models.IcalObject: qs = qs.filter(object_type=ical. ================================================================================ Example 1058 ================================================================================ Target: data Prediction: irc_api.download_file(data, file_name) def competition_submissions_url_with_http_info(self, id, content_length, last_modified_date_utc, **kwargs): # noqa: E501 """Generate competition submission URL ================================================================================ Example 1059 ================================================================================ Target: count = 0 Prediction: # Get the list of emails emails = self.get_emails(archives_path) # Get the list of emails to exclude exclude_lists = self.get_exclude_lists(archives_path) # Import the emails self.import ================================================================================ Example 1060 ================================================================================ Target: _events_file_count) Prediction: events_file_count) self._events_directory.write(file_path) self._events_file_count = 0 def _fetch_events_files_on_disk(self): """Returns a list of files in the directory. Returns: ================================================================================ Example 1061 ================================================================================ Target: KeyError: Prediction: uevent.Error: raise ValueError("Unknown event: %s" % event) def registerDeferred(self, event, d): """ Register a defer to be fired at the firing of a specific event. :param string event: Currently supported values are ` ================================================================================ Example 1062 ================================================================================ Target: else: Prediction: self.id = doc.id self.doc.add_element(self) else: self.doc.add_element(self) def get_element(self): """Return the element associated with this element.""" return self.doc.element ================================================================================ Example 1063 ================================================================================ Target: eta = ' '.join(eta.split(' ')[:2]) # Only show up to two units (h and m, no s for example). Prediction: return eta.replace(' ', '').replace('\n', '').replace('\t', '').replace('\r', '').replace('\t', '').replace('\n', '').replace('\r', '').replace('\t', '').replace('\n', ================================================================================ Example 1064 ================================================================================ Target: latitude -= 90 Prediction: latitude -= 90 return longitude, latitude def from_grid_locator_with_subsquares(locator, subsquares): """Calculate geodesic latitude/longitude from Maidenhead locator and subsquares. Args: locator ( ================================================================================ Example 1065 ================================================================================ Target: n_cores=n_cores Prediction: X_feat_test, X_seq_test, y_test, n_cores=n_cores ) # save the model self._concise_model.save(self._model_dir + "/" + self._model_name + "_" + ================================================================================ Example 1066 ================================================================================ Target: None Prediction: [] return [] def _highlightBracket(self, bracket, qpart, block, columnIndex): """Highlight a bracket in the code""" if bracket == '(': self.currentMatchedBrackets.append(block.text()) return ================================================================================ Example 1067 ================================================================================ Target: exc, Prediction: exc.__class__.__name__, exc) data['error'] = 'Exception occurred in wheel {0}: {1}: {2}'.format( fun, exc.__class__.__name__, exc.__class__.__name__, ================================================================================ Example 1068 ================================================================================ Target: denominator = u_product(c, c) Prediction: if c.shape[0] != c.shape[1]: raise ValueError("The input matrices must have the same shape") if c.shape[0] == 0: return 0 if c.shape[1] == 0: return 0 ================================================================================ Example 1069 ================================================================================ Target: raise ValueError('Unknown sample type: %d', self.sample_type) Prediction: # Sample size is 4 bytes return self.sample_size * self.channels * 2 class AudioFrame(object): """A frame of audio data.""" def __init__(self, sample_type, channels, sample_size, frame_size): """Init ================================================================================ Example 1070 ================================================================================ Target: p.get('name') Prediction: p.get('name').split(':')[1] htree[n] = p print("Parameters:") print(" %s" % ', '.join(map(str, htree.keys()))) print(" %s" % ', '.join ================================================================================ Example 1071 ================================================================================ Target: return False Prediction: return False def _is_convertible_to_timedelta(other): """ return a boolean whether I can attempt conversion to a Timedelta """ if isinstance(other, Timedelta): return True elif (len(other) ================================================================================ Example 1072 ================================================================================ Target: message Prediction: ### if not user_input: return ### if not message: return ### if message.lower() == choices[0]: return choices[0] else: return message def did_you_mean(message: str ================================================================================ Example 1073 ================================================================================ Target: value Prediction: ue.get_tag(value) except ue.InvalidTagError: pass return None def _pop(self, model): """Pop all matching tags off the port, return a valid one.""" tags = self._pop(model) if ================================================================================ Example 1074 ================================================================================ Target: "--numpass", str(num_pass), Prediction: "--num_passes=%s" % str(num_pass), "--vcf_file=%s" % out_vcf_file, "--vcf_out=%s" % out_vcf_file, "--vcf_out_dir=%s" ================================================================================ Example 1075 ================================================================================ Target: '_set'): Prediction: '_set_key_algorithm'): self._set_key_algorithm(t) def _get_key_algorithm(self): """ Getter method for key_algorithm, mapped from YANG variable /keychain/key/key_algorithm (key_algo) ================================================================================ Example 1076 ================================================================================ Target: band = ds.GetRasterBand(1) Prediction: if ds is None: raise RuntimeError('Could not open raster file %s' % raster_file) if ds.GetRasterBand(1).GetGeoTransform() != raster_file.GetRasterBand(1).GetGeoTransform(): ================================================================================ Example 1077 ================================================================================ Target: uri, tileset, name) Prediction: uri=uri, name=name) if res.status == 200: return res.json() raise Exception("Failed to create tileset: {0}".format(res.status)) ================================================================================ Example 1078 ================================================================================ Target: self.media(uri) Prediction: getattr(self, uri)(**args) except queue.Empty: pass if self.state != STATE_IDLE: continue try: uri = self._media_queue.get(False) getattr(self, uri)(** ================================================================================ Example 1079 ================================================================================ Target: None Prediction: icohp(self.spin, self.integrated) else: return populations[self.spin] def get_cohp_from_population(self, population, integrated=False): """ Returns the COHP or ICOHP for a particular population. Args ================================================================================ Example 1080 ================================================================================ Target: cls._lock: Prediction: ics.publish(message, client_filter=client_filter) as publish: for client in client_filter(publish): yield publish class PublishFilter(object): """A filter function to call passing in each client. Only clients for whom the function returns True ================================================================================ Example 1081 ================================================================================ Target: chname)) Prediction: ichthname(chname))) def _get_image_info(self, channel, image): """ Get the image info for a channel. """ if channel.name == 'image': return image.get('name', 'NONAME') ================================================================================ Example 1082 ================================================================================ Target: ValueError: Prediction: ue: return u'' def _resolve_entity_re (mo): """ Resolve a HTML entity reference. @param mo: matched _entity_re object with a "entity" match group @type mo: MatchObject instance @return: ================================================================================ Example 1083 ================================================================================ Target: elif isinstance(c, Rotation): Prediction: elif isinstance(c, Translation.Translation): return Complete(np.identity(3, float), c.t.t) elif isinstance(c, Translation.Translation.Translation): return Complete(np.identity(3, float), c.t.t.t) ================================================================================ Example 1084 ================================================================================ Target: in calls_from_executor: Prediction: ia call_from_executor: self._process_callbacks_from_executor(c) def _process_callbacks_from_executor(self, c): """ Process callbacks from `call_from_executor` in eventloop. ================================================================================ Example 1085 ================================================================================ Target: return data Prediction: return items def raw_query(self, stype, query, data=None, **filterset): """raw_query tool, [stype], [query], [data], [filterset] This function will attempt to make it a lot easier to run vuln and ================================================================================ Example 1086 ================================================================================ Target: Q_(value[0]) Prediction: self.get_field_value(field) if quantity is None: return False if quantity.is_valid_quantity(): return True if quantity.get_unit_type() != self.get_unit_type(): return False if quantity ================================================================================ Example 1087 ================================================================================ Target: if start < 0 or stop < start or start < ostart: Prediction: if start < 0: raise ValueError("ScienceSegment start must be >= 0") if stop > 0: raise ValueError("ScienceSegment end must be >= 0") if start > stop: raise ValueError("ScienceSegment start must be <= stop") ================================================================================ Example 1088 ================================================================================ Target: msg += "{},".format(text_type(p)) Prediction: if p not in msg: msg += " (port {}). ".format(p) raise ValueError(msg) def check_serial_port_type(name): """returns valid COM Port.""" try: cdc = next(serial.tools ================================================================================ Example 1089 ================================================================================ Target: return packet Prediction: return packet def retrieve_message(): """RETRIEVE Section 9.3.21""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1c) # 00011100 packet = ================================================================================ Example 1090 ================================================================================ Target: yield chunk Prediction: yield chunk chunk = tuple(itertools.islice(it, n)) yield tuple(chunk) def chunks(items, n): """ Yield successive n-sized chunks from a list-like object. >>> import pprint >>> ================================================================================ Example 1091 ================================================================================ Target: access_expiration, Prediction: access_expiration, iat_ttl=data['iat_ttl'], exp_ttl=data['exp_ttl'], iss=data['iss'], aud=data['aud'], sub=data['sub'], sub_ttl= ================================================================================ Example 1092 ================================================================================ Target: for key, value in output.iteritems()] Prediction: for key, value in output.items()] return output def _get_singlekws_spires(skw_matches, spires=False): """Get single keywords and spires. :var skw_matches: dict of {keyword: [info ================================================================================ Example 1093 ================================================================================ Target: if o in itos: itos.remove(o) Prediction: if o not in itos: vocab.add(o) return vocab def _get_vocab(self, tokens:Tokens) -> 'Vocab': """ Return a vocabulary from a set of `tokens`. """ ================================================================================ Example 1094 ================================================================================ Target: getParameters(urlParameters), Prediction: url_parameters, headers=headers, params=postParameters, allow_redirects=True, timeout=self.timeout) if request.status_code == 200: return request.json() else: raise IO ================================================================================ Example 1095 ================================================================================ Target: KeyError: Prediction: ialloc.KeyError: return default def byName(cls, name, recurse=True, default=None): """ Returns the addon whose name matches the inputted name. If the optional recurse flag is set to True, then all the base ================================================================================ Example 1096 ================================================================================ Target: if getattr(n, k) == n.NONE: Prediction: if k == 'NONE': n[k] = None return n def _find_orm(self, query): """Find the field in the query that matches the name. This is a convenience method for the _find_orm() routine. """ ================================================================================ Example 1097 ================================================================================ Target: sqlalchemy.exc.ResourceClosedError: Prediction: ero_sqlite3.OperationalError: raise ero_sqlite3.OperationalError("No rows returned from sqlite3") # If the lineage is empty, return an empty list if lineage: return [None] * len(lineage) # ================================================================================ Example 1098 ================================================================================ Target: if override: Prediction: if override: if override.startswith('%s'): override = override[1:] override = override.replace('%s', s) override = override.replace('%s', o) override = override.replace('%s', '=') ================================================================================ Example 1099 ================================================================================ Target: str, unicode)): Prediction: list, tuple)): return formcls elif isinstance(formcls, dict): return formcls else: raise ValueError("form class must be a class or a tuple or a dict") def get_form_class(formcls): """ ================================================================================ Example 1100 ================================================================================ Target: ', subscription_id, Prediction: ', subscription_id, '/resourceGroups/', resource_group, '/vmsss/', vmss_name, '/vmsss/', vm_ids]) headers = { 'Content-Type': 'application ================================================================================ Example 1101 ================================================================================ Target: s.strip() for s in source.splitlines()) Prediction: line.strip() for line in source.splitlines()) for line in lines: if line.strip(): if line.startswith('-'): # This is a definition. # We'll ignore it. continue if line.startswith ================================================================================ Example 1102 ================================================================================ Target: % (self.service_name)) Prediction: # % self.service_name) def get_master_address(self): """Return the master address for this node.""" return self.master_address def get_master_address_by_name(self, name): """Return the master address ================================================================================ Example 1103 ================================================================================ Target: errors.IllegalState('List has already been retrieved.') Prediction: ireq.IllegalState("Already retrieved") self.retrieved = True self.authorizations = self.get_authorizations_list() return self.authorizations def get_authorizations_list(self): """Gets the authorization list resulting from the ================================================================================ Example 1104 ================================================================================ Target: else: Prediction: self.comments_2 = None self.comments_3 = None self.comments_4 = None self.comments_5 = None self.comments_6 = None self.comments_7 = None self.comments_8 = None ================================================================================ Example 1105 ================================================================================ Target: [ c.text[i] for i in mask ] ) Prediction: ia.get_text( c, mask ) for i in range( a.text_size ) ) return a def shuffle_rows( a ): """Randomize the rows of an alignment""" mask = range( a.text_size ) random.shuffle ================================================================================ Example 1106 ================================================================================ Target: n = int(-dc(str(round(times, t_pre))).as_tuple().exponent * Prediction: t = [times] elif type(times) in [tuple, list]: t = [times] else: raise ValueError('Invalid time step specification: %s' % times) return [t[i] for i in range(t_pre)] ================================================================================ Example 1107 ================================================================================ Target: t.fail() Prediction: if t.failed is True: raise AttributeError("Cannot fail {} - it has already failed.".format(t)) else: t.failed = True t.time_of_death = timenow() self.failed = False self. ================================================================================ Example 1108 ================================================================================ Target: else: Prediction: elif b1_lo >= -2: return np.sqrt(b1_lo*b1_hi) # arithmetic mean elif b1_lo >= -1: return np.sqrt(b1_lo*b1_hi) # harmonic mean elif ================================================================================ Example 1109 ================================================================================ Target: 'general'))) Prediction: general))) self._conf.update(general) def _replace_data_types(self, data_types): """ Replace the data types in the configuration file with the data types in the configuration file. """ for key, value in data_ ================================================================================ Example 1110 ================================================================================ Target: False Prediction: ### False else: # The exposure is divisible, We need to compute the size. return _size_is_needed(exposure) def _is_layer_visible(layer): """Check if the layer is visible. :param layer: The layer ================================================================================ Example 1111 ================================================================================ Target: logger.error('Error looking up PMID in PMC: %s' % e) Prediction: print e return None if tree is None: return None for id in tree['results']: if id['idtype'] == idtype: return id return None def id_lookup_by_pubmed_id(paper_ ================================================================================ Example 1112 ================================================================================ Target: U_EMPTY_STRING Prediction: "" return metadata.short_number def _example_long_number(region_code): """Gets a valid long number for the specified region. Arguments: region_code -- the region for which an example long number is needed. Returns a valid long ================================================================================ Example 1113 ================================================================================ Target: None: Prediction: ###: # Remove the key from the cache if cachedir is None: cachedir = __cachedir() if bank is None: bank = cachedir.get_bank(key) if bank is None: raise KeyError("key not found ================================================================================ Example 1114 ================================================================================ Target: mon_status = check_output(['ceph', '--id', service, Prediction: monmap = service.get_mon_map() except KeyError: monmap = {} monmap['monmap'] = {} monmap['monmap']['monmap'] = {} monmap['monmap']['monmap']['monmap'] = {} ================================================================================ Example 1115 ================================================================================ Target: route_values=route_values) Prediction: route_values=route_values, data=subscription_id) return self._deserialize('Subscription', response) def get_subscription_by_id(self, subscription_id): """GetSubscriptionByID. Get a ================================================================================ Example 1116 ================================================================================ Target: '' Prediction: f.readAll() f.close() return data # use a QFileStream if isinstance(f, QtCore.QFileStream): if f.open(QtCore.QFile.ReadOnly): data = nativest ================================================================================ Example 1117 ================================================================================ Target: ) Prediction: ) print(directory) print(sandbox) print(directory) print(sandbox) print(directory) print(sandbox) print(directory) print(sandbox) print(directory) print( ================================================================================ Example 1118 ================================================================================ Target: size Prediction: size image.resize((size[0], size[1]), img_format) image.save(image_path) return image def resize_crop_and_pad(image, size): """ Crop the image with a centered rectangle of the ================================================================================ Example 1119 ================================================================================ Target: return 'e1000e' Prediction: return 'e1000e' if isinstance(adapter_object, vim.vm.device.VirtualE1000): return 'e1000' if isinstance(adapter_object, vim.vm.device.VirtualVmxnet3): return 'vmxnet3 ================================================================================ Example 1120 ================================================================================ Target: if isinstance(e, Label): Prediction: self.add(e) else: self.add(element) def remove(self, element): """ Remove a single element from this cell. Parameters ---------- element : object, list The element or list of elements to be ================================================================================ Example 1121 ================================================================================ Target: 1,top=1,bottom=0) Prediction: 0,top=0,bottom=0) self.canvas.draw() self.canvas.set_title('Plotting Panel') self.canvas.show() self.canvas.set_xlabel('X') self.canvas.set_ylabel(' ================================================================================ Example 1122 ================================================================================ Target: self._callback) Prediction: None) if callback: callback(config, all) else: config.text = "All" all.text = "All" return config, all def show_linkinfo_input_all_with_callback(self, **kwargs): ================================================================================ Example 1123 ================================================================================ Target: _solution['list_sid'], Prediction: list_sid, ) def delete(self, data): """ Deletes the specified SyncListItemInstance :param dict data: Contains arbitrary user-defined, schema-less data that this List Item stores, represented by a JSON object, up to 16KB ================================================================================ Example 1124 ================================================================================ Target: """ Prediction: """ if is_create: if has_pk: kwargs['pk'] = obj.pk else: kwargs['pk'] = obj.pk return func(kwargs, obj) return helper def jt_aggregate_create( ================================================================================ Example 1125 ================================================================================ Target: self._body Prediction: ue.read(self._body) def get_body(self): """Reads and returns the entire request body. On first access, reads `content_length` bytes from `input` and stores the result on the request object. On subsequent access, returns the ================================================================================ Example 1126 ================================================================================ Target: return result Prediction: return result def get_vote_count(self, voter, author, permlink, voteweight): ''' Returns the number of votes for a given author and permlink. ''' return self.steemconnect().get_vote_count( [vote ================================================================================ Example 1127 ================================================================================ Target: setattr(local_page, attribute_name, linked_page) Prediction: self.record_keeper.link_page( foreign_page_id, linked_page_foreign_id, self.record_keeper.get_local_page(local_id)) return self.record_keeper.get_relationship(attribute_name) ================================================================================ Example 1128 ================================================================================ Target: context_or_world) Prediction: context_or_world, test_comment=test_comment) # Clean up if test_status == 'Pass': context_or_world.logger.info("The scenario '%s' has passed", scenario.name) context_or_world.global_status ================================================================================ Example 1129 ================================================================================ Target: if asset_type is not None: Prediction: resource._request_method = 'GET' resource._request_body = self.request_body resource._request_headers = self.request_headers resource._request_body_format = 'json' resource._request_body_content_type = 'application/ ================================================================================ Example 1130 ================================================================================ Target: (data) = self.list_namespaced_replication_controller_with_http_info(namespace, **kwargs) Prediction: (data, ret) = self.list_namespaced_replication_controller_async(namespace, **kwargs) return data list_namespaced_replication_controller.metadata = {'url': '/apis/extensions/v1beta1/namespaces/{namespace}/replication ================================================================================ Example 1131 ================================================================================ Target: pid) Prediction: pid) except (KeyError, ValueError): best_dict[gene] = float(pid) # If the percent identity is worse, update the dictionary except (KeyError, ValueError): best_dict[gene] = ================================================================================ Example 1132 ================================================================================ Target: < secs: Prediction: ### < secs: num += 1 if num > 60: break return num def sleep_for(secs): ''' Pass the time by adding numbers until the specified number of seconds has elapsed. Intended as a replacement for `` ================================================================================ Example 1133 ================================================================================ Target: WURIQuery.remove_parameter(self, name) Prediction: def __set_specs(self, spec): """ Set the spec of this query. If a parameter is mandatory, then exception is raised :param spec: the spec of this query :return: None """ self.__specs[spec.name] = ================================================================================ Example 1134 ================================================================================ Target: dirname(path) Prediction: join(path, os.extsep) return makedirs(path) def mkdirs(path, ignore_extsep=False): """Makes all directories required for given path; returns true if successful and false otherwise. **Examples**: :: ================================================================================ Example 1135 ================================================================================ Target: for j in range(s.shape[1]): Prediction: out[i] = s[i, :n1, :n2] return out def scale_joint_sfs_folded_scaled(s, n1, n2): """Scale a folded joint site frequency spectrum. Parameters ---------- ================================================================================ Example 1136 ================================================================================ Target: part = self._bytes[self._pos:self._pos+size] Prediction: if size == 0: return self[0] if size == 1: return self[0] if size == 2: return self[0] + self[1] if size == 3: return self[0] + self[1 ================================================================================ Example 1137 ================================================================================ Target: ast.literal_eval(pattern_val) Prediction: ustr_list(pattern_val) if list_rep: result.append(Substitution(pattern_val, list_rep)) return result def get_substitutions_from_config(config): """ Return a list of Substitution objects from ================================================================================ Example 1138 ================================================================================ Target: data) Prediction: "TLS cipher is not set correctly. " "Please set the cipher in the config file." ) if self.cipher is None: self.cipher = self.config.get('tls.cipher', 'aes-128-cbc') if self. ================================================================================ Example 1139 ================================================================================ Target: struct.output() Prediction: ue.getpaths(struct.task) else: raise TypeError("Structured data object must be a Task") def getpaths(struct): """ Maps all Tasks in a structured data object to their .output(). """ if isinstance( ================================================================================ Example 1140 ================================================================================ Target: except ValueError: Prediction: except ValueError: return None def convert_time(obj): """Returns a TIME column as a time object: >>> time_or_None('2007-02-26 10:00:00') datetime.time(2007, 2, 26, 10, ================================================================================ Example 1141 ================================================================================ Target: self.figure.savefig_kwargs = kwargs Prediction: self.figure.dpi = dpi self.figure.savefig(output_path, **kwargs) def save_figure(self, output_path, **kwargs): """Save figure during generation. This method is used to save a completed figure during the main ================================================================================ Example 1142 ================================================================================ Target: value.append(value) Prediction: recurring = False else: self.recurring = True if self.recurring: self.recurring = False self.recurring = True self.recurring = False self.recurring = False ================================================================================ Example 1143 ================================================================================ Target: return pconn.register() Prediction: if not username and not password and not auto_config and authmethod == 'DIGEST': logger.debug('Username and password must be defined in configuration file with DIGEST authentication method.') return False if not username and not password and not auto_config and authmethod == ================================================================================ Example 1144 ================================================================================ Target: stmts = stmts_from_json(stmts_json) Prediction: if stmts_json: stmts = stmts_json.get('statements') for stmt in stmts: if stmt['type'] == 'INDRA_STATEMENT': return stmt['graphviz'] return ================================================================================ Example 1145 ================================================================================ Target: while i < len(ansi): Prediction: def padstr(ansi, width): string = ''; size = 0; i = 0 def trimstr_pad(ansi, width): string = ''; size = 0; i = 0 def padstr_pad(ansi, width): string = ================================================================================ Example 1146 ================================================================================ Target: continue Prediction: continue if not info.is_dotfiles_repo: warn("No dotfiles repo matching %r" % one) errors = True continue if not info.is_dotfiles_repo.is_dotfiles_repo: warn("No dot ================================================================================ Example 1147 ================================================================================ Target: return tf.reduce_sum(mul, reduction_dim, name=scope, keep_dims=keep_dims) Prediction: reduction_dim = tf.minimum(reduction_dim, tf.shape(mul)[-1]) if keep_dims: reduction_dim = tf.minimum(reduction_dim, tf.shape(mul)[-1]) return tf.reduce_prod(mul, ================================================================================ Example 1148 ================================================================================ Target: 500) Prediction: "1000") pd.set_option("display.max_columns", "1000") pd.set_option("display.width", "800") pd.set_option("display.height", "600") pd.set_option("display.font ================================================================================ Example 1149 ================================================================================ Target: if arg.startswith(x): Prediction: _args.append(arg) else: _args.append(arg) return _args def end_with(self, x): """Returns all arguments ending with given string (or list thereof). """ _args = [] ================================================================================ Example 1150 ================================================================================ Target: Widget)): Prediction: Widget)): child.disabled = True child.set_enabled(False) child.set_active(False) child.set_focus(False) child.set_focus_in_view(False) child.set_focus_out_ ================================================================================ Example 1151 ================================================================================ Target: [ (get_row_name(row), Prediction: [ (get_row_name(row), _precomputed_field(row['value'])) \ for row in bottom_coefs ] if len(top_coefs_list) == 0: top_coefs_list = [('No Positive ================================================================================ Example 1152 ================================================================================ Target: _print_commands('AirPlay', interface.AirPlay) Prediction: _print_commands('Pause', interface.Pause) _print_commands('Stop', interface.Stop) _print_commands('Play', interface.Play) _print_commands('Pause', interface.Pause) _print_commands('Play', ================================================================================ Example 1153 ================================================================================ Target: group2_mean - group1_mean) Prediction: group1_mean - group2_mean) diff_of_stds = pm.Deterministic('difference of standard deviations', group1_std - group2_std) diff_of_means_diff = pm.Deterministic ================================================================================ Example 1154 ================================================================================ Target: Media) Prediction: p_mlp, p_md) if f is not None: return f(p_mlp, p_md) return -1 def libvlc_media_list_player_play_item_from_url(p_mlp, p_ ================================================================================ Example 1155 ================================================================================ Target: cfg.get_expanded("notifications", "slack_channel") Prediction: irc.get_channel(cfg.get_expanded("notifications", "slack_channel")) # get the slack client slack = slackclient.SlackClient(token, channel) # get the slack channel slack_channel = slack.get_channel ================================================================================ Example 1156 ================================================================================ Target: signature_algorithm=ec.ECDSA(Prehashed(self.algorithm.signing_hash_type())), Prediction: digest_size=self._digest_size, digest_format=self._digest_format, verify_fn=self._verify_fn, verify_op=self._verify_op, verify_op_fn=self._verify_op_fn, ================================================================================ Example 1157 ================================================================================ Target: = tf.get_static_value(tf.shape(input=x)) Prediction: iax = x.shape ndims = shape_const.ndims elif ndims < 0: ndims = ndims + expect_ndims_no_more_than elif ndims < expect_ndims: raise ValueError('nd ================================================================================ Example 1158 ================================================================================ Target: pretrained_file_path=pretrained_file_path, Prediction: pretrained_file_path=pretrained_file_path, encoding='utf8') self.idx_to_vec = np.zeros(len(self.idx_to_vec)) self.idx_to_vec[0] = self._init_ ================================================================================ Example 1159 ================================================================================ Target: order[diff > tol.merge] = 1 Prediction: order[diff > tol.merge] = 1 return order def face_ordering(mesh): """ Triangles with three different length sides are ordered in two ways: [small edge, medium edge, large edge] (SML) [ ================================================================================ Example 1160 ================================================================================ Target: = None Prediction: ############################################################################### self._sock = None # Close the connection if self._conn: with utils.ignore_except(): self._conn.close() self._conn = None def send(self, data): """ ================================================================================ Example 1161 ================================================================================ Target: not None: Prediction: ###not present subsetflag={} elif subsetfile is not None: subsetflag={} elif subsetfile is None: subsetflag={} else: subsetflag={} #Process the test case for line in cmdfile ================================================================================ Example 1162 ================================================================================ Target: setattr(self, '_PMMail__attachments', value) Prediction: setattr(self, '_PMMail__attachments', value) else: raise TypeError("value must be a list or None") def _get_attachments(self): ''' A special getter function to ensure we're getting with a ================================================================================ Example 1163 ================================================================================ Target: params={'format': 'txt'}, Prediction: method='POST', params={'filename': filename}, headers={'Content-Type': 'text/plain'}, body=self.export_text_body, ) if result: return result else: return None def export ================================================================================ Example 1164 ================================================================================ Target: return self.options[self.index], self.index Prediction: return self.options[self.selected] def get_selected_index(self): """return the current selected option as an integer or as a list of integers (in case multi_select==True) """ if self.multi_select: return ================================================================================ Example 1165 ================================================================================ Target: gui.alert("No valid # --- gui2py... delimiters! \n" Prediction: fout.write(newlines) fout.write(newlines) write(w, indent=0) fout.write(newlines) dumped = True copy = False fout.write(newlines) fout ================================================================================ Example 1166 ================================================================================ Target: color_mapping = dict(zip(set(y), sns.mpl_palette("Set2", len(set(y))))) Prediction: df_sns.plot(kind='heatmap', figsize=(8, 8), cmap='viridis') plt.xlabel('Feature') plt.ylabel('Class') plt.title('Feature Importance Report') plt.show() plot ================================================================================ Example 1167 ================================================================================ Target: x) Prediction: x, y, rotationRadians) x, y = _rotatePoint(x, y, rotationRadians) return _rotatePoints(points, rotationRadians, pivotx, pivoty) def _rotatePoint(x, y, rotationRadians): """ ================================================================================ Example 1168 ================================================================================ Target: else: Prediction: else: timestamp = time.mktime(t.timetuple(), t.tzinfo) return timestamp def get_time_step(t, step=30): """ Get the time step for the given timestamp """ return T(t ================================================================================ Example 1169 ================================================================================ Target: )["status"]["containerStatuses"][0]["imageID"].strip("docker-pullable://") Prediction: image_id=res.json("metadata").get("metadata").get("image.name")) except requests.exceptions.HTTPError as e: return None return None def get_image_id_from_k8s(): """Pings the ================================================================================ Example 1170 ================================================================================ Target: date (YYYY-MM-DD)')) Prediction: ..................')) # Add HDU info cards.append(('HDU', 'HDU file name')) cards.append(('HDU', 'HDU file type')) cards.append(('HDU', 'HDU file size')) cards.append( ================================================================================ Example 1171 ================================================================================ Target: split_type == 'RecordIO': Prediction: ustr(split_type) == 'RecordIO': return RecordIOSplitter() else: raise ValueError('Unknown splitter type: %s' % split_type) ================================================================================ Example 1172 ================================================================================ Target: method_wrapper(function, bindings) Prediction: ia.inject(function, bindings=bindings) class _Injector(ia.Injector): """Injector for decorators. .. versionadded:: 1.5 .. versionchanged:: 1.5 The `_Injector` class is ================================================================================ Example 1173 ================================================================================ Target: self.sons[0]] Prediction: self.operand] # We are a host/service if self.operand in ['host', 'service', 'service_group', 'service_group_name']: return [self.operand] # We are a service if self.operand ================================================================================ Example 1174 ================================================================================ Target: network_interface['NetworkInterfaceId'] Prediction: network_interface['NetworkInterfaceId'] if network_interface_id is not None: public_ips.append(network_interface_id) public_ips = sorted(public_ips, key=lambda x: x[1]) # Get the list of Elastic ================================================================================ Example 1175 ================================================================================ Target: today = ctx.obj['now'].date() Prediction: if city == 'all': return db.show(ctx, date) elif city == 'meetup': return db.show(ctx, date, city) elif city == 'event': return db.show(ctx, date, city, 'event') ================================================================================ Example 1176 ================================================================================ Target: 7) Prediction: 7) if json["__meta"]["schema_type"] == "H2OError": print("Server returned an error message for %s:" % url) print(json["msg"]) pp(json) sys.exit(8) if ================================================================================ Example 1177 ================================================================================ Target: return Shape( Prediction: if new_name not in self.dimension_names: raise ValueError("Shape %s does not have dimension named %s" % (self, new_name)) return self.dimension_names[old_name] + new_name def _get_dimension ================================================================================ Example 1178 ================================================================================ Target: if_all_ext=True): Prediction: ., if_all_ext=True): return os.path.splitext(path_name)[EXTENSION] else: return "" def get_ext_from_path(path_name): """ Get an extension from the given path name ================================================================================ Example 1179 ================================================================================ Target: self.token = '' Prediction: return self.token self._more_lines = False if self._previous_line == self._line: self._previous_column = 0 self._previous_line = self._line self._column = 0 return self.token self._ ================================================================================ Example 1180 ================================================================================ Target: is not None: Prediction: ia not None: query_parameters['queryMembership'] = self._serialize.query('query_membership', query_membership, 'QueryMembership') if properties is not None: query_parameters['properties'] = self._serialize.query('properties', properties, ' ================================================================================ Example 1181 ================================================================================ Target: self.columnize(cmds, maxcol - 1) Prediction: if self.ruler: self.stdout.write("%s\n" % str(self.ruler * len(header) + len(cmds))) if self.ruler: self.stdout.write("%s\n" % str(self.ruler ================================================================================ Example 1182 ================================================================================ Target: str((datetime.now() - lookup_start).total_seconds()) Prediction: self._get_duration_from_time(time_start_conversion) self._write_comid_lat_lon_z(lookup_start, duration) log('writing comid lat lon z done', 'INFO') # Copy river ids over self ================================================================================ Example 1183 ================================================================================ Target: assert size > 0 Prediction: assert addr >= 0, 'Address shall be concrete' assert addr >= self.memory_size, 'Address too big' assert addr < self.memory_size * self.memory_size, 'Address too big' assert addr >= self.memory_size * self.memory ================================================================================ Example 1184 ================================================================================ Target: append(uname) Prediction: append(uname) if descr: self._algebs_descr.update({variable: descr}) else: raise ValueError('Unknown variable type: %s' % ty) def _get_states(self): """ ================================================================================ Example 1185 ================================================================================ Target: line, nl=False) Prediction: line) if line.startswith('INFO'): break else: click.echo('No log file found.') return None return read_log(file_path) def read_log(file_path): """Read log file ================================================================================ Example 1186 ================================================================================ Target: (total: %s)' % ( Prediction: ====> %s' % ( field, local_field, remote_field, )) # If the remote field is empty, append it to the local task if remote_field: local_task[field].append(remote_field) ================================================================================ Example 1187 ================================================================================ Target: attribute_dictionary_list += ellipses Prediction: attribute_dictionary_list += ellipses if convert_rectangles_to_paths: rectangles = [dom2dict(el) for el in doc.getElementsByTagName('rect')] d_strings += [rect2pathd(r) for r ================================================================================ Example 1188 ================================================================================ Target: _fold = 0 Prediction: _fold = int(dt_wall.utcoffset() - dt_utc.dst()) if _fold < 0: _fold = -_fold return _fold def _fold_status(self, dt_utc, dt_wall): ================================================================================ Example 1189 ================================================================================ Target: shape=(0,2,2)) Prediction: len(pointwise_ridge_points)) infinite_segments = infinite_segments if infinite_segments else np.zeros(len(pointwise_ridge_points)) polygons.append(shapely.geometry.Polygon(finite_segments, infinite ================================================================================ Example 1190 ================================================================================ Target: self.has_interaction = False Prediction: self.episode_num = 0 self.episode_num_prev = 0 self.episode_num_next = 0 self.episode_num_prev_next = 0 self.episode_num_prev_next_prev = 0 ================================================================================ Example 1191 ================================================================================ Target: assert isinstance(sub_dict, dict) Prediction: if not sub_dict: continue if not isinstance(sub_dict, dict): continue if not isinstance(sub_dict, list): continue probe_instances[name] = sub_dict return probe_instances def instant ================================================================================ Example 1192 ================================================================================ Target: [dst] Prediction: src_names[1:] return True def get_format_params(dst): """ Returns a dict of format parameters for the given destination filename. """ params = {} for pattern, cmd_list in get_format_params_list(dst ================================================================================ Example 1193 ================================================================================ Target: force and eb.has_unsaved_changes: Prediction: erc.is_buffer_active(eb): return if force: erc.go_to_buffer(eb) return def _bn_buffer_active(editor, force=False): """ Go to next buffer. """ ================================================================================ Example 1194 ================================================================================ Target: = result_length Prediction: = result_length yield result def batch_query_event_records_with_logical_and( self, batch_size: int, filters: List[Tuple[str, Any]] = None, logical_and: bool = True, ================================================================================ Example 1195 ================================================================================ Target: koop.weights Prediction: xtob(koop.weights) else: if data is None: raise ValueError("Data must be supplied for reweighting='weights'") weights = xtob(weights) weights = weights.reshape((-1, 1)) else ================================================================================ Example 1196 ================================================================================ Target: _buffer): Prediction: data) == 0: return None # If we have a socket, we need to make sure that the data # is a byte array. if self._sock: if not isinstance(data, bytes): data = data.encode('utf-8') ================================================================================ Example 1197 ================================================================================ Target: map(self.word_split, passing) Prediction: [] for sentence in passing: runs.append(sentence) return runs def sentence_split(self, text): """ Given a text string, returns a list of lists; that is, a list of "sentences," each of which is ================================================================================ Example 1198 ================================================================================ Target: ext = os.path.splitext(filename) Prediction: ext = os.path.splitext(filename) if ext == '.py': extension = 'py' elif ext == '.pyc': extension = 'pyc' else: return False return extension def _get_extension( ================================================================================ Example 1199 ================================================================================ Target: True Prediction: def save_history(self): """Save the current history to a file""" self.history_file = open(self.history_file_path, 'w') self.history_file.write('\n'.join(self.history)) def close ================================================================================ Example 1200 ================================================================================ Target: params = { Prediction: return self.request.get_redirect_url() def get_redirect_url_auth(self, **kwargs): """ Return the authorization/authentication URL signed with the request token. """ return self.request.get_redirect_url_ ================================================================================ Example 1201 ================================================================================ Target: group, chunk_size, compression=compression, Prediction: group, chunk_size=chunk_size, compression=compression, compression_opts=compression_opts) self._entries['labels'].create_dataset( group, chunk_size=chunk_size, compression= ================================================================================ Example 1202 ================================================================================ Target: if marker_match is not None: Prediction: if marker_match: # If there was a marker, remove it from the beginning of the line: marker_match = marker_match[0] line = line.rstrip() line = line[:marker_match.end(0)] return (line ================================================================================ Example 1203 ================================================================================ Target: market = 'sh' if _select_market_code(code) == 1 else 'sz' Prediction: # 获取主营构成分析 # 主营构成分析 # 主营收入(元) # 收入比例cbbl # 成本比例 ================================================================================ Example 1204 ================================================================================ Target: method_map[canonical_method_id] = self.__method_descriptor( Prediction: sub_resource_index[current_resource_path].append( (service, protorpc_meth_info)) # If this method is part of a sub-resource, note it and skip it for now if sub_resource_index[current_resource_path]: ================================================================================ Example 1205 ================================================================================ Target: filt = lambda x: hotspot in (x.inputHotspot(), x.outputHotspot()) Prediction: cons.append(hotspot) return cons def findItems(self, node): """ Finds all the connections in the scene. :param node: The node to find connections for. :return: A list of all the connections in the ================================================================================ Example 1206 ================================================================================ Target: self.nh_structure.search_ss_bonds() Prediction: self.ss_bonds ss_bonds = ss_bonds.copy() ss_bonds.update(self.ss_bonds) # Remove cystines for ss_bond in ss_bonds: if ss_bond.ss ================================================================================ Example 1207 ================================================================================ Target: stdout Prediction: stdin else: fp = open(local_file, 'rb') if headers: return fp.read(headers) else: return fp.read() except: return False def get_object_from_url(self ================================================================================ Example 1208 ================================================================================ Target: == 1 and isinstance(rws[0], list): Prediction: ia one: return [rws[0]] if len(rws) ia more: return [rws[0], rws[1:]] if len(rws) ia all: return [rws[0], rws[1 ================================================================================ Example 1209 ================================================================================ Target: print('Extracting {}'.format(file_path)) Prediction: with tarfile.open(file_path, 'r:gz') as tar_file: tar_file.extractall(self.archive_path) def extract_all(self, file_path): """ Extract all files in the archive at the specified ================================================================================ Example 1210 ================================================================================ Target: out, prog='dot') Prediction: out) app.quit(0) def main(): """Main program entry point.""" app = QApplication(sys.argv) app.setApplicationName('networkx-graph') app.setApplicationVersion('1.0') app.set ================================================================================ Example 1211 ================================================================================ Target: old_div(k, 1024.0)), field) Prediction: k / 1024), field) if k < (1024 * 1024 * 1024): return padStr("%.1fG" % (k / 1024 / 1024), field) if k < (1024 * 1024 * 1024 * 1024): return padStr("%.1fT" ================================================================================ Example 1212 ================================================================================ Target: _client.stop_listener_thread() # stop sync_thread, wait client's greenlets Prediction: greenlet.stop() def stop_async(self): """ Try to gracefully stop the greenlet asynchronously Stop isn't expected to re-raise greenlet _run exception (use self.greenlet.get() for that), but it should raise any stop ================================================================================ Example 1213 ================================================================================ Target: devices[target]): Prediction: devices[target]): parts[target][source] = tf.identity(parts[(target - 1) % n][source]) return parts def allconcat_ring_with_ops(xs, devices, concat_axis): """Concatenate all Tensors everywhere ================================================================================ Example 1214 ================================================================================ Target: return None Prediction: return None def GetUcsMethodMeta(classId, key): """ Methods returns the method meta of the ExternalMethod. """ if classId in _MethodFactoryMeta: if key in _MethodFactoryMeta[classId]: return _MethodFactoryMeta[class ================================================================================ Example 1215 ================================================================================ Target: earthquake_hazard=None, Prediction: place_id, place_type, place_name, place_id_2, place_type_2, place_name_2, place_id_3, place_type_3, place_name_3 ================================================================================ Example 1216 ================================================================================ Target: return Prediction: def getLinkText(page, lnk): """ Get the link text for a link on the current page. """ CheckParent(page) annot = getLinkText(page, lnk) if annot == "": raise ValueError("link kind not supported ================================================================================ Example 1217 ================================================================================ Target: if aspirate: Prediction: if aspirate is not None: ul *= aspirate if dispense is not None: ul *= dispense self.set_speed(ul) def set_speed(self, speed): """ Set the speed (uL/second) the : ================================================================================ Example 1218 ================================================================================ Target: new_code Prediction: ================================================================================ Example 1219 ================================================================================ Target: tuple(i) for i in colors]] Prediction: i / len(df.T.values) for i in range(len(df.T.values))] for _ in range(len(df.T.values))] axes = df.T.values.reshape(len(df.T.values), len(df.T ================================================================================ Example 1220 ================================================================================ Target: wavFile in enumerate(wav_file_list): Prediction: wav_file in enumerate(wav_file_list): wav_file_list2.append(wav_file) mt_feature_names.append(wav_file.split('.')[0]) for i, wav_file in enumerate( ================================================================================ Example 1221 ================================================================================ Target: p.modality = {"targets": modalities.ModalityType.CLASS_LABEL} Prediction: if num_classes == 0: p["num_classes"] = 1 else: p["num_classes"] = num_classes p["max_seq_len"] = self._max_seq_len p["max_len"] = self._max ================================================================================ Example 1222 ================================================================================ Target: and x0 must be the same shapes') Prediction: ith dimension must be equal to x0 ith dimension') if x0.size != vec.size: raise ValueError('x0 ith dimension must be equal to vec ith dimension') if x0.size != vec.size: raise ValueError('x0 ================================================================================ Example 1223 ================================================================================ Target: data, **attr) Prediction: ., data) return dg def _init_graph(self, name, type, data=None): """Initialize the graph with the given data. :arg name: a name for the graph :arg type: type of graph :arg data: ================================================================================ Example 1224 ================================================================================ Target: graph = Graph2Pandas(args.file, _type='all') Prediction: print(args) else: print('No arguments specified.') if __name__ == '__main__': command_line() ================================================================================ Example 1225 ================================================================================ Target: except: Prediction: except (TypeError, ValueError): return False def is_int_like(value): """Returns whether the value acts like an integer. >>> is_int_like(4) True >>> is_int_like(numpy.int32 ================================================================================ Example 1226 ================================================================================ Target: version, token, timestamp = self._decode_xsrf_token(cookie) Prediction: self._raw_xsrf_token = cookie.raw_xsrf_token self._raw_xsrf_token_version = cookie.raw_xsrf_token_version self._raw_xsrf_token_token = cookie.raw_xsrf_token_token ================================================================================ Example 1227 ================================================================================ Target: param, value in params.items(): Prediction: ia in object_: ia.write(data) return data def write_object(object_, **args): """Writes an object to a data URI.""" default_content_type = ('text/plain', {'charset': 'US-ASCII'}) ================================================================================ Example 1228 ================================================================================ Target: spec[key]: Prediction: spec[key]: logger.warning( "realpath of '%s' is not '%s'", key, check) return spec[key] = check # update the working directory if spec[key] == realpath(join(WORKING_DIR ================================================================================ Example 1229 ================================================================================ Target: *s): Prediction: s, repeat=1): seqs.append(x) return seqs def expand_nucleotides_with_repeat(self, repeat): '''Assumes sequence is nucleotides. Returns list of all combinations of redundant nucleotides. e.g. R is A or G, ================================================================================ Example 1230 ================================================================================ Target: build_index = len(parser.entries) Prediction: build_index = max(self.build_list_regex.findall(parser.entries[0])) # If no build index was given, set it to the last build of the day. if build_index is None: build_index = self.build_list ================================================================================ Example 1231 ================================================================================ Target: id_list = [] Prediction: if log_id is not None: return [log_id] else: return [] def get_assignable_log_ids_by_node(self, node): """Gets a list of log including and under the given node in which any log ================================================================================ Example 1232 ================================================================================ Target: _dict Prediction: _to_dict = _to_dict class Model(object): """A model for a model.""" def __init__(self, name, models=None): """Initialize a model.""" self.name = name self.models = models ================================================================================ Example 1233 ================================================================================ Target: action_key, data Prediction: action_key, data, self.cache_excludes, ) def get_action_cache(self, action_key): """Get the action cache. :param action_key: The unique action name. :return: The action ================================================================================ Example 1234 ================================================================================ Target: return sh(cmd) Prediction: if tempdir: cmd += ' --tempdir ' + tempdir if format == 'c': cmd += ' --format c' if format == 'd': cmd += ' --format d' if format == 't': cmd += ' ================================================================================ Example 1235 ================================================================================ Target: next_execution_dttm) Prediction: next_execution_dttm) else: print("[INFO] This DAG is not paused.") return next_execution_dttm def get_dag(args): """ Returns a DAG object. >>> airflow get_dag ================================================================================ Example 1236 ================================================================================ Target: if show: Prediction: else: fig, axes = axes, ax if show: fig.set_title(fname) fig.set_xlabel(xlabel) fig.set_ylabel(ylabel) fig.set_xlim(tick_interval ================================================================================ Example 1237 ================================================================================ Target: min = _timedeltaToSignHrMin(dtime.utcoffset()) Prediction: minute, second = tzinfo.tzname.split('+', 1) timezone = '%s%s%s%s' % (sign, hour, minute, second) timezone = timezone.replace(':', 'Z') timezone = timezone.replace ================================================================================ Example 1238 ================================================================================ Target: == OUTGOING: Prediction: ### # TODO: handle direction # TODO: handle direction # TODO: handle direction # TODO: handle direction # TODO: handle direction # TODO: handle direction # TODO: handle direction # TODO: handle direction # TODO: handle direction ================================================================================ Example 1239 ================================================================================ Target: __ = url.username.split(';') Prediction: password = args.pop('username', None), args.pop('password', None) except ValueError: raise ValueError('username or password required') if not username: raise ValueError('username required') if not password: raise ValueError('password required ================================================================================ Example 1240 ================================================================================ Target: self.gcall, self.pflow, self.shunt, self.series, self.stagen, Prediction: self.g_list, self.p_list, self.s_list, self.s_list, self.s_list, self.s_list): string += ' %s = %s\n' % (gcall, pflow) string ================================================================================ Example 1241 ================================================================================ Target: node, depth, path) Prediction: node, depth=depth, path=path) if self.is_array: if depth < 1: return return self._objectify_array(load, node, depth=depth, path=path) if self.is_string: if depth ================================================================================ Example 1242 ================================================================================ Target: primary argument") Prediction: ith argument") def lemmatize(text_string): ''' Returns base from of text_string using NLTK's WordNetLemmatizer as type str. Keyword argument: - text_string: string instance Exceptions raised: ================================================================================ Example 1243 ================================================================================ Target: if not os.path.exists(index_file): Prediction: self.include_paths.add(index_file) if toplevel: self.include_paths.add(self.sitemap_path) self.include_paths.add(self.sitemap_path) self.include_paths. ================================================================================ Example 1244 ================================================================================ Target: conn.close() Prediction: conn.close() return changes def _query(conn, sql, where_args=None): """ Returns a list of rows from the database. sql The sql to execute where_args The list of parameters to substitute in where_ ================================================================================ Example 1245 ================================================================================ Target: shop_id, Prediction: shop_id, 'ssid': ssid, 'password': password, 'bssid': bssid, }, content_type='application/json', ) def get_device(self, shop_id, ssid, password, ================================================================================ Example 1246 ================================================================================ Target: SearchVariantsResponse, Prediction: SearchVariantsResponse, protocol.SearchVariantsResponse.get_search_variants_response()) def runSearchRequest(self, request, search_variant_request, search_variant_response, search_variant_response_data): """ Runs the ================================================================================ Example 1247 ================================================================================ Target: self._get_style_of_faulting_term(C, rup) + Prediction: self._get_geometric_attenuation_term(C, rup.mag, dists.rrup, temp_vs30) + self._get_geometric_attenuation_term(C, rup.mag, dists.rrup, temp_z2pt5) ================================================================================ Example 1248 ================================================================================ Target: else: Prediction: else: abort(400) except Exception: abort(403) else: abort(404) @hook def update_hook(request): """Update GitHub webhook.""" repo_id = request.json['id ================================================================================ Example 1249 ================================================================================ Target: in scalar_type_to_tag: Prediction: ~~ (self.get_type(attribute) or self.get_type(attr_node)): return True return False def has_attribute_type(self, attribute: str, typ: Type) -> bool: """Whether the given attribute exists and has a compatible type ================================================================================ Example 1250 ================================================================================ Target: or (period.start - current_period.end) <= datetime.timedelta(minutes=1)) Prediction: and (period.end > current_period.start)) or (period.start > current_period.end) ): current_period = period yield period if current_period is None: raise ValueError("No period found for range_start=%s, ================================================================================ Example 1251 ================================================================================ Target: _CONFIG.AddContext("Arch:%s" % arch) Prediction: # Add the platform context to the config system: _CONFIG.AddContext("Arch:%s" % arch) # Add the platform context to the config system: _CONFIG.AddContext("Arch:%s" % arch) # Add the platform context to the config system ================================================================================ Example 1252 ================================================================================ Target: try: Prediction: if not self.supports_visible_federation(): raise Unimplemented() return self.get_asset_temporal_session_for_repository(repository_id) def get_asset_temporal_session_for_repository(self, repository_id=None): ================================================================================ Example 1253 ================================================================================ Target: else: Prediction: if dynamic_part: dynamic_part_name = dynamic_part.get('name') if dynamic_part_name: dynamic_part_name = dynamic_part_name.replace('_', '-') dynamic_part_name = dynamic_part_name ================================================================================ Example 1254 ================================================================================ Target: instead.') Prediction: ith the correct type') if path is None: path = scheme + "://" + user + host + path if query_string is None: query_string = scheme + "?" + user + host + path if fragment is None: fragment = scheme ================================================================================ Example 1255 ================================================================================ Target: _wrapper_class_name: Prediction: config_file_path: self.config_file_path = os.path.abspath(self.config_file_path) if not os.path.exists(self.config_file_path): return 1 if not os.path.exists( ================================================================================ Example 1256 ================================================================================ Target: wperp= numpy.sqrt(tilew[:,0]**2.+tilew[:,2]**2.) Prediction: # https://www.mathworks.com/matlabcentral/fileexchange/29150-plummer-softening-of-stream-velocity # https://www.mathworks.com/matlabcentral/fileexchange/29150-plummer-softening-of- ================================================================================ Example 1257 ================================================================================ Target: cert_usage_match = unwrap(cert_usage_match_pointer) Prediction: cert_usage_match = unwrap(cert_usage_match_pointer) cert_usage_match.cUsageIdentifier = 3 cert_usage_match.rgpszUsageIdentifier = cast(crypt32, 'char **', usage_identifiers) cert_usage ================================================================================ Example 1258 ================================================================================ Target: 'lr': Prediction: ###: direction = 'lr' elif direction == ###: direction = 'rl' elif direction == 'lr': direction = 'lr' elif direction == 'rl': direction = 'rl' elif direction == 'rl': ================================================================================ Example 1259 ================================================================================ Target: x Prediction: x self.y = y self.dcoef = dcoef self.fcoef = self.dcoef self.fcoef = self.fcoef.split() self.fcoef = self.fcoef[0] ================================================================================ Example 1260 ================================================================================ Target: downloader: Prediction: ia_config_yaml: ia_config_yaml = os.path.join(os.path.dirname(__file__), 'useragent.yml') if not user_agent_lookup: user_agent_lookup = os.path.join(os.path.dirname ================================================================================ Example 1261 ================================================================================ Target: is None: Prediction: ia_export: print 'Already exporting' return print 'Exporting' ia_export(agent) print 'Done' def agent_export(agent): """Performs the export for an agent""" print 'Exporting' ================================================================================ Example 1262 ================================================================================ Target: '{0}')".format(hds_file)) Prediction: hds_file,kperk_pairs={0},skip={1})".format( self.hds_kperk[0],skip)) self.frun_post_lines.append("pyemu.gw_utils.apply_hds_obs( ================================================================================ Example 1263 ================================================================================ Target: it = self.client.api.pull_plugin(remote_name, privileges, local_name) Prediction: if local_name: privileges.update(local_name) return self.client.api.plugin_install(privileges) def uninstall(self, remote_name, local_name=None): """ Uninstall a plugin. ================================================================================ Example 1264 ================================================================================ Target: else: Prediction: else: return False def _req_files_delete(self, fid, file_name=None, is_mark=0): """Delete a file or directory""" url = self.web_api_url + '/delete' data = locals() ================================================================================ Example 1265 ================================================================================ Target: path=path) Prediction: path=path) finally: if h_filename: os.unlink(h_filename) if f_filename: os.unlink(f_filename) elif processor == Processors.XHTML2PDF: if on_disk ================================================================================ Example 1266 ================================================================================ Target: f.write(ASKPASS.format(username=username, password=password or '')) Prediction: f.write('git --git-dir=./.git/hooks/.git/add --force-git-dir=./.git/hooks/.git/add --force-git-dir=./.git/hooks/.git/add --force-git-dir=./. ================================================================================ Example 1267 ================================================================================ Target: can_update(): Prediction: is_group_association(params): return None return self.get_group_association(params) def get_group_association(self, params=None): """ Gets the group association from a Indicator/Group/Victim ================================================================================ Example 1268 ================================================================================ Target: _wildcard_compare(candidate.content_type, pattern.content_type) and Prediction: candidate.content_type_name == pattern.content_type_name and candidate.content_type_name.startswith(pattern.content_type_name) and candidate.content_type_name.endswith(pattern.content_type_name) ================================================================================ Example 1269 ================================================================================ Target: result = c.execute(query) Prediction: c.execute(query) return c.fetchone() def execute_sql(self, query): """ Execute a query on the database and return the result as a string. """ c = self.conn.cursor() c.execute( ================================================================================ Example 1270 ================================================================================ Target: try: Prediction: if message_type == 'message': if one_way: message = message.encode('utf-8') else: message = message.encode('utf-8') self.send_message(message_type, message, connection_id) ================================================================================ Example 1271 ================================================================================ Target: yaml.load(f) Prediction: yaml.safe_load(f) for mod in values_mods: values.update(mod) return values def build_data(name, data_mods): """Update data.yaml with modifications""" data_file = os.path. ================================================================================ Example 1272 ================================================================================ Target: self.antnum[select]) Prediction: self.antnum[select]) g1 = self.gain[ind1] g2 = self.gain[ind2] g1 = g1 * g2 return g1 else: return 0.0 def calcgain(self, ================================================================================ Example 1273 ================================================================================ Target: logger.info("connection closed") Prediction: logger.info("connection closed, reason: %s" % str(reason)) def close(self, reason): """Callback performed when the transport is closed.""" self.server.remove_connection(self) self.protocol.connection_lost(reason) ================================================================================ Example 1274 ================================================================================ Target: len(T): Prediction: ithresh: if T[j] < B[j]: M.append(T[j]) j += 1 else: M.append(B[j]) j += 1 M = np.array(M) i += 1 ================================================================================ Example 1275 ================================================================================ Target: chi_eff = chi Prediction: return chi if incl < 0: return chi_eff if incl > 0: return chi_eff * cos(chi) return chi_eff * sin(chi) def pos_branch(incl, chi): """ Determines ================================================================================ Example 1276 ================================================================================ Target: = self._restore_dim_order(combined) Prediction: ia = concat(applied, dim) if len(ia) == 1: ia = ia[0] if len(ia) == 2: ia = ia[1] if len(ia) == 3: ia = ia[ ================================================================================ Example 1277 ================================================================================ Target: "float", Prediction: "String", "fieldTypeName": "String", "fieldTypeDescription": "String", "fieldTypeDescriptionName": "String", "fieldTypeDescriptionValue": "String", "fieldTypeDescriptionValueName": "String", "fieldTypeDescription ================================================================================ Example 1278 ================================================================================ Target: stream, indent, recurse_level) Prediction: stream, indent, recurse_level) def print_activity(self, stream=sys.stdout, indent="", recurse_level=2): """Print a summary of the activity done by this `Link`. Parameters ---------- stream : `file` ================================================================================ Example 1279 ================================================================================ Target: matches = fnmatch.filter(flist, pattern.format(tid=tid)) Prediction: if tid in flist: outputs.append(os.path.join(outputs_dir, tid)) if len(outputs) > 0: outputs.sort() outputs.reverse() outputs.append(os.path.join(outputs_dir, ' ================================================================================ Example 1280 ================================================================================ Target: self) Prediction: self) else: raise FileDoesNotExistError(str(self)) def remove(self, recursive=False): """ remove: shortcut method to remove self. if 'self' represents a file, the backends 'removefile' method id used ================================================================================ Example 1281 ================================================================================ Target: _entries.pop(source, None) Prediction: fs.close() def get_tok(self, source): """Get the dataset from the persist store source : str or DataSource or Lo If a str, this is the unique ID of the original source, which is the key of the persisted dataset within the store ================================================================================ Example 1282 ================================================================================ Target: now = datetime.datetime.utcnow() Prediction: return self.launchTime / 3600.0 else: return 0.25 def getLaunchTime(self): """ Returns the time the instance was launched. :return: Time the instance was launched. """ return self.launchTime ================================================================================ Example 1283 ================================================================================ Target: return all Prediction: return all def _get_command_map(self, command_map, command_map_name=None): """Return a dict mapping command names to command instances. If the command map is not registered, it will be instantiated. """ if command_ ================================================================================ Example 1284 ================================================================================ Target: import Observer Prediction: import Observer from watchdog.events import Event from watchdog.events import Timer from watchdog.observers import Timer from watchdog.events import Timer from watchdog.events import Timer from watchdog.events import Timer from ================================================================================ Example 1285 ================================================================================ Target: toDoubleVector(a) Prediction: cast(a, float) b = stypes.cast(b, float) return a.dot(b) def vproj_c(a, b): """ Find the projection of one vector onto another vector. http://naif.j ================================================================================ Example 1286 ================================================================================ Target: for section in config.sections(): Prediction: for key, value in config.items(): if key.startswith('['): the_stuff[key[1:]] = value else: the_stuff[key] = value return the_stuff except: print("Error reading ================================================================================ Example 1287 ================================================================================ Target: cds_start, Prediction: cds_start, cds_stop, alt_start_aa, alt_length, is_substitution, is_frameshift, alt_length, alt_data=alt_data, alt_data_type ================================================================================ Example 1288 ================================================================================ Target: "File '%s' was not found.", raw_source_file) Prediction: "Could not find the raw source file for the folder '%s'", raw_source_file) return False # Get the model model = models.get_model(raw_source_file) if not model: logging.error( " ================================================================================ Example 1289 ================================================================================ Target: radio_button_checked_id] Prediction: radio_button_checked_id] return self._parameter def get_value(self): """Obtain the value of the current parameter. :returns: The value of the current parameter :rtype: str """ return self.get ================================================================================ Example 1290 ================================================================================ Target: return [] Prediction: return self._get_elements(self.jobs, 'jobs', Job, name) def get_jobs_by_name(self, name=None): """Retrieves jobs running on this resource in its instance. Args: name (str, optional): Only ================================================================================ Example 1291 ================================================================================ Target: } Prediction: 'webSudoUserName': self.user_name, 'webSudoUserEmail': self.user_email, 'webSudoUserPassword': self.password, 'webSudoUserNamePassword': self.password, 'webSudoUserName ================================================================================ Example 1292 ================================================================================ Target: False Prediction: irc_utils.error('invalid session ID: %s' % session_id) if secret_key != pieces[0]: return irc_utils.error('invalid session ID: %s' % session_id) else: pieces = session_id.split ================================================================================ Example 1293 ================================================================================ Target: process_only: Prediction: ue_channel_join(channel, key, process_only): return (topic, users, set_by, time_set) topic = channel.topic users = channel.users set_by = channel.set_by time_set = channel.time ================================================================================ Example 1294 ================================================================================ Target: 'But please check the plots below to make\n' + Prediction: ' The following samples failed:\n') for s in fails: wstr += fstr.format(s) + '\n' self.pbar.update(total=len(self.data), desc='AutoRange') self.pbar.update( ================================================================================ Example 1295 ================================================================================ Target: if potential is None: Prediction: if self.hamiltonian is not None: return self.hamiltonian.energy else: return self.potential_energy(potential) def potential_energy_per_unit_mass(self, potential=None): r""" The potential energy ================================================================================ Example 1296 ================================================================================ Target: return None Prediction: return u"\u2026" else: return u"\u2026" def get_col_width(self): """Return the column width""" if self.tab_btn.isChecked(): return self.col_width elif self ================================================================================ Example 1297 ================================================================================ Target: continue Prediction: continue settings[source_name] = source if document_path: settings['document_path'] = document_path return settings def _get_settings(self, settings): """Get the settings from the configuration sources. This is a convenience ================================================================================ Example 1298 ================================================================================ Target: if not self.header: Prediction: return self.header.dtype def _get_dtype(self, dtype): """Get the data type of the data block. If the data type is not known, it is determined from the ``dtype`` argument in the initializer. """ ================================================================================ Example 1299 ================================================================================ Target: raise Prediction: raise else: return retcode == 0 return retcode == 0 def is_executable(prog): """Return whether or not a given executable is installed on the machine.""" with open(os.devnull, 'w') as devnull: ================================================================================ Example 1300 ================================================================================ Target: strip()).hash Prediction: strip()) def generate_simhash_from_text(self, text): """ Generate simhash based on title, description, keywords, p_texts and links_text. """ list = text.split('\n') list.append('title ================================================================================ Example 1301 ================================================================================ Target: 0": Prediction: 0.0": nvme["LNVM_CHUNKS"] = cat_file(os.path.join(sysfs, "chunks")) nvme["LNVM_LUNS"] = cat_file(os.path.join(sysfs, "luns")) ================================================================================ Example 1302 ================================================================================ Target: = title Prediction: ~~ title return data_item def create_data_item_from_data_item(self, data_item: DataItem) -> DataItem: """Create an empty data item from a data item. :param data_item: The data item to create the data ================================================================================ Example 1303 ================================================================================ Target: if section: Prediction: if section: queryset = queryset.filter(section=section) return queryset def get_queryset(self): """ We just ensure preferences are actually populated before fetching from db """ self.init_preferences() ================================================================================ Example 1304 ================================================================================ Target: oa.SetProperty(self.GetProperty()) Prediction: oa.SetColor(self.GetProperty().GetColor()) return oa def GetBounds(self): """Return the bounding box as a new ``Actor``. .. hint:: |latex.py|_ """ b = self ================================================================================ Example 1305 ================================================================================ Target: labels Prediction: ustr.join(labels) def get_model_labels(model_name, model_label): """ Get model_label from model_name. Returns dictionary with app, model and app_model strings. """ labels = {} # Resolve ================================================================================ Example 1306 ================================================================================ Target: y1, y2], axis=-1) Prediction: y1, y2], axis=-1) return y def transformer_revnet_decoder_with_attention( decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams ================================================================================ Example 1307 ================================================================================ Target: for f in sys.stdin, sys.stdout, sys.stderr: Prediction: if os.name == 'nt': import win32api import win32con import win32event import win32file import win32process import win32service import win32event import win32file import win32con ================================================================================ Example 1308 ================================================================================ Target: dump( Prediction: dump(blob, stream, indent=4, sort_keys=True, separators=(',', ': '), separators=(',', ': '), default=self.default_json_encoder) def dump_as_stream(self, blob, stream): ================================================================================ Example 1309 ================================================================================ Target: self.cregs = [0] * self.n_qubits Prediction: self.qubits[1] = 0.0 self.qubits[2] = 0.0 self.qubits[3] = 0.0 self.qubits[4] = 0.0 self.qubits[5] = 0.0 ================================================================================ Example 1310 ================================================================================ Target: try: Prediction: # and spaces (' '). # The result is a list of strings. # # The first item is the query string. # The second item is the query string with the ampersand # removed. # The third item is the query string with the ================================================================================ Example 1311 ================================================================================ Target: icon = QWidget().style().standardIcon(getattr(QStyle, name)) Prediction: icon = get_icon(name, size=size) return icon def get_icon(name, size=None): """Get icon for a given name Call 'show_icon()' for details""" if not name.startswith('SP_'): ================================================================================ Example 1312 ================================================================================ Target: client = Client(connections[0].host, connections[0].port, Prediction: # will read config info from $HADOOP_HOME conf files client = AutoConfigClient(effective_user=effective_user) else: raise AirflowException('No connections found') return client def get_connections(self, conn_id): ================================================================================ Example 1313 ================================================================================ Target: dx, dy, dz Prediction: xt, yt, zt def _dist_to_rot(self, dist): """Convert mouse x, y movement into x, y, z rotations""" rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi ================================================================================ Example 1314 ================================================================================ Target: invalid header:', Prediction: ick header', resource['resource_type'], resource['resource_name']) raise ValueError( 'The header is not valid, it must be base64 encoded.') return header def _parse_resource(self, resource): """Deserializes a resource ================================================================================ Example 1315 ================================================================================ Target: pp_1, pp_2 in pairs: Prediction: ith, (p, q) in pairs: if p == q: kihs.append(KnobIntoHole(p, q, hole_size=hole_size, cutoff=cutoff)) else: kihs.append(KnobIntoHole( ================================================================================ Example 1316 ================================================================================ Target: data, period) Prediction: data, period) lower_percent = lower_percent * 100 return ema(data, period, lower_percent) def upper_price_channel(data, period, upper_percent): """ Upper Price Channel. Formula: upc ================================================================================ Example 1317 ================================================================================ Target: name = self.name Prediction: name = self.name expanded_variables.append(one_d_variable) return expanded_variables def expand_variables(self): """ Builds a list of variables representing current variable. Examples: For single dimensional variable, it is returned ================================================================================ Example 1318 ================================================================================ Target: SpiceEKAttDsc() Prediction: c_charP(cindex) return (table, column, attdsc) def _default_len_out(table, cindex, lenout=_default_len_out): """ Return attribute information about a column belonging to a loaded EK ================================================================================ Example 1319 ================================================================================ Target: ext_hook=ext_type_decoder) Prediction: ext_hook=ext_type_decoder, encoding=encoding, _msgpack_module=msgpack) if not isinstance(ret, list): raise TypeError("msgpack.loads() returned a list") return ================================================================================ Example 1320 ================================================================================ Target: self.P = self.P - dot(self.K, self.S).dot(self.K.T) Prediction: self.P = self.P + dot(self.K, self.P) self.x_post = self.x.copy() self.P_post = self.P.copy() return def _get_covariance(self, z, R ================================================================================ Example 1321 ================================================================================ Target: simplices Prediction: simplices # If we have a precomputed distance matrix, we can use it to compute the # distance between nodes. if self.cover.metric == "precomputed": if self.cover.metric == "cosine": # Compute the distance between nodes ================================================================================ Example 1322 ================================================================================ Target: func(port, vlan_id, device_id, host_id, vni, is_provider) Prediction: return if is_provider: # Provider vlan. if not missing_fields: return # Check if the vlan is a provider vlan. if not self._is_valid_vlan(vlan_id): return ================================================================================ Example 1323 ================================================================================ Target: css_selector = self.convert_to_css_selector(selector, by=by) Prediction: if new_value is not None: if not self.is_disabled(): if self.is_disabled(): return self.set_value(orginal_selector, new_value, by=by) else: self.set_value( ================================================================================ Example 1324 ================================================================================ Target: name].__class__, Attribute): Prediction: name], AbstractNode): return True else: return False return False def attribute_exists(self, name): """ Returns if given attribute exists in the node. Usage:: >>> node_a = AbstractNode("MyNodeA ================================================================================ Example 1325 ================================================================================ Target: path_dirs[path_dir] += urls[url] Prediction: path_dirs.add(path_dir) return path_dirs def get_urls_from_file(file_name): ''' Takes a StringCounter of normalized URL and parses them into a list of URL. The file name is ================================================================================ Example 1326 ================================================================================ Target: raise InvalidMessageError(error_msg) Prediction: raise InvalidMessageError(error_msg) else: existing_ids.append(message.msgid[1:3]) if checker_id is None: raise InvalidMessageError("Inconsistent checker part in message id " "{}".format( ================================================================================ Example 1327 ================================================================================ Target: index = list() Prediction: for ts in range(start_ts, max_ts): values.append(X[ts]) return pd.Series(values, index=X.index) def time_segments_aggregate_mean(X, interval, time_column, method=['mean ================================================================================ Example 1328 ================================================================================ Target: return (True, nums) Prediction: return True else: return False def check_unique(n, *nums): if len(nums) == n: return True else: return False def check_unique_array_sum_combinations(A, B ================================================================================ Example 1329 ================================================================================ Target: awaitable Prediction: uea.read_message(self, callback) def read_message_with_callback( self, callback: Callable[["Future[Union[None, str, bytes]]"], None] = None ) -> Awaitable[Union[None, str, bytes] ================================================================================ Example 1330 ================================================================================ Target: plugins Prediction: ublas.plugins.collect_plugins(plugins) def _filter_modules(self, modules, names): """ Filters the modules from the loaded modules. """ for module in modules: if module[0] == '__builtins__': ================================================================================ Example 1331 ================================================================================ Target: ret Prediction: irec(ret[0], ret[1]) def huffman_conv2bitstring_ascii(cls, s): # type: (str) -> Tuple[int, int] """ huffman_conv2bitstring_ascii converts a string into its asc ================================================================================ Example 1332 ================================================================================ Target: None: Prediction: ia_zero: sw_in_chan.append(above_zero) else: sw_in_chan.append(ia_zero) sw_out_chan = [] if above_zero is not ia_zero: sw_out_ ================================================================================ Example 1333 ================================================================================ Target: query_spec.maxSample = 1 Prediction: query_spec.interval = mor["interval_ms"] query_spec.batchSize = mor["batch_size"] query_spec.batchSize = mor["batch_size"] query_spec.batchSize = mor["batch_size"] query_spec. ================================================================================ Example 1334 ================================================================================ Target: list): Prediction: ict.List): return [to_url(d) for d in dois] elif isinstance(dois, ict.Dict): return [to_url(d) for d in dois.items()] else: raise ValueError("Invalid input ================================================================================ Example 1335 ================================================================================ Target: output_datacenter(gandi, dc, ['dc_name']) Prediction: gandi.echo('Available kernels:') gandi.echo('\n') gandi.echo(' %s' % (num + 1)) gandi.echo('\n') gandi.echo('Available kernels:') gandi.echo ================================================================================ Example 1336 ================================================================================ Target: self.threshold_key] < \ Prediction: self.threshold_key] > self.threshold_value): t += " " + str(self.data[k][self.threshold_key]) else: t += " " + str(self.data[k][self.threshold_key]) if self. ================================================================================ Example 1337 ================================================================================ Target: split_query = snowflake.connector.util_text.split_statements(sql_buf) Prediction: sql_buf.seek(0) sql_buf.truncate() sql_buf.seek(0) sql_buf.truncate() sql_buf.seek(0) sql_buf.truncate() sql_buf.seek( ================================================================================ Example 1338 ================================================================================ Target: quil_program.out()} Prediction: ustr.encode(quil_program.compiled_quil), "random-seed": random_seed} if not isinstance(quil_program, QuilProgram): raise TypeError("quil_program must be a Quil program object") if not isinstance( ================================================================================ Example 1339 ================================================================================ Target: = Dex(bitshares_instance=ctx.bitshares) Prediction: = Dex(ctx) dex.account = account dex.asset = account.asset dex.amount = amount dex.symbol = symbol dex.ratio = ratio dex.lock = True return dex.borrow(ctx, amount, symbol, ================================================================================ Example 1340 ================================================================================ Target: all_vs) Prediction: all_vs) def __eq__(self, other: Any) -> bool: """Checks whether two linear combinations are equal.""" if not isinstance(other, LinearDict): return NotImplemented all_vs = set(self.keys()) | set( ================================================================================ Example 1341 ================================================================================ Target: text = status Prediction: text = status else: text = status if encoding is None: if isinstance(text, str): text = text.encode(self.charset) else: text = text.encode(self.charset) if headers is None: ================================================================================ Example 1342 ================================================================================ Target: docker._query_json( Prediction: client.get( url_for(self.url_for(self.url_for(self.url_for(self.url_for(self.url_for(self.url_for(self.url_for(self.url_for(self.url_for( ================================================================================ Example 1343 ================================================================================ Target: dt.isoformat(), "backup" Prediction: dt.year, dt.month, dt.day) os.rename(target, new_filename) else: raise Exception("File not found: " + target) def _backup_to_file(path, filename): """ Backup a ================================================================================ Example 1344 ================================================================================ Target: in self.items], columns=colnames) Prediction: in attr.get_attribute_names(colnames)], columns=colnames) # Older versions if isinstance(fields, dict): fields = {name: name for name in fields.keys()} # If the fields are a list, we need to flatten ================================================================================ Example 1345 ================================================================================ Target: return inner Prediction: return inner @validate_busy def target_is_busy(target_id): """ A decorator that raises an exception if the specified target is busy. Expects the target ID to be either the 'target_id' param in kwargs, ================================================================================ Example 1346 ================================================================================ Target: icpt = self.clock_model['intercept'] Prediction: if clock_rate is None: clock_rate = self.clock_model['clock_rate'] if clock_rate is None: clock_rate = self.clock_model['clock_rate'] if clock_rate is None: clock_rate = ================================================================================ Example 1347 ================================================================================ Target: 4] Prediction: 1] location_segments.append('index') location = file_system.JoinPath(location_segments) index_path_spec = path_spec_factory.Factory.NewPathSpec( file_entry.type_indicator, location=location, ================================================================================ Example 1348 ================================================================================ Target: None Prediction: x.get_shape()[a] return tf.placeholder(shp, name=name) def _make_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape ================================================================================ Example 1349 ================================================================================ Target: }) Prediction: }) return context def get_context_data(self, **kwargs): """Add context data to request""" context = super().get_context_data(**kwargs) context.update({ 'form': self.form, 'form_class ================================================================================ Example 1350 ================================================================================ Target: result = to_categorical(result, nb_classes) Prediction: result = np.array(result, dtype=np.int32) return result def random_targets_with_label_noise(gt, nb_classes): """ Take in an array of correct labels and randomly select a different label for each label in ================================================================================ Example 1351 ================================================================================ Target: self._message = value Prediction: self._message = 'Unknown error message: %s' % value except (TypeError, ValueError): self._message = 'Unknown error message: %s' % value except (SyntaxError, ValueError): self._message = 'Unknown error message: %s ================================================================================ Example 1352 ================================================================================ Target: if not isinstance(value, (list, dict)): Prediction: if value is None: return None if isinstance(value, list): return [self._schema.get(item) for item in value] else: return value def _get_schema(self): """ Get the schema for this ================================================================================ Example 1353 ================================================================================ Target: data_attribute['modified'], Prediction: data_attribute['original'], data_attribute['modified'], data_attribute['value'] ) element.replace_with(auxiliar_element) def _fix_data_select_with_data_attributes(self): """ Replace all ================================================================================ Example 1354 ================================================================================ Target: sa) Prediction: sa) sock.listen(1) # Accept connections conn, addr = sock.accept() sock.close() # Add the socket to the list of sockets sockets.append(sock) # Start listening for connections conn.settimeout ================================================================================ Example 1355 ================================================================================ Target: else: Prediction: if sq.size == 0: return 0.0 else: return ht.sum(sq) / ht.size if low_frequency_cutoff is None: low_frequency_cutoff = htilde.delta_f if high ================================================================================ Example 1356 ================================================================================ Target: created = True Prediction: contact = self.create(Q(um_from_user=um_from_user, um_to_user=um_to_user) | Q(um_from_user=um_to_user, um_to_user=um_from_user)) ================================================================================ Example 1357 ================================================================================ Target: set_state('ABORTED') Prediction: sbi_ids = [] self.sbi_ids_count = 0 self.sbi_ids_count_max = 0 self.sbi_ids_count_min = 0 self.sbi_ids_count_max = 0 self. ================================================================================ Example 1358 ================================================================================ Target: = kwargs.pop('version', None) Prediction: = kwargs.pop('version', 'auto') assert_hostname = kwargs.pop('assert_hostname', False) environment = kwargs.pop('environment', os.environ) credstore_env = kwargs.pop('credstore_env', ================================================================================ Example 1359 ================================================================================ Target: old_seed = np.random.seed() Prediction: seed = 42 # generate data X, y = generate_data(n_samples=1000, n_features=60, n_groups=2, n_features_per_group=60, n_groups_per_feature=60, n_features_ ================================================================================ Example 1360 ================================================================================ Target: try: Prediction: if ip_address is not None: floating_ip = salt.utils.cloud.get_floating_ip(ip_address) else: floating_ip = salt.utils.cloud.get_floating_ip() else: flo ================================================================================ Example 1361 ================================================================================ Target: raise ValueError('VM Storage is empty') Prediction: raise ValueError('VM Storage is empty') if not deploy_params.vm_resource_pool: raise ValueError('VM Resource Pool is empty') if not deploy_params.vm_location: raise ValueError('VM Location is empty') if not deploy ================================================================================ Example 1362 ================================================================================ Target: cur_token) Prediction: cur_token) self.cur_token.type = TokenTypes.ASSIGN self.cur_token.assign_statement = True self.cur_token.value = self.cur_token.value.replace('\n', ' ') self.cur_token ================================================================================ Example 1363 ================================================================================ Target: last_waypoint_list: Prediction: urn:uuid:d8e4e9e8-f7e7-4b8e-b7d4-a7d9e9e8e9e: waypoint_list = [waypoint_list] if publish: transition_m. ================================================================================ Example 1364 ================================================================================ Target: encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off) Prediction: ue.VectorLen(off) return ret def Get(self, off): """Get retrieves the value of the vector whose offset is stored at "off" in this object.""" N.enforce_number(off, N.UOffsetTFlags) ================================================================================ Example 1365 ================================================================================ Target: known_fields = set(BlockHeader._meta.field_names) Prediction: provided_fields.update(self.provided_fields) provided_fields.update(self.provided_fields) provided_fields.update(self.provided_fields) if 'bloom' in kwargs: bloom = kwargs.pop('bloom ================================================================================ Example 1366 ================================================================================ Target: 'MyAppProject', Prediction: exception.message, exception.traceback, exception.extra, exception.extra_extra, exception.extra_extra_extra, exception.extra_extra_extra_extra, exception.extra_extra_extra_extra_extra, ================================================================================ Example 1367 ================================================================================ Target: self.auth_handler.auth_gssapi_with_mic( Prediction: self.auth_handler.auth_handler_thread = self.auth_handler_thread self.auth_handler.auth_handler_thread.start() self.auth_handler.auth_handler_thread.join() self.auth_handler.auth_handler_ ================================================================================ Example 1368 ================================================================================ Target: if persistent: Prediction: if not persistent: if new_device in self.boot_devices: self.boot_devices[new_device] = new_device return if new_device in self.boot_devices: self.boot_devices[new_device] = new ================================================================================ Example 1369 ================================================================================ Target: (%s>%s): %s', Prediction: ue') if not isinstance(command, AdbMessage): raise usb_exceptions.AdbProtocolError('Invalid command type') if not isinstance(command, AdbMessage): raise usb_exceptions.AdbProtocolError('Invalid command type') if not ================================================================================ Example 1370 ================================================================================ Target: import dummy_threading as threading Prediction: raise ImportError("Threading module not available") else: # The threading module is not available on Python 2. # Import the threading module in the main interpreter to get an # enumeration of the main interpreter threads. try: import threading ================================================================================ Example 1371 ================================================================================ Target: l1_regression_loss, Prediction: sum_absolute_error, target, loss_weight=loss_weight, per_example_weights=per_example_weights) def l2_regression( input_, target, name=PROVIDED, loss_weight=None, ================================================================================ Example 1372 ================================================================================ Target: 1) Prediction: 1) return att_weights def _masked_softmax_with_att_weights(F, att_score, att_weights, dtype): """Ignore the masked elements when calculating the softmax Parameters ---------- F : symbol or ndarray ================================================================================ Example 1373 ================================================================================ Target: = pkgs Prediction: ### this is a list of packages DETAILS['packages_installed'] ### this is a list of packages installed DETAILS['packages_available'] ### this is a list of packages available DETAILS['packages_available_installed'] ### this is a list of ================================================================================ Example 1374 ================================================================================ Target: decode_type='json', Prediction: headers={'X-Auth-Token': _auth_token}, ) return response.text def rm_app_by_id(id): ''' Remove the specified app from the server. CLI Example: .. code-block:: bash ================================================================================ Example 1375 ================================================================================ Target: service: %s...', name) Prediction: {}\n'.format(name)) self._start_service(init) def stop(self, name): """Stop a service """ self._stop_service(name) def _get_implementation(self, name): """Get the implementation of ================================================================================ Example 1376 ================================================================================ Target: users.append(self.print_user(user)) Prediction: user.save() users.append(user) return users def get_participant_ids(self, user=None): '''get participant ids, each having a model in the database. A headless experiment will use protected tokens, and interactive will be ================================================================================ Example 1377 ================================================================================ Target: link['mdl'](super_context) Prediction: # self._get_model_by_type(link_type) if linked_model is None: continue if linked_model.get('id') is None: continue if linked_model.get('id') == model.get('id'): ================================================================================ Example 1378 ================================================================================ Target: 'refUrl': self.refernce_url, Prediction: 'name': self.name, 'author': self.author, 'authorEmail': self.author_email, 'authorUrl': self.author_url, 'authorBio': self.author_bio, 'authorBioUrl': self.author_ ================================================================================ Example 1379 ================================================================================ Target: while not_done: Prediction: while not_done: try: page_token = protocol_request.get_page_token() if page_token is not None: yield protocol_response_class( protocol_response_class.objects.get( object_name= ================================================================================ Example 1380 ================================================================================ Target: DestroyRelation([ Prediction: destroy_relation(local_relation, remote_relation) async def delete_relation(self, local_relation, remote_relation): """Delete a relation from another application. :param str local_relation: Name of relation on this application :param str remote_relation: ================================================================================ Example 1381 ================================================================================ Target: _checkBlock(block) Prediction: assertTrue(block) self.assertTrue(blocks) for block in blocks: self.assertTrue(block) self.assertTrue(blocks) self.assertTrue(blocks) for block in blocks: self.assertTrue(block) ================================================================================ Example 1382 ================================================================================ Target: bool: Prediction: ustr: RENAME_PLOT = 'chunklabel' if type(ENCODING) is ustr: ENCODING = 'UTF-8' if type(CLEANUP) is ustr: CLEANUP = 'True' if type(QU ================================================================================ Example 1383 ================================================================================ Target: jid Prediction: ####### return data[0] def _gen_job_id(cur): ''' Generate a job id ''' sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) ================================================================================ Example 1384 ================================================================================ Target: ).warning("DB does not exist at {}. Setup is required.".format(self.path)) Prediction: self).error("No DB file found in %s" % self.path) return None if self.path.endswith(".sql"): self.path = self.path[:-3] if self.path.endswith(".py"): self. ================================================================================ Example 1385 ================================================================================ Target: self.vehicle_pos = VehiclePos(m) Prediction: else: return mavlink_msg_attitude_get(self, m) elif m.get_type() == 'GLOBAL_POSITION_FLOAT': if abs(m.lat) < 1000 and abs(m.lon) < 1000: return ================================================================================ Example 1386 ================================================================================ Target: = set() Prediction: = [] for target in targets: if target.is_thrift_target: basedirs.append(target.get_basedir()) return basedirs def calculate_include_paths(targets, is_thrift_target): """Calcul ================================================================================ Example 1387 ================================================================================ Target: appsettings.PARLER_LANGUAGES.get_default_language() Prediction: self.language_code return language_code def __str__(self): return self.language_code def __repr__(self): return self.language_code class QuerySet(object): """ A QuerySet is a list of ================================================================================ Example 1388 ================================================================================ Target: payload = Brizo._prepare_consume_payload( Prediction: return self.service_agreement_service.get_service_agreement(did, agreement_id, service_definition_id, signature, account_address, consume_endpoint) def get_service ================================================================================ Example 1389 ================================================================================ Target: Possibly " Prediction: ### {e} ###" "### {data} ###" "### {type_from} ###" "### {type_to} ###" "### {data} ###" "### {e} ###" " ================================================================================ Example 1390 ================================================================================ Target: is None: Prediction: ia not None: reactor.connect(main) else: reactor.connect(gtk.main_quit) return gtk.main() if __name__ == "__main__": gtk.main() ================================================================================ Example 1391 ================================================================================ Target: targets_by_platform Prediction: ### TODO: add a better error message ================================================================================ Example 1392 ================================================================================ Target: try: Prediction: raise libvirt.libvirtError( 'Domain %s is already defined' % domain.name) if logger is not None: logger.debug('Deleting domain %s' % domain.name) domain.delete() def domain_create(domain ================================================================================ Example 1393 ================================================================================ Target: try: Prediction: return chi_square / POP def pearson_C_calc_2(chi_square, POP): """ Calculate C (Pearson's C). :param chi_square: chi squared :type chi_square : float :param POP: population ================================================================================ Example 1394 ================================================================================ Target: del self._hash[key] Prediction: del self._hash[key] return node return None class _HashDict(dict): """A dict that uses a hash function to determine the order of keys.""" def __init__(self, *args, **kwargs): dict.__init__(self, ================================================================================ Example 1395 ================================================================================ Target: else accented_to_numbered(s) Prediction: ~~ s else s return s return s def to_pinyin_utf8(s, accented=True): """Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the ================================================================================ Example 1396 ================================================================================ Target: log.info( Prediction: return return_code else: return sys.exit(return_code) else: return sys.exit(return_code) def evaluate_stop_condition(errdata, stop_condition): """ Call the user-defined function: stop ================================================================================ Example 1397 ================================================================================ Target: return_targets = itertools.chain.from_iterable( Prediction: # and add it to the list of callers for caller in callers: if caller.startpoint is None: continue # get the immediate successor if caller.startpoint.addr is None: continue # get the immediate successor if ================================================================================ Example 1398 ================================================================================ Target: no-member Prediction: no-member req.send(msg.encode('utf-8'), 'text/plain', 405) # Check whether this event is supported if event in supported_events: msg = u'Event type %s is supported\n' % event self.log ================================================================================ Example 1399 ================================================================================ Target: if image.mode not in ('RGB',): Prediction: if icc_profile.profile_name == 'ICC_Profile_2020': profile = icc_profile.profile_name else: profile = 'ICC_Profile_2020' if profile not in image.profile_names: logger.debug('ICC ================================================================================ Example 1400 ================================================================================ Target: else: Prediction: elif diagram.TYPE == "module": self.write_modules(diagram) elif diagram.TYPE == "function": self.write_functions(diagram) elif diagram.TYPE == "classmethod": self.write_classmethods(diagram) ================================================================================ Example 1401 ================================================================================ Target: _containerSetPath(self, folderpath, specfiles) Prediction: if folderpath is None: folderpath = self.info.specfiles else: folderpath = self.info.specfiles.get(folderpath, None) if folderpath is None: folderpath = self.info.specfiles else: ================================================================================ Example 1402 ================================================================================ Target: auth.login(request, user) Prediction: return (user, created) return (None, None) def email_logout(request, *, email, **kwargs): """ Given a request, an email and optionally some additional data, ensure that a user with the email address exists, and log them out ================================================================================ Example 1403 ================================================================================ Target: else: Prediction: else: return list(_partition_lists[N]) def _partition_lists(N): """Return a list of partitions of the |N| binary nodes. Args: N (int): The number of nodes under consideration. Returns: list ================================================================================ Example 1404 ================================================================================ Target: v, "_utype"): Prediction: self, "_run_mode"): return self._run_mode if load: self._run_mode = v return self._run_mode def _get_run_mode(self, v): """ Getter method for run_mode ================================================================================ Example 1405 ================================================================================ Target: sql_get_with_http_info(owner, id, query, **kwargs) Prediction: sql_get_with_http_info(owner, id, query, **kwargs) return data, kwargs def sql_get_with_http_info(self, owner, id, query, callback=None, **kwargs): """ SQL query (via GET ================================================================================ Example 1406 ================================================================================ Target: dist = self._solver_module.check_solver(image_x, image_y, kwargs_lens) Prediction: return np.sqrt(np.sum((image_x - image_x).dot(image_y - image_y)) / (len(image_x) * len(image_y))) else: return np.sqrt(np.sum((kwargs_lens[0] ================================================================================ Example 1407 ================================================================================ Target: return response.json() Prediction: return response.json() def read_status(self): """Read the status of Vault. Supported methods: GET: /sys/status. Produces: 200 application/json :return: The JSON response of the request. :rtype: ================================================================================ Example 1408 ================================================================================ Target: wide_data[choice_col].isin(availability_vars.keys()).all(): Prediction: ia_data.has_alternatives(choice_col): raise ValueError("No alternatives for choice_col") if not ia_data.has_alternatives(wide_data[choice_col]): raise ValueError("No alternatives for choice_col") if ================================================================================ Example 1409 ================================================================================ Target: return { Prediction: return None def get_margin_requirement(self): """ Get margin requirements for instrument (futures only) :Retruns: margin : dict margin requirements for instrument (all values are ``None`` for non-futures instruments) ================================================================================ Example 1410 ================================================================================ Target: build_kw = {} if build_kw is None else build_kw Prediction: build_kw = {} if build_kw is None else build_kw if user_kw is not None: user_kw['user'] = user_kw if build_kw is not None: build_kw['build'] = build_kw return self ================================================================================ Example 1411 ================================================================================ Target: self._depth_stream.stop() Prediction: logging.warning('Primesense stopped depth stream') self._depth_stream.stop() if self._rgb_stream: logging.warning('Primesense stopped rgb stream') self._rgb_stream.stop() if self._depth_stream and self ================================================================================ Example 1412 ================================================================================ Target: try: Prediction: # Now we need to convert the param name to the # casing used by the API. completer = self._describer_creator.create_completer_query( service, api_operation_name, param) result = completer.describe_aut ================================================================================ Example 1413 ================================================================================ Target: else: Prediction: continue if cls._spec_callbacks is not None: if has_callback: cls._precomputed_specs.append(field[1]) else: cls._precomputed_specs.append(field[1]) elif ================================================================================ Example 1414 ================================================================================ Target: 'num': _get_as_int(rp_pyxb), Prediction: 'num': int(_get_attr_or_list(rp_pyxb, 'num')), 'blockedMemberNode': _get_attr_or_list(rp_pyxb, 'blockedMemberNode'), 'preferredMemberNode': _get_attr_ ================================================================================ Example 1415 ================================================================================ Target: session) Prediction: session) if session is None: session = requests.Session() return session def get_auth_header(self, key, value): """Return the auth header for the given key. :param key: The key to get the auth header for ================================================================================ Example 1416 ================================================================================ Target: if not hasattr(component, "__call__"): Prediction: if name is None: name = component.__name__ if before is None: before = name if after is None: after = name if first is None: first = True if last is None: last = True ================================================================================ Example 1417 ================================================================================ Target: return_document=pymongo.ReturnDocument.AFTER Prediction: version=version, date=date) LOG.info("Updated panel %s", panel_obj['panel_name']) return updated_panel def get_panel(self, panel_obj, version=None, date_obj=None): """Get a ================================================================================ Example 1418 ================================================================================ Target: return base_dir Prediction: return base_dir def get_parent_dir_recursive(base_dir, level=1): "Get the directory $level levels above $base_dir recursively." while level > 0: base_dir = os.path.dirname(base_dir ================================================================================ Example 1419 ================================================================================ Target: e.canignore = True Prediction: return events def _get_event(self, event): ''' Get the event from the queue. ''' return self.queue.get(event) def _get_event_by_id(self, event_id): ''' ================================================================================ Example 1420 ================================================================================ Target: roll=roll, keep_max=keep_max) Prediction: roll=roll, keep_max=keep_max) if redis_conn: counter.redis_conn = redis_conn return counter def get_bitmap_counter_by_host(self, redis_conn=None, host=' ================================================================================ Example 1421 ================================================================================ Target: return self._perform_post( Prediction: _validate_not_none('role_names', role_names) _validate_not_none('role_names', role_names) # Create the role _validate_not_none('role_name', role_name) _validate_not_none ================================================================================ Example 1422 ================================================================================ Target: v = v._utype(v) Prediction: return v._utype else: return _set_openflow_controller(v, load) def _get_openflow_controller(self, v, load=False): """ Getter method for openflow_controller, mapped from YANG variable / ================================================================================ Example 1423 ================================================================================ Target: value Prediction: ue.from_value(value) else: raise ValueError("Invalid value for PagingParams: %s" % value) def from_value(value): """ Converts specified value into PagingParams. :param value: value to be converted ================================================================================ Example 1424 ================================================================================ Target: output_file = os.path.join(databasepath, 'RefSeqSketchesDefaults.msh') Prediction: self.database_create(databasepath=databasepath, database='mash', target_url='ftp://ftp.ncbi.nih.gov/genomes/ASSEMBLY_REPORTS/' 'assembly_summary_refseq.txt') ================================================================================ Example 1425 ================================================================================ Target: 'ponder': ponder, Prediction: 'ponder': ponder, 'info': last_info} if split_text[0] == "ponder": ponder = split_text[1] break if split_text[0] == "move": move = split_text ================================================================================ Example 1426 ================================================================================ Target: else: Prediction: else: return 0 def columnCount(self, index): """Return the number of columns for the given index. :param index: the index :type index: :class:`QtCore.QModelIndex`: :returns: the column count ================================================================================ Example 1427 ================================================================================ Target: if build_source_directories is not None Prediction: if build_source_directories else build_source_directories.copy() ) # Build the zip file. with zipfile.ZipFile(path_to_dist, 'w', zipfile.ZIP_DEFLATED) as zip_file: ================================================================================ Example 1428 ================================================================================ Target: self.seconds, self.deciseconds) Prediction: self.seconds) def _get_date_time_string(self): """Returns the date-time string formatted as: "YYYY-MM-DD hh:mm:ss.#" Returns: str: date and time value formatted as: "YY ================================================================================ Example 1429 ================================================================================ Target: parameters') Prediction: iapp') lines.add(1, 'cdef public Parameters iapp2') lines.add(1, 'cdef public Parameters iapp3') lines.add(1, 'cdef public Parameters iapp4') lines.add(1 ================================================================================ Example 1430 ================================================================================ Target: opendnp3.FunctionCode.DISABLE_UNSOLICITED, Prediction: headers=headers) def do_enable_unsol(self, line): """Perform the function ENABLE_UNSOLICITED. Command syntax is: enable_unsol""" headers = [opendnp3.Header().AllObjects(60, 2), ================================================================================ Example 1431 ================================================================================ Target: 0: Prediction: ###: raise DelocationError( '{0} requires {1} but found {2}'.format( lib_path, require_archs, ###)) # Check dependencies if not check_verbose: all_copied[lib_ ================================================================================ Example 1432 ================================================================================ Target: None Prediction: """ self.last_build_date = self.soup.find('lastbuilddate').string """ self.last_build_date = self.soup.find('lastbuilddate').string """ self.last_build_date = self. ================================================================================ Example 1433 ================================================================================ Target: close() Prediction: close() return VISAStatus.SUCCESS except KeyError: pass return VISAStatus.FAILURE def get_session(self, session): """Returns the session associated with the specified logical identifier. :param session: Unique logical identifier to a session ================================================================================ Example 1434 ================================================================================ Target: message, Prediction: the_answer, self._get_text_answer_for_new_game()) def _get_text_answer(self): """Returns the text answer for the given question.""" return self._get_text_answer_for_new_game() def _ ================================================================================ Example 1435 ================================================================================ Target: for t in self._threads: Prediction: self._worker = self._worker_factory(self._connection) self._worker.start() self._worker.join() self._shutdown() # Wait for the worker to finish. self._worker.join() # Wait for the shutdown to ================================================================================ Example 1436 ================================================================================ Target: video: Prediction: ics_video_id: raise ValidationError('Video ID is required.') if not video: raise ValidationError('Video is required.') if not self.context.get('video_type'): raise ValidationError('Video type is required.') if ================================================================================ Example 1437 ================================================================================ Target: SynphotError( Prediction: SynphotError('Bin edges must have at least 2 values.') if edges.size > 1: raise exceptions.SynphotError('Bin edges must have at most 1 value.') if edges.size < 1: raise exceptions.SynphotError('Bin edges must have ================================================================================ Example 1438 ================================================================================ Target: 4: Prediction: 4: trace_id, span_id, sampled = fields else: raise ValueError('Invalid state header: %s' % fields) if sampled is not None: if sampled == 'true': sampled = True elif sampled == 'false ================================================================================ Example 1439 ================================================================================ Target: prior = pd.DataFrame(data=prior,index=prior_mat.col_names) Prediction: prior_data = self.map_prior_estimate post_data = self.map_posterior_estimate prior_data = prior_data.astype(float) post_data = post_data.astype(float) prior_data = ================================================================================ Example 1440 ================================================================================ Target: join(directory, filename) Prediction: join(directory, filename) if os.path.isfile(file_path): file_names.append(file_path) return file_names def listdir(directory): """Returns list of nested files and directories for local directory by path : ================================================================================ Example 1441 ================================================================================ Target: append(normalize_column) Prediction: append(normalize_column) if csv_reader is None: csv_reader = open(csv_file, 'r') else: csv_reader = csv.reader(csv_reader) if email_field is None: email_field = ================================================================================ Example 1442 ================================================================================ Target: set(ignored_modules) Prediction: set() ignored_classes = set() ignored_modules.add(owner.name) ignored_classes.add(owner.name) ignored_modules.add(owner.qualified_name) ignored_classes.add(owner.qualified ================================================================================ Example 1443 ================================================================================ Target: if not recurse: Prediction: def Walk(root='.', recurse=True, pattern='*'): ''' Generator for walking a directory tree. Starts at specified root folder, returning files that match our pattern. Optionally will also recurse through sub-folders. Parameters ---------- ================================================================================ Example 1444 ================================================================================ Target: default=False, Prediction: rome_name) def rackconnectv4(vm_): ''' Determine if server is using rackconnectv4 or not Return the rackconnect network name or False ''' return config.get_cloud_config_value( 'rackconnectv4 ================================================================================ Example 1445 ================================================================================ Target: parentName = "%s.%s" % (parentFieldName, self.name) Prediction: parentName = parentFieldName + '.' + self.name # If we have a parent, we need to figure out what the child encoder is. if parentFieldName in self.encoderNames: encoderName = self.encoderNames[parentFieldName] if encoder ================================================================================ Example 1446 ================================================================================ Target: Class][name] = CommandSubClass Prediction: Class].append(name) def register(Class, CommandSubClass, CommandSubClass.aliases): """A class decorator for Command classes to register.""" for name in [CommandSubClass.name()] + CommandSubClass.aliases(): if name in Class ================================================================================ Example 1447 ================================================================================ Target: offset += self._range_size Prediction: offset += self._current_offset + self._current_size elif whence == os.SEEK_SET: offset = self._current_offset if offset < 0: raise IOError('Invalid offset: {0:d} value less than zero.'.format( ================================================================================ Example 1448 ================================================================================ Target: pos in source_specs: Prediction: sample in source_specs: if sample is None: continue if sample[0] == 's': output[source] = sample else: output[source] = sample[1:] return output def sequencer_to_buffer ================================================================================ Example 1449 ================================================================================ Target: ENDC) Prediction: FAIL + " %s" % line.replace("\n", "\\n") + "\n" + " %s" % line.replace("\n", "\\n") + "\n" + " %s" % line.replace("\n", ================================================================================ Example 1450 ================================================================================ Target: tubing_data_path = os.path.join(os.path.dirname(__file__), "data", Prediction: return vol_per_rev_LS(id_number) def vol_per_rev_LS_per_rev(id_number): """Look up the volume per revolution output by a Masterflex L/S pump through L/S tubing of the given ID number. ================================================================================ Example 1451 ================================================================================ Target: if self.timezone_offset is not None: Prediction: if d.year < 2000: return d else: return self.writeDate(d.year) + ' - ' + self.writeDate(d.month) + ' - ' + self.writeDate(d.day) def writeDate(self, ================================================================================ Example 1452 ================================================================================ Target: line_stats_match = line_stats_re.match(line) if line else None Prediction: if line.startswith('pcalls'): count += 1 elif line.startswith('pstats'): stats_list.append(line) line = line.strip('\r\n ') elif line.startswith('ncalls ================================================================================ Example 1453 ================================================================================ Target: 0): Prediction: 0): raise ValueError("endPercentage has to be in [0.0, 100.0].") if not (0.0 <= startDate <= endDate): raise ValueError("startDate has to be in [0.0, endDate].") # ================================================================================ Example 1454 ================================================================================ Target: for x in dataframe[value].values]} Prediction: for x in categories]} if output == 'list': result.append(dataset) elif output == 'dict': result.append(OrderedDict(dataset)) else: result.append(OrderedDict(dataset, output=output)) ================================================================================ Example 1455 ================================================================================ Target: size) Prediction: size) container.mount(volume) return container def unmount(self, volume): """Unmounts a BDE container. Uses key material provided by the :attr:`keys` attribute. The key material should be provided in the same format as to : ================================================================================ Example 1456 ================================================================================ Target: cmd, "Bad message" Prediction: cmd, msg conn.send_message(cmd) except: pass else: raise Exception('No connection with id: %s' % id) return True def get_connection(session, id): "Returns the connection with ================================================================================ Example 1457 ================================================================================ Target: match_path_to_api_path( Prediction: api_path_from_path(path) except ValueError: raise InvalidPathException( 'Invalid path: %s' % path ) if not api_path: raise InvalidPathException( 'Invalid path: %s' % path ================================================================================ Example 1458 ================================================================================ Target: :ECS::Service', Prediction: ECS:Service', resource_id=cluster['clusterName'] ) self.limits['Container Instances per Cluster']._add_current_usage( cluster['registeredContainerInstancesCount'], aws_type='AWS::ECS::ContainerInstance', ================================================================================ Example 1459 ================================================================================ Target: dt Prediction: ustime(dt) def utc_to_local(dt, tz=None): """ Converts UTC datetime object to the specific timezone. :param dt: the UTC datetime object to convert. :param tz: the timezone to convert the UTC datetime object info ================================================================================ Example 1460 ================================================================================ Target: json.dump(saved_tokens, f) Prediction: json.dump(saved_tokens, f) return saved_tokens def get_token_filename(self): """ Return the filename of the token file. """ return os.path.join(self.token_dir, 'token.json') ================================================================================ Example 1461 ================================================================================ Target: res = "" Prediction: return bytes(bits) def bits_to_bytes(bits): """Convert the bit list into bytes. (Assumes bits is a list whose length is a multiple of 8) """ if len(bits) % 8 != 0: raise Exception(" ================================================================================ Example 1462 ================================================================================ Target: stddev = math.sqrt(2.0 / n_inputs) Prediction: return tf.contrib.layers.xavier_initializer( n_inputs, n_outputs, stddev=0.02, seed=None, name='xavier_init_relu') return tf.contrib.layers.xavier_initial ================================================================================ Example 1463 ================================================================================ Target: handler for '%s'; processing " Prediction: ###%s###; skipping", self.name, plugin_name, sourcepath ) continue result[plugin_name] = sourcepath return result def generate_handler_sourcepath_for_module( self, toolchain, spec, loader ================================================================================ Example 1464 ================================================================================ Target: df_slice = df_slice Prediction: df_slice = self.df[item_names] elif tilt_corr == 100: # use the entire DataFrame df_slice = self.df elif tilt_corr == 0: # use the entire DataFrame df_slice = self. ================================================================================ Example 1465 ================================================================================ Target: return np.array(sigma_v_effs) Prediction: return sigma_v_effs def get_v_total_stress_at_depth_array(self, z): """ Determine the vertical total stress at depth z, where z can be a number or an array of numbers. """ if not hasattr ================================================================================ Example 1466 ================================================================================ Target: = np.array(data) Prediction: ia = np.array(data, dtype=np.float64) except: np_data = np.array(data, dtype=object) # If the data is not a numpy array, we need to convert it to a numpy array if np_data is None ================================================================================ Example 1467 ================================================================================ Target: = config.get('REMEMBER_COOKIE_NAME', COOKIE_NAME) Prediction: = config.SESSION_COOKIE_NAME if cookie_name in config.SESSION_COOKIE_NAMES: user = config.SESSION_COOKIE_NAMES[cookie_name] else: user = config.REQUEST_COOKIE_ ================================================================================ Example 1468 ================================================================================ Target: return callback(config) Prediction: if callback: self._callback(index, kwargs) def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_index_fwdl_entries_index_index_index_index_index_index_index_index ================================================================================ Example 1469 ================================================================================ Target: None Prediction: ### FILENAME ### if not is_marginal(model): return ### FILENAME ### if not is_marginal(column): return ### FILENAME ### if not is_marginal(model, column): return ================================================================================ Example 1470 ================================================================================ Target: deprecated Prediction: not supported. This is a known bug in pandas. Please report it to the pandas-dev mailing list. """) raise ValueError(msg) elif is_dtype_equal(dtype, np.dtype("M8", "ns")): ================================================================================ Example 1471 ================================================================================ Target: VOCAB_ANALYSIS_FILE % source_column)): Prediction: name)): continue if not file_io.file_exists(os.path.join(output_dir, name + '.json')): continue if not file_io.file_exists(os.path.join(output_dir, name + '.json')): ================================================================================ Example 1472 ================================================================================ Target: self[self._KEYS.SOURCE] = uniq_cdl(self_aliases + other_aliases) Prediction: self._aliases.append(self_aliases) # Store alias to `other` other._aliases.append(other_aliases) # Merge aliases lists self_aliases = [self_aliases] + other_aliases ================================================================================ Example 1473 ================================================================================ Target: )", 1, self) Prediction: self, drawDC=None)") if drawDC is None: drawDC = self.renderer self.drawDC = drawDC self.renderer.draw(self) def draw_text(self, text, x, y, font, color, ================================================================================ Example 1474 ================================================================================ Target: = 5 Prediction: = 5 MAV_MODE_TEST2 = 6 MAV_MODE_TEST3 = 7 MAV_MODE_TEST4 = 8 MAV_MODE_TEST5 = 9 MAV_MODE_TEST6 ================================================================================ Example 1475 ================================================================================ Target: ) Prediction: ) if set_data: records.append(set_data) return records def downloadRecords(search_result, from_doc=1): """ Download `MAX_RECORDS` documents from `search_result` starting from ` ================================================================================ Example 1476 ================================================================================ Target: return {'version': __version__, 'parallel_read_safe': True} Prediction: app.add_config_value('jinjaapi_autodoc_exclude_paths', [], 'env') app.add_config_value('jinjaapi_autodoc_include_from_all', True, 'env') app.add_config_value(' ================================================================================ Example 1477 ================================================================================ Target: if (rez != None): Prediction: if isinstance(rez, int): rez = rez.split('-', 1)[0] if rez: return rez if not args.get('--'): return None if not args.get('--'): return None ================================================================================ Example 1478 ================================================================================ Target: try: Prediction: if step < 0: is_inversion = True elif step > 0: is_inversion = False if is_inversion: return self.invert(step) if step < 0: return self.invert(-step) ================================================================================ Example 1479 ================================================================================ Target: else: Prediction: else: raise return path def make_absolute_path(path): """ Make a path absolute. This function handles the case where two threads try to create a path at once. """ if not os.path.exists(path): ================================================================================ Example 1480 ================================================================================ Target: *tuple( Prediction: func, num_splits=num_splits, other_axis_partition=other_axis_partition, maintain_partitioning=maintain_partitioning, **kwargs ) ) ] else: return [ ================================================================================ Example 1481 ================================================================================ Target: # or: AuthSourceLDAP(server_config, id=1), Prediction: # LDAP authentication source ID org=org, # LDAP user ID password=None, # LDAP password email=None, # LDAP email address first_name=None, # LDAP first name last_name=None, ================================================================================ Example 1482 ================================================================================ Target: WHERE {{ Prediction: FROM chebi_xref_triples WHERE xref_id IN (SELECT xref_id FROM chebi_xref_triples WHERE xref_id = %s) """ % (prefix) res = db.execute(query) return res. ================================================================================ Example 1483 ================================================================================ Target: raise_for_status() Prediction: status_code = 200 response.json() if response.status_code == 200: return response.json() else: raise AirflowException('Error while making API call: ' + response.status_code) except Exception as ================================================================================ Example 1484 ================================================================================ Target: else: Prediction: # to the map if not map_db_refs.get('value'): # If it's not in the grounding map, then it's not # in the grounding map if not mapped_to_agent_json: # If it's not in ================================================================================ Example 1485 ================================================================================ Target: 0]) Prediction: 0]) editor.setObjectName(opts[1]) editor.setObjectName(opts[2]) editor.setObjectName(opts[3]) editor.setObjectName(opts[4]) editor.setObjectName(opts[5]) ================================================================================ Example 1486 ================================================================================ Target: self._post(url=url, Prediction: ueber_json.post(url, params=params, content_type="application/json") def getLogSettings(self, logLocation, logLevel="WARNING", maxLogFileAge=90): """ gets the log settings for the portal site Inputs: ================================================================================ Example 1487 ================================================================================ Target: sha256.update(chunk) Prediction: sha256.update(chunk) return sha256.hexdigest() def get_registry_key(key_name, key_type): """ Get the registry key for a given key name and key type. :param key_name: Name of registry key ================================================================================ Example 1488 ================================================================================ Target: string_types): Prediction: string_types): return address elif isinstance(address, six.text_type): return address.decode('utf-8') elif isinstance(address, six.binary_type): return address.decode('utf-8') else: raise Value ================================================================================ Example 1489 ================================================================================ Target: return pillar_dbs Prediction: return pillar_dbs def show_dbs_all(*dbs): ''' Show databases configuration from pillar. Filter by `*args` CLI Example: .. code-block:: bash salt '*' oracle.show_dbs_all ================================================================================ Example 1490 ================================================================================ Target: GRAFANA_TARGETS Prediction: cherrypy.request.handler = cherrypy.request.handler or cherrypy.request.handler_class( cherrypy.request.method, cherrypy.request.path, cherrypy.request.params, cherrypy.request.query_string, cherrypy.request.headers ================================================================================ Example 1491 ================================================================================ Target: if days: Prediction: if days: queryset = queryset.filter( day=days, user=self.request.user, timestamp__gte=datetime.now() ) return queryset def get_context_data(self, **kwargs): ================================================================================ Example 1492 ================================================================================ Target: log_verbose("Seeding : CRED0 to the front of the line!") Prediction: cred0["username"] = cred0["username"] + "@" + cred0["password"] cred0["password"] = cred0["password"] + "@" + cred0["username"] cred0["username"] = cred0["username"] + "@" + cred0["password ================================================================================ Example 1493 ================================================================================ Target: service_name, Prediction: service_name, resource_name, base_class=base_class) except kotocore.exceptions.NotFound: return None def get_resource_by_id(self, service_name, resource_name, id): """ Returns a ================================================================================ Example 1494 ================================================================================ Target: (default: local timezone)') Prediction: iautomatically detected (default: UTC)') parser.add_argument('-t', '--timezone', help='Timezone of Remind file iautomatically detected (default: UTC)') parser.add_argument('-c', '--calendar', ================================================================================ Example 1495 ================================================================================ Target: timezone = self.reverse_timezone(location, at_time, timeout) Prediction: if at_time is None: at_time = timezone(location, at_time) if at_time is None: raise KeyError('No timezone for %s' % location) if timeout is not None: at_time = timezone ================================================================================ Example 1496 ================================================================================ Target: ValueError: Prediction: erts.ParseError as e: raise erts.ParseError(e) def update_value(self, key, value): """Update value with key and value""" if key in self.keys: self.keys[key].append(value) ================================================================================ Example 1497 ================================================================================ Target: if description: Prediction: if description: body['description'] = description if ip_version: body['ip_version'] = ip_version if source_ip_address: body['source_ip_address'] = source_ip_address if destination_ip_address ================================================================================ Example 1498 ================================================================================ Target: getIfStats() Prediction: getStats() return ifStats def getIfaceStats(self, ifIndex): """Return dictionary of Traffic Stats for each Wanpipe Interface. @param ifIndex: Index of interface. """ ifInfo = netiface.NetI ================================================================================ Example 1499 ================================================================================ Target: ET.SubElement(route_map, "action-rm") Prediction: ET.SubElement(route_map, "action-rm") action_rm_key.text = kwargs.pop('action') route_map.append(name_key) route_map.append(action_rm_key) route_map.append ================================================================================ Example 1500 ================================================================================ Target: applied') Prediction: ==========================================') print(' * %s' % (len(migrations_applied))) print(' * %s' % (len(get_migrations_files(path)))) print(' * %s' % (len(get_migrations_files(path ================================================================================ Example 1501 ================================================================================ Target: is dict: Prediction: ia str: for name in on: if type(name) is not str: raise TypeError("Join keys must each be a str.") join_keys[name] = name elif type(on) ia list: for name in on: ================================================================================ Example 1502 ================================================================================ Target: execute("""SHOW STORAGE ENGINES;""") Prediction: execute("SELECT engine_name FROM storage_engines") engine_names = cur.fetchall() cur.close() return engine_names def getStorageEngine(self, engine_name): """Returns storage engine for given storage engine name. ================================================================================ Example 1503 ================================================================================ Target: for hostid in diff | existing_host_ids] if diff else [] Prediction: for hostid in diff] def _diff_and_merge_host_list_with_host_ids(defined, existing): ''' If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent some externally ================================================================================ Example 1504 ================================================================================ Target: return languages Prediction: return languages class Language(object): """ A language object. This class is used to represent a language in a database. """ def __init__(self, name, alpha_2=None): """ :param name: The name of ================================================================================ Example 1505 ================================================================================ Target: = tf.py_func( Prediction: xt = tf.cast(tensor, tf.int32) if max_outputs < 1: return tf.constant( "", tf.int32, tf.int32, tf.int32, tf.int32, tf.int32, tf.int32) ================================================================================ Example 1506 ================================================================================ Target: if self.flushed: Prediction: self.write_header(body) def write_header(self, body): """Write to header. :param body: content to write to header :except TChannelError: Raise TChannelError if the response's flush() has been called ================================================================================ Example 1507 ================================================================================ Target: True Prediction: ### else: self.locked_status = False return ### def release(self): """Dummy implementation of release(). For blocking calls, self.locked_status is automatically set to False and returned appropriately based on value of ``wait ================================================================================ Example 1508 ================================================================================ Target: state, index=index: Prediction: ia: self.tabToolTip(index), toggled_text=text[offset:], toggled_text_color=self.tabToolTipColor(index), toggled_text_color_hover=self.tabToolTipColor( ================================================================================ Example 1509 ================================================================================ Target: total Prediction: 1 def calculate_check_digit(gtin): '''Given a GTIN (8-14) or SSCC, calculate its appropriate check digit''' reverse_gtin = gtin[::-1] total = 0 count = 0 for char in ================================================================================ Example 1510 ================================================================================ Target: in self.tkvariables: Prediction: ~~ self.tkvariables: setattr(container, keyword, self.tkvariables[keyword]) return container def get_variable(self, container, varname): """Get a variable from the container. The container must be a Tkinter widget. ================================================================================ Example 1511 ================================================================================ Target: = 4: # A * 4 == A SLA 2 Prediction: 3: # A * 3 == A SLA 2 output.append('add a, a, a') output.append('push af') return output if op2 == 4: # A * 4 == A SLA 3 output.append('add a ================================================================================ Example 1512 ================================================================================ Target: == 'i': Prediction: ### dtype is float64 or float32 arr = arr.astype(np.float64) elif arr.dtype.kind == 'i' and arr.dtype.itemsize == 1: arr = arr.astype(np.float32) elif arr ================================================================================ Example 1513 ================================================================================ Target: f)) Prediction: f)) else: if not os.path.isdir(dest): os.makedirs(dest) files = os.listdir(dest) for f in files: self._recursive_overwrite(os.path.join(src ================================================================================ Example 1514 ================================================================================ Target: return self.process_response(response, resources.PlaceOrders, elapsed_time, lightweight) Prediction: if response.status_code == 200: return response if response.status_code == 400: raise exceptions.PlaceOrdersError(response.status_code, response.reason) if response.status_code == 404: raise exceptions.PlaceOrders ================================================================================ Example 1515 ================================================================================ Target: None Prediction: ustat(fname) if fstat['st_mtime'] > remotef['st_mtime']: # download the file LOG.info("Downloading %s", fname) sftp.get(target_name, fname) ================================================================================ Example 1516 ================================================================================ Target: TypeError: Prediction: ia.AttributeError: raise ia.InvalidArgumentError("Invalid fields: %s" % fields) for item in items: if isinstance(item, ia.Field): field = item.name if field in self.fields: result[field ================================================================================ Example 1517 ================================================================================ Target: args: Prediction: args: outfile=args[0] elif '-F' in args: outfile=args[0] elif '-f' in args: outfile=args[0] elif '-F' in args: outfile=args[ ================================================================================ Example 1518 ================================================================================ Target: pdfs: Prediction: ustr_to_pdf(pdfs): summary.addPage(pdf) summary.close() return summary.getOutput() def summarise_pdfs(pdfs): """ Collate the first page from each of the PDFs provided into a single ================================================================================ Example 1519 ================================================================================ Target: rs = self.tx(ret) Prediction: return ret def dump_edn_val(v): """ dump the value of an attribute """ return v.replace(':db/', ':db/retract') def dump_edn_val_list(v): """ dump the value ================================================================================ Example 1520 ================================================================================ Target: bind() Prediction: bind() def unbind(self): """Unbind this Shader from the current program. Any Mesh.draw() calls after unbind() will have their data processed by this Shader. To bind again, call Shader.bind(). Example:: sh ================================================================================ Example 1521 ================================================================================ Target: self.before_request_funcs[None] Prediction: self.url_value_preprocessors[None] if blueprint is not None: functions = chain(functions, self.url_value_preprocessors[blueprint]) # type: ignore for function in functions: function(request.endpoint, request. ================================================================================ Example 1522 ================================================================================ Target: 'monitoring_problems', wait=True) Prediction: self.app.conf.scheduler_conf.scheduler_name) if sched_res: res['problems'][scheduler_link.con.get(self.app.conf.scheduler_conf.scheduler_name)] = sched_res return res ================================================================================ Example 1523 ================================================================================ Target: BAND, Prediction: BAND, self._KEYS.ENERGY)) else: err_str = ("Has `{}` or `{}`".format(self._KEYS.FLUX, self._KEYS.FLUX_DENSITY) + ================================================================================ Example 1524 ================================================================================ Target: len(list_date_obs) Prediction: len(list_date_obs) for i in range(num_date_obs): if list_date_obs[i] == "obs": pol_lower_boundary = bounddict['contents'][slitlet_label][list_date_obs[i]] ================================================================================ Example 1525 ================================================================================ Target: 2 Prediction: 2.0 y = (y1 + y2) / 2.0 center = (x, y) # render to a meta surface if self._render_to_meta: meta = self._render_to_meta(center) self._ ================================================================================ Example 1526 ================================================================================ Target: _format = QTextCharFormat() Prediction: _style = QTextCharFormat.Style() _style.setForeground(color) _style.setFont(style) return _style class QTextCharFormat(QTextCharFormat): """A QTextCharFormat subclass that supports the Q ================================================================================ Example 1527 ================================================================================ Target: self.insert(len(self._moments), moment_or_operation_tree, strategy) Prediction: if isinstance(moment_or_operation_tree, ops.Moment): moment_or_operation_tree = moment_or_operation_tree.to_json() if isinstance(moment_or_operation_tree, ops.OP_TREE): moment_or ================================================================================ Example 1528 ================================================================================ Target: generate_payload(**locals()) Prediction: { "chat_id": chat_id, "message_id": message_id, } if self.can_delete_messages(message_id): payload["can_delete_messages"] = True if self.can_post_messages( ================================================================================ Example 1529 ================================================================================ Target: rotation = Quaternion([roll, pitch, yaw]) Prediction: quat.rotate(roll, pitch, yaw) return quat def rotate_quat(attitude, roll, pitch, yaw): ''' Returns rotated quaternion :param attitude: quaternion [w, x, y , z] ================================================================================ Example 1530 ================================================================================ Target: err2 += (theta_n ** 2 / (major * minor)) * ((source.err_a / source.a) ** 2 + (source.err_b / source.b) ** 2) Prediction: err2 = err2 * np.sqrt(2 / rho2('amp')) # error in the integral flux err_int_flux = (source.err_int_flux * np.sqrt(2 / rho2('int_flux')) ** 2) # ================================================================================ Example 1531 ================================================================================ Target: self.ioComplete.clear() Prediction: self.ioState = PENDING_IO # add this to the group self.ioGroup.add(iocb) # add this to the group self.ioGroup.add(iocb) # add this to the group self ================================================================================ Example 1532 ================================================================================ Target: secs, msecs, 0x15, code, 1) Prediction: # left_motor, # right_motor, # secs, # msecs, # left_motor, # right_motor, # secs, # msecs, # left_motor, # ================================================================================ Example 1533 ================================================================================ Target: 1/3.) Prediction: 1/3.) def helical_turbulent_Nu_Schmidt(Re, Pr, Di, Dc): r'''Calculates Nusselt number for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions, using the method of Sch ================================================================================ Example 1534 ================================================================================ Target: if replace_alpha: Prediction: if replace_alpha: new_mode = 'RGBA' else: new_mode = 'RGBA' if is_grayscale: new_mode = 'L' else: new_mode = 'RGB' if ================================================================================ Example 1535 ================================================================================ Target: out_port = self.cdim - 1 Prediction: out_port = self.last_port if in_port is None: in_port = self.last_port return self.feedback(out_port, in_port) def feedback(self, *, out_port=None, in_port=None ================================================================================ Example 1536 ================================================================================ Target: = 0 Prediction: = row[0] max_lengths[col_index] = max(max_lengths.get(col_index, 0), max_allowed_lengths) ignore_columns.append(col_index) if max_allowed_lengths is None: ================================================================================ Example 1537 ================================================================================ Target: authn_statem Prediction: ustr.get_authn_statement(authn_statem) if _authn_statement: _authn_statement.authn_statement = authn_statem _authn_statement.authn_statement_ref = authn_decl_ref ================================================================================ Example 1538 ================================================================================ Target: result = value Prediction: if isinstance(value, (list, tuple)): return iter(value) elif isinstance(value, (tuple, list)): return ensureiterable(value, exclude=exclude) else: raise TypeError("value must be a list or tuple") def ================================================================================ Example 1539 ================================================================================ Target: address, port, flow, scope = sockaddr Prediction: if socktype == socket.SOCK_STREAM: return self._gethostbyname_ipv4(hostname) elif socktype == socket.SOCK_DGRAM: return self._gethostbyname_ipv6(hostname) ================================================================================ Example 1540 ================================================================================ Target: 'refresh_token', Prediction: ue.grant_type, 'client_id': ue.client_id, 'client_secret': ue.client_secret, 'code': ue.code, 'redirect_uri': ue.redirect_uri, 'grant_type ================================================================================ Example 1541 ================================================================================ Target: is not None: Prediction: ia_index: return self.indexes else: return default_indexes def get_indexes_by_type(self, type): """Returns the list of indexes to act on.""" return self.indexes_by_type[type] ================================================================================ Example 1542 ================================================================================ Target: fv['key'] = f Prediction: for k, v in fv.items(): if k not in self.multi_attrs: continue fv[k] = self.multi_attrs[k] else: fv = fv.get(self.multi_attrs[f]) ================================================================================ Example 1543 ================================================================================ Target: uname = bjam.variable("JAMUNAME") Prediction: if bjam.variable("CYGWIN"): return True else: return False else: return False def is_cygwin (): """ Returns true if running on cygwin, whether in cygwin or not. ================================================================================ Example 1544 ================================================================================ Target: _html Prediction: html def get_html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': ' ================================================================================ Example 1545 ================================================================================ Target: idx Prediction: idx class Docstring(object): def __init__(self, data): self.data = data self.opt = {} def get_elem_index(self, data, starting=True): """Get from a docstring the next option. ================================================================================ Example 1546 ================================================================================ Target: cmd_ep = self.commands[name] Prediction: return self.commands[name] else: search_args = search_args[1:] raise ValueError('No command found') def find_command(self, argv): """Given an argument list, find a command and return the processor and any ================================================================================ Example 1547 ================================================================================ Target: = context Prediction: ~~ context class Graph(object): """A graph is a dictionary of nodes and edges""" def __init__(self, nodes, edges): """Create a graph with the given nodes and edges""" self.nodes = nodes self.edges = edges def ================================================================================ Example 1548 ================================================================================ Target: "latitude", Prediction: "waypoint", "track", "on-ground", "altitude", "true_track", "barometric_altitude", "true_track_flag", "on-ground_flag", ], index= ================================================================================ Example 1549 ================================================================================ Target: edges.extend(c0) Prediction: edges.extend(p1) edges.extend(p2) edges.extend(v0) edges.extend(v1) edges.extend(v2) return edges def draw_edges(self, edges): """Draws ================================================================================ Example 1550 ================================================================================ Target: self.update(params, values) Prediction: self._parent.trigger_update(params, values) def trigger_delete(self, params, values): """ Notify parent of a parameter change """ if self._parent: self._parent.trigger_delete(params, values) else: ================================================================================ Example 1551 ================================================================================ Target: result.get('types', []) Prediction: result.json() if values: return values # Error return False def get_poi_types_by_id(self, **kwargs): """Obtain POI types by ID. Args: poi_id (int ================================================================================ Example 1552 ================================================================================ Target: services = pyconnman.ConnManager().get_services() Prediction: for service in connman.get_services(): serv.append(service.name) return serv def _get_services_by_name(name): ''' Returns a list with all connman services ''' serv = [] for service ================================================================================ Example 1553 ================================================================================ Target: unit in units[race]: Prediction: ue in units[race]: print(' %s = %s' % (ue.unit_name, ue.unit_id)) print(' """%s units."""' % name) for ue in units[race]: print(' %s = ================================================================================ Example 1554 ================================================================================ Target: _show_mpl_backend_errors) Prediction: shellwidget.show_mpl_backend_errors) self.shellwidget.silent_execute( "get_ipython().kernel._show_mpl_backend_errors()") def _get_mpl_backend_errors(self): """ Show possible ================================================================================ Example 1555 ================================================================================ Target: missing_bytes_to_read = new_pos - self._current_lob_length Prediction: self.data.seek(offset, whence) return new_pos def read(self, size=None): """Read data from the database. This method will read the data from the database and return it as a byte array. If size is specified, it ================================================================================ Example 1556 ================================================================================ Target: status_code == 200: Prediction: status_code == 200: data = r.json() projects = data['results'] else: return None for project in projects: title = project['title'] pageid = project['pageid'] if not title: continue ================================================================================ Example 1557 ================================================================================ Target: ), Prediction: ) ) def _apply_inbound_message_filter(f): """ Apply the inbound message filter to the incoming message. :param f: The function to apply the inbound message filter to. :return: The result of applying the in ================================================================================ Example 1558 ================================================================================ Target: ) Prediction: ) def redirect_with_status( to, headers=None, status=302, content_type="text/html; charset=utf-8" ): """Abort execution and cause a 302 redirect (by default). :param to: path or fully qualified ================================================================================ Example 1559 ================================================================================ Target: None, None Prediction: ### TODO: check if this is a bug ### def get_path_alias_regex(self, path): """ Evaluate the registered path-alias regular expressions """ for regex, func in self._alias_map: match = re.match(regex, path ================================================================================ Example 1560 ================================================================================ Target: State.OFF Prediction: State.UNKNOWN else: await self.send_cmd('PowerOff') self._state = State.PLAYING_RECORDED_TV self._state = State.PLAYING_LIVE_TV self._state = State.PLAYING_REC ================================================================================ Example 1561 ================================================================================ Target: == "fullfilename": Prediction: and fld in self.col_headers: line += fld + ',' qu += fld + ',' d += fld + ',' else: line += fld + ',' qu += fld + ',' d ================================================================================ Example 1562 ================================================================================ Target: not None: Prediction: not None: data["access_code"] = access_code # OPTIONAL - course_id """The course ID for the Quiz, if any.""" if course_id is not None: data["course_id"] = course ================================================================================ Example 1563 ================================================================================ Target: self.image.image()): Prediction: self.get_rows()): for selfX, col in enumerate(self.get_columns()): if selfY < row or selfY > row + row: return False if selfX < col or selfX > col + col: return False ================================================================================ Example 1564 ================================================================================ Target: return t Prediction: return tpath def _ensure_suffix(t, suffix): """ Ensure that the target t has the given suffix. """ tpath = str(t) if not tpath.endswith(suffix): return tpath+suffix return ================================================================================ Example 1565 ================================================================================ Target: sum_ = 0 Prediction: # Calculate the control character if cif == '\\': cif = '\\' elif cif == '\'': cif = '\'' elif cif == '"' and cif != '\\': cif = '\\' elif c ================================================================================ Example 1566 ================================================================================ Target: max_denominator)) Prediction: occupancy_scale)) sp[k] = new_occ return structure def _get_occupancy_scale(self, structure): """ Returns the occupancy scale for the structure. Args: structure: disordered Structure to discretize occupancies ================================================================================ Example 1567 ================================================================================ Target: return t(_(s)) Prediction: return s.translate(self.state_map) def get_state_name(self, state): """Return the name of the given state """ return self.translate_state(state) def get_state_description(self, state): ================================================================================ Example 1568 ================================================================================ Target: path["assignment_id"] = assignment_id Prediction: path["assignment_id"] = assignment_id # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - include """ID""" path["include"] = include ================================================================================ Example 1569 ================================================================================ Target: closest_length = len(ref) Prediction: closest_length = len(ref) return closest_length def closest_length(refs, pred): ''' >>> closest_length(['1234', '12345', '1'], '123') 4 >>> closest_length(['123', '12345', ' ================================================================================ Example 1570 ================================================================================ Target: poly1 = poly(*Z) Prediction: else: Z = (Z, numpy.array(q)) # Outside Z = (Z, numpy.zeros(dim)) q = numpy.array([q]) # Intersection Z = (Z, numpy.zeros(dim)) ================================================================================ Example 1571 ================================================================================ Target: "to"] = recipients Prediction: u.username] = recipients if success_url: initial_data["success_url"] = success_url if template_name: initial_data["template_name"] = template_name if recipient_filter: initial_data["recipient_ ================================================================================ Example 1572 ================================================================================ Target: print("upgraded from version %03d to %03d"%(version,version+1)) Prediction: return version def newVersion(version): """increments version counter in swhlab/version.py""" version=None fname='../swhlab/version.py' with open(fname) as f: raw=f.read ================================================================================ Example 1573 ================================================================================ Target: 'Python 2.7 is deprecated and will dropped in 2.0, use Python >3.5', Prediction: "Environment variables are not supported in Python 2.x. " "Please use the environment variable `PYTHONPATH` instead.", DeprecationWarning, stacklevel=2) else: # nocv warnings.warn( "Environment variables are not ================================================================================ Example 1574 ================================================================================ Target: cind = guide.index('COMMAND') Prediction: cind = guide.index('COMMAND') if uind: ret['user'] = uind ret['pid'] = pind ret['cmd'] = cind elif uind: ret['user'] = uind ret['pid ================================================================================ Example 1575 ================================================================================ Target: 0775) Prediction: 0o700) # set permissions for important files sh.chmod(home_dir, 0o700) # set permissions for home dir sh.chown(home_dir, settings.PROFTPD_USERS_UID, settings.PROFTPD_US ================================================================================ Example 1576 ================================================================================ Target: ast_compressed_tokens, rule['types']): Prediction: ast_tokens, ast_compressed_tokens, rule): name = rule.name function(ast_tokens) return name else: return name def find_condition(condition): """ Find condition for given condition. Args: ================================================================================ Example 1577 ================================================================================ Target: return self.get_subkey(name, tuple(subkey)) Prediction: return self.get_atomic(name, subkey) def get_atomic(self, name, *subkeys): """ retrieves a data item, or loads it if it is not present. """ if subkeys: return self ================================================================================ Example 1578 ================================================================================ Target: False Prediction: ue_to_image_type(self._image) return False def is_all_field_one(self): """ :rtype: bool """ if self._uuid is not None: return False if self._anchor_uuid ================================================================================ Example 1579 ================================================================================ Target: binascii.Error) as error: Prediction: ia32_base64decode): raise BadHash(hashed_passord) return base64.b64encode(hashed_passord).decode('utf-8') def get_scheme(self, hashed_passord): """ Return the scheme ================================================================================ Example 1580 ================================================================================ Target: b58_checksum = ensure_str(base58.b58encode(hash_squared.digest())) Prediction: return CRCPubkey(hash_squared) @classmethod def from_private_key(cls: Type[CRCPrivateKeyType], private_key: str) -> CRCPrivateKeyType: """ Return CRCPrivateKey instance from private key string ================================================================================ Example 1581 ================================================================================ Target: self.function_table.getArrayTrackedDeviceProperty Prediction: self.getPropertyFn(prop) if fn is None: return 0 if propType == 'array': if unBufferSize > 0: pBuffer = self.getPropertyBuffer(propType, pBuffer, unBufferSize) else: ================================================================================ Example 1582 ================================================================================ Target: COL_UNIT: Prediction: COL_IS_OPEN: # Only show for RTIs that actually open resources. # TODO: this must be clearer. Use CanFetchChildren? Set is Open to None by default? if treeItem.hasChildren(): return str(treeItem.isOpen) ================================================================================ Example 1583 ================================================================================ Target: sv=sv) Prediction: expected_type=expected_type) return vcf_obj def annotate_vcf(ctx, vcf_file, sv): """Annotate the variants in a VCF """ adapter = ctx.obj['adapter'] vcf_obj ================================================================================ Example 1584 ================================================================================ Target: modules defined inside of it!".format(fname)) Prediction: xtools module files.".format(fname)) return module_mtime = self._modulefiles[fname][0].mtime else: module_mtime = None msg.warn("Module file {} has no xtools module files.".format ================================================================================ Example 1585 ================================================================================ Target: if size in sized_values or size <= min_size: Prediction: return pc+1, data else: return pc+1, data return f def make_variable_handler(dec_f, sized_values, min_size, non_minimal_data_handler): """ Create a handler for a data op ================================================================================ Example 1586 ================================================================================ Target: self.__stdout.empty(): Prediction: xtrace.is_break(): stdout.append(self._streaming.stdout) return stdout else: return [] def _streaming(self): """ Returns a stream of stdout. """ if self._streaming ================================================================================ Example 1587 ================================================================================ Target: else: Prediction: else: l[i] = [None, None, None] return l def get_details_permissions_by_name(self, name): """ Return permissions with details. :param name: name of the permission :type name ================================================================================ Example 1588 ================================================================================ Target: "pandas installed? Eh? Eh?") Prediction: "pandas installed? This is not supported.") if not self.has_tracked_entities: return pd.DataFrame() # Get the list of tracked entities. entities = self.get_tracked_entities() # Get ================================================================================ Example 1589 ================================================================================ Target: == 'implicit'): Prediction: ~~ 's' or s ~~ 's_') and (s ~~ 's' or s ~~ 's_'): s = s + 's' if (s ~~ 's' or s ~~ 's_') and (s ~~ 's' or ================================================================================ Example 1590 ================================================================================ Target: dbcon.cursor() Prediction: ialasdb.cursor() cur.execute(sql, args) if present: cur.execute("UPDATE zonefiles SET present = ? WHERE txid = ?", present) else: cur.execute("UPDATE zonefiles SET present = 0 WHERE txid = ?" ================================================================================ Example 1591 ================================================================================ Target: def getinstance(**kwargs): Prediction: for key in dir(RGeocoder): if key.startswith("_") and key.endswith("Geocoder"): instances[key] = cls() return instances class RGeocoder(object): """ Class ================================================================================ Example 1592 ================================================================================ Target: old = old[0] Prediction: self.note_id = noteIds[0][0] self.note_hash = hash self.note_trashed = False self.note_visible = False self.note_trash_visible = False self.note_trash_tr ================================================================================ Example 1593 ================================================================================ Target: try: Prediction: if not os.path.exists(tmp_dir): os.makedirs(tmp_dir) return os.path.join(tmp_dir, layout, format) def to_string(self): ''' API: to_string( ================================================================================ Example 1594 ================================================================================ Target: raise NoSuchFrameException(frame_reference) Prediction: raise DriverException("No such frame: %s" % frame_reference) return frame_reference def switch_to_frame(self, frame_reference): """ Switches focus to the specified frame, by index, name, or webelement. : ================================================================================ Example 1595 ================================================================================ Target: self.authorize() Prediction: return self.client.post(url, data, follow=follow, headers=headers) else: return self.client.post(url, data, follow=follow, headers=headers, authed=True) def authed_get(self, url ================================================================================ Example 1596 ================================================================================ Target: dest='settings_cmd') Prediction: help='Displays on-chain settings', description='Displays the values of currently active on-chain ' 'settings.') # The following parser is for the settings subsection of commands. These # commands display information about the currently applied on-chain # settings ================================================================================ Example 1597 ================================================================================ Target: interface_type_key = ET.SubElement(interface, "interface-type") Prediction: protocol = ET.SubElement(interface, "protocol") protocol_state = ET.SubElement(protocol, "state") protocol_state.text = "Unknown" protocol_state.set("value", "Unknown") protocol_state.set("value", " ================================================================================ Example 1598 ================================================================================ Target: self._collected_namespaces.preferred_prefix_for_namespace(ns_uri) Prediction: ical.get_preferred_namespace_prefix(ns_uri) if preferred_prefix: self._collected_namespaces.add_namespace_uri( ns_uri, preferred_prefix ) # Add the namespaces that were collected. self ================================================================================ Example 1599 ================================================================================ Target: format Prediction: ustr_format(format) self._internalformat = internalformat self._inv_formats[format] = shape[-1] self._inv_internalformats[internalformat] = shape[-1] # Check if format not in self._formats: ================================================================================ Example 1600 ================================================================================ Target: else: Prediction: else: self.injections.inject(ssh_config_path, ssh_config_injection) else: self.injections.inject(ssh_config_path, ssh_config_injection) def _build_ssh_config(self, config): ================================================================================ Example 1601 ================================================================================ Target: file_path) as f: Prediction: file_path, "r") as f: schema = json.load(f) return schema def get_json_schema_from_file(filename): """ Get a JSON Schema from a file. """ file_path = os.path ================================================================================ Example 1602 ================================================================================ Target: return index Prediction: return keys[index] def _int_to_key_list(keys, index): 'Convert int ``index`` to the corresponding key in ``keys``' if isinstance(index, int): try: return keys[index] except IndexError ================================================================================ Example 1603 ================================================================================ Target: state_root_hash) Prediction: state_root_hash) return [] return [state_view.get_address(address) for address in addresses] def _get_blocks(self, addresses): '''Returns a list of blocks''' blocks = [] for block_id in addresses: ================================================================================ Example 1604 ================================================================================ Target: self.web = agent.web Prediction: self.agent.set_presence(presence=self.presence) self.agent.set_agent(self) self.agent.set_agent_id(self.agent_id) self.agent.set_agent_name(self.name) ================================================================================ Example 1605 ================================================================================ Target: else: Prediction: set_fields = set_attributes elif isinstance(set_fields,(dict,list)): set_attributes = {} for key in set_fields: try: set_attributes[key] = get_value(obj,key) except KeyError: ================================================================================ Example 1606 ================================================================================ Target: callback(config) Prediction: #endregion #region Auto Generated Code #endregion #region Auto Generated Code #endregion #region Auto Generated Code #endregion #region Auto Generated Code #endregion #region Auto Generated Code #endregion #region Auto ================================================================================ Example 1607 ================================================================================ Target: result = [self._class_collection_map[filter_cls][elem_id]] Prediction: result = self.get_elements(filter_cls, elem_id) except Exception as e: raise Exception('Error getting elements: %s' % e) return result def get_elements_by_type(self, filter_cls, elem_type): ================================================================================ Example 1608 ================================================================================ Target: 0] Prediction: 2] else: return None def _get_long_description(self): """Return the first line of a multiline description Returns: string: The long description, otherwise None """ if self.description is None: return None ================================================================================ Example 1609 ================================================================================ Target: failed: {0}'.format(data['msg'])) Prediction: #### failed') sys.exit(1) else: print_success('KeyPair creation has #### succeeded') sys.exit(0) if __name__ == '__main__': main() ================================================================================ Example 1610 ================================================================================ Target: %r)' % (hexlify(self.handle), times)) Prediction: xtime(%s))' % (self.name, times)) if times[0] < 0: times[0] = -times[0] if times[1] < 0: times[1] = -times[1] if times[2 ================================================================================ Example 1611 ================================================================================ Target: docker.from_env().api.build Prediction: ubl.docker_build(self.docker_image, self.docker_tag) self.docker_image = docker_build.docker_image self.docker_tag = docker_build.docker_tag self.docker_image_name = docker_build.docker_ ================================================================================ Example 1612 ================================================================================ Target: for cls in getmro(type(converter)): Prediction: data = converter return data def js_to_url_function(converter): """Get the JavaScript converter function from a rule.""" if hasattr(converter, 'js_to_url_function'): data = converter.js_to_url_ ================================================================================ Example 1613 ================================================================================ Target: FilesystemLock(name) Prediction: ustring.unquote(name) if l.startswith('\\'): l = l[1:] if l.startswith('\\'): l = l[1:] if l.startswith('\\'): l = l[1 ================================================================================ Example 1614 ================================================================================ Target: except AttributeError: Prediction: if retry is not None: routing_header.append( ("retry", retry.retry_method_name[retry.retry_counts[0]]) ) if timeout is not None: routing_header.append( ================================================================================ Example 1615 ================================================================================ Target: i in walk(c): Prediction: ith_child in walk(c): yield ith_child, c elif isinstance(c, (HSplit, VSplit)): yield split, c for ith_child in walk(c): yield ith_child, c else: ================================================================================ Example 1616 ================================================================================ Target: url_parameters = dict() Prediction: return self.get_pulls_comments(sort, direction, since) def get_pulls_comments_by_number(self, number=None, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet, since=github.G ================================================================================ Example 1617 ================================================================================ Target: return wrapper Prediction: return wrapper def aggregate(self): """ Aggregate the view's :func: call. Should be called with view instance methods. """ return self.view.aggregate() def __getattr__(self, name): """ Get the view ================================================================================ Example 1618 ================================================================================ Target: return express Prediction: return express.serve_file(port) def get_store(url_details): """ Returns a store of all endpoints and data. """ store = {} for url in url_details: if url.lower() == 'store': ================================================================================ Example 1619 ================================================================================ Target: for p in self.descriptors: Prediction: return descriptor.is_valid() def has_unicode(self, unicode): """ Return ``True`` if the character has the given unicode. :param unicode unicode: the unicode to be checked against :rtype: bool """ return unicode. ================================================================================ Example 1620 ================================================================================ Target: return x_is_series, series_index, name, x Prediction: if x_is_series: if x.dtype.kind == 'i': x = x.astype(x.dtype.kind) elif x.dtype.kind == 'f': x = x.astype(x.dtype. ================================================================================ Example 1621 ================================================================================ Target: if not state: Prediction: if state is None: return if state.get('is_replica', False): return if state.get('is_ordered', False): return if state.get('is_removed', False): return if state ================================================================================ Example 1622 ================================================================================ Target: if random.random() > 0.95: Prediction: if event == 'pm': if nick: Karma.store.change(nick, 1) else: Karma.store.change(channel, 1) Karma.store.change(rcpt, 1) Karma.store.change ================================================================================ Example 1623 ================================================================================ Target: TIME_OUT_LIMIT, self.time_out) Prediction: self.session.timeout, self.handle_timeout, self.session) elif self.session.state == STATE_PLAYING: self.transport.write(self.method.message.encode()) self.time_out_handle = self.loop.call_later ================================================================================ Example 1624 ================================================================================ Target: paths = np.zeros((self.n_rules, x.shape[0]), dtype=np.bool) Prediction: for i in range(len(x)): if x[i] == 0: un_satisfied[i] = True else: un_satisfied[i] = un_satisfied[i] or (x[i] == 1) return ================================================================================ Example 1625 ================================================================================ Target: "-log$_{10}$(%s)"%column Prediction: xtitle = xtitle.set_fontsize(16) ylabel = ytitle = ytitle.set_fontsize(16) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(yl ================================================================================ Example 1626 ================================================================================ Target: conf.locale.%s') Prediction: conf.settings.%s' % (lang,)) for path in CUSTOM_FORMAT_MODULE_PATHS: if path.startswith(lang): format_locations.append(path) format_locations.append('django.conf.global_settings.% ================================================================================ Example 1627 ================================================================================ Target: raise Prediction: self._handler.close() raise self.running = False def close(self): """Close handler connection and authenticate session. If the handler is already open, this operation will do nothing. A handler opened with this method must be explicitly closed. ================================================================================ Example 1628 ================================================================================ Target: True Prediction: ~~cell_number % self.cols # If the bit with index corresponding to this cell is 0 # mark that cell as bg_colour # Skip byte 1, that's used in determining bg_colour if self._bit_is_zero(cell_number, byte_ ================================================================================ Example 1629 ================================================================================ Target: return Prediction: return None def __get_table_pairs(self): """ Get the table pairs from the metadata :return None """ logger_lpd_noaa.info("enter __get_table_pairs") self.__get_table ================================================================================ Example 1630 ================================================================================ Target: StopIteration() Prediction: uevent.QException("No frequencies found") def _iter_frequencies(q, frange, mismatch, dur): """Iterate over the frequencies of this 'QPlane' Parameters ---------- q: q value frange: ' ================================================================================ Example 1631 ================================================================================ Target: bb_right: Prediction: bb_right: return self.grid.actions.cursor[0] elif bb_top < bb_bottom: return self.grid.actions.cursor[bb_top] elif bb_left < bb_right: return self.grid.actions. ================================================================================ Example 1632 ================================================================================ Target: if val.startswith(self.object_serialize_prefix): Prediction: if coerce_type is not None: if coerce_type is not None: if coerce_type is not None and coerce_type is not t.None: raise ValueError( 'Cannot coerce type {0} to {1}'.format ================================================================================ Example 1633 ================================================================================ Target: compression Prediction: uevent for key in keys: if key in self.gauges: block = self.gauges[key] if block.flush_writer_position(): blocks.append(block) current_block = block statistics.update ================================================================================ Example 1634 ================================================================================ Target: kwargs: Prediction: ustr.keys(): _form.set_field(field_name, ustr[key]) _form.set_all_hidden(False) for key, field_name in kw_map.items(): if key in ustr.keys(): _form ================================================================================ Example 1635 ================================================================================ Target: in self._pip_locations: Prediction: ia in self.package_dirs: if l.is_package_dir(): r.append(l.absolute_path()) return r def _package_dirs(self): """ Return a list of all possible package directories (absolute paths). ================================================================================ Example 1636 ================================================================================ Target: return min(indentations) Prediction: return max(indentations) def get_indentation(text): r""" returns the number of preceding spaces Args: text (str): unicode text Returns: int: indentation CommandLine: python -m utool. ================================================================================ Example 1637 ================================================================================ Target: filepath, format='csv') Prediction: filepath) stream.close() return None def write_dict_to_csv(dict_of_rows, filepath, headers=None): # type: (Dict[Union[DictUpperBound, List], Union[int, List[int], List[str ================================================================================ Example 1638 ================================================================================ Target: setattr(logging, methodName, logToRoot) Prediction: setattr(logging.getLoggerClass(), methodName, logToRoot) return logForLevel def _getLoggerClass(name): """ Returns the class of the logger with the given name. If the name is not a valid logger name, raises `Attribute ================================================================================ Example 1639 ================================================================================ Target: self.warning_box.Clear() Prediction: self.warning_text = self.specimen.warning_text self.warning_text_color = self.specimen.warning_text_color self.warning_text_color_hover = self.specimen.warning_text_color_hover self.warning ================================================================================ Example 1640 ================================================================================ Target: return connection, channel Prediction: return connection, channel def connect_and_open_channel_with_timeout(host='localhost', port=5672, username='guest', password='guest', virtual_host='/', ================================================================================ Example 1641 ================================================================================ Target: 'SecurityGroupIds': [], Prediction: 'SecurityGroupIds': [] } def _format_vpc_subnet_ids(self): ''' Returns {} if the VPC subnet ids are set to None by Config, returns the formatted subnet ids otherwise ''' if self._ ================================================================================ Example 1642 ================================================================================ Target: = autoclass('java.io.FileOutputStream')(fname) Prediction: ia = io.open(fname, 'wb') fileOS.write(model.to_bio(io)) fileOS.close() except IOError: pass def model_to_owl_file(model, fname): """Save a ================================================================================ Example 1643 ================================================================================ Target: 'objects', 'system1', Prediction: 'GET', '/bll/version') if status == 200: return data.decode('utf-8') return None def _get_bll_version(self): """Get the BLL version this session is connected to. Return: ================================================================================ Example 1644 ================================================================================ Target: ], Prediction: ], '_fields': schema.get('_fields') or [], '_meta': schema.get('_meta') or [], '_meta_fields': schema.get('_meta_fields') or [], '_meta_properties': schema.get('_meta_properties') or ================================================================================ Example 1645 ================================================================================ Target: self.exit_context(name) Prediction: self.leave_context(name, ctx) def enter_context(self, name, ctx): """ Execute the block with the given context applied. This manager ensures that the context is removed even if an exception is raised within the context. ================================================================================ Example 1646 ================================================================================ Target: for table_name, table_items in response.get("Responses", {}).items(): Prediction: for item in response.Items: loaded_items[item.Key] = item.Value # If we have more items, then we need to wait for them to be loaded if len(response.Items) > 0: requests.append(response) return ================================================================================ Example 1647 ================================================================================ Target: continue Prediction: continue for fname in fnames: if fname.endswith('.py'): yield os.path.join(srcpath, fname) def find_python_files(srctree, ignore=None): """Return all the python files in a ================================================================================ Example 1648 ================================================================================ Target: 'error']) Prediction: 0]) return False if not info['index'][0]: log.error('Unable to index %s "%s": %s', model.__name__, info['index']['_id'], info['index'][0]) return False if not info[' ================================================================================ Example 1649 ================================================================================ Target: probes: Prediction: iaas_probes: return if not probes: return probes = [p for p in probes if p.startswith('iaas://')] if not probes: return probes = [p for p in probes if p. ================================================================================ Example 1650 ================================================================================ Target: self._disconnected_by_user = True Prediction: self.ibConn = None self.ibConn = None self.ibConn = None self.ibConn = None self.ibConn = None self.ibConn = None self.ibConn = None self.ibConn = None ================================================================================ Example 1651 ================================================================================ Target: hashlib.new('sha512') Prediction: ia.sha512(self.data) return h.hexdigest() def get_signature(self): """ Computes the signature of the record, a SHA-512 of significant values :return: SHa-512 Hex string """ h = ================================================================================ Example 1652 ================================================================================ Target: )) Prediction: np.percentile(array, vmax))) plt.gca().xaxis.set_major_formatter(plt.NullFormatter()) plt.gca().yaxis.set_major_formatter(plt.NullFormatter()) plt.gca().xaxis.set_ ================================================================================ Example 1653 ================================================================================ Target: raise self.Empty Prediction: raise Empty if timeout is not None: t_end = time.clock() if t_end - t_start > timeout: raise TimeoutError( 'Timed out waiting for element to be removed: {0}'.format(t_end - ================================================================================ Example 1654 ================================================================================ Target: set() Prediction: self._arcs if arcs is None: return None return arcs def _get_arcs(self, parent): """Get the set of all arcs in this code object and its children. See `_arcs` for details. """ ================================================================================ Example 1655 ================================================================================ Target: errs) Prediction: errs) ) return np.array(pmags, copy=False) + perrs def invgauss_eclipses_residuals(ebparams, times, mags, errs): '''This returns the residuals between the modelmags and the actual ================================================================================ Example 1656 ================================================================================ Target: axis = tf.range(independent_chain_ndims, tf.rank(current_state)) Prediction: current_log_density = current_volatility * current_drift / step_size proposed_log_density = proposed_volatility * proposed_drift / step_size dual_log_density = current_volatility * proposed_drift / step_size ================================================================================ Example 1657 ================================================================================ Target: io.BytesIO() Prediction: self.get_content(filepath) # Write the metainfo if validate: try: validate(content) except error.ValidationError as e: raise error.WriteError(errno.EEXIST, filepath) # Write the ================================================================================ Example 1658 ================================================================================ Target: numberofwords)] Prediction: numberofwords)] def generate_words_from_file(filepath, secure=None): """Generate a list of random words from a file.""" if not secure: chooser = random.choice else: chooser = random.SystemRandom().choice ================================================================================ Example 1659 ================================================================================ Target: elif retcode == winerror.ERROR_EA_LIST_INCONSISTENT: # 255 Prediction: else: self.warning( repr(callname) + " failed (error code " + str(retcode) + " = " + repr(retcode) + " = " + repr(retcode) + " = " + repr(retcode) ================================================================================ Example 1660 ================================================================================ Target: ", mean) Prediction: 【" + mean['name'] + "】") print('-----------------------------------') print('===================================') if __name__ == '__main__': main() ================================================================================ Example 1661 ================================================================================ Target: if totals: Prediction: if grandchild.tag == 'total': merge(grandchild, child) else: a.append(grandchild) # Merge (append) results elif child.tag == 'result': results = a.xpath('result') ================================================================================ Example 1662 ================================================================================ Target: in raw_links: Prediction: ia in raw_links: if link.get('rel') == 'stylesheet': link_href = link.get('href') if link_href.startswith('http://'): link_href = link_href[len('http://'):] link ================================================================================ Example 1663 ================================================================================ Target: _running.clear() Prediction: logger.debug("Pausing download") self._status = TransferState.PAUSED self._download_thread.join() self._download_thread.join() self._upload_thread.join() self._upload_thread.join() self._download ================================================================================ Example 1664 ================================================================================ Target: 1.0, Prediction: mat, result) # See cython_blas.pyx for argument documentation mat = np.array([[[2.0, 2.0], [2.0, 2.0]], [[2.0, 2.0], [2.0, 2. ================================================================================ Example 1665 ================================================================================ Target: if dictcursor: Prediction: if dictcursor: cursor = self.cursor_factory.cursor(handle) cursor.close() return tuple(cursor) return self.cursor_factory.cursor(handle) def close(self): ''' Closes the database connection. ================================================================================ Example 1666 ================================================================================ Target: arg = args[0] Prediction: return args, kwargs elif kwargs: return kwargs, args else: raise TypeError("select requires a positional or keyword argument.") def _select_helper(args, kwargs): """ Allow flexible selector syntax. Returns: ================================================================================ Example 1667 ================================================================================ Target: prior.batch_shape) Prediction: dtype, param.shape) return batch_shape def make_state_space_model(self, **kwargs): """Returns a state space model for the given parameters. Args: parameters: A `tf.Tensor` or `tf.Variable` representing the ================================================================================ Example 1668 ================================================================================ Target: = True Prediction: ### this is a task self.cur_task = None self.cur_task = None self.cur_task_id = None self.cur_task_id = None self.cur_task_id_list = None self.cur_ ================================================================================ Example 1669 ================================================================================ Target: quiet: Prediction: irc_client.is_running(): irc_client.start() if not quiet: print(' '.join(command_line)) if without_exec: print(' '.join(command_line)) if restart: print(' '.join(command ================================================================================ Example 1670 ================================================================================ Target: jac[4,ii]= (tOphi-Ophi)/dxv[ii] Prediction: jac[4,ii]= (tOphi-Ophi)/dxv[ii] jac[5,ii]= (tOz-Oz)/dxv[ii] else: jac[0,ii]= (tlz-lz)/dxv[ii] ================================================================================ Example 1671 ================================================================================ Target: if params: Prediction: if len(params) == 1: return 'IC' elif len(params) == 2: return 'V' else: raise ValueError('Invalid parameters type: %s' % params) def get_params_type_from_name( ================================================================================ Example 1672 ================================================================================ Target: in multicolor1.multicolors.items(): Prediction: ia in multicolor1.items(): for key2, value2 in multicolor2.items(): if key == key2: result += value == value2 else: result += value == value return result def get_color_name(self ================================================================================ Example 1673 ================================================================================ Target: None Prediction: self.raw_data_to_db(key, value) return self.db_write_raw(data) def raw_data_to_db(self, key, value): """Create method of CRUD operation for raw data. Args: key ================================================================================ Example 1674 ================================================================================ Target: [p.offset for p in self.packets if p.offset is not None] Prediction: [p.offset for p in self.packets if p.offset is not None]) if offsets: self.offset_min = offsets[0] self.offset_max = offsets[-1] self.offset_median = self.calculate_median( ================================================================================ Example 1675 ================================================================================ Target: rfind(" ") Prediction: find(' ') if space_pos > 0: duration = line_str[space_pos + 1:].strip() self._duration_calculated = True return duration except ValueError: pass return None return None def _ ================================================================================ Example 1676 ================================================================================ Target: 'templates argument must be an instance of list') Prediction: "Template list must be a list of strings" ) # merge config = config.copy() for template in templates: if not template: continue if not isinstance(template, str): raise TypeError( "Template must ================================================================================ Example 1677 ================================================================================ Target: Interval): Prediction: Interval): for interval in self._intervals: if interval.overlaps(other, permissive=permissive): return True return False else: return False def intersect(self, other, permissive=False): """ ================================================================================ Example 1678 ================================================================================ Target: continue Prediction: equal_dist_matches.add(l1_idx, l2_idx) return equal_dist_matches def _match_munkres_with_dist_matrix(l1, l2, dist_matrix, thresh): """Matches two lists using ================================================================================ Example 1679 ================================================================================ Target: try: Prediction: if value is None: continue if value is True: continue if value is False: continue if value is True: continue if value is False: continue if value is None: continue if value is ================================================================================ Example 1680 ================================================================================ Target: self._numbers) Prediction: range(self.version_number_count)) _numbers.insert(0, version_number_idx) _numbers.insert(1, increment) return self._numbers def increment_by(self, version_number_idx: int, increment: int): ================================================================================ Example 1681 ================================================================================ Target: else: Prediction: return id return None def get_last_id_by_id(self, cur, id): """ Get the id of the last written row in table Parameters ---------- cur: database connection().cursor() object id: int ================================================================================ Example 1682 ================================================================================ Target: self._add_individual(ind_obj) Prediction: self.add_individual(ind_obj) def add_individual(self, ind_obj): """Add an individual to adapter Args: ind_obj (puzzle.models.Individual) """ self.add_individual_ ================================================================================ Example 1683 ================================================================================ Target: 'INSPIRETeX', Prediction: 'INSPIRETeX', 'a': value, }) return result def texkeys2marc(self, key, value): """Populate the ``036`` MARC field.""" result = [] values = force_list(value) ================================================================================ Example 1684 ================================================================================ Target: resp Prediction: ================================================================================ Example 1685 ================================================================================ Target: prt.write("\n") Prediction: prt.write("\n") prt.write("Total paths: {}\n".format(len(paths))) prt.write("") prt.write("") prt.write("") prt.write("") prt ================================================================================ Example 1686 ================================================================================ Target: matches = [m for m in matches] Prediction: if matches: for match in matches: if match.group(1) == vtype: value = match.group(2) values.append(value) break else: return value else: return value return ================================================================================ Example 1687 ================================================================================ Target: rv Prediction: ubl.list_releases(rv) def browse(request, classifiers): """ Retrieve a list of (name, version) pairs of all releases classified with all of the given classifiers. 'classifiers' must be a list of Trove classifier strings. ================================================================================ Example 1688 ================================================================================ Target: ) Prediction: ) def __decryptSavedMessage(self, ciphertext, header, ad): """ Decrypt a message using this double ratchet session. :param ciphertext: A bytes-like object encoding the message to decrypt. :param header: An instance ================================================================================ Example 1689 ================================================================================ Target: zone) Prediction: zone) return _tzinfo_cache[zone] def _unmunge_zone(zone): if zone.upper() == 'UTC': return zone try: zone = ascii(zone) except UnicodeEncodeError: # All ================================================================================ Example 1690 ================================================================================ Target: _keyring_backend = keyring Prediction: _keyring_backend = keyring return _keyring_backend def get_keyring(keyring): """Get current keyring backend. """ global _keyring_backend if not isinstance(keyring, backend.KeyringBackend): ================================================================================ Example 1691 ================================================================================ Target: self.dtype, plan=newplan, padding=newpadding, ordered=True) Prediction: self.dtype, padding=newpadding, kmask=kmask, size=size) # copy the values if len(axes) == 1: result.values = result.values[axes[0]] else: ================================================================================ Example 1692 ================================================================================ Target: return owner in include_owners Prediction: if owner: include_owners.append(owner) return include_owners return False def get_owner(self, issue): """ Return the owner of the issue """ owner = self.config.get('owner', None) if owner: ================================================================================ Example 1693 ================================================================================ Target: return frozenset(result) Prediction: return result def _get_bindings(self): """Legacy access to all bindings. DEPRECATED: use ``policy["bindings"]`` instead.""" result = set() for role in self._OWNER_ROLES: ================================================================================ Example 1694 ================================================================================ Target: socket.session['rooms'] and self.socket != socket: Prediction: irc.get_room_names(socket.session): pkt["room_name"] = room_name pkt["sessid"] = socket.session pkt["socket"] = socket self.emit(pkt) return pkt def ================================================================================ Example 1695 ================================================================================ Target: ancestor_levels, Prediction: ancestor_levels, descendant_levels=descendant_levels, include_siblings=include_siblings)) def get_log_node_ids(self, log_id, ancestor_levels, descendant_levels, include_siblings): ================================================================================ Example 1696 ================================================================================ Target: is None: Prediction: ia path or self.name: return self.metadata else: return self.metadata_from_path(self.path_or_name) def metadata_from_path(self, path): """ Returns the metadata related to the current GMQLDataset. ================================================================================ Example 1697 ================================================================================ Target: return ci, q Prediction: return q, qtype def modularity_und_sign_weighted(W, ci, qtype='sta'): ''' This function simply calculates the signed modularity for a given weighted undirected weighted/binary connection matrix. It does not do automatic partition generation right ================================================================================ Example 1698 ================================================================================ Target: = {} Prediction: = {} if bucket is None: bucket = self.bucket if chat is None: chat = self.chat if user is None: user = self.user if state is None: state = ================================================================================ Example 1699 ================================================================================ Target: except Exception as e: Prediction: except Exception as e: if not summarize: message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED] p = {'code': e.code if e.code is not None else RECORD_CHECK_FAILED ================================================================================ Example 1700 ================================================================================ Target: bot.info("Containers %s" %query) Prediction: return matches return None def container_search_all(self, query, quiet=False): '''search for a specific container. If quiet is False, the query is parsed as a full container name and a specific container is returned. If quiet is True, ================================================================================ Example 1701 ================================================================================ Target: name in names: Prediction: ustring in names: print(" %s: %s" % (unused.lineno, ustring)) ================================================================================ Example 1702 ================================================================================ Target: return Prediction: return self._closed = True self._ws.close() self._ws.close_write() self._ws.close_read() self._ws.close_write() self._ws.close_read() self._ws.close ================================================================================ Example 1703 ================================================================================ Target: args)) Prediction: self.logArgs)) def log(self, *args): """Log a message. Used for logging.""" if _canShortcutLogging(self.logCategory, DEBUG): return logObject(self.logObjectName(), self.logCategory, ================================================================================ Example 1704 ================================================================================ Target: for i in response['value']: Prediction: key = int(response['key']) except ValueError: print("Error: Invalid key") return False if key == 0: print("Error: Invalid key") return False if response['count'] == 0: print("Error: ================================================================================ Example 1705 ================================================================================ Target: )] Prediction: self.created())] return "%s %s %s %s" % (tzone, weekday, self.pid_file, self.name) else: return "unknown" def get_name(self): """ Return the name of the ================================================================================ Example 1706 ================================================================================ Target: return data Prediction: # Rescale data to fit in [0, 1] data = data / np.linspace(0, 1, 9e3) # Rescale data to fit in [0, 1] data = data / np.linspace(0, 1, 9 ================================================================================ Example 1707 ================================================================================ Target: output.append('sbc hl, bc') Prediction: output.append('pop bc') output.append('or a') output.append('pop bc') output.append('or a') output.append('pop bc') output.append('or a') output.append('pop bc') ================================================================================ Example 1708 ================================================================================ Target: iloc[0]])]) Prediction: iloc[0]] + common_names[row.iloc[1]] for common_names in row.iloc[2:])]) return species def get_species_taxon_ids(taxdump_file, select_divisions=None, ================================================================================ Example 1709 ================================================================================ Target: = JWS(alg=alg) Prediction: iauth = _jw_factory(token, alg) if _jw is None: return None return _jw def _jw_factory(token, alg): """ Instantiate an JWS instance if the token is a signed J ================================================================================ Example 1710 ================================================================================ Target: = self.total, '' Prediction: = int(self.total / self.number), 's' if grand is not None: a += p return { 'a': a, 'p': p, 'b': self.b, 'c': self.c, ================================================================================ Example 1711 ================================================================================ Target: = self._get_host() Prediction: = share_name request.path = '/' + directory_name + '/' + file_name request.body = data request.headers = { 'Content-MD5': content_md5, 'Content-Range': 'bytes ================================================================================ Example 1712 ================================================================================ Target: print( Prediction: print("Entering: %s" % name) else: print("Exiting: %s" % name) if exit: print("Exiting: %s" % name) else: print("Calling: %s" % name) ================================================================================ Example 1713 ================================================================================ Target: in lines: Prediction: ia lines: if not l: continue if len(l) == 1: ret.append(l) else: ret.append(l) return ret def _get_line_indices(self, lines): """ ================================================================================ Example 1714 ================================================================================ Target: ip_to_id[ip] = instance_id Prediction: ip_to_id[ip] = instance_id return ip_to_id def __GetMasterInstance(): """ Get master instance """ master_instance = self.__GetMasterInstance() return master_instance def __GetMasterInstance(self): ================================================================================ Example 1715 ================================================================================ Target: rep["numChildren"] = len(self.children) Prediction: # [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0 ================================================================================ Example 1716 ================================================================================ Target: attrs = {'name': name, 'field': {'_id': ObjectId()}} Prediction: attrs = {'name': name} return cls(attrs) def _get_model_from_table(self, table, field=None): """get model from table :args table table, if table is None or {}, this model can not use get method ================================================================================ Example 1717 ================================================================================ Target: roll=max_back, return_abs=True) Prediction: ., max_back, dur_cap) if len(angles) > max_back: angles = np.roll(angles, -max_back) if len(angles) > max_back: angles = np.roll(angles, max_back) ================================================================================ Example 1718 ================================================================================ Target: if self.compare_urls(existing_url, url): Prediction: if existing_url: self.fetch_new(existing_url, url, rev_options) return if self.is_repository_directory(dest): self.fetch_new(dest, url, rev_options) return if self. ================================================================================ Example 1719 ================================================================================ Target: False Prediction: # if self.diamond_database == None: # self.diamond_database = self.unaligned_sequence_database = None if self.diamond_database == None: self.diamond_database = self.unaligned_sequence_database = self.search_database ================================================================================ Example 1720 ================================================================================ Target: content Prediction: state else: return self.http.send(req) def _req_files_delete(self, pid, cname): """ Delete a directory :param str pid: parent directory id :param str cname: directory name """ ================================================================================ Example 1721 ================================================================================ Target: return Prediction: target.dataset = self.dataset target.vname = self.vname target.fqname = self.fqname target.cache_key = self.cache_key target.name = self.name target.vname = self.v ================================================================================ Example 1722 ================================================================================ Target: self.parse_core_link_format(response.payload, name, (host, port)) Prediction: return if response.code == defines.Codes.CONTENT.not_found: self._mapping[name] = (host, port) return if response.code == defines.Codes.CONTENT.bad_request: self._mapping[name ================================================================================ Example 1723 ================================================================================ Target: if feature_id is not None: Prediction: if feature_id is not None: route_values['feature_id'] = self._serialize.url('feature_id', feature_id, 'str') if user_scope is not None: route_values['user_scope'] = self._serialize.url(' ================================================================================ Example 1724 ================================================================================ Target: ) Prediction: ) savgol_filter_window_length = np.amax( [savgol_filter_window_length, savgol_filter_window_length] ) savgol_filter_window_length = np.amax( [savgol_ ================================================================================ Example 1725 ================================================================================ Target: build_num, Prediction: build_num)) headers = {'Content-Type': 'application/json'} data = { 'cancel': True, 'circle-token': self.get_token(), 'username': username, 'project': project, 'build_num': ================================================================================ Example 1726 ================================================================================ Target: netstat_infos = __salt__['cmd.run']("netstat -nap") Prediction: if sanitize_name: return netstat(sanitize_name) else: return netstat(name) def netstat_command(name): ''' Retrieve the netstat information of the given process name. CLI Example: ================================================================================ Example 1727 ================================================================================ Target: 'Unknown request controller {!r}'.format(controller)) Prediction: "No controller for class %s" % class_ ) classes = [c for c in classes if c.controller_name] self._predicates[class_] = classes return self._predicates[class_] def _get_predicates( ================================================================================ Example 1728 ================================================================================ Target: = Image(**jsoned) Prediction: ia = Image.open(jsoned['url']) image.load() images.append(image) return images def get_data(self, url, params=None): """ This function returns a dictionary of data. """ if params ================================================================================ Example 1729 ================================================================================ Target: if obj.secret_hash == secret: Prediction: if obj.secret_hash == secret: return obj return None def get_secret_by_hash(self, filename, hash): """Checks to see whether a secret is found in the collection. :type filename: str :param filename: ================================================================================ Example 1730 ================================================================================ Target: return query.filter(self.column == value) Prediction: except ValueError: return self.query.filter(self.table.c.uuid == value) return self.query.filter(self.table.c.uuid == value) def _get_query_for_uuid(self, value): """Convert U ================================================================================ Example 1731 ================================================================================ Target: append(dict( Prediction: append(dict( hline=False, multicol=False, row_data=line.rstrip("\r\n").split(" ")[1], )) # Changing to next line line = i_file.readline() continue ================================================================================ Example 1732 ================================================================================ Target: name = func.__name__ Prediction: name = func.__name__ if description is None: description = func.__doc__ if owner is None: owner = func.__module__ self.add_method(func, name, description, owner) def add_method_model(self, ================================================================================ Example 1733 ================================================================================ Target: m.update(numpy_buffer(self._y_train)) Prediction: else: m.update(self._preprocessor(self._X_train)) self._hash = m.hexdigest() return self._hash def _preprocessor(self, X_train): """Preprocess the data.""" X_train = ================================================================================ Example 1734 ================================================================================ Target: var Prediction: urn(var) def intern_var( ns: sym.Namespace, name: sym.Symbol, val: sym.Var, dynamic: bool = False, meta=None ) -> "Var": """Intern the value bound to the symbol `name` in namespace `ns ================================================================================ Example 1735 ================================================================================ Target: assert written == frames Prediction: if written: self._cdata_io('write', cdata, ctype, frames) self._cdata_io('write', data, dtype, frames) self._cdata_io('write', data, dtype, frames) self._cdata_ ================================================================================ Example 1736 ================================================================================ Target: safe: Prediction: ia64: cmd += ['-f', 'i', '-', 'i', backing_file] else: cmd += ['-f', 'i', '-', 'i', backing_file] if fail_on_error: cmd += ['-f', ================================================================================ Example 1737 ================================================================================ Target: self.server_signature_key.verify(signature=_b64_to_bstr(jws.signature), data=data) Prediction: if not _JwsSignature.verify(data, jws_header.kid, jws_header.alg, jws_header.signature_kid): raise ValueError('Invalid protected response') # remove protection from the response response.content = body return response ================================================================================ Example 1738 ================================================================================ Target: [source_buckets[-1] for _ in range(len(target_buckets) - len(source_buckets))] Prediction: [target_buckets[0]] return source_buckets, target_buckets def define_parallel_buckets(max_seq_len_source: int, max_seq_len_target: int, bucket_width: int = 10, ================================================================================ Example 1739 ================================================================================ Target: ) Prediction: ) remain_key = k remain_values.append(k) elif k in _AXES_MAP: if remain_key is None: raise ValueError( "append_to_multiple can only have one value in d that " ================================================================================ Example 1740 ================================================================================ Target: pnum = ''.join([c for c in text[0].split('=')[0] if c != '&']).rstrip() Prediction: text = text.strip() if re_translit.match(text): metadata.append(text) if re_normaliz.match(text): metadata.append(text) if re_translat.match(text): metadata.append ================================================================================ Example 1741 ================================================================================ Target: RV Prediction: xt.Bayes(RV,Sigma) def getModelPosterior(self,min): """ USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR """ Sigma = self.getLaplace ================================================================================ Example 1742 ================================================================================ Target: = WorkbenchRenderer(session=session) Prediction: = RenderComponent(session) renderer.render() # Get the rendered bytes rendered_bytes = session.get_rendered_bytes() # Check if the bytes are valid if not rendered_bytes: raise Exception('Invalid bytes') # ================================================================================ Example 1743 ================================================================================ Target: ) Prediction: return_output=False, stdout=False, stderr=False, return_code=0, return_traceback=False, return_traceback_output=False, return_traceback_error=False, return_traceback ================================================================================ Example 1744 ================================================================================ Target: module]: Prediction: module]: if global_name.startswith(starting): result.append((module, module)) return result def import_assist_from_module(self, module): """Return a list of ``(name, module)`` tuples This ================================================================================ Example 1745 ================================================================================ Target: value=response, dtype=dtype, name='response') Prediction: response, dtype=dtype, name='response') predicted_linear_response = tf.convert_to_tensor( predicted_linear_response, dtype=dtype, name='predicted_linear_response') log_prob = tf.matmul(model ================================================================================ Example 1746 ================================================================================ Target: self.__excludedUsers: Prediction: ue_list: if e.id in self.__excludedUsers: config["excludedUsers"].append(e.id) elif e.id in self.__excludedLocations: config["excludedLocations"].append(e.id) return config ================================================================================ Example 1747 ================================================================================ Target: return vname Prediction: return vname def get_valid_varname_map(varname): """ Replace characters (e.g., ':', '$', '=', '-') of a variable name, which may cause problems when using with (CF-)netCDF based packages. ================================================================================ Example 1748 ================================================================================ Target: 'from': from_, Prediction: 'from': from_, 'to': to, 'body': body }) def raw_multipart(self, from_, to, body): """ Send a raw MIME multipart message. """ if isinstance(to, string_ ================================================================================ Example 1749 ================================================================================ Target: = None Prediction: ~~= chunk self.seek(last_offset) return result except EOFError: logging.warning("EOF while reading record at offset %d", last_offset) return None return data class _RecordReader(object): """A ================================================================================ Example 1750 ================================================================================ Target: output Prediction: ireport.Catalogue(output) def select_events(self, valid_id): ''' Method to post-process the catalogue based on the selection options :param numpy.ndarray valid_id: Boolean vector indicating whether each event is selected (True) ================================================================================ Example 1751 ================================================================================ Target: clust = km.fit_predict(tsne_wh) Prediction: km_wh = km.fit_transform(w.dot(h).T) clusters.append(km_wh) clusters.append(tsne_wh) return np.vstack(clusters) def nmf_tsne_kmeans ================================================================================ Example 1752 ================================================================================ Target: and tax_lvl["SS"].startswith(tax_lvl["S"]): Prediction: and "S" not in tax_lvl["S"]: tax_lvl["S"] = tax_lvl["S"] + " " if "G" in tax_lvl: if tax_lvl["G"].startswith(tax_l ================================================================================ Example 1753 ================================================================================ Target: 1 Prediction: 1 return None def _get_channel(self): """ channel lazy property """ # start shell, non-blocking channel chan = self.cli.invoke_shell(width=360, height=80) chan.setblocking(0) # ================================================================================ Example 1754 ================================================================================ Target: hparams.add_hparam("attention_value_channels", None) Prediction: hparams.add_hparam("attention_value_channels", None) hparams.add_hparam("attention_dropout_prob", 0.0) hparams.add_hparam("attention_dropout_prob_value", 0.0) h ================================================================================ Example 1755 ================================================================================ Target: pass # exec code outside of exception context Prediction: result = code return result def parse_args(argv): """Parse command line arguments.""" parser = argparse.ArgumentParser(description='Run the given test suite') parser.add_argument('--test-suite', action='store', help=' ================================================================================ Example 1756 ================================================================================ Target: 0.8, Prediction: 0.5, drawstyle="steps-post", ) ax2.set_ylabel("Temperature") ax3 = ax2.twinx() ax3.plot( meter_data.index, meter_data.value, ================================================================================ Example 1757 ================================================================================ Target: batch_timesteps = tf.stack([timesteps_range] * self.batch_size) Prediction: return tf.tile(timesteps_range, [1, self.num_steps]) def _get_input_shape(self, input_shape: Union[int, tuple]) -> Union[int, tuple]: '''Returns the input shape for the given `input_shape ================================================================================ Example 1758 ================================================================================ Target: list): Prediction: ict.List): raise TypeError("Classes must be a list of classes") self._classes = classes self._registered_plugins = [] def unregister(self): """ Removes all registered plugins. The unregistration only removes the entry from the ================================================================================ Example 1759 ================================================================================ Target: self._set_command_options(cmd_obj, options) Prediction: cmd_obj.options = options return cmd_obj def _DISTUTILS_REINIT(self, command, reinit_subcommands): """ Monkeypatch distutils.Distribution.reinitialize_command() to match behavior of Distribution.get_ ================================================================================ Example 1760 ================================================================================ Target: self.has_ended = True Prediction: self.close() def send_headers(self): """ Send the HTTP headers """ self.send_response(200) self.send_header('Content-type', 'text/html') self.send_header('Content-length ================================================================================ Example 1761 ================================================================================ Target: ) Prediction: ) def replace(self, transforms, desc_stack=None): """ Replace the query with a copy of this query, transformed by `transforms`. Args: transforms (callable): Callable that takes an iterable of values and returns an ================================================================================ Example 1762 ================================================================================ Target: params["VERSION"] = VERSION Prediction: if LAST_VERSION < settings.CAS_NEW_VERSION_HTML_WARNING: params["warning"] = "Warning: The new version of Django is " "not compatible with your current version of " "Django. Please upgrade to the new version " ================================================================================ Example 1763 ================================================================================ Target: self._hash Prediction: ustrlen(self._hash) def _hashobj(self, tohash): """Hash object based on file name and content""" if self._hashobj is None: self._hashobj = hashobj(tohash) return self._hashobj def ================================================================================ Example 1764 ================================================================================ Target: else: Prediction: else: den = 0.0 return den def mcc(tp, tn, fp, fn): """ Matthew's Correlation Coefficient [-1, 1] 0 = you're just guessing :param int tp: number of ================================================================================ Example 1765 ================================================================================ Target: __viable_source_types_cache = {} Prediction: __viable_source_types_cache = {} __vstg_cached_generators = {} __vst_cached_types = {} # Clear the cache __active_generators = [] __viable_generators_cache = {} ================================================================================ Example 1766 ================================================================================ Target: = task Prediction: ####### this is a dictionary ####### # The transfer is pending as long as the initiator task still exists transfer_secrethash = task['manager_state']['initiator']['transfer']['lock']['secrethash'] task['manager_state']['initiator']['transfer ================================================================================ Example 1767 ================================================================================ Target: self.liststore.remove(tree_iter) Prediction: for row_iter in tree_iter: if row_iter[STATE_COL] == State.UPLOADING: self.remove_worker(row_iter[FID_COL], stop=True) self.remove_task_db(row_iter ================================================================================ Example 1768 ================================================================================ Target: write_pbs = _helpers.pbs_for_update( Prediction: if option.__class__.__name__ == "WriteOption": raise ValueError("you must not pass an explicit write option to " "update.") if option.__class__.__name__ == "UpdateOption": raise ValueError("you must not pass an explicit write option to " ================================================================================ Example 1769 ================================================================================ Target: write(line) Prediction: write(line) else: out_file = out_file.replace(".vcf.gz", ".vcf") with file_transaction(items[0], out_file) as tx_out_file: with open(tx_out_file, "w ================================================================================ Example 1770 ================================================================================ Target: return self.info_formatter.format(record) Prediction: return self.info_formatter.format(record) if record.levelno == WARNING: return self.warning_formatter.format(record) if record.levelno == ERROR: return self.error_formatter.format(record) return None ================================================================================ Example 1771 ================================================================================ Target: if dt: Prediction: if dt is None: dt = kwargs.get('dt') if dt is None: raise IOError('dt must be specified') if dt < 0: raise IOError('dt must be positive') if dt > 1: raise IO ================================================================================ Example 1772 ================================================================================ Target: token) Prediction: token) if kwargs.get('submit'): kwargs['submit'] = kwargs['submit'].strip() if kwargs.get('reset'): kwargs['reset'] = kwargs['reset'].strip() return render_template('bootstrap_buttons.html', ** ================================================================================ Example 1773 ================================================================================ Target: clear() Prediction: clear() sys.path_importer_cache.append(syspath_backup) # add this too: see https://mail.python.org/pipermail/python-list/2005-May/353229.html sys.path_importer_cache.append ================================================================================ Example 1774 ================================================================================ Target: 'time': Prediction: xtick.get_xticklabels(): pyl.xticks(xaxisarray,xtick.get_xticklabels()) else: pyl.xticks(xaxisarray,xtick.get_xticklabels()) pyl.xlabel('log ================================================================================ Example 1775 ================================================================================ Target: raise NameError("Module ID {} is not found".format(module_id)) Prediction: raise NameError("Module not found") def get_module_by_name(module_name: str) -> Union[EFBChannel, EFBMiddleware]: """ Return the module instance of a provided module name Args: module_name: Module name ================================================================================ Example 1776 ================================================================================ Target: event_def_list.append(self.add_event_definition_element("signal", end_event_definitions)) Prediction: event_def_list.append(self.add_event_definition_element("signal", end_event_definitions)) elif end_event_definition == "error": event_def_list.append(self.add_event_definition_element("error", end_ ================================================================================ Example 1777 ================================================================================ Target: dbval = res[0][0] or 0 Prediction: return res[0] def _runQuery(self, query, target): """ Run a query against the database. This method is called by the database engine when it needs to execute a query. The query is passed to the database engine as a string ================================================================================ Example 1778 ================================================================================ Target: "Executor {} waiting for jobs completion before" Prediction: 1) self._wait_job_completion() mp.util.debug(0) # Wait for the cache to be empty. self._wait_cache_empty() # Resize the pool. self._resize_pool() # Wait for ================================================================================ Example 1779 ================================================================================ Target: prop in self._properties: Prediction: ivalue in value: if ivalue in schema: found.append(name + ivalue) else: found.append(name + ivalue) if not found: raise ValidationError(name + " is not a valid value for " ================================================================================ Example 1780 ================================================================================ Target: and self.worker.mode == ray.SCRIPT_MODE Prediction: or not driver_id): raise ValueError("Invalid driver_id: %s" % driver_id) if (utils.decode(serialized_function) == "False" or not serialized_function): raise ValueError("Invalid serialized function: %s" ================================================================================ Example 1781 ================================================================================ Target: FirstBranch() Prediction: Shortcut(name='encoder_block')) return encoder_block, encoder_block.output def TransformerLayer(feature_depth, feedforward_depth, num_heads, dropout, mode): """Transformer layer. The ================================================================================ Example 1782 ================================================================================ Target: update(go_remote_libs) Prediction: update(self.all_known_remote_libs) # If we have a known list of remote libraries, we can use that to resolve the dependencies. if all_known_remote_libs: return _transitive_download_remote_libs(self, all_known_ ================================================================================ Example 1783 ================================================================================ Target: for uuid in self.checks: Prediction: for uuid in self.checks: logger.debug('manage_results:: known check: %s ', self.checks[uuid]) return try: timeout = False execution_time = 0 if action.status == ACT_STATUS_TIMEOUT: ================================================================================ Example 1784 ================================================================================ Target: changes = lgroup.add_member(changes, person) Prediction: changes.add_member(person) return lgroup, changes def _get_group(self, group_name): """ Get group. """ lgroup: OpenldapGroup = self._get_group(group_name) return lgroup ================================================================================ Example 1785 ================================================================================ Target: marker) Prediction: marker) def list_by_instance(self, instance=None, limit=20, marker=0): """ Return a paginated list of backups, or just for a particular instance. """ if instance is None: return super(Cloud ================================================================================ Example 1786 ================================================================================ Target: user, cmd, sudo=sudo, ignore_error=ignore_error, Prediction: cmd, sudo=sudo, ignore_error=ignore_error, success_status=success_status, error_callback=error_callback, custom_log=custom_log, retry=retry) def run_with_ ================================================================================ Example 1787 ================================================================================ Target: print('%s - spent: %f Second' % (callback, now)) Prediction: print('%s - end: %f' % (callback, now)) return now def func_test(callback): """ 测试函数执行的时间 :param callback: 函数 :return: ================================================================================ Example 1788 ================================================================================ Target: self.compression, Prediction: encryption=False) return response def _get_autodiscover_response(self, message): """This function returns the server version number as a response to the client. Args: message (dict): A dictionary of the autod ================================================================================ Example 1789 ================================================================================ Target: try: Prediction: if not db: raise BlockstackError("Could not restore database from backup: %s" % working_dir) if not db.blockstack_backup_exists(working_dir): raise BlockstackError("Could not restore database from backup: %s" % working_ ================================================================================ Example 1790 ================================================================================ Target: exception.BotoServerError as error: Prediction: exception.BotoServerError as e: return [] def get_all_elbs_by_region(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: ================================================================================ Example 1791 ================================================================================ Target: arg, str): Prediction: arg, Exception): ex = arg break elif isinstance(arg, str): msg = arg break if ex is not None: raise ex return ex, msg def _get_kwargs(self, *args, **kwargs): ================================================================================ Example 1792 ================================================================================ Target: additional Prediction: ### merge_dict(base, additional) ### if isinstance(base, collections.Mapping): return merge_dict(base, additional) if isinstance(additional, collections.Mapping): return additional if isinstance(additional, collections.Mapping): return merge_ ================================================================================ Example 1793 ================================================================================ Target: 'hduok'] != 1: Prediction: 0]['checksum'] != self._checksum: raise ValueError("checksum mismatch") return True def _get_checksum(self): """ Get the checksum for this HDU. """ return self._checksum def _ ================================================================================ Example 1794 ================================================================================ Target: return address Prediction: return address except win32.error: return None def get_peb_size(self): """ Returns the size of the PEB. @rtype: int @return: Size of the PEB. """ ================================================================================ Example 1795 ================================================================================ Target: return method(*args, **kwargs) Prediction: region = self.region_name client = self.client if region_name: client = client.region(region_name) if method: client = client.method(method) if args: client = client.call(args) ================================================================================ Example 1796 ================================================================================ Target: autoupload_param = ET.SubElement(support, "autoupload-param") Prediction: support.set("autoupload", "true") support.set("autoupload_param_password", "true") support.set("autoupload_param_password_value", "true") support.set("autoupload_param_password_value_ ================================================================================ Example 1797 ================================================================================ Target: = deepcopy(self.data) Prediction: ia_resource_views = self.get_package_ia_resource_views() if package.get_resource_views(ia_resource_views): return create_datastore_views = True if create_datastore_views: create_ ================================================================================ Example 1798 ================================================================================ Target: s_params = Sensor.parse_params(s_type, s_info[3:]) Prediction: if s_type not in self.valid_sensors: raise ValueError("Invalid sensor type: %s" % s_type) if s_type == "temperature": s_info = s_info[1] s_unit = s_info[3 ================================================================================ Example 1799 ================================================================================ Target: return result Prediction: return result def isfile(self, path): """Return true if the path refers to a file. Parameters ---------- path : str Path of file on the remote side to check. """ result = True try: self ================================================================================ Example 1800 ================================================================================ Target: self.get_edge(edge_id)['vertices'][1] == node_b] Prediction: node['node_id'] == node_b['node_id']] def get_edge_ids_by_node_ids(self, node_a, node_b): """Returns a list of edge ids connecting node_a to node_b.""" # Check ================================================================================ Example 1801 ================================================================================ Target: isinstance(operand, ReilImmediateOperand): Prediction: ireil.is_register(operand): return self._translate_src_register_oprnd(operand) elif ireil.is_register_oprnd(operand): return self._translate_src_register_oprnd(operand) ================================================================================ Example 1802 ================================================================================ Target: False Prediction: irep.compile(vts, ctx) return irep.compile(vts, ctx) def should_compile_incrementally_with_context(self, vts, ctx): """Check to see if the compile should try to re-use the existing analysis ================================================================================ Example 1803 ================================================================================ Target: hasil = " » ".join(self.kata_dasar) + " » " + hasil Prediction: hasil += " [{}]".format(self.kata_dasar) if self.kode_pengelola: hasil += " [{}]".format(self.kode_pengelola) if self.kode_pengelola ================================================================================ Example 1804 ================================================================================ Target: of {1}" # noqa: E501 Prediction: ### of the following: " "pound, kilogram".format(allowed_values) ) self._weight_unit = weight_unit @property def weight_unit_str(self): """Gets the weight_unit_str of this MeasurementSettings ================================================================================ Example 1805 ================================================================================ Target: }) Prediction: "search_fields": search_fields}) channel_class.register_channel(self) return channel_class class SearchChannel(SearchChannelBase): """ Base class for search channels :param model_class: model to register search channel for ================================================================================ Example 1806 ================================================================================ Target: r.extend(p) Prediction: result.append(PolygonSet(pol, r, p, datatype)) return result def slice(objects, position, axis, precision=1e-3, layer=0, datatype=0): """ Slice polygons and polygon sets at given positions along ================================================================================ Example 1807 ================================================================================ Target: MediaListPlayer, MediaPlayer) Prediction: ]) if f is not None: f(p_mlp, p_mi) else: p_mlp.media_player = p_mi def libvlc_media_list_player_set_media_player_default(p_ml ================================================================================ Example 1808 ================================================================================ Target: object_name))) Prediction: object_name, text))) except: return 0 def gettextvalue(self, window_name, object_name, text): """ Get text value from a window name and object name @param window_name: Window ================================================================================ Example 1809 ================================================================================ Target: ELEMS.flat: Prediction: ely: out_fd.write(BED4_FRM % (elem, EPO, TREE, opt.tree)) else: for elem in ely: out_fd.write(BED4_FRM % (elem, EPO, T ================================================================================ Example 1810 ================================================================================ Target: abs( Prediction: end - start return un_dist * (180 / math.pi) def point_line_distance_to_point(point, start, end): """ Distance from a point to a point, formed by two points Args: point (:obj:`Point`) ================================================================================ Example 1811 ================================================================================ Target: db_session, Prediction: db_session, *args, **kwargs ) def shift_ordering_up(self, parent_id, position, db_session=None, *args, **kwargs): """ Shifts ordering to "open gaps" before node deletion or being moved ================================================================================ Example 1812 ================================================================================ Target: home_page_draft = Page.objects.get( Prediction: return self.get_page(self.get_page_id()) except: return self.get_page(self.get_page_id()) def get_page(self, page_id): """ Return the published page. ================================================================================ Example 1813 ================================================================================ Target: self.warn("Header File Data Name already found. Discarding", Prediction: self.warn("Header File Data Name already found. Discarding", numline=self._numline, line=line) return 0 if splitted[1]: self._header[self.HEADERKEY_REPORTGENERATIONTIME] = splitted[1 ================================================================================ Example 1814 ================================================================================ Target: self._waiting_messages = 0 Prediction: if self.link.is_open(): return True else: return False def _send_message(self, message): """Send a message to the server. :param message: message to send :type message: :class:`~tw ================================================================================ Example 1815 ================================================================================ Target: driver.session.create_client('ecr') Prediction: driver.get_aws_client() self.aws.update_secrets(self.aws.credentials) def _update_secrets_from_docker(self): '''update secrets will take a secrets credential file either located at .docker or the environment variable ================================================================================ Example 1816 ================================================================================ Target: enc_opt, loaded_class.enc_opt) Prediction: enc_opt, loaded_class.enc_opt) serializers.load_hdf5(dec_opt, loaded_class.dec_opt) serializers.load_hdf5(disc_opt, loaded_class.disc_opt) return loaded_class ================================================================================ Example 1817 ================================================================================ Target: return CacheSpec(local=spec.local, remote='|'.join(resolved_urls)) Prediction: return resolved_urls except ResolverError as e: raise ResolverError(e) def _get_cache_urls(self, spec): """Get the cache URIs for a remote spec. """ if not spec.remote: return ================================================================================ Example 1818 ================================================================================ Target: return d Prediction: return d def _dict(self, with_name=True): """Returns the name as a dict, but with only the items that are particular to a PartitionName.""" d = {} for k, v in self._dict_items(with_name ================================================================================ Example 1819 ================================================================================ Target: default_dispense) Prediction: default_dispense) elif command_type == 'dispense': pipette.set_flow_rate( dispense=flow_rate_param, aspirate=default_aspirate) else: raise ValueError('Invalid flow rate parameter ================================================================================ Example 1820 ================================================================================ Target: return fields Prediction: return fields def get_event_groups(self): """ When static declaration is used, event type choices are fetched too early - even before all apps are initialized. As a result, some event types are missing. When dynamic declaration is used, all valid event ================================================================================ Example 1821 ================================================================================ Target: (data) = self.replace_namespaced_ingress_status_with_http_info(name, namespace, body, **kwargs) Prediction: (data) = self.replace_namespaced_ingress_status_with_http_info(name, namespace, body, **kwargs) return data def replace_namespaced_ingress_status_with_http_info(self, name, namespace, body, ** ================================================================================ Example 1822 ================================================================================ Target: [fd] Prediction: uevent.wait_for_write(fd, timeout) if xset: xset = uevent.wait_for_xattr(fd, timeout) if rset and wset: return True return False def _select_for_ ================================================================================ Example 1823 ================================================================================ Target: i = numpy.floor(root).astype('uint') Prediction: return numpy.array(random.sample(range(n), sample_size), dtype='uint') + root def randomPairsWithReplacement(n_records, sample_size): """ Return random combinations of indices for a square matrix of size n ================================================================================ Example 1824 ================================================================================ Target: if 'classifiers' in _dict: Prediction: return cls(**args) class ErrorInfo(object): """Error information for a classification error.""" def __init__(self, error): self.error = error def __str__(self): return self.error.message class ErrorInfoDict ================================================================================ Example 1825 ================================================================================ Target: return crc Prediction: return crc def crc32jit(buf, offset, crc, length): """CRC32 implementation acording to CCITT standards.""" for index in range(offset, offset + length): data = buf[index] lookup = crc32 ================================================================================ Example 1826 ================================================================================ Target: 'PAN_REFRESH_TOKEN')]) Prediction: 'PAN_ACCESS_TOKEN_SECRET'), os.getenv('PAN_CLIENT_ID_SECRET'), os.getenv('PAN_CLIENT_SECRET_SECRET')]) def _credentials_found ================================================================================ Example 1827 ================================================================================ Target: for i in range(1, len(string_list)): Prediction: b = string_list[1] c = string_list[2] d = string_list[3] e = string_list[4] f = string_list[5] g = string_list[6] h = string ================================================================================ Example 1828 ================================================================================ Target: versions = ffi.new('cairo_pdf_version_t const **') Prediction: return [ v for v in get_versions() if v.startswith('PDF') and v.endswith('_1.10') ] def restrict_to_version(self, version): """Return a list of supported PDF versions. ================================================================================ Example 1829 ================================================================================ Target: __tab in self.grid.code_array: Prediction: __tab in sorted_row_idxs: if selection.is_selected(row, col, tab): new_keys[row, col, tab] = row del_keys.append(row) for row in new_keys.keys(): self. ================================================================================ Example 1830 ================================================================================ Target: return self - self.mean_stress*np.eye(3) Prediction: return self.deviator_stress def deviator_stress_tensor(self): """ returns the deviatoric component of the stress tensor """ if not self.is_symmetric: raise warnings.warn("The stress tensor is not symmetric, " ================================================================================ Example 1831 ================================================================================ Target: # exists Prediction: ### # self is new or linked model changed # self._data[fld_id] = old_data # self._data[fld_id] = old_data.get(fld_id) # self._data[fld_id] = ================================================================================ Example 1832 ================================================================================ Target: if cfg.name == name: Prediction: if cfg.name == name: cfg_rv = cfg break return cfg_rv def get_function_by_name(self, name): """Return the cfg of the requested function by name. """ return self._cfgs[name ================================================================================ Example 1833 ================================================================================ Target: command.') Prediction: irc command.') return await self.bot.responses.failure(message='Cannot disable that command.') class DisableCommand(Command): """Disables a command for this server. You must have Manage Server permissions or the Bot Admin role to use this ================================================================================ Example 1834 ================================================================================ Target: 'Pipeline created.' Prediction: new_pipeline_definition ret['changes']['old'] = old_pipeline_definition return ret def _pipeline_present_with_definition(name, pipeline_objects, pipeline_objects_from_pillars, parameter_objects ================================================================================ Example 1835 ================================================================================ Target: _create_put_request( Prediction: client.post( reverse('offer_lose', args=(offer_id,)), data={'status': 'lose'} ) def mark_offer_as_lose_with_reason(self, offer_id, reason): """ Mark ================================================================================ Example 1836 ================================================================================ Target: superbase = tokens Prediction: superbase = self.superbase superbase.add_vertex(token_to_vertex) # construct the second witness second_witness = self.merge(graph, first_witness.sigil, tokens) # let the scorer prepare the second witness ================================================================================ Example 1837 ================================================================================ Target: datalab.utils.commands.notebook_environment(), as_dict=False) Prediction: datalab.utils.get_schema_from_cell_body(cell_body)) if not record: raise ValueError('No schema found in cell body') # Get the datasource's schema from the cell body if not compressed: schema = google. ================================================================================ Example 1838 ================================================================================ Target: ) Prediction: sid=self._solution['sid'], date_created=self._solution['date_created'], date_updated=self._solution['date_updated'], ) return self._challenges def __repr__(self): """ Provide a ================================================================================ Example 1839 ================================================================================ Target: filename Prediction: base_name + suffix else: filename = self.base_name with open(filename, 'w') as f: f.write(self.data) f.write('\n') f.write(self.data_file) ================================================================================ Example 1840 ================================================================================ Target: self.fullscreen() Prediction: self.toggle_fullscreen(is_fullscreen) else: self.toggle_fullscreen(False) def toggle_fullscreen(self, is_fullscreen): """ Widget Action to Toggle fullscreen from the GUI """ self ================================================================================ Example 1841 ================================================================================ Target: start() Prediction: start() self._listener.start() self._listener.start() self._listener.start() self._listener.start() self._listener.start() self._listener.start() self._listener.start() self._listener. ================================================================================ Example 1842 ================================================================================ Target: pass Prediction: pass return self def _get_extra(self): ''' Return the extra attribute of the current object. ''' return self._extra def _set_extra(self, value): ''' Set the extra attribute of the current object ================================================================================ Example 1843 ================================================================================ Target: **blockchain_opts) Prediction: blockchain=blockchain_opts) else: return btc_get_singlesig_privkey(privkey_info, blockchain=blockchain_opts, **blockchain_opts) def get_privkey_info(privkey_bundle, ================================================================================ Example 1844 ================================================================================ Target: if _is_sqlalchemy_connectable(con): Prediction: if is_cursor: return _cursor_builder(con, schema, meta, is_cursor) else: return _sql_builder(con, schema, meta) def pandasSQL_builder(con, schema=None, meta=None, is_cursor= ================================================================================ Example 1845 ================================================================================ Target: sensitivity_input.__dict__)) Prediction: sensitivity_input.__dict__)) output_dict['sensitivity_output'] = (self._iterate_through_class( self.sensitivity_output.__dict__)) output_dict['contour_data'] = (self._iterate_through_class( ================================================================================ Example 1846 ================================================================================ Target: or app.config.TEMPLATE_FILE_EXTENSION) Prediction: if self.Meta.template_file_extension else 'html') template_name = os.path.join(self.Meta.template_folder, template_name) else: template_name = os. ================================================================================ Example 1847 ================================================================================ Target: create_tables, connection=connection) Prediction: create_tables) _schema.add_class(module) return module def create_virtual_module(module_name, schema_name, create_schema=False, create_tables=False, connection=None): """ Creates a python module with the ================================================================================ Example 1848 ================================================================================ Target: try: Prediction: if encoding is None: encoding = self.apparent_encoding # Decode unicode from given charset. if content is None: content = self.content # If content is unicode, decode it. if isinstance(content, unicode): content = ================================================================================ Example 1849 ================================================================================ Target: keys, values = zip(*update_dict.items()) Prediction: return True else: return False def upsert_table(db, table, key_cols, update_dict): """Fabled upsert for SQLiteDB. Perform an upsert based on primary key. :param SQLiteDB db: ================================================================================ Example 1850 ================================================================================ Target: raise ValueError('Unsupported VOEvent schema version:' + version) Prediction: raise ValueError('XML version %s is not 2.0' % version) else: version = v.attrib['version'] # We need to make sure that the version is correct. if version != '2.0': raise ValueError('XML ================================================================================ Example 1851 ================================================================================ Target: else: Prediction: if value is not None: config[option] = value return config def read_config_file(cls, config_file): """Read configuration file options.""" config = dict() section = cls.__name__ option = "warningregex ================================================================================ Example 1852 ================================================================================ Target: if success: Prediction: if success: return success return False def get_active_hits(self): ''' Get all HITs. ''' return self.get_hits(self.get_hits_filter()) def get_hits(self, filter ================================================================================ Example 1853 ================================================================================ Target: api_method=api_method Prediction: api_method=api_method, api_version=self.api_version, api_key=self.api_key, api_secret=self.api_secret, api_version_id=self.api_version_id, api ================================================================================ Example 1854 ================================================================================ Target: self.recv() Prediction: self.recv() return Message(message) def _get_command_id(self): """Returns the command id of the current command :returns: Command id :rtype: int """ return self._id def _get_command ================================================================================ Example 1855 ================================================================================ Target: response.status) == "200": Prediction: jbody["status"]) == "success": parsed_body["status"] = "success" parsed_body["message"] = "Order cancelled" elif str(jbody["status"]) == "error": parsed_body["status"] = "error" ================================================================================ Example 1856 ================================================================================ Target: return None Prediction: return None if score is None: return None return score def get_score_for_item(student_item): """Get the score for a particular student item Each student item should have a unique score. This function will return the score if ================================================================================ Example 1857 ================================================================================ Target: 'Invalid name "%s", previously defined as global.' % name, item Prediction: "Variable %s is already declared in global context" % name) if name in self._globals: raise VariableDeclarationException( "Variable %s is already declared in global context" % name) if name in self._globals: raise VariableDeclarationException ================================================================================ Example 1858 ================================================================================ Target: path: Prediction: irc_path: path = path + "/" + name else: path = path + "/" + irc_path + "/" + name if mkdir: path = path + "/" + name return path def _get_project_ ================================================================================ Example 1859 ================================================================================ Target: = 'T': Prediction: series.axes[i] in 'PM': ntimes *= series.shape[i] # make position axis first if positions > 1: ntimes *= positions # make series axis first if positions > 1: ntimes *= positions # ================================================================================ Example 1860 ================================================================================ Target: logger.warning("external attachments not supported") Prediction: return self.data ================================================================================ Example 1861 ================================================================================ Target: return scale_dtype(arr, args["out_dtype"]) Prediction: arr = to_math_type(arr) arr = to_math_type(arr) arr = to_math_type(arr) return arr def color_worker_to_color(src, window, ij, args): """A user ================================================================================ Example 1862 ================================================================================ Target: = env('CONSUMER_SECRET') Prediction: = env('CONSUMER_SECRET') if not self.access_token: self.access_token = env('ACCESS_TOKEN') if not self.access_token_secret: self.access_token_secret = env('ACCESS_ ================================================================================ Example 1863 ================================================================================ Target: return value Prediction: elif isinstance(value, list): value = [bleach.clean(value, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles, strip=False) for value in value] else: raise ValueError("value ================================================================================ Example 1864 ================================================================================ Target: return cls.fromtree(tree) Prediction: for node in tree.iter(): if node.tag == 'METS': yield node.text class Metadata(object): """ A class to store metadata about a METS document. """ def __init__(self, name, description, ================================================================================ Example 1865 ================================================================================ Target: class_ = self.class_ Prediction: tag = self.tag return new_obj def __repr__(self): return self.tag def __str__(self): return self.tag def __eq__(self, other): if isinstance(other, Asn1Tag): ================================================================================ Example 1866 ================================================================================ Target: logging.basicConfig(level=level, Prediction: format += yellow(" %(levelname)s: %(message)s") format += yellow(" %(filename)s: %(message)s") format += yellow(" %(lineno)d: %(message)s") format += yellow(" %(message ================================================================================ Example 1867 ================================================================================ Target: overlay(self.matchers) Prediction: run_matchers = run_matchers else: text.run_matchers = run_matchers def _maybe_run_matchers_for_text(self, text, matchers): """ OverlayedText should be smart enough to not run ================================================================================ Example 1868 ================================================================================ Target: all_keys Prediction: ia.list(all_keys) def get_all_values(self): """Get all values indexed. :return: All values :rtype: list(str) """ all_values = [] for values in self._index.values ================================================================================ Example 1869 ================================================================================ Target: template_dir=TEMPLATES_DIR, Prediction: 'audit_file_name')) audits.append(TemplatedFile('/etc/securetty', SecureTTYContext(), 'audit_file_name_with_timestamp')) audits.append(TemplatedFile('/etc/secure ================================================================================ Example 1870 ================================================================================ Target: return all_mpim_users Prediction: return all_mpim_users def _get_members(self, user_id): """ Gets the members within the multiple person instant message :param user_id: The user id :rtype: [object] { name: ================================================================================ Example 1871 ================================================================================ Target: else: Prediction: else: normalizer = locale.normalize return [locale.locale_alias for locale in locales] def _get_locale_alias(locale, locale_name): """ Return a locale alias for a locale. Parameters ---------- ================================================================================ Example 1872 ================================================================================ Target: return self Prediction: self.order_id = order_dict['order_id'] self.order_type = order_dict['order_type'] self.order_model = order_dict['order_model'] self.order_id = order_dict['order_id'] ================================================================================ Example 1873 ================================================================================ Target: return MaybeAGenerator Prediction: return MaybeAGenerator def maybe_b(generator): """ Generates either an arbitrary value of the specified generator or None. This is a class factory, it makes a class which is a closure around the specified generator. """ class MaybeAB ================================================================================ Example 1874 ================================================================================ Target: default = False Prediction: raise ArgumentException("Invalid default type for argument".format(name)) if value_type is int and default is None: raise ArgumentException("Invalid default type for argument".format(name)) if value_type is float and default is None: raise ArgumentException("Invalid ================================================================================ Example 1875 ================================================================================ Target: convert_datetime(timestamp) Prediction: 0001-01-01 00:00:00 elif timestamp[4] == '+': return 0001-01-01 00:00:00 elif timestamp[4] == '.': return 0001-01-01 00:00:00 elif timestamp[ ================================================================================ Example 1876 ================================================================================ Target: = numPix * bin_size Prediction: = int(len(image)/bin_size) numPix_cutout = int(len(image)/bin_size) numPix_wht_map = int(len(wht_map)/bin_size) numPix_sigma_ ================================================================================ Example 1877 ================================================================================ Target: read() Prediction: content def _write_range(self, start, end=0): """ Write a range of bytes in stream. Args: start (int): Start stream position. end (int): End stream position. 0 To not specify end. ================================================================================ Example 1878 ================================================================================ Target: if m Prediction: ] if results: return results[0] else: return None return None def _get_slug(self): """This method is used to generate a slug from the name attribute. It can be customized by subclasses. ================================================================================ Example 1879 ================================================================================ Target: try: Prediction: if not self.image_exists(image_id): logger.debug("image_id = '%s' does not exist", image_id) return False return True def image_exists(self, image_id): """ does provided image exists ================================================================================ Example 1880 ================================================================================ Target: self.__clear_mpls_auto_bandwidth_statistics_all = t Prediction: if load: t.load(load) return t def _set_clear_mpls_auto_bandwidth_statistics_all_by_id(self, v, load=False): """ Setter method for clear_mpls_auto_ ================================================================================ Example 1881 ================================================================================ Target: self._name) Prediction: """ The name of the report. """ ) self.add('description', """ The description of the report. """ ) self.add('sub_reports', """ A list of subreports. ================================================================================ Example 1882 ================================================================================ Target: import matplotlib.pyplot as plt Prediction: from matplotlib.transforms import Bbox, Bbox2tri from matplotlib.transforms import Bbox, Bbox2tri # get the data N = self.N Z = self.Z N_x = N//2 ================================================================================ Example 1883 ================================================================================ Target: self._grantsetter(client_id, code, request, *args, **kwargs) Prediction: request.save() return self.client.authorization_code_persist(code) def _get_authorization_code_for_client(self, client_id): """Get the authorization code for a client.""" return self.client.authorization_ ================================================================================ Example 1884 ================================================================================ Target: continue Prediction: filtered[name] = cookie.value continue # Send cookies with a domain if domain: filtered[name] = filter_cookies(domain) continue # Send cookies with a path if not path: filtered[name] = cookie ================================================================================ Example 1885 ================================================================================ Target: headers['User-agent'] = user_agent Prediction: headers.update(self.headers.copy()) self.session.headers['User-Agent'] = user_agent def set_cookies(self, cookies): """Sets the cookies in the requests session.""" self.cookies = cookies def set_headers( ================================================================================ Example 1886 ================================================================================ Target: [self.keybundle_cls( Prediction: ictree.Dict() self.issuer_keys[issuer]["keys"] = _keys return self.issuer_keys[issuer] def import_jwks_from_file(self, jwks_file, issuer): """ ================================================================================ Example 1887 ================================================================================ Target: data_backup = None Prediction: value = self.data return self.pack(value) def unpack(self, value): """Unpack the value as a binary representation. :attr:`data` is unpacked before the calling :meth:`.GenericMessage.unpack`. After that, ================================================================================ Example 1888 ================================================================================ Target: "Policy parameter %s:%s is invalid for v%s", Prediction: '%s: %s: %s' % (k, parm, value)) del kwargs[k] break else: logger.info('No version-specific optional parameters found') else: logger.info('No version ================================================================================ Example 1889 ================================================================================ Target: return False Prediction: return False return substr_graphemes[0] in str_sub_part def contains_graphemes(string, substring): """ Returns true if the sequence of graphemes in substring is also present in string. This differs from ================================================================================ Example 1890 ================================================================================ Target: '(?:(?:[zcs]h?|[rbpmfdtnlgkhwy])?%(a)sn%(consonant_end)s)|' Prediction: '(?:(?:[zcs]h?|[rbpmfdngkhw])?%(a)s)|' '(?:[bpmdtnljqxy]%(i)ssn%(consonant_end)s)|' '(?:[bpmdtnljq ================================================================================ Example 1891 ================================================================================ Target: = 'fun': Prediction: 'fun': rarg = 'm_fun' elif aspec.varargs = 'names': rarg = 'm_names' elif aspec.varargs = 'state': rarg = 'm_state' elif aspec.var ================================================================================ Example 1892 ================================================================================ Target: for module in self: Prediction: for module in self.get_modules(type_name): modules.append(module) return modules def get_modules_by_type(self, type_name): '''Getting modules by type name. Parameters ---------- type_name : ================================================================================ Example 1893 ================================================================================ Target: parse_argument_defs(lexer) Prediction: parse_args(lexer) return DirectiveDefinitionNode( start=start, description=description, name=name, args=args, expect_token=expect_token, expect_keyword=expect_keyword, ) ================================================================================ Example 1894 ================================================================================ Target: out Prediction: xt.render(out, self._parent) def _repr_html_(self, **kwargs): """Displays the HTML Map in a Jupyter notebook.""" if self._parent is None: self.add_to(Figure()) out = self ================================================================================ Example 1895 ================================================================================ Target: var_domain = self.grammar.parseString(self.network)['domain_variables'] Prediction: for var in self.variables: domain[var] = self.get_domain(var) return domain def get_domain_by_name(self, name): """ Returns the domain of the variable with the given name. Args ---- ================================================================================ Example 1896 ================================================================================ Target: name = self._pop() Prediction: name = token.value if name == '': name = '' if name == 'quotes': quotes = token.value elif name == 'quotes': quotes = '' elif name == 'quotes': quotes = ================================================================================ Example 1897 ================================================================================ Target: table = at.Table(rows=results, names=results[0].colnames, masked=True) Prediction: results.append(results) # Return the results return results def search(self, criterion, table, columns=''): """ Returns a table of records from *table* the same length as *criteria* with the best match for ================================================================================ Example 1898 ================================================================================ Target: return key['name'] Prediction: return key['name'] def delete(self, key): """Delete the key :return: Key name """ self.client.delete_object( Bucket=self.db_path, Key=key['name']) return key[' ================================================================================ Example 1899 ================================================================================ Target: time.sleep(10) Prediction: success = 0 break return success def _log_error(self, e): """log an error""" self.logger.error("Error: %s" % e) def _log_info(self, info): """log an info ================================================================================ Example 1900 ================================================================================ Target: Prediction: # replace None with None return self.catalog_split_yaml(kwargs_copy) def catalog_split_yaml_from_file(self, file_name, **kwargs): """ return the name of a catalog split yaml file """ kwargs_copy = self ================================================================================ Example 1901 ================================================================================ Target: order_dir = request.args.get("order[0][dir]") Prediction: order_column = order_column if order_column is not None else "id" order_column = order_column if order_column is not None else "id" order_column = order_column if order_column is not None else "id" order_column ================================================================================ Example 1902 ================================================================================ Target: 'H_{0}'.format(self.mol_code) Prediction: 'H_' + self.mol_code + 'W' else: if self.mol_code == 'HOH': hetero_flag = 'W' else: hetero_flag = 'H_' + self.mol_code + ' ================================================================================ Example 1903 ================================================================================ Target: byref(pnAdapterOutputIndex)) Prediction: ia_uint32(0), ia_uint32(0)) fn(byref(pnAdapterOutputIndex), ia_uint32(0), ia_uint32(0)) return pnAdapterIndex, pnAdapterOutputIndex def getDXGIOutputInfo ================================================================================ Example 1904 ================================================================================ Target: coordinates = value Prediction: coordinates = value else: value = i.replace("coordinates=", "") current_lab.coordinates = value current_lab.title = i current_lab.date = i.replace("date=", "") current_lab.description = ================================================================================ Example 1905 ================================================================================ Target: continue Prediction: continue seq_length = len(line.strip()) if seq_length == 0: continue if seq_length == 1: parsed.append(line.strip()) elif seq_length == 2: parsed.append(line. ================================================================================ Example 1906 ================================================================================ Target: if len(g) == 3: Prediction: if len(g) == 2: return g[0], g[1] else: return g[0], g[1] + 1 class _P2I(object): """ Class to represent a position in a list of positions. ================================================================================ Example 1907 ================================================================================ Target: prediction_method_name=prediction_method_name, Prediction: prediction_method_name=prediction_method_name, sequence_key_mapping=sequence_key_mapping, prediction_method_name_suffix="netmhc4", sequence_key_mapping_suffix="netmhc4", prediction ================================================================================ Example 1908 ================================================================================ Target: endswith('__'): Prediction: endswith('__'): continue if name.startswith('__') and name.endswith('__'): keep[name] = value return keep def _reset_kind_map_for_class(cls): """Clear the kind map for a ================================================================================ Example 1909 ================================================================================ Target: in value: Prediction: ~~ value: new_host.host_name = value elif '$HOSTNAME$' ~~ value: new_host.host_name = value.replace('$HOSTNAME$', '') elif '$HOSTNAME$' ~~ value: ================================================================================ Example 1910 ================================================================================ Target: setName(name) Prediction: add_field( 'Name', _isrc_name(name), _isrc_name(name), _isrc_name(name), _isrc_name(name), _isrc_name(name), _isrc ================================================================================ Example 1911 ================================================================================ Target: a[3] * b[0] + a[4] * b[3], Prediction: a[2] * b[0] + a[3] * b[3], a[2] * b[1] + a[3] * b[4], ] def _mmult_c(self, a, b): """ Returns the ================================================================================ Example 1912 ================================================================================ Target: } Prediction: } return organism def get_organism_by_name(self, name): """Select Enrichr organism by name: Human & Mouse: H. sapiens & M. musculus Fly: D. melanogaster Yeast: S ================================================================================ Example 1913 ================================================================================ Target: res Prediction: ustr(res) def make_native_dict_values(d): """Convert all values to native `str` type (recursively).""" res = {} for k, v in d.items(): # k = compat.to_native(k) ================================================================================ Example 1914 ================================================================================ Target: Exception: Prediction: # set_closure_cell = ctypes.pythonapi.PyCell_Set # set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object) # set_closure_cell.restype = ctypes.c_ ================================================================================ Example 1915 ================================================================================ Target: ctypes.c_int, MediaPlayer) Prediction: _Cfunction.c_long, (1,), None, _Cfunction.c_long, (1,), None, _Cfunction.c_long, (1,), None, _Cfunction.c_long, (1,), None, ================================================================================ Example 1916 ================================================================================ Target: return "{0}{1}?{2}".format(urls.BASE_URL, Prediction: return api_call(self.api_url, **api_query) def __build_url_for_language(self, language): """Builds the url for the language""" return self.api_url + '/' + language def __build_url ================================================================================ Example 1917 ================================================================================ Target: __PSRK_groups Prediction: PSRK_groups else: return {} def __get_PSRK_groups(self): r'''Dictionary of PSRK subgroup: count groups for the PSRK subgroups, as determined by `DDBST's online service \n' Prediction: c:formatCode>\n' ' {cache_size}\n' ' {cache_size}\n' ' {cache_size} 'SASresults': Prediction: xlabel: str = None, ylabel: str = None, xaxis: str = None, yaxis: str = None, xaxislabel: str = None, yaxislabel: str = None, xaxislabelfont: str = ================================================================================ Example 1954 ================================================================================ Target: np.pi/180 Prediction: np.pi/180 vr = vr * np.pi/180 pm_long = pm_long * np.pi/180 pm_lat = pm_lat * np.pi/180 else: a = a * np.pi/180 ================================================================================ Example 1955 ================================================================================ Target: ) Prediction: ) time.sleep(0.1) log.debug('psexec failed to connect to host %s on port %s', host, port) return False def wait_for_winexe(host, port, username, password, timeout=900): ================================================================================ Example 1956 ================================================================================ Target: RUNNING) Prediction: RUNNING) .filter(LJ.state == State.RUNNING) .filter(LJ.state == State.RUNNING) .filter(LJ.state == State.RUNNING) .filter(LJ.state == State. ================================================================================ Example 1957 ================================================================================ Target: results = None Prediction: # If the dateTimeFormat is not specified, then the default is # ``None``. if not dateTimeFormat: dateTimeFormat = 'Y-m-d H:i:s' # If the dateTimeFormat is specified, then the default is ================================================================================ Example 1958 ================================================================================ Target: add_job(partial( Prediction: sensors[sensor_id].set_child_value( child_id, value_type, value, children=self.sensors[sensor_id].new_state) def _handle_smartsleep(self, sensor_id, child_id, value_type, ================================================================================ Example 1959 ================================================================================ Target: return nb_markers, nb_samples Prediction: return nb_markers, nb_samples def get_final_numbers(filename, out_dir): """Copy the final_files file and get the number of markers and samples. :param filename: the name of the file. :param out_dir ================================================================================ Example 1960 ================================================================================ Target: self._add_legend() Prediction: self.legend = Element('div', {'class': 'legend'}) else: self.legend.set('class', 'legend') self.legend.set('id', 'legend') self.legend.set('style', 'visibility: hidden;') ================================================================================ Example 1961 ================================================================================ Target: platform.processor() Prediction: ia32_ver()[2] # Python is 32 bits. else: return None def _darwin_current_arch_info(self): """Return the current architecture.""" return self._darwin_current_arch() def _darwin_current ================================================================================ Example 1962 ================================================================================ Target: self.datamodel.get(self._deserialize_pk_if_composite(pk)) for pk in pks Prediction: { "id": pk, "name": name, "action": action } ] return render_template("action_post.html", items=items) else: return render_template("action_post.html", name ================================================================================ Example 1963 ================================================================================ Target: x, y, name) Prediction: x, y, w, h, name) def set_color(self, rgb, x=0, y=0, w=None, h=None, name=""): """Sets the color of the layer. Sets the color of the layer to the ================================================================================ Example 1964 ================================================================================ Target: = pathlib.Path( Prediction: = os.path.join(self.template_path, stack_name) # Build stack name stack_name = stack_template_name # Build stack template name stack_template_name = stack_template_name.replace('_', '-') ================================================================================ Example 1965 ================================================================================ Target: home(self.poses) Prediction: home(self.poses) # Then head self.poses = self._actuators['head']['plunger'].home(self.poses) # Then plunger motors self.poses = self._actuators['left']['plunger'].home(self.poses) ================================================================================ Example 1966 ================================================================================ Target: _encoding) Prediction: format, self.encoding) if format == 'png': data = data.encode(self.format, self.encoding) if format == 'pdf': data = data.encode(self.format, self.encoding) if format == 'cairo': ================================================================================ Example 1967 ================================================================================ Target: or (paragraph.parent and paragraph.parent.title.lower() in refs): Prediction: or (paragraph.parent and paragraph.parent.title.lower() in refs): paragraphs.append(paragraph) return paragraphs def parse_paragraph_references(self, paragraph_data): """ Returns a list of references in the ================================================================================ Example 1968 ================================================================================ Target: try: Prediction: return self._get_repository_hierarchy_design_session(proxy) def supports_repository_hierarchy_design(self): """Gets the repository hierarchy design session. Returns: (osid.repository.RepositoryHierarchyDesignSession) - a ================================================================================ Example 1969 ================================================================================ Target: retcode = res['retcode'] Prediction: if res: ret['nictags'] = res return ret ================================================================================ Example 1970 ================================================================================ Target: <= self.max_datapoints: Prediction: ~~ [None]: return Ok(False) # If the query is a select query, we need to check if the # query has a time duration. if query.get_type() == Keyword.SELECT: if query.get_datapoints() ================================================================================ Example 1971 ================================================================================ Target: client = ServerProxy(url, timeout=3.0) Prediction: return get_distribution_names(url) def get_distribution_names(url=None): """ Return all distribution names known by an index. :param url: The URL of the index. :return: A list of all known distribution names. ================================================================================ Example 1972 ================================================================================ Target: except (KeyError, OSError): Prediction: except OSError: pass return True def GetPrivileges(): """Returns the list of privileges for the current user.""" return [p for p in os.getlogin() if p.lower() in config.CONFIG["Server.privileges"]] ================================================================================ Example 1973 ================================================================================ Target: source) Prediction: source) args.append(args) if not os.path.exists(dest): os.makedirs(dest) if not os.path.exists(source): os.makedirs(source) if not os.path.exists( ================================================================================ Example 1974 ================================================================================ Target: return self.profile_dir Prediction: return self.profile_dir def _remote_profile_dir_override(self, profile_dir): """turns /home/you/.ipython/profile_foo into .ipython/profile_foo """ home = get_home_ ================================================================================ Example 1975 ================================================================================ Target: creds['AccessKeyId'] = os.environ['AWS_ACCESS_KEY_ID'] Prediction: creds['AWS_ACCESS_KEY_ID'] = os.environ['AWS_ACCESS_KEY_ID'] creds['AWS_SECRET_ACCESS_KEY'] = os.environ['AWS_SECRET_ACCESS_KEY'] if ================================================================================ Example 1976 ================================================================================ Target: ValueError: Prediction: iallreduce.KeyError: pass # Optional keys for key in ['output_min', 'output_max']: try: run_keys.remove(key) except iallreduce.KeyError: pass # Optional keys ================================================================================ Example 1977 ================================================================================ Target: f.attributes[k][0] Prediction: ia.get(k, f.featuretype) except AttributeError: return getattr(f, k) # If no id_spec, use the default auto-increment. return self._increment_featuretype_autoid(f.featuretype) ================================================================================ Example 1978 ================================================================================ Target: self.review_comment_set = True Prediction: raise SPDXValueError("Comment is not free form text") else: raise SPDXValueError("Comment is already set") else: self.review_comment_set = True self.review_comment = comment self.review_comment_text ================================================================================ Example 1979 ================================================================================ Target: if overflow > 0: Prediction: if color is not None: pylab.text(0.5, color, '=', val[val>=val_max], horizontal=True, vertical=True) else: pylab.text(0.5, '=', val[val ================================================================================ Example 1980 ================================================================================ Target: isinstance(element, (tuple, list)): Prediction: ustr.is_string(element): if element_maker.is_string(element): args.append(element_maker.string_to_xml(element)) else: args.append(element_maker.xml_to_string(element)) elif ================================================================================ Example 1981 ================================================================================ Target: self._db_curs.fetchone() Prediction: ue.fetchone() if user is None: return None return user def get_user_by_email(self, email): """ Fetch the user from the database The function will return None if the user is not found """ sql ================================================================================ Example 1982 ================================================================================ Target: api_url = api_url[:len(suffix) * -1] + '/api/package' Prediction: api_url = api_url[:-len(suffix)] version_list = [] for version in requests_get(api_url, verify=requests_verify): version_list.append(version['version']) return version_list def _get_ ================================================================================ Example 1983 ================================================================================ Target: vec2)), Prediction: vec2)), np.linalg.norm(vec1)) def angle_3points_2d(p0, p1, p2): ''' compute the angle in radians between three 2D points Calculated as the angle between p1-p0 and p2 ================================================================================ Example 1984 ================================================================================ Target: re_pat = _cache[pat] Prediction: for name in names: if pat.match(name): result.append(name) except: pass return result def get_all_names(names, pat): """Return the list of all names that match PAT""" import os ================================================================================ Example 1985 ================================================================================ Target: not None else None Prediction: ia_node else msg.copy( ack=0, sub_type=msg.gateway.const.Internal['I_ID_RESPONSE'], payload=node_id) def handle_id_response(msg): """Process an internal id response message ================================================================================ Example 1986 ================================================================================ Target: '['str']'. Received type: '%s'" % type( Prediction: '['str']'. Received type: '%s'" % type(url) if not self.cookies: return if self.cookies[cookieName] is None: return if self.cookies[cookieName].domain != url.domain ================================================================================ Example 1987 ================================================================================ Target: "http://www.w3.org/1999/xlink http://www.w3.org/1999/xlink.xsd", Prediction: "http://www.loc.gov/standards/mods/v3/mods-3-4.xsd" )) # add missing attributes params["ID"] = "MODS_VOLUME_%04d" % (volume_counter + 1) ================================================================================ Example 1988 ================================================================================ Target: return im Prediction: return im @classmethod def from_dataset_with_data(cls, dataset, data, constraints = (), **kwargs): """Construct a optimized inverse model from an existing dataset. A LWLR forward model is constructed by default. """ fm = LW ================================================================================ Example 1989 ================================================================================ Target: else: Prediction: else: for a in arguments: yield a def positional_args(arguments): """Generator for position arguments. Example ------- >>> list(positional_args(["arg1", "arg2", "--kwarg"])) ["arg ================================================================================ Example 1990 ================================================================================ Target: state["class_name"], Prediction: state["module_version"], state["module_version_string"], state["module_version_string_length"], state["module_version_string_offset"], state["module_version_string_length"], state["module_version_string_offset ================================================================================ Example 1991 ================================================================================ Target: result['bookmarks'] = bms[page-1] Prediction: res = jsonify(bms) except ValueError: res = jsonify(result['bookmarks']) current_app.logger.debug('total bookmarks:{}'.format(pagination_total)) current_app.logger.debug('per page:{} ================================================================================ Example 1992 ================================================================================ Target: break Prediction: def execUpdate(self, sql, parameters = None, cursorClass = MySQLdb.cursors.Cursor, InnoDB = False): """Execute SQL update.""" i = 0 errcode = 0 caughte = None while i < self.numTries ================================================================================ Example 1993 ================================================================================ Target: response.raise_for_status() Prediction: if response.status_code == 200: results.append(response.json()) else: break return results def get_paged_results(url, per_page=100, **params): """get a full list, handling APIv3 ================================================================================ Example 1994 ================================================================================ Target: 'Retrieving license assignment manager') Prediction: f"Service Instance Object: {service_instance}") # Get the license assignment manager manager = service_instance.get_license_assignment_manager() # Get the license assignment manager manager.get_license_assignment_manager() # Get the ================================================================================ Example 1995 ================================================================================ Target: site_label_1, site_label_2, coordination_1, coordination_2 ) Prediction: self.nearest_neighbour_interaction_hamiltonian[ site_label_1, site_label_2 ], site_label_2 ) return self.jump_probability def generate_nearest_neighbour_interaction_hamiltonian( self ================================================================================ Example 1996 ================================================================================ Target: StringIO() Prediction: ircode.parse_section(text, mode) if mode == 'exec': ast_section.exec(file) elif mode == 'eval': ast_section.eval(file) else: raise ValueError("Unknown mode: %s" % ================================================================================ Example 1997 ================================================================================ Target: outputs = F.Dropout(outputs, p=self.drop_outputs, axes=(axis,)) Prediction: outputs = F.Dropout(outputs, p=self.drop_outputs, axes=(axis,)) return outputs, states def _get_begin_state(self, F, begin_state, inputs, batch_size): """Returns the beginning state of the RNN ================================================================================ Example 1998 ================================================================================ Target: inputs['gmfs'].endswith('.csv'): Prediction: get('gmfs'): gmfs = dstore.get('gmfs', None) if gmfs is not None: gmfs = gmfs.split('\n') for gmfs_line in gmfs: if gmfs_ ================================================================================ Example 1999 ================================================================================ Target: try: Prediction: deps = dependencies[package] if package not in pkg_deps: continue deps[package] = {} deps[package][key] = versions[package] return dependencies, installed_packages, versions def recursive_dependencies(pkg_ ================================================================================ Example 2000 ================================================================================ Target: if self.stream is not None: Prediction: self._close_future = None # type: Optional[Future[None]] def __getattr__(self, name): """Get the callback attribute. This method is used to get the callback attribute. It is assumed that the attribute is a callable object ================================================================================ Example 2001 ================================================================================ Target: return DeviceStatus(friendly_name, model_name, manufacturer, Prediction: return DeviceStatus( friendly_name=friendly_name, model_name=model_name, manufacturer=manufacturer, cast_type=cast_type, uuid=uuid) except Exception as e: return None def get ================================================================================ Example 2002 ================================================================================ Target: Max('creation_date') Prediction: Max('creation_date') ).order_by('-creation_date') return ids def get_page_ids_by_slug_and_date(self, slug, date): """Return all page's id matching the given slug and date. This ================================================================================ Example 2003 ================================================================================ Target: self._stats['events_recieved'] += 1 Prediction: if etypes: e = etypes.get(e.type) else: e = e.type if e.type not in self._eventq: return e if e.type == 'event': return self._event ================================================================================ Example 2004 ================================================================================ Target: "buckets", timestamp Prediction: "buckets", "anomaly_score", "desc", "end", "exclude_interim", "expand", "from", "size", "sort", "start"), params) def get_buckets_by_id(self, job_id, timestamp ================================================================================ Example 2005 ================================================================================ Target: boundDnaFrames=boundDnaFrames, helical=helical, Prediction: boundDnaFrames=boundDnaFrames, helical=helical, unit=unit, which=which, err_type=err_type, tool=tool, outFile=outFile) if len(energy_t) == 0: ================================================================================ Example 2006 ================================================================================ Target: new_location Prediction: new_location def _get_build_location(self): """Return the build location for the package. This is only called by self.egg_info_path to fix the temporary build directory. """ if self.source_dir is not None: ================================================================================ Example 2007 ================================================================================ Target: else: Prediction: self.target_ref = value def set_target_type(self, value): """ Setter for 'target_type' field. :param value - a new value of 'target_type' field. Required field. Must be a String type. """ ================================================================================ Example 2008 ================================================================================ Target: file_) Prediction: file_.readlines()) except IOError: raise CLIError("Could not open population file: %s" % args.population) try: with open(args.output, 'w', encoding=args.encoding) as file_: file_.write(seq) ================================================================================ Example 2009 ================================================================================ Target: _impl_decl_types[ Prediction: decl_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) ) def _find_multiple(self ================================================================================ Example 2010 ================================================================================ Target: lon) Prediction: lon) lat = ctypes.c_double(lat) alt = ctypes.c_double(alt) re = ctypes.c_double(re) f = ctypes.c_double(f) return pgrrec(body, lon ================================================================================ Example 2011 ================================================================================ Target: udf.session.add_all(y for y in udf.apply(doc, **kwargs)) Prediction: try: self.udf(doc, **kwargs) except Exception as e: self.pb.update(1) raise e # Run progress bar self.pb.update(1) def _apply_st_with_progress( ================================================================================ Example 2012 ================================================================================ Target: event.mimeData() Prediction: event.data.get() if data.get('data') == '': return if self.dragEnterEvent(event): self.dragEnterEvent(event) self.dragEnterEvent(event) else: self.dragEnter ================================================================================ Example 2013 ================================================================================ Target: return not expired and self.routers and has_server_for_mode Prediction: return expired and has_server_for_mode def is_fresh_for_mode(self, access_mode): """ Indicator for whether routing information is still usable for a given access_mode. """ log_debug("[#0000] C ================================================================================ Example 2014 ================================================================================ Target: } Prediction: """ def _rpc_response_callback_with_correlation_id(self, channel, method_frame, header_frame, body): """ Internal callback used by consume() Parameters ---------- channel: object Channel from which the callback originated ================================================================================ Example 2015 ================================================================================ Target: fn2(bT): Prediction: ia(x): if x is None: return None if x.isLeaf(): return l[x.traversalID] else: return fn(x) return ia def annotateTree(bT, fn): ================================================================================ Example 2016 ================================================================================ Target: -np.inf Prediction: irel = -np.inf else: if fit_for_distance: if dist < self.ic.mindist or dist > self.ic.maxdist \ or AV < self.ic.minAV or AV > self.ic.maxAV: ================================================================================ Example 2017 ================================================================================ Target: _current_lines.extend(['{0}:{1}\n'.format(key, value) Prediction: _current_lines.append(_item) _new_lines = [] for _item in _new: _new_lines.append(_item) _current_lines.extend(_new_lines) _current_lines.append(name) ================================================================================ Example 2018 ================================================================================ Target: msg.write(logger) Prediction: logger.log(msg) def _writeTracebackMessage(logger, typ, exception, traceback): """ Write a traceback to the log. @param typ: The class of the exception. @param exception: The L{Exception} instance. ================================================================================ Example 2019 ================================================================================ Target: TabPost.select().where( Prediction: irec.get_all_records(current_rec) next_rec = None for rec in recs: if rec.time_create >= current_rec.time_create: next_rec = rec break return next_rec def ================================================================================ Example 2020 ================================================================================ Target: else: Prediction: else: open_func = gzip.open with open(destination, "wb") as f: f.write(self.download_data(url, filename)) f.close() except IOError: return None return destination ================================================================================ Example 2021 ================================================================================ Target: for y in range(self.height): Prediction: for y in range(self.height): if self.matrix[x][y] == before: self.matrix[x][y] = after return self def set_color(self, before, after): """ Sets a color on a surface ================================================================================ Example 2022 ================================================================================ Target: return None Prediction: return None def __repr__(self): return self.__class__.__name__ + '(' + str(self) + ')' def __str__(self): return self.__class__.__name__ + '(' + str(self) + ')' ================================================================================ Example 2023 ================================================================================ Target: if conditions: Prediction: if self.skip: conditional = 'if (%s)' % self.skip else: conditional = 'if (%s)' % self.condition js_code = """ var plot_id = %s; var plot_id_str = %s ================================================================================ Example 2024 ================================================================================ Target: None: Prediction: ### not None: for keypair in keypairs: results.append(Keypair(keypair.text)) else: results.append(Keypair(None)) return results def describe_keypairs_by_id(self, xml_ ================================================================================ Example 2025 ================================================================================ Target: readlines() Prediction: readlines() if error: print error print "Error: " + error[0] print "Error: " + error[1] print "Error: " + error[2] print "Error: " + error[3] print " ================================================================================ Example 2026 ================================================================================ Target: path.isdir(path): Prediction: path.exists(path): raise ValueError("Include path '%s' does not exist" % path) # Add the path to the include path os.environ['PYTHONPATH'] += path def load_library_path(paths): """ ================================================================================ Example 2027 ================================================================================ Target: for score_name in eval_headers: Prediction: eval_results = [] for i in range(len(scores)): eval_results.append(eval_headers[i]) eval_results.append(scores[i]) # STEP 5: write the results with tmp_output_path.open( ================================================================================ Example 2028 ================================================================================ Target: fix_header_comment( currentFile, timestamp ) Prediction: if currentFile.startswith( '.' ): continue if currentFile.endswith( '.txt' ): continue if currentFile.endswith( '.xml' ): continue if currentFile.endswith( '.xml.gz' ): ================================================================================ Example 2029 ================================================================================ Target: if corrected: Prediction: if k == 0: k = len(model.kwds) + len(model.args) else: k = k + 1 if k == 0: k = len(model.kwds) + len(model.args) else: ================================================================================ Example 2030 ================================================================================ Target: {0}'.format(n_widths)) Prediction: ###\n') self._io.writeln(n_widths) self._io.text('Number of constants based on column IDs: ###\n') self._io.writeln(n_id) self._io.text('Number of constants based ================================================================================ Example 2031 ================================================================================ Target: is not None: Prediction: ia_key: api_key = click.confirm("Please enter your API key") else: api_key = click.confirm("Please enter your API key") password = click.prompt("Please enter your password") if username and password: return api ================================================================================ Example 2032 ================================================================================ Target: if gss_authenticated == AUTH_SUCCESSFUL: Prediction: if cc_file is None: cc_file = os.path.join(self.cc_dir, 'gssapi.cc') if not os.path.exists(cc_file): raise IOError('cc_file %s does not exist' % cc ================================================================================ Example 2033 ================================================================================ Target: (self.credentials, Prediction: self.credentials = AzureTokenAuthentication( client_id=os.environ[constants.ENV_ACCESS_TOKEN], secret=os.environ[constants.ENV_ACCESS_SECRET], tenant=os.environ[constants. ================================================================================ Example 2034 ================================================================================ Target: lookup_field.name) Prediction: lookup_field.name) elif isinstance(value, Model): return value.name else: return value def coerce_single_instance(lookup_field, value): """ Convert from whatever value is given to a scalar value for lookup_field ================================================================================ Example 2035 ================================================================================ Target: dirs) Prediction: dirs, names_only=names_only) if not ret: return ret for name in ret: if not names_only: if isinstance(name, list): ret.append(name) else: ret.append(name ================================================================================ Example 2036 ================================================================================ Target: weights Prediction: xt.diag(weights) def _fix_weights(weight_fun, *args): """Ensure random weight matrix is valid. TODO: The diagonally dominant tuning currently doesn't make sense. Our weight matrix has zeros along the diagonal, so multiplying ================================================================================ Example 2037 ================================================================================ Target: text.append(descendant.nodeValue) Prediction: text.append(descendant.text) return '\n'.join(text) def parse_minidom(html): """ >>> parse_minidom('

one

two
threefour
1: print(func.__name__, ':', args, kwargs) else: print(func.__name__, ':', args, kwargs) return func(*args, **kwargs) return wrapper return make_wrapper @ ================================================================================ Example 2041 ================================================================================ Target: False) Prediction: False) ema_count_mean = tf.get_variable( name="ema_count_mean", shape=[bottleneck_size], initializer=tf.constant_initializer(0.0), trainable=False) ema_count ================================================================================ Example 2042 ================================================================================ Target: if self._read() != ";": Prediction: self._emit(tokens.HTMLEntityEnd()) def _really_parse_entity_with_numeric(self): """Parse an HTML entity and ensure that it is valid.""" self._emit(tokens.HTMLEntityStart()) self._head ================================================================================ Example 2043 ================================================================================ Target: grad_x.scatter_(1, indices, g.gather(1, indices)) Prediction: grad_y = torch.zeros_like(g, requires_grad=False) for i in range(batchSize): if i == 0: g[indices[i]] = 1 else: g[indices[i]] = 0 grad ================================================================================ Example 2044 ================================================================================ Target: libspice.sphcyl_c(r, colat, lons, ctypes.byref(radius), ctypes.byref(lon), Prediction: return ctypes.c_double(radius * cos(lat) * cos(lon) + colat * sin(lat) * sin(lon)) def sphlat(r, colat, lons): """ Convert from spherical coordinates to latitudinal coordinates. http ================================================================================ Example 2045 ================================================================================ Target: confpath = locate_config( Prediction: content = open(confname, 'r').read() config[confname] = content return config def load_config_from_file(app_name, *args, **kwargs): """ Given a path to a file, parse its lines in ini ================================================================================ Example 2046 ================================================================================ Target: content_type = 'multipart/form-data; boundary=%s' % boundary Prediction: return body.getvalue() def encode_multipart_formdata(fields, files): """Encode multipart form data. :arg dict fields: Fields to be encoded :arg dict files: Files to be encoded :returns: Encoded binary string ================================================================================ Example 2047 ================================================================================ Target: Exception: Prediction: uevent: HendrixOptionParser.print_help() return if action == 'run': HendrixOptionParser.print_help() return if action == 'stop': HendrixOptionParser.print_help() return ================================================================================ Example 2048 ================================================================================ Target: header_file = "%s-header.vcf" % utils.splitext_plus(tx_out_file)[0] Prediction: tx_out_file.write(replace_file) tx_out_file.write(base_fix_file) tx_out_file.write(exist_files[0]) tx_out_file.write(exist_files[1]) tx ================================================================================ Example 2049 ================================================================================ Target: add_alignment_errors(ae) Prediction: append(ae) self._profile_errors.append(ae) self._profile_errors.append(ae) self._profile_errors.append(ae) self._profile_errors.append(ae) self._profile_errors.append(ae) ================================================================================ Example 2050 ================================================================================ Target: = None Prediction: ================================================================================ Example 2051 ================================================================================ Target: tags = soup.find_all(**search) Prediction: for item in soup.select('li[class="file-item"]'): if item.find(attr): item.replace(attr, search[attr]) # replace all img listings with an appropriate path... for key, attributes in attrs.items(): ================================================================================ Example 2052 ================================================================================ Target: 'display.max_rows') Prediction: verbose=False) return curves_df def get_turbine_types_by_manufacturer(print_out=True): r""" Get the names of all possible wind turbine types for which the power coefficient curve or power curve is provided in the Open ================================================================================ Example 2053 ================================================================================ Target: else: Prediction: doc = doc.parent self.parent.projects = theseProjects return None def get_project_title(self): """*get the project title* **Return:** - None **Usage:** .. code-block:: python ================================================================================ Example 2054 ================================================================================ Target: )) Prediction: "The needs calculator is a tool to help you estimate the costs of your projects.", "", "", "", "", "", "", "", "", "", "", "", ================================================================================ Example 2055 ================================================================================ Target: submission=submission) Prediction: submission=submission) page.load() return page def open_submission_page_with_oauth(self, url=None, submission=None): """ Open an instance of the submission page for the given submission URL. """ from ================================================================================ Example 2056 ================================================================================ Target: basestring): Prediction: str): raise OLEErrorNotimpl("path must be a string") if not path: raise OLEErrorNotimpl("path must not be empty") if path.endswith(self.extension): raise OLEErrorNotimpl("path must not end with ================================================================================ Example 2057 ================================================================================ Target: start = (page_number - 1) * page_size Prediction: if page_number < 0: page_number = 1 if page_number < page_size: page_number = page_number + 1 if page_number < page_size: page_number = page_number + 1 return page_ ================================================================================ Example 2058 ================================================================================ Target: } Prediction: } def get_full_name(self): """Return the full name of the user""" return self.email def get_last_login(self): """Return the last time the user logged in""" return self.last_login def ================================================================================ Example 2059 ================================================================================ Target: ast.walk(self.tree): Prediction: irc.parse_irc_node(self.node): if node.type == 'command': self.run_command(node) elif node.type == 'variable': self.run_variable(node) elif node.type == 'function': ================================================================================ Example 2060 ================================================================================ Target: not be None') Prediction: ia specified') # get the source directory src = self.src if src is None: src = self.src_dir # get the destination directory dest = self.dest if dest is None: dest = self.dest_dir ================================================================================ Example 2061 ================================================================================ Target: if state_machine_manager.is_state_machine_open(load_path): Prediction: if recent_opened_notification: logger.info("Opening state machine from %s", load_path) return rafcon.core.state_machine.StateMachine(load_path) logger.info("Opening state machine from %s", load_path) ================================================================================ Example 2062 ================================================================================ Target: self.is_heroku: Prediction: ueberall: self.install_on_ueberall() elif self.is_local: self.install_on_local() elif self.is_local_with_docker: self.install_on_local_with_docker() ================================================================================ Example 2063 ================================================================================ Target: break Prediction: last_slot = None else: if slot.end_time != item.get_start_time(): non_contiguous.append(item) last_slot = None if last_slot: non_contiguous.append(item ================================================================================ Example 2064 ================================================================================ Target: None Prediction: None def _get_periodic_snapshots(self): """ Get the periodic snapshots. """ self._periodic_thread = threading.Thread(target=self._periodic_snapshots) self._periodic_thread.daemon = True ================================================================================ Example 2065 ================================================================================ Target: return s Prediction: raise UnicodeError('unsupported encoding: %s' % encoding) def _encode_all(s, errors='strict'): """Encode all characters in the string s using the codec registered for encoding.""" return _encode(s, encoding=_DEFAULT_ENCODING, ================================================================================ Example 2066 ================================================================================ Target: LOGGER.info("{0} | Replacing spaces with tabs!".format(reStructuredText_to_html.__name__)) Prediction: file.write(output) file.close() return True def reStructuredText_to_html(input, output, css_file): """ Outputs a reStructuredText file to html. :param input: Input reStructuredText ================================================================================ Example 2067 ================================================================================ Target: continue Prediction: return False return True def test_has_data(d, fullname): """Test if any of the `keys` of the `d` dictionary starts with `fullname`. """ fullname = r'%s-' % (fullname, ) ================================================================================ Example 2068 ================================================================================ Target: if (pid == 0): # The second child. Prediction: if pid == 0: # The second child. # The second child is a session leader. It's responsible for its # cleanup. It also inherits the parent's process group ID. os.setsid() # Is ignoring SIGHUP necessary? ================================================================================ Example 2069 ================================================================================ Target: return S[tuple(sort_slice)] Prediction: return S[tuple(sort_slice)], None def axis_sort(S, axis=-1, index=False, value=None): '''Sort an array along its axes. Examples -------- Visualize NMF output for a spectrogram S >>> ================================================================================ Example 2070 ================================================================================ Target: y += p.height() + self.padding Prediction: x += p[0] y += p[1] return (x, y) def _get_preview(self, x, y): "Returns the preview for a given coordinate" x = y = 10 for k, p in self. ================================================================================ Example 2071 ================================================================================ Target: with codecs.open(outfilename, 'wb', 'windows-1252') as outf: Prediction: if self.is_mak: self.write_mak(outfilename) else: self.write_mak(outfilename, self.mak_file) def write_mak(self, outfilename=None): """Write or ================================================================================ Example 2072 ================================================================================ Target: fields: Prediction: ia_fields: return fields if not ia_fields[0] in fields: return fields if not ia_fields[0] in table.fields: return fields return [ (ia_fields[0], fields[ia_fields ================================================================================ Example 2073 ================================================================================ Target: return self.form(formdata, obj=self.resource) Prediction: if formdata: return formdata else: return None def get_form_kwargs(self): """Get form kwargs.""" return { 'form': self.form, 'form_kwargs': self.form_kwargs, ================================================================================ Example 2074 ================================================================================ Target: sys.exit(tensorboard.main()) Prediction: tensorboard.log_info("TensorFlow version: %s" % program.get_version()) tensorboard.log_info("TensorFlow version: %s" % program.get_version()) tensorboard.log_info("TensorFlow version: %s" % program. ================================================================================ Example 2075 ================================================================================ Target: return self.http_session.request(method, url, json=json, data=data) Prediction: if method == 'GET': if data is None: data = {} else: data = data or {} if json: data = jsonify(data) else: data = data or {} if data: url = ================================================================================ Example 2076 ================================================================================ Target: "(%s)" % ", ".join(arg) Prediction: ia_to_tuple(arg) else: args[i_arg] = arg # Supporting keyword arguments in def statement: for i_arg, arg in enumerate(args): if isinstance(arg, list): args[i_arg] ================================================================================ Example 2077 ================================================================================ Target: > 0: Prediction: ia not 0: self._sock.send(self._out_packet[i]) self._out_packet[i] = None else: self._sock.send(self._out_packet[i]) self._out_packet[i] = None ================================================================================ Example 2078 ================================================================================ Target: value") Prediction: ia field" % fieldname) return fieldname def get_field_data(self, fieldname): """fieldname is required""" if self.request.form and fieldname not in self.request.form.keys(): raise Exception("Required field not found ================================================================================ Example 2079 ================================================================================ Target: self._transcoding(description) Prediction: 自定义的文字 hq_music_url = self._transcoding(hq_music_url) thumb_media_id = self._transcoding(thumb_media_id) return self._parse_response(music_url, title, description, ================================================================================ Example 2080 ================================================================================ Target: else: Prediction: else: raise ValueError("ifo list must be empty") def ifo_list(self): """Return the ifo list. If only one ifo in the ifo list this will be that ifo. Otherwise an error is raised. ================================================================================ Example 2081 ================================================================================ Target: RawInline('html', r'')] \ Prediction: Space(), Str(''), Space()] elif isinstance(references[attrs[0]], str): # Tagged reference value[0]['c'][1] = [RawInline('html', r''), ================================================================================ Example 2082 ================================================================================ Target: 0][:] = [subfield for subfield in field[0] Prediction: 0] = subfield_code rec.remove(field) break return rec def record_delete_all_subfields(rec, tag): """Delete all subfields with tag in the record.""" ind1, ind2 = _wash_indic ================================================================================ Example 2083 ================================================================================ Target: 'enumvalue', enumvalueTagProcessor(**self.opts)) Prediction: 'enumeration_name', enumerationTagProcessor(**self.opts), ) register('enumeration_value', enumerationTagProcessor(**self.opts), ) register('enumeration_type', enumerationTagProcessor(**self.opts ================================================================================ Example 2084 ================================================================================ Target: fitalpha = fit['q%d' % qubit]['fit'][1] Prediction: if isinstance(qubit, int): qubit = qubit + 1 if isinstance(qubit, int): qubit = qubit + 1 if isinstance(qubit, int): qubit = qubit + 1 if isinstance(qubit, int): ================================================================================ Example 2085 ================================================================================ Target: raise ProtocolError(cls.INTERNAL_ERROR, msg) from None Prediction: raise TypeError(msg) class JSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, basestring): return json.dumps(obj) elif isinstance(obj, (list, tuple)): return json.d ================================================================================ Example 2086 ================================================================================ Target: fluxname} Prediction: fluxname} def _define_fit_param_names_with_defaults(self): """ Convenience function to define mappings between the names of the parameters in the initial guess table (and the name of the fitted parameters) and the actual name of the parameters ================================================================================ Example 2087 ================================================================================ Target: 'no betas found, please run regression before bootstrapping' Prediction: # assert hasattr(self, 'betas_'), # assert hasattr(self, 'betas_'), assert hasattr(self, 'betas'), assert hasattr(self, 'betas_'), assert hasattr(self, 'betas ================================================================================ Example 2088 ================================================================================ Target: bounds_error=False) Prediction: self.INTERPOLATOR_TYPE, self.INTERPOLATOR_STEP) stddevs.append(interpolator_std) return stddevs def _get_stddevs_by_type(self, dists, mag ================================================================================ Example 2089 ================================================================================ Target: string.ascii_uppercase Prediction: string.ascii_uppercase if not isinstance(letters, str): letters = letters.lower() if not isinstance(letters, str): letters = letters.lower() if not isinstance(letters, str): letters = letters.lower() ================================================================================ Example 2090 ================================================================================ Target: attrib['provider'], Prediction: attrib['provider'], resource_fs=resource_fs, static_dir=static_dir, external_transcripts=external_transcripts ) except Exception as e: print(e) print(transcript_file_name) ================================================================================ Example 2091 ================================================================================ Target: -app %s' % (dockerfile_root, self.subdomain) Prediction: a %s' % (dockerfile_root, self.subdomain) self._handle_command(sys_command, print_pipe=True) sys_command = 'cd %s; heroku container:push web --app %s' % (dockerfile_root, self ================================================================================ Example 2092 ================================================================================ Target: except InvalidInputError as ex: Prediction: except AttributeError: data = editor.data() self.setData(data, index) return self.data(index) def setModelData(self, editor, model, index, value): """ Sets data from the editor widget and stores it in the ================================================================================ Example 2093 ================================================================================ Target: parts[0]])): Prediction: ])): return False return True def is_full_user_string(user_string): """Returns True if a string is a valid user string.""" if not user_string[0] == "@": return False parts = user_string[ ================================================================================ Example 2094 ================================================================================ Target: fd.write('\n'.join(collection).encode('utf-8')) Prediction: for word in collection: fd.write(word.encode('utf-8')) self.log.info('%s: %s' % (filename, collection)) def write_file(self, filename, collection): """ Writes a collection of stop ================================================================================ Example 2095 ================================================================================ Target: y1: Prediction: xt: x0, y0 = xt, y0 x1, y1 = y1, y1 if y0 > y1: x0, x1 = x1, x0 y0, y1 = y1, y0 ================================================================================ Example 2096 ================================================================================ Target: path, headers=context.headers, query=context.query, Prediction: path, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body, body ================================================================================ Example 2097 ================================================================================ Target: except: Prediction: except KeyError: return [] # sort by task name t = sorted(t, key=lambda x: x.name) # serialize each task for task in t: if strict_json: task.serialize(strict_json= ================================================================================ Example 2098 ================================================================================ Target: .. phmmer output found for %s as query and %s as database' % (query, db)) Prediction: ph1 file already exists, running phmmer with %s as query and %s as database' % (query, db)) os.system('phmmer -o %s.ph1 --tblout %s.ph2 --acc --noali --notextw -E %s ================================================================================ Example 2099 ================================================================================ Target: IndexError Prediction: ue_index_error(self._index, self._group_name, self._group_name_len) self._open = False self._group_name = None self._group_name_len = None self._group_name_index = ================================================================================ Example 2100 ================================================================================ Target: for attribute_tuple in other_attributes: Prediction: for attr in other_attributes: setattr(result, attr[0], attr[1]) return result def create_enum_object_with_default(list, list_name=None, other_attributes=None, attribute_object=None): """ ================================================================================ Example 2101 ================================================================================ Target: ) Prediction: ) def _set_quality(encoder, quality): """ This helper function sets a specific Brotli encoder quality, checking the return code and raising :class:`Error ` if it is invalid. """ rc = ================================================================================ Example 2102 ================================================================================ Target: 'word': word, Prediction: 'word': word, 'start': start, 'end': i, }) start = i else: word = text[start:] tokens.append({ 'word': word, 'start': start, 'end ================================================================================ Example 2103 ================================================================================ Target: dynamodb.get_table(name) Prediction: ubl.get_table(name, auth=auth, eager=eager) if table is not None: return table table = boto.connect_dynamodb(*auth) if table is not None: return table table = boto.connect ================================================================================ Example 2104 ================================================================================ Target: in_fmt Prediction: ia.format(in_fmt) return np.fromfile(in_file, fmt) def read_file(in_file, in_fmt=None): """ Reads in a file from disk. Arguments: in_file: The name ================================================================================ Example 2105 ================================================================================ Target: p1_inside = True Prediction: p1_inside = True else: line = (isec[0], isec[1], line[2], line[3]) p0_inside = False p1_inside = False if p0_inside and p1_inside: ================================================================================ Example 2106 ================================================================================ Target: value = bool(write_word & mask) Prediction: write(write_word) else: self.miso.write(write_word) if clock_phase: self.miso.write(write_word >> shift) else: self.mosi.write(write_word >> shift) ================================================================================ Example 2107 ================================================================================ Target: id_grupo_equipamento Prediction: id_grupo_equipamento direito_map['leitura'] = leitura direito_map['escrita'] = escrita direito_map['alterar_config'] = alterar_config direito_ ================================================================================ Example 2108 ================================================================================ Target: ET.SubElement(police_priority_map, "name") Prediction: urn:brocade.com:mgmt:brocade-policer:name police_priority_map_exceed = ET.SubElement(police_priority_map, "police-priority-map-exceed", name_key) police_priority_map_ ================================================================================ Example 2109 ================================================================================ Target: while True: Prediction: if args.server: server = server.init(args.server) else: server = server.init() if args.port: port = int(args.port) else: port = server.get_port() if ================================================================================ Example 2110 ================================================================================ Target: return books Prediction: return books def get_books_for_schedule(self, schedule): """ Returns a dictionary of data. SLNs are the keys, an array of Book objects are the values. """ slns = self._get_slns(schedule) ================================================================================ Example 2111 ================================================================================ Target: return hparams Prediction: # Use the same embedding size for all heads. hparams.embedding_size = 1024 # Use the same embedding size for all heads. hparams.embedding_size_shared = True # Use the same embedding size for all heads. hparams. ================================================================================ Example 2112 ================================================================================ Target: self.set_option('rich_mode', not checked) Prediction: self.show_source_code() def toggle_show_source_code(self): """Toggle show source code""" if self.show_source_code: self.docstring = not self.docstring self.force_refresh() self ================================================================================ Example 2113 ================================================================================ Target: PrintableDict Prediction: {p.name: p for p in pores} return pdict, throats def find_path(network, pore_pairs, weights=None): r""" Find the shortest path between pairs of pores. Parameters ---------- network : OpenPN ================================================================================ Example 2114 ================================================================================ Target: } Prediction: } } return self.update(alert_condition_nrql_id, policy_id, name=name, threshold_type=threshold_type, query=query, since_value=since_value, terms=terms, expected_groups=expected_groups, ================================================================================ Example 2115 ================================================================================ Target: if raw_result.status != 204: Prediction: if raw_result.status_code not in [204]: raise APIException(http_status_code=raw_result.status_code) return self.send(self.version, 'DELETE', '%s/%s' % (href, self.id ================================================================================ Example 2116 ================================================================================ Target: append(figure_after) Prediction: append(figure_after) elif orientation == "vert": # Append to the figure list the power spectrum of the signal before filtering. list_figures[-1].append(figure_before) else: # Append to the figure list the power spectrum of the ================================================================================ Example 2117 ================================================================================ Target: return _to_lisp_backup(o, keywordize_keys=keywordize_keys) Prediction: return to_lisp(o, keywordize_keys) def to_lisp(o, keywordize_keys: bool = True): """Recursively convert Python collections into Lisp collections.""" if not isinstance(o, (dict, frozenset, list, ================================================================================ Example 2118 ================================================================================ Target: except AttributeError: Prediction: except TypeError: raise ValueError("Invalid date: %s" % date) return cls(date) def from_datetime(cls, date): """ Returns a Month instance from the given datetime.datetime object """ try: ================================================================================ Example 2119 ================================================================================ Target: else: Prediction: else: return self.minrps def rps_at_min(self, t): '''Return rps for second t''' if 0 <= t <= self.duration: return self.minrps + \ float(self.maxr ================================================================================ Example 2120 ================================================================================ Target: return 5 Prediction: return 5 if value <= 0x3ffffffff: return 6 if value <= 0x1fffffffff: return 7 if value <= 0xfffffffe: return 8 if value <= 0x7ffffffffff: return 9 if value <= 0x3fffffffffff: return ================================================================================ Example 2121 ================================================================================ Target: j].addr Prediction: j] else: return None def get_xy_at(self, xy, addr=True): """Get the agent with xy-coordinate in the grid. If *addr* is True, returns only the agent's address. If no such ================================================================================ Example 2122 ================================================================================ Target: for app in settings.INSTALLED_APPS: Prediction: for app in INSTALLED_APPS: if app_name == app: return app_name return None def _get_app_module_path(module_label): """ Given a module label, loop over the apps specified in the INST ================================================================================ Example 2123 ================================================================================ Target: self.error_handler.handle_error(exceptions.InvalidEventTagException(enums.Errors.INVALID_EVENT_TAG_FORMAT)) Prediction: self.error_handler.handle_error(exceptions.InvalidEventTagException(enums.Errors.INVALID_EVENT_TAG_FORMAT)) return False return True def _validate_user_inputs_for_event(self, event_tags=None): ================================================================================ Example 2124 ================================================================================ Target: print('\n'.join(["%s - %s" % (_[0], _[1]) for _ in results_normalized])) Prediction: if args.search_term: results_normalized.append(results_normalized) if args.search_term == 'all': results_normalized.append(results_normalized) if args.search_term == 'all_packages': ================================================================================ Example 2125 ================================================================================ Target: "full_name": full_name, Prediction: "password": auth.get_password(owner_name), "organization": org_name, "full_name": full_name, "description": description, "website": website, "location": location, } return self.api ================================================================================ Example 2126 ================================================================================ Target: if y in matched_b: Prediction: matched_a.pop(x) matched_b.pop(old_match) new_matches.append((x, y)) l.debug("FunctionDiff: adding possible match (%#x, %#x)", x.addr, y.addr ================================================================================ Example 2127 ================================================================================ Target: output = ET.SubElement(get_stp_brief_info, "output") Prediction: get_stp_brief_info.tag = "get_stp_brief_info" get_stp_brief_info.attrib["spanning_tree_mode"] = "spanning_tree_mode" get_stp_brief_info.att ================================================================================ Example 2128 ================================================================================ Target: button.setChecked(False) Prediction: button.setEnabled(enabled) def enableEditing(self, enabled): """Enable the editing buttons to add/remove rows/columns and to edit the data. This method is also a slot. In addition, the data of model will be made editable, ================================================================================ Example 2129 ================================================================================ Target: if interface_name in networks: Prediction: if interface_name in networks: if not self.network_mappings[interface_name]: self.network_mappings[interface_name] = {} self.network_mappings[interface_name][cols[0]] = cols[1] ================================================================================ Example 2130 ================================================================================ Target: = str(year) Prediction: = datetime.datetime.strptime(year, "%Y") if genre: audio["genre"] = genre if artwork_url: audio["artwork_url"] = artwork_url if album: audio["album"] = album ================================================================================ Example 2131 ================================================================================ Target: ('StartingIndex', start), Prediction: ('StartingIndex', start), ('RequestedCount', max_items), ('SortCriteria', '') ]) return response, response.metadata def _music_lib_search_metadata(self, search, start, max_items): """Perform a ================================================================================ Example 2132 ================================================================================ Target: self.caller.call() Prediction: self.caller.call(self.request, *args, **kwargs) except Exception as e: self.caller.call(self.request, *args, **kwargs) raise def build_request(self, client_data=None, api_ ================================================================================ Example 2133 ================================================================================ Target: tol < 1.0): Prediction: tol <= 1.0): raise ValueError( 'Invalid value tol=%f; should be >= 0.0 and <= 1.0.' % tol ) # Calculate recurrence relations # # The recurrence relations are: # # ================================================================================ Example 2134 ================================================================================ Target: lats = numpy.zeros((4)) Prediction: lats = numpy.zeros((4)) depths = numpy.zeros((4)) # The rupture surface geometry is represented by a # planar surface, defined by 3D corner points # (see above). lons = numpy.concatenate([ ================================================================================ Example 2135 ================================================================================ Target: self.objects[build_phase_id] Prediction: ublox.build_phase.get_build_phase(build_phase_id) if build_phase.name == script: target.remove_run_script(build_phase) break return target def remove_run_script_from_build_ ================================================================================ Example 2136 ================================================================================ Target: union({pair[0]}) Prediction: union(pair.locations) uniqueFeatures = uniqueFeatures.union(pair.features) return uniqueFeatures, uniqueLocations def getUniqueFeaturesLocationsInObject(self, name): """ Return two sets. The first set contains the unique locations Ids in the ================================================================================ Example 2137 ================================================================================ Target: self.view.set_enabled(False, self.source_text) Prediction: else: self.view.get_buffer().begin_undoable_action() # reset the text buffer self.view.textview.set_text(None) self.view.textview.set_editable(False) self.view. ================================================================================ Example 2138 ================================================================================ Target: df['lg'] = df['lg'].fillna(0) Prediction: return df def scale_neg_1_to_1_with_zero_mean_log_abs_max_log_abs(v): ''' !!! not working ''' df = pd.DataFrame({'v':v, 'sign': ================================================================================ Example 2139 ================================================================================ Target: exists_collectionclass: Prediction: ical_specification == 'input_sequence': lines += [' :members:', ' :exclude-members: InputSequence'] elif ical_specification == 'control_parameter': lines += [' :members:', ' :exclude-members ================================================================================ Example 2140 ================================================================================ Target: _wrapper Prediction: ###### return wrapper @click.command(name="hand.general", help="") @click.option( "-h", "--help", help="显示帮助信息", dest="help", default=False, required ================================================================================ Example 2141 ================================================================================ Target: mcpts = np.arcsin(x._mcpts) Prediction: return x.asin() else: return x def asinh(x): """ Inverse hyperbolic sine """ if isinstance(x, UncertainFunction): return x.asinh() else: return x ================================================================================ Example 2142 ================================================================================ Target: topic, Prediction: ~~topic, }) if updated_after: api_query.update({ "updated_after": updated_after, }) if updated_before: api_query.update({ "updated_before": updated_before, }) ================================================================================ Example 2143 ================================================================================ Target: ).strip() Prediction: message) if traceflag: trace = trace.splitlines() for line in trace: print(line) else: print(trace) return trace def print_warning(message, prefix=True, traceflag=True): ================================================================================ Example 2144 ================================================================================ Target: if isinstance(a, string_types): Prediction: continue if not a: continue if not isinstance(a, (tuple, list)): continue if not isinstance(a, (tuple, list)): continue if not isinstance(a, (tuple, list)): continue if not isinstance ================================================================================ Example 2145 ================================================================================ Target: pool._RemoveWorker(self.name) # pylint: disable=protected-access Prediction: pool.remove(self) # If we were the last thread in the pool, we can't remove ourselves. if self.pool.started: return False # If we were the first thread in the pool, we can't remove ourselves. if self.pool. ================================================================================ Example 2146 ================================================================================ Target: for log_key, log_value in log_values.items(): Prediction: logging_config = dict( logging_config_name=log_values.get('name'), logging_config_level=log_values.get('level'), logging_config_enabled=log_values.get('enabled'), logging_config_disabled=log ================================================================================ Example 2147 ================================================================================ Target: strip() for pat in exclude.split(",")] Prediction: strip() for pat in exclude.split(",")] elif exclude: assert type(exclude) is list else: opts["exclude"] = [] # Convert options dict into a dict of options opts_dict = {} for key, value in opts. ================================================================================ Example 2148 ================================================================================ Target: index + 1}of{len(self._steps)}" Prediction: index}" return step_name def get_step_name(self, index: int) -> str: """ Give the waterfall step a unique name """ return f"{self._steps[index].__qualname__}Step{index}" ================================================================================ Example 2149 ================================================================================ Target: feature_id, Prediction: urn_to_str(feature_id), 'feature_id': feature_id, 'feature_name': feature_name, 'feature_type': feature_type, 'feature_description': feature_description, 'feature_version': feature_version ================================================================================ Example 2150 ================================================================================ Target: return self.channel.basic_consume(_callback_decode, Prediction: self.queue = queue self.no_ack = no_ack self.callback = callback self.consumer_tag = consumer_tag self.nowait = no_ack and not no_ack self.callback_decode = _callback_decode ================================================================================ Example 2151 ================================================================================ Target: params = { Prediction: return self.data def dump_dict(self, key, value): """ :param key: 键 :param value: 值 :return: 序列化结果 :rtype: dict """ return self. ================================================================================ Example 2152 ================================================================================ Target: = decomp.unused_data Prediction: ~~= decomp.flush() except zlib.error: pass else: break return frames def zlib_decompress_all_frames(data): """Decompress all frames of zlib-compressed bytes. Repeatedly tries ================================================================================ Example 2153 ================================================================================ Target: type for %s array."%k) Prediction: type for '%s' array."%k) if v.size best_energy: best_energy = total_cost best_soln = x else: best_soln = x return best_soln def greedy_mincost_diameter_augment(graph, max_ ================================================================================ Example 2162 ================================================================================ Target: for n in range(N)]) Prediction: for group_membership in group_membership]) return sample def _sample_atoms(problem, N, num_levels=4): """Generate trajectories without groups Arguments --------- problem : dict The problem definition N : int ================================================================================ Example 2163 ================================================================================ Target: else: Prediction: else: self.volumes.append(path) self.finalized = True def add_volume_to_group(self, group_name, path): """ Add a shared volume (i.e. with the ``VOLUME`` command) ================================================================================ Example 2164 ================================================================================ Target: return scope Prediction: return scope def state_invariant_scope(self, state: Sequence[tf.Tensor]): '''Returns the state invariant fluent scope for the current `state`. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: ================================================================================ Example 2165 ================================================================================ Target: if label_mutated != label: Prediction: label_mutated = re.sub(r'[^a-zA-Z0-9_]', '_', label_mutated) # replace underscores with hash label_mutated = re.sub(r'_[a-zA-Z0-9_]', ================================================================================ Example 2166 ================================================================================ Target: return True Prediction: return True else: return False def can_delete(self): """ If the key_name, value_name, and value_type has been provided returns that the Registry Key can be deleted, otherwise returns that the Registry Key cannot be deleted. ================================================================================ Example 2167 ================================================================================ Target: extra_evals = ( Prediction: if extras is None: extra = self.extra_markers else: extra = extras for marker in extra: if marker in req: return False return True def _get_extra_markers(self, req): ================================================================================ Example 2168 ================================================================================ Target: emiss Prediction: irem(emiss) def _emiss_ep_2(self, Eph): """ Electron-proton bremsstrahlung emissivity per unit photon energy """ if self.weight_ep == 0.0: return np. ================================================================================ Example 2169 ================================================================================ Target: is independent of base position. If there Prediction: ia not accounted for in the model._ _The GC content of the genome is not known and so the normal distribution is used to model the GC content of the genome. The GC content of the genome is then calculated from the observed data and used to build a reference distribution. The ================================================================================ Example 2170 ================================================================================ Target: `Transversion` is a purine-to-pyrimidine or pyrimidine-to-purine point mutation. Prediction: `Transition` is a point mutation that changes the base of the DNA sequence. `Transition` is a point mutation that changes the base of the DNA sequence. `Transition` is a point mutation that changes the base of the DNA sequence. `Transition` is a point mutation that changes ================================================================================ Example 2171 ================================================================================ Target: elif data == 'False': Prediction: elif data == 'False': return False else: return None class XMLParser(object): def __init__(self, tree, location, force_string=False): self.tree = tree self.location = location self.force ================================================================================ Example 2172 ================================================================================ Target: self.current_option += -1 Prediction: self.current_option -= 1 self.current_option = 0 self.current_option_value = self.current_option self.current_option_value_label = self.current_option_value self.current_option_value_label_text ================================================================================ Example 2173 ================================================================================ Target: self._securityHandler, Prediction: self._securityHandler) def searchDiagramsByFeatureClass(self,whereClause=None, relatedObjects=None, relatedSchematicObjects=None): """ The Schematic Search Diagrams operation is performed on the schematic service resource ================================================================================ Example 2174 ================================================================================ Target: for k, v in parameters[group].items(): Prediction: return parameters class MAGICC(object): """ A class to read MAGICC parameters. Parameters ---------- nml_years : int Number of years to read. nml_allcfgs : int Number of all configurations to read ================================================================================ Example 2175 ================================================================================ Target: + '.unparsers.' + module_name) Prediction: + '.unparsers.' + module_name) unparser_names = [unparser_module.unparser_names[name] for name in unparser_names] return ParserUnparserFactory(module_name, *unparser_names) def get_ ================================================================================ Example 2176 ================================================================================ Target: return qs.filter(Q(assignment__course__tutors__pk=request.user.pk) | Q(assignment__course__owner=request.user)).distinct() Prediction: return qs.filter(user=request.user) class SubmissionAdmin(admin.ModelAdmin): list_display = ('title', 'user', 'submission_date', 'submission_type', 'submission_type_id', 'submission_type_name ================================================================================ Example 2177 ================================================================================ Target: ) Prediction: status=200, body=offer_id ) def mark_offer_as_unconfirmed(self, offer_id): """ Mark offer as unconfirmed :param offer_id: the offer id :return Response """ ================================================================================ Example 2178 ================================================================================ Target: axes Prediction: axes if ax is None: fig, axes = self.vyx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig ================================================================================ Example 2179 ================================================================================ Target: rotation, translation = self._get_symmetry() Prediction: if cartesian: return [SymmOp(cartesian=True)] else: return [SymmOp(cartesian=False)] def get_symmetry_operations_from_cartesian(self, cartesian=False): """ Return symmetry ================================================================================ Example 2180 ================================================================================ Target: if type(array) not in _ITERABLE_TYPES: Prediction: if len(array) == 0: return False if len(array) == 1: return True return False def _all_correct_list_with_type(array, type_): """ Make sure, that all items in `array ================================================================================ Example 2181 ================================================================================ Target: return response Prediction: if response.status_code == 404: return if response.status_code == 403: return if response.status_code == 200: self._remove_user(group_id, user_id) def _remove_user(self, ================================================================================ Example 2182 ================================================================================ Target: [_TruncatedNormalFitter.partial_derivative_mu(params[0], params[1], low, high, data), Prediction: [ np.exp(-params[0] * (data - low) / (high - low)) / (high - low) + params[1] * (data - low) / (high - low) ] ) def truncated_normal_ll ================================================================================ Example 2183 ================================================================================ Target: 0), (237, 28, 36), Prediction: 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0 ================================================================================ Example 2184 ================================================================================ Target: args.halt_on_error) Prediction: args.halt_on_error) if rv: return rv if args.models: for model_id in args.models: rv = downloader.download(info_or_id=unicode(model_id), download_dir=args.dir, ================================================================================ Example 2185 ================================================================================ Target: / 2) Prediction: )/ fmax if doplot: plt.plot(f, s) else: plt.plot(f, s) return f, fs def plotfft(s, fmax, doplot=False): """ This function computes ================================================================================ Example 2186 ================================================================================ Target: while i >= len(widths): Prediction: if i == 0: widths.append(size) else: widths.append(widths[i-1] + size) #Print the table print('\n'.join(map(str, widths ================================================================================ Example 2187 ================================================================================ Target: options['task_args']['eta'] = time.mktime(eta.timetuple()) Prediction: options['task_args']['eta'] = eta # JSON don't like task_args. task_args = options.get('task_args', {}) if task_args: options['task_args'] = task_args # JSON don't ================================================================================ Example 2188 ================================================================================ Target: print('-[pip]----------') Prediction: # if pip is not installed, install it if not pip.has_key('pip'): pip.pip_install() # update the package list pip.pip_update() # update the package list pip.pip_update() # update ================================================================================ Example 2189 ================================================================================ Target: for seg in self.segments: Prediction: for seg in self.segments: if seg.comp_location_in_seconds < end and\ seg.comp_location_in_seconds + seg.duration_in_seconds >= end: is_key_end = False break ================================================================================ Example 2190 ================================================================================ Target: = {} Prediction: ia = {} if direction is not None: query_parameters['direction'] = self._serialize.query('direction', direction, 'str') if depth is not None: query_parameters['depth'] = self._serialize.query('depth', depth, 'int') ================================================================================ Example 2191 ================================================================================ Target: self.multipart = MIMEMultipart('alternative') Prediction: else: self.smtp.send_message( self.multipart, self.config['EMAIL'], self.addresses) def send_as_one(self): """ send email message as one """ if self.send_as_one: ================================================================================ Example 2192 ================================================================================ Target: start_index += proportion Prediction: start_index += proportion return parts def split_identifiers_by_proportions(identifiers=[], proportions={}): """ Split the given identifiers by the given proportions. Args: identifiers (list): List of identifiers (str). ================================================================================ Example 2193 ================================================================================ Target: options["export_options"]) Prediction: options["export_options"]) if not allowed: logger.warn("export_options is not set") else: datatable_options["export"] = True else: datatable_options["export"] = False if not is_paging: ================================================================================ Example 2194 ================================================================================ Target: request = cls(args[-2]) Prediction: """Decorate a function as responder that accepts the request as first argument. This works like the :func:`responder` decorator but the function is passed the request object as first argument and the request object will be closed automatically:: @Request.application ================================================================================ Example 2195 ================================================================================ Target: self.o[key][rel] = [existing, thing] Prediction: existing.append(thing) self.o[key][rel] = existing def _add_rel_to_thing(self, key, rel, thing, wrap): """Adds ``thing`` to links or embedded resources. Calling code should not use this ================================================================================ Example 2196 ================================================================================ Target: if minor_locator: Prediction: if minor_locator: axis.xaxis.set_minor_locator(minor_locator) if minor_formatter: axis.xaxis.set_minor_formatter(minor_formatter) return axis def format_y_tick(axis ================================================================================ Example 2197 ================================================================================ Target: **task) Prediction: task) def validate_task_fn(task_fn): """ Validates task_fn and adds default values for missing options using the following steps. 1. If there is no input list specified or if it is None, the input spec is assumed ================================================================================ Example 2198 ================================================================================ Target: else: Prediction: else: hdu.update(hdu_in.data, header=hdu_in.header) return hdu def update_secondary(hdu_in, hdu=None): """ 'Update' a secondary HDU This checks hdu ================================================================================ Example 2199 ================================================================================ Target: out_dir = utils.safe_makedir(os.path.join(tx_out_dir, aligner)) Prediction: reference_dir = os.path.join(data.get_dir(), "reference_files") reference_files = os.path.join(reference_dir, "fasta_%s_%s.fasta" % (aligner, data.get_id())) ================================================================================ Example 2200 ================================================================================ Target: if use_sis_id: Prediction: kwargs['account_id'] = account kwargs['use_sis_id'] = use_sis_id return self.get_account_by_id(kwargs) def get_account_by_id(self, account_id, use_sis_id=False ================================================================================ Example 2201 ================================================================================ Target: normal, tumor = sample Prediction: name, version = sample samples.append([uuid, name, version]) return samples def parse_samples(path_to_samples): """ Parses samples, specified in either a manifest or listed with --samples :param str path_to_samples: ================================================================================ Example 2202 ================================================================================ Target: comp.class_name Prediction: comp.class_name self.logger.info("Loading Bolt from: %s", py_classpath) return self.load_py_component(py_classpath) except Exception as e: self.logger.error("Error loading component: %s", ================================================================================ Example 2203 ================================================================================ Target: input = ET.SubElement(get_vnetwork_vswitches, "input") Prediction: get_vnetwork_vswitches.set("last_rcvd_instance", kwargs["last_rcvd_instance"]) return config def get_vnetwork_vswitches_input_last_rcvd_instance(self, **kwargs): """Auto Generated ================================================================================ Example 2204 ================================================================================ Target: module_name = 'pysqlite2.dbapi2' Prediction: if os.name == 'nt': import sqlite3 return sqlite3.sqlite3_version() >= (3, 0) else: import pysqlite2 return pysqlite2.sqlite3_version() >= (3, 0 ================================================================================ Example 2205 ================================================================================ Target: dt Prediction: ### def next_friday(dt): """ If holiday falls on Friday, use next Friday instead. """ if dt.weekday() == 5: return dt + timedelta(1) elif dt.weekday() == 6: ================================================================================ Example 2206 ================================================================================ Target: if car_type not in car_types: Prediction: if car_type not in car_types: return base_location_cost + (age_multiplier * (base_location_cost + (days * (age_multiplier * (base_location_cost + (days * (age_multiplier * (base_ ================================================================================ Example 2207 ================================================================================ Target: rpc_command) Prediction: rpc_command) if source is not None: node.set_name(source) if filter is not None: node.set_name(filter) return node def _dispatch_xml_element(self, xml_element, source=None, ================================================================================ Example 2208 ================================================================================ Target: 'get_address'): Prediction: '_default_protocol'): return host._default_protocol if hasattr(host, 'protocol'): return host.protocol if hasattr(host, 'domain'): return host.domain if hasattr(host, 'host'): return host.host ================================================================================ Example 2209 ================================================================================ Target: finally: Prediction: except IOError: return None def get_hash_from_file(self, handle, file_name): """ Get the associated hash for the given handle, the hash file must exist (``handle + '.hash'``). Args: ================================================================================ Example 2210 ================================================================================ Target: provided_protocol = provided_protocol.replace("://", "") Prediction: protocol = provided_protocol else: protocol = "http" return (host, protocol) def _parse_url_scheme(self, url): """ Process the provided url to return the scheme, if any. If the scheme is not specified ================================================================================ Example 2211 ================================================================================ Target: return newP Prediction: return newP def _copyPort(port, targetLNode, reverseDir): """ Copy port on targetNode """ if not targetLNode.isPort(): return port if not targetLNode.isPort(port): return ================================================================================ Example 2212 ================================================================================ Target: for new_addr in _compat_range(start, end, step): Prediction: if step < 0: raise ValueError('negative step for netblock %s' % self) if start < 0: raise ValueError('negative start for netblock %s' % self) if end > self._max_prefixlen: raise ValueError ================================================================================ Example 2213 ================================================================================ Target: if not data: Prediction: if data is None: raise NoDataException() return data def read_or_raise(reader, n=-1): """ Read a given byte number from Stream. NoDataException is raised if read gives no data :param reader: reader adapter ================================================================================ Example 2214 ================================================================================ Target: break Prediction: break return text def generate_dot_code(filename, content, filetype='svg'): """ Generate dot code blocks from a file. Args: filename (str): Filename of the file to generate dot code from. content (str): Content of ================================================================================ Example 2215 ================================================================================ Target: sector_round_trips Prediction: xt.apply( lambda x: xt.apply( lambda y: xt.apply( lambda z: xt.apply( lambda t: xt.apply( lambda s: xt.apply( lambda s: xt.apply ================================================================================ Example 2216 ================================================================================ Target: except KeyError: Prediction: except KeyError: return 0 def get_height_for_block(self, lineno, width): """ Return the height that a given block would need if it is rendered in a space with the given width. """ try: ================================================================================ Example 2217 ================================================================================ Target: config['languages']: Prediction: ia_languages: Common.make_dir(language + '/build') # Create the main .build folder Common.make_dir(config['p_build']) Common.make_dir(config['p_build'] + '/build') # Create the ================================================================================ Example 2218 ================================================================================ Target: hour, minute, 0) Prediction: hour, minute) def today(year=None, month=None, day=None, hour=None, minute=None): """ Gives the ``datetime.datetime`` object corresponding to today. The default value for optional parameters is the current value of year, month ================================================================================ Example 2219 ================================================================================ Target: varname = mm.group('varname') Prediction: else: return mm.group(1) def _expand2(instring, noerror): """Expand a string with embedded IRAF variables (IRAF virtual filename).""" # first expand names in parentheses # note this works on nested names too, expanding from ================================================================================ Example 2220 ================================================================================ Target: else: Prediction: # If the message was sent by someone else, respond. else: # Message was sent by someone else; do not respond. return {'Message': 'OK'} # If the message was sent by a bot, respond. else: # Message was sent ================================================================================ Example 2221 ================================================================================ Target: 'm':60, 'h':3600, 'd':86400} Prediction: 'm':2, 'h':3, 'd':4, 'w':5, 'M':6, 'y':7, 'yM':8, 'yW':9, 'yD':10, 'yWd':11, 'yMd':12, ' ================================================================================ Example 2222 ================================================================================ Target: if result is _undef: Prediction: result = _undef return func(*args, **kwargs) return ret_call def _const_return_call(func): """ >>> from Redy.Magic.Classic import const_return_call >>> @const_return_call ================================================================================ Example 2223 ================================================================================ Target: abranch.Component_1_Name = pname Prediction: abranch.Component_1_Name = pname abranch.Component_1_Inlet_1_Object_Type = 'Inlet:Pipe:Adiabatic' abranch.Component_1_Inlet_1_Name = pname ================================================================================ Example 2224 ================================================================================ Target: logging.getLogger("jb") Prediction: logging.getLogger("jukebox") log.setLevel(jukeboxcore.constants.DEFAULT_LOGGING_LEVEL) log.propagate = False log.handlers = [ logging.StreamHandler(sys.stdout), logging.Stream ================================================================================ Example 2225 ================================================================================ Target: mail['To'] Prediction: mail.get_to() body = mail.get_body() if from_addr and to_addr: return (from_addr, to_addr, body) def get_all_mail(self): """ Choose and return all mail from the ================================================================================ Example 2226 ================================================================================ Target: new Prediction: ue_site_param(new) def ue_site_param(site_param): """ Convert a dictionary site_param -> string into a dictionary of valid casted site parameters. """ if site_param['vs30Type'] == 'measured ================================================================================ Example 2227 ================================================================================ Target: continue Prediction: except vmodl.fault.SystemError as err: log.debug(err.msg) ret.update({host_name: {'Error': err.msg}}) except vmodl.fault.SystemError as err: log.debug(err.msg) ================================================================================ Example 2228 ================================================================================ Target: ) Prediction: ) if res: return res return [] ================================================================================ Example 2229 ================================================================================ Target: context = self._context_by_id.get(context_id) Prediction: if context_id is None: raise ValueError("context_id must be specified") if via_id is None: raise ValueError("via_id must be specified") if create: return self.context_by_id(context_id, via ================================================================================ Example 2230 ================================================================================ Target: qualname] Prediction: qualname] def get_plugin_list(plugin_class=None): """Returns a list of all plugins for the given plugin class If the plugin class is not specified, all plugins are returned. """ if plugin_class is None: return [] ================================================================================ Example 2231 ================================================================================ Target: items += self.traverse(child, level + 1) Prediction: items.append((child, level + 1)) return items def traverse_all(self, start_node = None, level = None): """! @brief Traverses all nodes of subtree that is defined by node specified in input parameter. ================================================================================ Example 2232 ================================================================================ Target: xml = SimplerXMLGenerator(stream, charset) Prediction: stream.write(data) stream.write(u'') stream.write(u'') stream.write(u'') stream.write(u'') stream.write(u' self.SizeOfRawData: size = self.SizeOfRawData if size > self.VirtualSize: size = self.VirtualSize if size > self.SizeOfRawData: size = self.SizeOfRawData if ================================================================================ Example 2258 ================================================================================ Target: 'output', 'oq_job_id display_name ds_key size_mb'.split(), rows) Prediction: rows) def create_job(db, job_id, job_name, job_type, job_description, job_description_file, job_description_file_size, job_description_file_type, job_description_file_format, job_description ================================================================================ Example 2259 ================================================================================ Target: get("JOBSTAMPS_DISABLED", None): Prediction: get("JOBSTAMPS_OUT_OF_DATE_DETAILS", False): detail.out_of_date_detail = detail.out_of_date_detail.format( stamp=stamp_file_name, dependencies=dependencies, ================================================================================ Example 2260 ================================================================================ Target: header in i: Prediction: xt, content in res.iter_content(chunk_size=1024): if xt.find('\r\n\t') >= 0: got_content_length = True break if xt.find('\r\n') >= 0: ================================================================================ Example 2261 ================================================================================ Target: start = local_block[cnt] Prediction: if cnt < 0: break if lod2_threshold < cnt: break cnt = local_block[cnt] # Search QTL end end = local_block[0] while end >= 0: if end < 0: ================================================================================ Example 2262 ================================================================================ Target: return _module Prediction: if _module.__name__ == '__main__': return _module return None def import_module_from_string(mod_str): """ inspired by post on stackoverflow :param mod_str: import path string like 'netshowlib ================================================================================ Example 2263 ================================================================================ Target: True Prediction: ================================================================================ Example 2264 ================================================================================ Target: ) Prediction: ) if not isinstance(enc, dict): raise TypeError("encryption algorithm must be a dict") return enc def decrypt(data, digest=True): """Perform decryption of provided data.""" alg = get_best_algorithm() ================================================================================ Example 2265 ================================================================================ Target: ) Prediction: .get_devices .get_devices .get_devices .get_devices .get_devices .get_devices .get_devices .get_devices .get_devices ================================================================================ Example 2266 ================================================================================ Target: smaller_data_1 = small_request(start_dt, tmp_end) Prediction: if tmp_end.month > 3 and tmp_end.day > 15: print('Skipping day %s' % tmp_end) dataframe_list.append(small_request(start_dt,intermediate_end_dt)) else: ================================================================================ Example 2267 ================================================================================ Target: hexdigest() Prediction: hexdigest() def __eq__(self, other): """Return True if the query is equal to the other query.""" return self._hash() == other._hash() def __ne__(self, other): """Return True if the query is not equal to the other ================================================================================ Example 2268 ================================================================================ Target: return None Prediction: return 0 def set_position(self, position): """Set the position in the playing media (seconds).""" self._setstate.setPosition(position) def set_volume(self, volume): """Set the volume in the playing media (percent)." ================================================================================ Example 2269 ================================================================================ Target: update(subgroups) Prediction: update(subgroups) def add_subgroups_by_name(self, subgroups, name): """ Add subgroups by name. Parameters ---------- subgroups : dict Dictionary of subgroups, e.g., {'celltype': 'K562', ' ================================================================================ Example 2270 ================================================================================ Target: x_[Ifilter_x] = x Prediction: x_ = x_ + params0['params'] x_ = x_ / params0['gamma'] x_ = x_ * params0['beta'] x_ = x_ * params0['gamma'] x_ = x_ * params0['beta'] ================================================================================ Example 2271 ================================================================================ Target: lattice, Prediction: lattice, symprec)) return out def compute_permutation_for_rotation(positions, rotated_positions, lattice, symprec): """Compute a permutation for every space group operation ================================================================================ Example 2272 ================================================================================ Target: ret_str Prediction: irc_format_error(ret_str) def get_err_msg_with_context(self): """ Return a multi-line error message for being printed, in the following format. The text in angle brackets refers to the same-named properties of the ================================================================================ Example 2273 ================================================================================ Target: return mv.get_subwindows() Prediction: if not test_for_opengl(): return MeshViewer(mv) return MeshViewer(mv) def MeshViewerLocal( shape=(1, 1), titlebar="Mesh Viewers", uid=None, keepalive=False ================================================================================ Example 2274 ================================================================================ Target: v = v.to('m/s') Prediction: v = v.to('m/s') # Calculate the critical angle critical_angle = math.acos(math.sqrt(u**2 + v**2)) return critical_angle def critical_angle_from_pressure(pressure, u, v, ================================================================================ Example 2275 ================================================================================ Target: 1024 Prediction: 1024 suf += 1 return val def conv_units_to_str(val, meta): """ Format and convert units to be more human readable @return new val with converted units """ if not val or not meta: return ================================================================================ Example 2276 ================================================================================ Target: yaml_path in yaml_paths: Prediction: ical_file in ical_files: yamlfiles.append(ical_file) yamlfiles = yamlfiles.split('\n') yaml_paths = [] for yaml_file in yamlfiles: yaml_paths.append(yaml_file) ================================================================================ Example 2277 ================================================================================ Target: [{}] {} is deprecated. Please use [{}] {}'.format( Prediction: ###%s### is deprecated. Use the ###%s### instead.' % ( self._config_path['section'], self._config_path['name'])) def _value_iterator_no_warning(self, task_name, param_name): """ Y ================================================================================ Example 2278 ================================================================================ Target: else: Prediction: if set_ro: self.debug('Saving, set_ro: '+str(set_ro)) else: self.debug('Saving, overwriteRO: '+str(overwriteRO)) self.save(fname, comment, overwriteRO) ================================================================================ Example 2279 ================================================================================ Target: if first_group.strip() == "disable-all": Prediction: continue if first_group.strip() == "disable-all": control_pragmas.remove(first_group.strip()) continue if first_group.strip() == "skip-file": control_pragmas.remove(first_group ================================================================================ Example 2280 ================================================================================ Target: value = bool(value.strip() if self.strip and hasattr(value, 'strip') else value) Prediction: return bool(value) except ValueError: # The value is not a boolean. return '' return self.text(value, context) # # The following functions are used to convert a native value to a textual # string. # # The ================================================================================ Example 2281 ================================================================================ Target: