text
stringlengths
78
104k
score
float64
0
0.18
def get_incremental_uncovered_lines(abs_path: str, base_commit: str, actual_commit: Optional[str] ) -> List[Tuple[int, str, str]]: """ Uses git diff and the annotation files created by `pytest --cov-r...
0.000522
def read(self, length=1000, blocking=False): """ Read ``length`` bytes from current process output stream. Note: This method is not fully non-blocking, however it behaves like one. """ size_p = PLARGE_INTEGER(LARGE_INTEGER(0)) if not blocking: windll....
0.003017
def _get_index(self, value): """ Return the index of the given value in `state_values`. Parameters ---------- value Value to get the index for. Returns ------- idx : int Index of `value`. """ error_msg = 'value {0...
0.001903
def selection_sort(arr, simulation=False): """ Selection Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): # "Select" the ...
0.019737
def set_proxy(self, proxy): # pragma: no cover, not with unit tests """Set HTTP proxy :param proxy: proxy url :type proxy: str :return: None """ if proxy: logger.debug('PROXY SETTING PROXY %s', proxy) self._requests_con.proxies = { ...
0.005236
def get_ignored_for_calculations_metadata(self): """Gets the metadata for the ignore flag. return: (osid.Metadata) - metadata for the ignore flag *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group...
0.007519
def tail(self, lines=10): """\ Return the last lines of the file. """ self.seek_end() end_pos = self.file.tell() for i in range(lines): if not self.seek_line(): break data = self.file.read(end_pos - self.file.tell() - 1) if da...
0.005
def get_raw_fixed_block(self, unbuffered=False): """Get the raw "fixed block" of settings and min/max data.""" if unbuffered or not self._fixed_block: self._fixed_block = self._read_fixed_block() return self._fixed_block
0.007813
def locate(self, pattern): '''Find sequences matching a pattern. :param pattern: Sequence for which to find matches. :type pattern: str :returns: Indices of pattern matches. :rtype: list of ints ''' if len(pattern) > len(self): raise ValueError('Sear...
0.003145
def _ParseStorageMediaOptions(self, options): """Parses the storage media options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid. """ self._ParseStorageMediaImageOptions(options) self._ParseVSSProcessingOptions(optio...
0.002463
async def connect(self, **kwargs): """Connect to an arbitrary Juju model. kwargs are passed through to Connection.connect() """ kwargs.setdefault('loop', self.loop) kwargs.setdefault('max_frame_size', self.max_frame_size) kwargs.setdefault('bakery_client', self.bakery_cl...
0.002488
def inject_positional_args(self, method): """Decorator for injecting positional arguments from the configuration. This decorator wraps the given method, so that any positional arguments are passed with corresponding values from the configuration. The name of the positional argument must match the conf...
0.005898
def __discoverPlugins(): """ Discover the plugin classes contained in Python files, given a list of directory names to scan. Return a list of plugin classes. """ for app in settings.INSTALLED_APPS: if not app.startswith('django'): module = __import__(app) moduledir = ...
0.003067
def validate_average_best_span(): """Figure 2d? from Friedman.""" N = 200 num_trials = 400 avg = numpy.zeros(N) for i in range(num_trials): x, y = smoother_friedman82.build_sample_smoother_problem_friedman82(N=N) my_smoother = smoother.perform_smooth( x, y, smoother_cls=s...
0.003503
def put_privileges(self, body, params=None): """ `<TODO>`_ :arg body: The privilege(s) to add :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this opera...
0.005618
def createFileList(self): """SRTM data is split into different directories, get a list of all of them and create a dictionary for easy lookup.""" global childFileListDownload if childFileListDownload is None or not childFileListDownload.is_alive(): childFileListDownload =...
0.009569
def name_for_valid_number(numobj, lang, script=None, region=None): """Returns a carrier name for the given PhoneNumber object, in the language provided. The carrier name is the one the number was originally allocated to, however if the country supports mobile number portability the number might not...
0.000691
def put(text, cbname): """ Put the given string into the given clipboard. """ global _lastSel _checkTkInit() if cbname == 'CLIPBOARD': _theRoot.clipboard_clear() if text: # for clipboard_append, kwds can be -displayof, -format, or -type _theRoot.clipboard_append(t...
0.001368
def get_node(self, node_id): """ Return the node or raise a 404 if the node is unknown """ try: return self._nodes[node_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id))
0.010563
def change_nick(self,new_nick): """ Send a nick change request to the room. :Parameters: - `new_nick`: the new nickname requested. :Types: - `new_nick`: `unicode` """ new_room_jid=JID(self.room_jid.node,self.room_jid.domain,new_nick) p=Pre...
0.018325
def Dictionary(self): """Emulates the items() method of dictionaries.""" d = self.__dict__['__subject'].Dictionary().copy() d.update(self.__dict__['overrides']) return d
0.00995
def fetch(db=None, sql=None): ''' Retrieve data from an sqlite3 db (returns all rows, be careful!) CLI Example: .. code-block:: bash salt '*' sqlite3.fetch /root/test.db 'SELECT * FROM test;' ''' cur = _connect(db) if not cur: return False cur.execute(sql) rows =...
0.002849
def __deserialize_model(self, data, klass): """ Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ if not klass.swagger_types and not hasattr(klass, 'get_real_child_model'): return dat...
0.002988
def mk_token(self, load): ''' Run time_auth and create a token. Return False or the token ''' if not self.authenticate_eauth(load): return {} if self._allow_custom_expire(load): token_expire = load.pop('token_expire', self.opts['token_expire']) el...
0.00324
def safe_sparse_dot(a, b, dense_output=False): """Dot product that handle the sparse matrix case correctly Uses BLAS GEMM as replacement for numpy.dot where possible to avoid unnecessary copies. Parameters ---------- a : array or sparse matrix b : array or sparse matrix dense_output : b...
0.001229
def home(self) -> 'InstrumentContext': """ Home the robot. :returns: This instance. """ def home_dummy(mount): pass cmds.do_publish(self.broker, cmds.home, home_dummy, 'before', None, None, self._mount.name.lower()) self._hw_manager.hardware.home_...
0.00367
def posix_redirect_output(filename=None, permanent=True): """ Redirect stdout/stderr to a file, using posix dup2. """ sys.stdout.flush() sys.stderr.flush() stdout_fd = sys.stdout.fileno() stderr_fd = sys.stderr.fileno() if not permanent: stdout_fd_copy = os.dup(stdout_fd) ...
0.001054
def forecast(place, series=True): """NOAA weather forecast for a location""" lat, lon = place url = "http://graphical.weather.gov/xml/SOAP_server/ndfdXMLclient.php?" + \ "whichClient=NDFDgen&" + "lat=%s&lon=%s&" % (lat, lon) + \ "Unit=e&temp=temp&wspd=wspd&sky=sky&wx=wx&rh=rh&" + \ ...
0.018665
def get_whoami(self): """ A convenience function used in the event that you need to confirm that the broker thinks you are who you think you are. :returns dict whoami: Dict structure contains: * administrator: whether the user is has admin privileges * name: user...
0.003968
def create_collection(cls, target=None, drop=False, indexes=True): """Ensure the collection identified by this document class exists, creating it if not, also creating indexes. **Warning:** enabling the `recreate` option **will drop the collection, erasing all data within**. http://api.mongodb.com/python/cu...
0.042056
def keypair_field_data(request, include_empty_option=False): """Returns a list of tuples of all keypairs. Generates a list of keypairs available to the user (request). And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a...
0.001111
def zap_disk(block_device): ''' Clear a block device of partition table. Relies on sgdisk, which is installed as pat of the 'gdisk' package in Ubuntu. :param block_device: str: Full path of block device to clean. ''' # https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b...
0.001124
def highshelf(self, gain=-20.0, frequency=3000, slope=0.5): """highshelf takes 3 parameters: a signed number for gain or attenuation in dB, filter frequency in Hz and slope (default=0.5). Beware of clipping when using positive gain. """ self.command.append('treble') self...
0.004598
def single_random_manipulation_low(molecule, manipulations): """Return a randomized copy of the molecule, without the nonbond check.""" manipulation = sample(manipulations, 1)[0] coordinates = molecule.coordinates.copy() transformation = manipulation.apply(coordinates) return molecule.copy_with(coo...
0.002801
def parse_helpfull_output(help_output, regex=FLAG_HELP_RE_PY): """Parses the output of --helpfull. Args: help_output: str, the full output of --helpfull. Returns: A set of flags that are valid flags. """ valid_flags = set() for _, no_prefix, flag_name in regex.findall(help_outp...
0.002179
def _bin_exp(self, n_bin, scale=1.0): """ Calculate the bin locations to approximate exponential distribution. It breaks the cumulative probability of exponential distribution into n_bin equal bins, each covering 1 / n_bin probability. Then it calculates the center of mass in...
0.002005
def plot_caltrack_candidate( candidate, best=False, ax=None, title=None, figsize=None, temp_range=None, alpha=None, **kwargs ): """ Plot a CalTRACK candidate model. Parameters ---------- candidate : :any:`eemeter.CalTRACKUsagePerDayCandidateModel` A candidate mod...
0.000926
def DispatchSpout(*a, **kw): """Factory to dispatch spout class based on config.""" spout_class_name = get_config()['Spout'] spout_class = import_name(spout_class_name, default_ns='birding.spout') return spout_class(*a, **kw)
0.004149
def _set(self): """ Get/Set a set. """ class Sets(object): def __getitem__(_self, name): return self.getSet(name) def __setitem__(_self, name, values): self.getSet(name).setValues(values) def __iter__(_self): ...
0.005391
def clone_fluent_contentitems_m2m_relationships(self, dst_obj): """ Find all MTM relationships on related ContentItem's and ensure the published M2M relationships directed back to the draft (src) content items are maintained for the published (dst) page's content items. "...
0.001085
def get_user_channel(self, input_channel, input_type=None): """Returns the main raw channel for the process Provided with at least a channel name, this method returns the raw channel name and specification (the nextflow string definition) for the process. By default, it will fork from t...
0.00142
def directed_predicates_in_expression(expression: ShExJ.shapeExpr, cntxt: Context) -> Dict[IRIREF, PredDirection]: """ Directed predicates in expression -- return all predicates in shapeExpr along with which direction(s) they evaluate :param expression: Expression to scan :param cntxt: :return: ...
0.007686
def _handle_tag_text(self, text): """Handle regular *text* inside of an HTML open tag.""" next = self._read(1) if not self._can_recurse() or text not in self.MARKERS: self._emit_text(text) elif text == next == "{": self._parse_template_or_argument() elif t...
0.004184
def pull(directory: str) -> Commit: """ Pulls the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: the commit the subrepo is on """ if not os.path.exists(directory): raise ValueError(f"No subrepo found in \"{directory}...
0.002584
def send(self, message, body_params=None): """.. versionchanged:: 0.8.4 Send a message to CM :param message: a message instance :type message: :class:`.Msg`, :class:`.MsgProto` :param body_params: a dict with params to the body (only :class:`.MsgProto`) :type body_params...
0.006279
def summary(self, prn=None, lfilter=None): """prints a summary of each SndRcv packet pair prn: function to apply to each packet pair instead of lambda s, r: "%s ==> %s" % (s.summary(),r.summary()) lfilter: truth function to apply to each packet pair to decide whether it will be displayed""" for s, r...
0.007143
def get_under_hollow(self): """ Return HCP if an atom is present below the adsorbate in the subsurface layer and FCC if not""" C0 = self.B[-1:] * (3, 3, 1) ads_pos = C0.positions[4] C = self.get_subsurface_layer() * (3, 3, 1) ret = 'FCC' if np.any([np.linalg.no...
0.006522
def lookup(parser, var, context, resolve=True, apply_filters=True): """ Try to resolve the varialbe in a context If ``resolve`` is ``False``, only string variables are returned """ if resolve: try: return Variable(var).resolve(context) except VariableDoesNotExist: ...
0.001786
def _expand(self, coeffsin, nmax): """ Determine the Slepian expansion coefficients of a function. """ if self.coeffs is None: self.rotate(clat=90., clon=0., nrot=nmax) falpha = _shtools.SlepianCoeffs(self.coeffs, coeffsin, self.nrot) else: fal...
0.004695
def getHeader(): """return a header string with command line options and timestamp """ system, host, release, version, machine = os.uname() return "# UMI-tools version: %s\n# output generated by %s\n# job started at %s on %s -- %s\n# pid: %i, system: %s %s %s %s" %\ (__version__, ...
0.003929
def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None, attack=None, attack_params=None): """ Compute the accuracy of a TF model on some data :param sess: TF session to use when training the graph :param model: cleverhans.model.Model instance :param x: numpy array containing inp...
0.003878
def avl_split_first(root): """ Removes the minimum element from the tree Returns: tuple: new_root, first_node O(log(n)) = O(height(root)) """ if root is None: raise IndexError('Empty tree has no maximum element') root, left, right = avl_release_kids(root) if left is Non...
0.001949
def set_connection_ip_list(addresses=None, grant_by_default=False, server=_DEFAULT_SERVER): ''' Set the IPGrant list for the SMTP virtual server. :param str addresses: A dictionary of IP + subnet pairs. :param bool grant_by_default: Whether the addresses should be a blacklist or whitelist. :param s...
0.005252
def run_callback(self): """Runs the callback for the pipeline specified in the request. Raises: _CallbackTaskError if something was wrong with the request parameters. """ pipeline_id = self.request.get('pipeline_id') if not pipeline_id: raise _CallbackTaskError('"pipeline_id" parameter ...
0.007937
def make_oracle(input_qubits, output_qubit, x_bits): """Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}.""" # Make oracle. # for (1, 1) it's just a Toffoli gate # otherwise negate the zero-bits. yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit) yield(cirq.TOFFOLI(i...
0.002268
def cubehelix_palette(n_colors=6, start=0, rot=.4, gamma=1.0, hue=0.8, light=.85, dark=.15, reverse=False, as_cmap=False): """Make a sequential palette from the cubehelix system. This produces a colormap with linearly-decreasing (or increasing) brightness. That means that information ...
0.000469
def tracked_find(self, *args, **kwargs): """Replacement for regular ``find()``. """ _log.info("tracked_find.begin") # if tracking is off, just call find (ie do nothing) if self._tracking_off: _log.info("tracked_find.end, tracking=off") return self._coll_fi...
0.003417
def clone(name, clone_name, config=None): """ Clone an entry to the sshconfig. """ storm_ = get_storm_instance(config) try: # validate name if '@' in name: raise ValueError('invalid value: "@" cannot be used in name.') storm_.clone_entry(name, clone_name) ...
0.003086
def getdef(self, defname, tag='*'): """Return definition element with name *defname*""" if defname.startswith('a:'): defname = defname[2:] for xsd in self.__xsd_trees: xpath = "./%s[@name='%s']" % (tag, defname) elements = xsd.xpath(xpath) if eleme...
0.004695
def getFactory(self): """ Return a server factory which creates AMP protocol instances. """ factory = ServerFactory() def protocol(): proto = CredReceiver() proto.portal = Portal( self.loginSystem, [self.loginSystem, ...
0.006637
def update_product( self, product, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Makes changes to a Product resource. Only the ``display_name``, ``descrip...
0.005174
def rvalue(ddtt): """ R value (W/K) of a construction or material. thickness (m) / conductivity (W/m-K) """ object_type = ddtt.obj[0] if object_type == 'Construction': rvalue = INSIDE_FILM_R + OUTSIDE_FILM_R layers = ddtt.obj[2:] field_idd = ddtt.getfieldidd('Outside_Laye...
0.002322
def data(self): """Deprecated. Returns the data as a `list`""" import warnings warnings.warn( '`data` attribute is deprecated and will be removed in a future release, ' 'use %s as an iterable instead' % (PaginatedResponse,), category=DeprecationWarning, ...
0.009195
def set_default_viewport(self): """ Calculates the viewport based on the configured aspect ratio in settings. Will add black borders if the window do not match the viewport. """ # The expected height with the current viewport width expected_height = int(self.buffer_width ...
0.007463
def get_template(name): '''return a default template for some function in sregistry If there is no template, None is returned. Parameters ========== name: the name of the template to retrieve ''' name = name.lower() templates = dict() templates['tarinfo'] = {"gid": 0, ...
0.001506
def check(self, url_data): """Parse Word data.""" content = url_data.get_content() filename = get_temp_filename(content) # open word file and parse hyperlinks try: app = get_word_app() try: doc = open_wordfile(app, filename) ...
0.003398
def start(st_reg_number): """Checks the number valiaty for the Alagoas state""" divisor = 11 if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False if st_reg_number[0:2] != "03": return False aux = int(st_reg_number[0:len(st_reg_number) - 1]) ...
0.001044
def get_leaves(self): """ Get the list of all leaves. """ return self.fold_up(lambda n, fl, fg: fl + fg, lambda leaf: [leaf])
0.018072
def encode (self): """Encodes this SeqCmdAttrs to binary and returns a bytearray.""" byte = self.default for bit, name, value0, value1, default in SeqCmdAttrs.Table: if name in self.attrs: value = self.attrs[name] byte = setBit(byte, bit, value == value1) return struct.pack('B',...
0.01227
def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = '<OnCondition test="{0}"'.format(self.test) chxmlstr = '' for action in self.actions: chxmlstr += action.toxml() if chxmlstr: xmlstr += '>' + chxmlstr + '</OnC...
0.005076
def _get_general_coverage(data, itype): """Retrieve coverage information from new shared SV bins. """ work_bam = dd.get_align_bam(data) or dd.get_work_bam(data) return [{"bam": work_bam, "file": tz.get_in(["depth", "bins", "target"], data), "cnntype": "target", "itype": itype, "sample": dd....
0.009579
def cmd_init_pull_from_cloud(args): """Initiate the local catalog by downloading the cloud catalog""" (lcat, ccat) = (args.local_catalog, args.cloud_catalog) logging.info("[init-pull-from-cloud]: %s => %s"%(ccat, lcat)) if isfile(lcat): args.error("[init-pull-from-cloud] The local catalog alre...
0.010945
def rbind(dfs): """ acts like rbind for pandas dataframes """ if len(dfs) == 1: return dfs[0] df = dfs[0] for d in dfs[1:]: df = df.append(d) return df
0.005128
def _to_uniform_pwm(self, values): """ Convert raw pwm values to uniform values. :param values: The raw pwm values. :return: Converted, uniform pwm values (0.0-1.0). """ return [self._to_single_uniform_pwm(values[i]) for i in range(len(self._pins))]
0.006369
def get_illuminant_xyz(self, observer=None, illuminant=None): """ :param str observer: Get the XYZ values for another observer angle. Must be either '2' or '10'. :param str illuminant: Get the XYZ values for another illuminant. :returns: the color's illuminant's XYZ values. ...
0.003436
def convert_Decimal(x, encoder): """ Called when an instance of U{decimal.Decimal<http:// docs.python.org/library/decimal.html#decimal-objects>} is about to be encoded to an AMF stream. @return: If the encoder is in 'strict' mode then C{x} will be converted to a float. Otherwise an L{pyamf....
0.004792
def wait_for_running(self): """Waits for found servers to be operational""" self.server_attrs = self.consul.find_running( self.server_attrs, self.launch_timeout_s, )
0.008734
def schema(self): """ The DQL query that will construct this table's schema """ attrs = self.attrs.copy() parts = ["CREATE", "TABLE", self.name, "(%s," % self.hash_key.schema] del attrs[self.hash_key.name] if self.range_key: parts.append(self.range_key.schema + ",") ...
0.004138
def query_record_useful_review(comID, value): """ private funciton Adjust the number of useful votes and number of total votes for a comment. :param comID: comment id :param value: +1 or -1 :return: integer 1 if successful, integer 0 if not """ # retrieve nb_useful votes query1 = """...
0.003405
def withdraw(self, amount, currency, payment_method_id): """ Withdraw funds to a payment method. See AuthenticatedClient.get_payment_methods() to receive information regarding payment methods. Args: amount (Decimal): The amount to withdraw. currency (str): Curre...
0.002039
def getnames(): """ get mail names """ namestring = "" addmore = 1 while addmore: scientist = input("Enter name - <Return> when done ") if scientist != "": namestring = namestring + ":" + scientist else: namestring = namestring[1:] ad...
0.002849
def as_xml(self, allow_multifile=False, basename="/tmp/sitemap.xml"): """Return XML serialization of this list. If this list can be serialized as a single sitemap then the superclass method is used. If there is no single XML serialization (in the case that the number of list re...
0.003077
def get_graph_by_id(self, network_id: int) -> BELGraph: """Get a network from the database by its identifier and converts it to a BEL graph.""" network = self.get_network_by_id(network_id) log.debug('converting network [id=%d] %s to bel graph', network_id, network) return network.as_bel(...
0.012461
def _append(self, row): """ Standard .append() method. This method is for intended for internal use only. """ self.cursor.execute(self.append_statement, self.append_attrgetter(row))
0.036458
def delete_subnet_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete an RDS subnet group. CLI example:: salt myminion boto_rds.delete_subnet_group my-subnet-group \ region=us-east-1 ''' try: conn = _get_conn(region=regio...
0.001458
def calculate_embedding(self, batch_image_bytes): """Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output) """ return self.tf_session.run( self.embeddi...
0.002695
def get_message(self, set_slave_ok, sock_info, use_cmd=False): """Get a query message, possibly setting the slaveOk bit.""" if set_slave_ok: # Set the slaveOk bit. flags = self.flags | 4 else: flags = self.flags ns = self.namespace() spec = se...
0.001238
def IndexOfNth(s, value, n): """Gets the index of Nth occurance of a given character in a string :param str s: Input string :param char value: Input char to be searched. :param int n: Nth occurrence of char to be searched. :return: Index of the Nth occurrence in the...
0.001901
def getSCDPURL(self, serviceType, default=None): """Returns the SCDP (Service Control Protocol Document) URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace th...
0.006388
def drawSquiggle(page, p1, p2, breadth = 2, color=None, dashes=None, width=1, roundCap=False, overlay=True, morph=None): """Draw a squiggly line from point p1 to point p2. """ img = page.newShape() p = img.drawSquiggle(Point(p1), Point(p2), breadth = breadth) img.finish(color=color, d...
0.013393
def partial_update(self, request, *args, **kwargs): """ We do not include the mixin as we want only PATCH and no PUT """ instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=True, context=self.get_serializer_context()) serializer.is_valid(raise_exception=Tru...
0.010811
def GetRemainder(self): """Method to get the remainder of the buffered XML. this method stops the parser, set its state to End Of File and return the input stream with what is left that the parser did not use. The implementation is not good, the parser certainly procgres...
0.006098
def gallery(args): """ %prog gallery folder link_prefix Convert a folder of figures to a HTML table. For example: $ python -m jcvi.formats.html gallery Paper-figures/ https://dl.dropboxusercontent.com/u/15937715/Data/Paper-figures/ Maps the images from local to remote. """ from jcvi.a...
0.000759
def mutate(self, config): """ Mutates this genome. """ # TODO: Make a configuration item to choose whether or not multiple # mutations can happen simultaneously. if random() < config.node_add_prob: self.mutate_add_node(config) if random() < config.node_delete_prob: ...
0.002564
def read_file(filename): """Read a file.""" logging.debug(_('Reading file: %s'), filename) try: with open(filename) as readable: return readable.read() except OSError: logging.error(_('Error reading file: %s'), filename) return ''
0.003546
def _alignment(elist, flist, e2f, f2e): ''' elist, flist wordlist for each language e2f translatoin alignment from e to f alignment is [(e, f)] f2e translatoin alignment from f to e alignment is [(e, f)] return alignment: {...
0.000441
def check_pypi(self): """If the requirement is frozen to pypi, check for a new version.""" for dist in get_installed_distributions(): name = dist.project_name if name in self.reqs.keys(): self.reqs[name]["dist"] = dist pypi = ServerProxy("https://pypi.pyt...
0.005724
def getArrays(self, attr=None, specfiles=None, sort=False, reverse=False, selector=None, defaultValue=None): """Return a condensed array of data selected from :class:`Fi` instances from ``self.container`` for fast and convenient data processing. :param attr: list of :class:`Fi...
0.003328
def safe_unicode(value): """ Returns: * a `unicode` instance in Python 2.x, or * a `str` instance in Python 3.x. """ if sys.version_info < (3,0): if isinstance(value, str): return value.decode('utf-8') else: return unicode(value) else: return str...
0.006116
def bound_variable(self): """Return an object with a value property and a changed_event. The value property returns the value of the variable. The changed_event is fired whenever the value changes. """ class BoundVariable: def __init__(self, variable): ...
0.007028