text
stringlengths
78
104k
score
float64
0
0.18
def filter_(predicate, *structures, **kwargs): # pylint: disable=differing-param-doc,missing-param-doc, too-many-branches """Select elements of a nested structure based on a predicate function. If multiple structures are provided as input, their structure must match and the function will be applied to correspo...
0.009301
def _maybe_call_fn(fn, fn_arg_list, fn_result=None, description='target_log_prob'): """Helper which computes `fn_result` if needed.""" fn_arg_list = (list(fn_arg_list) if mcmc_util.is_list_like(fn_arg_list) else [fn_arg_list]) if fn_result ...
0.011628
def current() -> 'Process': """ Returns the instance of the process that is executing at the current moment. """ curr = greenlet.getcurrent() if not isinstance(curr, Process): raise TypeError("Current greenlet does not correspond to a Process instance.") retur...
0.011173
def save(self): """ Create or update a playlist. """ d = self._to_dict() if len(d.get('videoIds', [])) > 0: if not self.id: self.id = self.connection.post('create_playlist', playlist=d) else: data = self.connection.post('upd...
0.004902
def _image_width(image): """ Returns the width of the image found at the path supplied by `image` relative to your project's images directory. """ if not Image: raise Exception("Images manipulation require PIL") file = StringValue(image).value path = None try: width = spr...
0.002205
def _checkMode(self, ax_args): """Raise an exception if the mode in the attribute exchange arguments does not match what is expected for this class. @raises NotAXMessage: When there is no mode value in ax_args at all. @raises AXError: When mode does not match. """ mode ...
0.003636
def load_collection_from_url(resource, url, content_type=None): """ Creates a new collection for the registered resource and calls `load_into_collection_from_url` with it. """ coll = create_staging_collection(resource) load_into_collection_from_url(coll, url, content_type=content_type) retur...
0.003067
def user_data(self, access_token, *args, **kwargs): """Load user data from OAuth Profile Google App Engine App""" url = GOOGLE_APPENGINE_PROFILE_V2 return self.get_json(url, headers={ 'Authorization': 'Bearer ' + access_token })
0.007353
def create(self, workflow_id, email_id, data): """ Manually add a subscriber to a workflow, bypassing the default trigger settings. You can also use this endpoint to trigger a series of automated emails in an API 3.0 workflow type or add subscribers to an automated email queue th...
0.002315
def getRegToken(self): """ Acquire a new registration token. Once successful, all tokens and expiry times are written to the token file (if specified on initialisation). """ self.verifyToken(self.Auth.SkypeToken) token, expiry, msgsHost, endpoint = SkypeRegistrationToken...
0.006126
def paintGL(self): '''GL function called each time a frame is drawn''' if self.post_processing: # Render to the first framebuffer glBindFramebuffer(GL_FRAMEBUFFER, self.fb0) glViewport(0, 0, self.width(), self.height()) status = glCheckFramebufferStatus(...
0.004486
def query(self, *args): """ Query a fulltext index by key and query or just a plain Lucene query, i1 = gdb.nodes.indexes.get('people',type='fulltext', provider='lucene') i1.query('name','do*') i1.query('name:do*') In this example, the last two line are equivalent. ...
0.001898
async def iter( self, url: Union[str, methods], data: Optional[MutableMapping] = None, headers: Optional[MutableMapping] = None, *, limit: int = 200, iterkey: Optional[str] = None, itermode: Optional[str] = None, minimum_time: Optional[int] = None,...
0.003575
def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1): """ Adapted from Eric Tollerud. Finds matches in one catalog to another. Parameters lon1 : array-like Longitude of the first catalog (degrees) lat1 : array-like Latitude of the first catalog (shape of array must match `lo...
0.006156
def recompile(self, nick=None, new_nick=None, **kw): """recompile regexp on new nick""" if self.bot.nick == nick.nick: self.bot.config['nick'] = new_nick self.bot.recompile()
0.009346
def get_client_token(self, client_id=None, client_secret=None, op_host=None, op_discovery_path=None, scope=None, auto_update=True): """Function to get the client token which can be used for protection in all future communication. The access token receive...
0.002944
def service(self): """ Returns a Splunk service object for this command invocation or None. The service object is created from the Splunkd URI and authentication token passed to the command invocation in the search results info file. This data is not passed to a command invocation by default. Y...
0.0062
def _get_reverse_relationships(opts): """ Returns an `OrderedDict` of field names to `RelationInfo`. """ # Note that we have a hack here to handle internal API differences for # this internal API across Django 1.7 -> Django 1.8. # See: https://code.djangoproject.com/ticket/24208 reverse_rel...
0.000678
def _expand_tag_query(self, query, table_name = None): """ Expand Tag query dict into a WHERE-clause. If you need to prefix each column reference with a table name, that can be supplied via the table_name argument. """ where = unicode() opt = list() # h...
0.00772
def down(returns, factor_returns, **kwargs): """ Calculates a given statistic filtering only negative factor return periods. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_re...
0.001121
def view_conflicts(L, normalize=True, colorbar=True): """Display an [m, m] matrix of conflicts""" L = L.todense() if sparse.issparse(L) else L C = _get_conflicts_matrix(L, normalize=normalize) plt.imshow(C, aspect="auto") plt.title("Conflicts") if colorbar: plt.colorbar() plt.show()
0.003135
def annotation(self, type, set=None): """Will return a **single** annotation (even if there are multiple). Raises a ``NoSuchAnnotation`` exception if none was found""" l = self.count(type,set,True,default_ignore_annotations) if len(l) >= 1: return l[0] else: raise...
0.020649
def encode(self, response): """Encode a response to a L{WebResponse}, signing it first if appropriate. @raises EncodingError: When I can't figure out how to encode this message. @raises AlreadySigned: When this response is already signed. @returntype: L{WebResponse} ...
0.003219
def get_checksum(content, encoding="utf8", block_size=8192): """ Returns the MD5 checksum in hex for the given content. If 'content' is a file-like object, the content will be obtained from its read() method. If 'content' is a file path, that file is read and its contents used. Otherwise, 'content' ...
0.00064
def index_nearest(array, value): """ Finds index of nearest value in array. Args: array: numpy array value: Returns: int http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array """ idx = (np.abs(array-value)).argmin() return i...
0.003106
def version(versioninfo=False): ''' .. versionadded:: 2015.8.0 Returns the version of Git installed on the minion versioninfo : False If ``True``, return the version in a versioninfo list (e.g. ``[2, 5, 0]``) CLI Example: .. code-block:: bash salt myminion git.versio...
0.000616
def _id_for_pc(self, name): """ Given the name of the PC, return the database identifier. """ if not name in self.pc2id_lut: self.c.execute("INSERT INTO pcs (name) VALUES ( ? )", (name,)) self.pc2id_lut[name] = self.c.lastrowid self.id2pc_lut[self.c.lastrowid] = name ...
0.008451
def clean_obs_names(data, base='[AGTCBDHKMNRSVWY]', ID_length=12, copy=False): """Cleans up the obs_names and identifies sample names. For example an obs_name 'samlple1_AGTCdate' is changed to 'AGTC' of the sample 'sample1_date'. The sample name is then saved in obs['sample_batch']. The genetic codes ar...
0.003593
def trigger_revisions(self, trigger_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/triggers#list-trigger-revisions" api_path = "/api/v2/triggers/{trigger_id}/revisions.json" api_path = api_path.format(trigger_id=trigger_id) return self.call(api_path, **kwargs)
0.009677
def lreg(self, xcol, ycol, name="Regression"): """ Add a column to the main dataframe populted with the model's linear regression for a column """ try: x = self.df[xcol].values.reshape(-1, 1) y = self.df[ycol] lm = linear_model.LinearRegression...
0.003839
def calculate_dimensions(image_size, desired_size): """Return the Tuple with the arguments to pass to Image.crop. If the image is smaller than than the desired_size Don't do anything. Otherwise, first calculate the (truncated) center and then take half the width and height (truncated ag...
0.001857
def _read_mode_pocsp(self, size, kind): """Read Partial Order Connection Service Profile option. Positional arguments: * size - int, length of option * kind - int, 10 (POC-Serv Profile) Returns: * dict -- extracted Partial Order Connection Service Profile (P...
0.002151
def sample_rwalk(args): """ Return a new live point proposed by random walking away from an existing live point. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) Position of the initial sample. **This is a copy of an existing live point.** loglstar : float ...
0.00022
def create_cache_cluster(CacheClusterId=None, ReplicationGroupId=None, AZMode=None, PreferredAvailabilityZone=None, PreferredAvailabilityZones=None, NumCacheNodes=None, CacheNodeType=None, Engine=None, EngineVersion=None, CacheParameterGroupName=None, CacheSubnetGroupName=None, CacheSecurityGroupNames=None, SecurityGro...
0.005844
def to_dict(self): '''Save this service port into a dictionary.''' d = {'name': self.name} if self.visible != True: d[RTS_EXT_NS_YAML + 'visible'] = self.visible if self.comment: d[RTS_EXT_NS_YAML + 'comment'] = self.comment props = [] for name in ...
0.00519
def detachRequest(GmmCause_presence=0): """DETACH REQUEST Section 9.4.5""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 c = DetachTypeAndForceToStandby() packet = a / b / c if GmmCause_presence is 1: e = GmmCause(ieiGC=0x25) packet = packet / e return packet
0.003175
def setViews(self, received, windowId=None): ''' Sets L{self.views} to the received value splitting it into lines. @type received: str @param received: the string received from the I{View Server} ''' if not received or received == "": raise ValueError("recei...
0.0059
def add_chassis(self, chassis): """ :param chassis: chassis object """ res = self._request(RestMethod.post, self.user_url, params={'ip': chassis.ip, 'port': chassis.port}) assert(res.status_code == 201)
0.012346
def execute_loaders(self, env=None, silent=None, key=None, filename=None): """Execute all internal and registered loaders :param env: The environment to load :param silent: If loading erros is silenced :param key: if provided load a single key :param filename: optional custom fi...
0.001938
def _address_rxp(self, addr): """ Create a regex string for addresses, that matches several representations: - with(out) '0x' prefix - `pex` version This function takes care of maintaining additional lookup keys for substring matches. In case the given string is n...
0.009383
def create_course(self, courseid, init_content): """ :param courseid: the course id of the course :param init_content: initial descriptor content :raise InvalidNameException or CourseAlreadyExistsException Create a new course folder and set initial descriptor content, folder can ...
0.006557
def _coloredhelp(s): """ Colorize the usage string for docopt (ColorDocoptExit, docoptextras) """ newlines = [] bigindent = (' ' * 16) in_opts = False for line in s.split('\n'): linestripped = line.strip('\n').strip().strip(':') if linestripped == 'Usage': # l...
0.000557
def mk_kwargs(cls, kwargs): """ Pop recognized arguments from a keyword list. """ ret = {} kws = ['row_factory', 'body', 'parent'] for k in kws: if k in kwargs: ret[k] = kwargs.pop(k) return ret
0.007168
def profile_stats(adapter, threshold = 0.9): """ Compares the pairwise hamming distances for all the sample profiles in the database. Returns a table of the number of distances within given ranges. Args: adapter (MongoAdapter): Adapter to mongodb threshold (...
0.007676
def Policy(self, data=None, subset=None): """{dynamic_docstring}""" return self.factory.get_object(jssobjects.Policy, data, subset)
0.013605
def GetEntries(self, parser_mediator, cache=None, database=None, **kwargs): """Extracts event objects from the database. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. cache (Optional[ESEDBCache]): cache. ...
0.007653
def nested_tuple(container): """Recursively transform a container structure to a nested tuple. The function understands container types inheriting from the selected abstract base classes in `collections.abc`, and performs the following replacements: `Mapping` `tuple` of key-value pair `tuple`s....
0.004251
def _frange(start, stop=None, step=None): """ _frange range like function for float inputs :param start: :type start: :param stop: :type stop: :param step: :type step: :return: :rtype: """ if stop is None: stop = start start = 0.0 if step is None: ...
0.002488
def create_user_profile(sender, instance, created, **kwargs): """Create the UserProfile when a new User is saved""" if created: profile = UserProfile.objects.get_or_create(user=instance)[0] profile.hash_pass = create_htpasswd(instance.hash_pass) profile.save() else: # update ...
0.001876
def _install_packages(path, packages): """Install all packages listed to the target directory. Ignores any package that includes Python itself and python-lambda as well since its only needed for deploying and not running the code :param str path: Path to copy installed pip packages to. :pa...
0.003865
def disable_search_updates(): """ Context manager used to temporarily disable auto_sync. This is useful when performing bulk updates on objects - when you may not want to flood the indexing process. >>> with disable_search_updates(): ... for obj in model.objects.all(): ... obj.save...
0.001506
def parse_limit(limit_def): """Parse a structured flux limit definition as obtained from a YAML file Returns a tuple of reaction, lower and upper bound. """ lower, upper = get_limits(limit_def) reaction = limit_def.get('reaction') return reaction, lower, upper
0.003484
def load_config(from_key, to_key): """Load configuration from config. Meant to run only once per system process as class variable in subclasses.""" from .mappings import mappings kbs = {} for key, values in mappings['config'].iteritems(): parse_dict = {} ...
0.003534
def palette(self, label_im): ''' Transfer the VOC color palette to an output mask for visualization. ''' if label_im.ndim == 3: label_im = label_im[0] label = Image.fromarray(label_im, mode='P') label.palette = copy.copy(self.palette) return label
0.006349
def ind_nodes(self, graph=None): """ Returns a list of all nodes in the graph with no dependencies. """ if graph is None: graph = self.graph dependent_nodes = set( node for dependents in six.itervalues(graph) for node in dependents ) return [node for node...
0.005435
def init(self, formula, incr=False): """ Initialize the internal SAT oracle. The oracle is used incrementally and so it is initialized only once when constructing an object of class :class:`RC2`. Given an input :class:`.WCNF` formula, the method bootstraps the ...
0.001913
def _get_framed(self, buf, offset, insert_payload): """Returns the framed message and updates the CRC. """ header_offset = offset + self._header_len self.length = insert_payload(buf, header_offset, self.payload) struct.pack_into(self._header_fmt, buf, offse...
0.001261
def find_nearest(sorted_list, x): """ Find the nearest item of x from sorted array. :type array: list :param array: an iterable object that support inex :param x: a comparable value note: for finding the nearest item from a descending array, I recommend find_nearest(sorted_list[::-1], x)....
0.001218
def multi_path_generator(pathnames): """ yields (name,chunkgen) for all of the files found under the list of pathnames given. This is recursive, so directories will have their contents emitted. chunkgen is a function that can called and iterated over to obtain the contents of the file in multiple ...
0.001842
def _run_single(self, thread_id, agent, environment, deterministic=False, max_episode_timesteps=-1, episode_finished=None, testing=False, sleep=None): """ The target function for a thread, runs an agent and environment until signaled to stop. Adds rewards to shared episode re...
0.004215
def prepare_encoder(inputs, hparams, attention_type="local_1d"): """Prepare encoder for images.""" x = prepare_image(inputs, hparams, name="enc_channels") # Add position signals. x = add_pos_signals(x, hparams, "enc_pos") x_shape = common_layers.shape_list(x) if attention_type == "local_1d": x = tf.resh...
0.016667
def obfuscate(module, tokens, options, name_generator=None, table=None): """ Obfuscates *tokens* in-place. *options* is expected to be the options variable passed through from pyminifier.py. *module* must be the name of the module we're currently obfuscating If *name_generator* is provided it wil...
0.00079
def put(self, item): """Adds the passed in item object to the queue and calls :func:`flush` if the size of the queue is larger than :func:`max_queue_length`. This method does nothing if the passed in item is None. Args: item (:class:`contracts.Envelope`) item the telemetry envelope ...
0.009709
def execute(self, conn, acquisition_era_name,end_date, transaction = False): """ for a given block_id """ if not conn: dbsExceptionHandler("dbsException-failed-connect2host", "dbs/dao/Oracle/AcquisitionEra/updateEndDate expects db connection from upper layer.", self.logger.exception) ...
0.039583
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: return data kwargs = {} for attr, attr_ty...
0.004367
def getitem(self, index, context=None): """Get an item from this node if subscriptable. :param index: The node to use as a subscript index. :type index: Const or Slice :raises AstroidTypeError: When the given index cannot be used as a subscript index, or if this node is not...
0.002269
def _translate_glob(pat): """Translate a glob PATTERN to a regular expression.""" translated_parts = [] for part in _iexplode_path(pat): translated_parts.append(_translate_glob_part(part)) os_sep_class = '[%s]' % re.escape(SEPARATORS) res = _join_translated(translated_parts, os_sep_class) ...
0.002778
def Union(self, mask1, mask2): """Merges mask1 and mask2 into this FieldMask.""" _CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) tree.MergeFromFieldMask(mask2) tree.ToFieldMask(self)
0.004049
def save_objective(self, objective_form, *args, **kwargs): """Pass through to provider ObjectiveAdminSession.update_objective""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if objective_form.is_for_update(): return self.updat...
0.004425
def _sync_content_metadata(self, serialized_data, http_method): """ Synchronize content metadata using the Degreed course content API. Args: serialized_data: JSON-encoded object containing content metadata. http_method: The HTTP method to use for the API request. ...
0.003185
def set_client_cert(self, cert): """*Sets the client cert for the requests.* The cert is either a path to a .pem file, or a JSON array, or a list having the cert path and the key path. Values ``null`` and ``${None}`` can be used for clearing the cert. *Examples* | `Se...
0.005034
def clear(): """ Clear all data on the local server. Useful for debugging purposed. """ utils.check_for_local_server() click.confirm( "Are you sure you want to do this? It will delete all of your data", abort=True ) server = Server(config["local_server"]["url"]) for db_na...
0.002762
def ReleaseSW(self): ' Go away from Limit Switch ' while self.ReadStatusBit(2) == 1: # is Limit Switch ON ? spi.SPI_write(self.CS, [0x92, 0x92] | (~self.Dir & 1)) # release SW while self.IsBusy(): pass self.MoveWait(10)
0.013245
def generate_xml(self): """Generates an XML-formatted report for a single binding site""" report = et.Element('bindingsite') identifiers = et.SubElement(report, 'identifiers') longname = et.SubElement(identifiers, 'longname') ligtype = et.SubElement(identifiers, 'ligtype') ...
0.003485
def process_startup(): """Call this at Python startup to perhaps measure coverage. If the environment variable COVERAGE_PROCESS_START is defined, coverage measurement is started. The value of the variable is the config file to use. There are two ways to configure your Python installation to invok...
0.001202
def to_content_range_header(self, length): """Converts the object into `Content-Range` HTTP header, based on given length """ range_for_length = self.range_for_length(length) if range_for_length is not None: return "%s %d-%d/%d" % ( self.units, ...
0.004464
def _fix_set_options(cls, options): """Alter the set options from None/strings to sets in place.""" optional_set_options = ('ignore', 'select') mandatory_set_options = ('add_ignore', 'add_select') def _get_set(value_str): """Split `value_str` by the delimiter `,` and return ...
0.001936
def list_resource_groups(access_token, subscription_id): '''List the resource groups in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoin...
0.001901
def main(notify, hour, minute): """Runs billing report. Optionally sends notifications to billing""" # Read the config file and get the admin context config_opts = ['--config-file', '/etc/neutron/neutron.conf'] config.init(config_opts) # Have to load the billing module _after_ config is parsed so ...
0.000332
def _extract_buffers(obj, threshold=MAX_BYTES): """Extract buffers larger than a certain threshold.""" buffers = [] if isinstance(obj, CannedObject) and obj.buffers: for i, buf in enumerate(obj.buffers): nbytes = _nbytes(buf) if nbytes > threshold: # buffer la...
0.001294
def StopTiming(self, profile_name): """Stops timing CPU time. Args: profile_name (str): name of the profile to sample. """ measurements = self._profile_measurements.get(profile_name) if measurements: measurements.SampleStop() sample = '{0:f}\t{1:s}\t{2:f}\n'.format( mea...
0.009217
def color_array_by_hue_mix(value, palette): """ Figure out the appropriate color for a binary string value by averaging the colors corresponding the indices of each one that it contains. Makes for visualizations that intuitively show patch overlap. """ if int(value, 2) > 0: # Convert bi...
0.000919
def runExperimentPool(numObjects, numLocations, numFeatures, numColumns, networkType=["MultipleL4L2Columns"], longDistanceConnectionsRange = [0.0], numWorkers=7, nTri...
0.009215
def list_load_balancers(access_token, subscription_id): '''List the load balancers in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of load balancer list with properties....
0.001669
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` clas...
0.000301
def session_state_view(request, template_name, **kwargs): 'Example view that exhibits the use of sessions to store state' session = request.session demo_count = session.get('django_plotly_dash', {}) ind_use = demo_count.get('ind_use', 0) ind_use += 1 demo_count['ind_use'] = ind_use conte...
0.004274
def detectCustomImportPaths(self, prefix): """ Some prefixes does not reflect provider prefix e.g. camlistore.org/pkg/googlestorage is actually at github.com/camlistore/camlistore repository under pkg/googlestorage directory. """ for assignment in self.ip2pp_mapping: if prefix.startswith(assignment["ip...
0.029613
def calculate_dc_coefficients(contour): """Calculate the :math:`A_0` and :math:`C_0` coefficients of the elliptic Fourier series. :param numpy.ndarray contour: A contour array of size ``[M x 2]``. :return: The :math:`A_0` and :math:`C_0` coefficients. :rtype: tuple """ dxy = np.diff(contour, a...
0.004353
def domain(self, expparams): """ Returns a list of :class:`Domain` objects, one for each input expparam. :param numpy.ndarray expparams: Array of experimental parameters. This array must be of dtype agreeing with the ``expparams_dtype`` property. :rtype: list of ...
0.008299
def _set_link_crc_monitoring(self, v, load=False): """ Setter method for link_crc_monitoring, mapped from YANG variable /sysmon/link_crc_monitoring (container) If this variable is read-only (config: false) in the source YANG file, then _set_link_crc_monitoring is considered as a private method. Back...
0.005184
def tolist(self): """ Return the array as a list of rows. Each row is a `dict` of values. Facilitates inserting data into a database. .. versionadded:: 0.3.1 Returns ------- quotes : list A list in which each entry is a dictionary representing ...
0.006787
def _BuildFindSpecsFromGroupName(self, group_name, environment_variables): """Builds find specifications from a artifact group name. Args: group_name (str): artifact group name. environment_variables (list[str]): environment variable attributes used to dynamically populate environment var...
0.004155
def node_version(): """Get node version.""" version = check_output(('node', '--version')) return tuple(int(x) for x in version.strip()[1:].split(b'.'))
0.006135
def strip_tags(html): """Stripts HTML tags from text. Note fields on several Mambu entities come with additional HTML tags (they are rich text fields, I guess that's why). Sometimes they are useless, so stripping them is a good idea. """ from html.parser import HTMLParser class MLStripper(H...
0.006686
def use_comparative_assessment_offered_view(self): """Pass through to provider AssessmentOfferedLookupSession.use_comparative_assessment_offered_view""" self._object_views['assessment_offered'] = COMPARATIVE # self._get_provider_session('assessment_offered_lookup_session') # To make sure the ses...
0.007576
def user_group_membership_make_default(self, user_id, membership_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/group_memberships#set-membership-as-default" api_path = "/api/v2/users/{user_id}/group_memberships/{membership_id}/make_default.json" api_path = api_path.format...
0.013761
def is_git_repo(): """Check whether the current folder is a Git repo.""" cmd = "git", "rev-parse", "--git-dir" try: subprocess.run(cmd, stdout=subprocess.DEVNULL, check=True) return True except subprocess.CalledProcessError: return False
0.00361
def backend_inst_from_mod(mod, encoding, encoding_errors, kwargs): """Given a mod and a set of opts return an instantiated Backend class. """ kw = dict(encoding=encoding, encoding_errors=encoding_errors, kwargs=kwargs) try: klass = getattr(mod, "Backend") except AttributeEr...
0.001287
def start_event_stream(self): """ Start streaming events from `gerrit stream-events`. """ if not self._stream: self._stream = GerritStream(self, ssh_client=self._ssh_client) self._stream.start()
0.008547
def get_binary_stream(name): """Returns a system stream for byte processing. This essentially returns the stream from the sys module with the given name but it solves some compatibility issues between different Python versions. Primarily this function is necessary for getting binary streams on Pyth...
0.001661