Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
362,200
def compute_aesthetics(self, plot): data = self.data aesthetics = self.layer_mapping(plot.mapping) with suppress(KeyError): aesthetics[] = self.geom.aes_params[] env = EvalEnvironment.capture(eval_env=plot.environment) env = env.with_outer_namespac...
Return a dataframe where the columns match the aesthetic mappings. Transformations like 'factor(cyl)' and other expression evaluation are made in here
362,201
def acknowledge_message(self, delivery_tag, **kwargs): logger.info(, delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag)
Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame
362,202
def do_PROPPATCH(self, environ, start_response): path = environ["PATH_INFO"] res = self._davProvider.get_resource_inst(path, environ) environ.setdefault("HTTP_DEPTH", "0") if environ["HTTP_DEPTH"] != "0": self._fail(HTTP_BAD_REQUEST, "Depth must be .") ...
Handle PROPPATCH request to set or remove a property. @see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH
362,203
def get_splits_query(self): query = ( self.book.session.query(Split) .join(Account) .filter(Account.type != AccountType.trading.value) .filter(Account.commodity_guid == self.security.guid) ) return query
Returns the query for all splits for this security
362,204
def merge_result(res): if not isinstance(res, dict): raise ValueError() result = set([]) for _, v in res.items(): for value in v: result.add(value) return list(result)
Merge all items in `res` into a list. This command is used when sending a command to multiple nodes and they result from each node should be merged into a single list.
362,205
def titleForFilepath( url ): url = nativestring(url) if url in XdkEntryItem.TITLE_MAP: return XdkEntryItem.TITLE_MAP.get(url) url = nativestring(url).replace(, ) basename = os.path.basename(url) title = os.path.splitext(basename)[0] ...
Returns a gui title for this url. :return <str>
362,206
def parse_author(self, value): tokens = tuple([t.upper().strip() for t in value.split()]) if len(tokens) == 1: tokens = value.split() if len(tokens) > 0: if len(tokens) > 1: aulast, auinit = tokens[0:2] else: aulast...
Attempts to split an author name into last and first parts.
362,207
def pingable_ws_connect(request=None, on_message_callback=None, on_ping_callback=None): request.headers = httputil.HTTPHeaders(request.headers) request = httpclient._RequestProxy( request, httpclient.HTTPRequest._DEFAULTS) if version_info[0] == 4: ...
A variation on websocket_connect that returns a PingableWSClientConnection with on_ping_callback.
362,208
def dnd_endSnooze(self, **kwargs) -> SlackResponse: self._validate_xoxp_token() return self.api_call("dnd.endSnooze", json=kwargs)
Ends the current user's snooze mode immediately.
362,209
def predict_percentile(self, X, ancillary_X=None, p=0.5): alpha_, beta_ = self._prep_inputs_for_prediction_and_return_scores(X, ancillary_X) return pd.DataFrame(alpha_ * (1 / p - 1) ** beta_, index=_get_index(X))
Returns the median lifetimes for the individuals, by default. If the survival curve of an individual does not cross ``p``, then the result is infinity. http://stats.stackexchange.com/questions/102986/percentile-loss-functions Parameters ---------- X: numpy array or DataFrame ...
362,210
def five_prime(self, upstream=1, downstream=0): return pybedtools.BedTool(self.features())\ .each(featurefuncs.five_prime, upstream, downstream)\ .saveas()
Creates a BED/GFF file of the 5' end of each feature represented in the table and returns the resulting pybedtools.BedTool object. Needs an attached database. Parameters ---------- upstream, downstream : int Number of basepairs up and downstream to include
362,211
def client(self): if eventlet: with self.client_lock: self._set_client() else: self._set_client() return self._client
Return a lazy-instantiated pymongo client. When running with eventlet, connection causes IO and can result in more than one MongoDB client getting instantiatied, so we wrap the code in a semaphore to make sure only one mongodb client is instantiated per SimplDB class.
362,212
def split(u, axis=0): if axis < 0: axis = u.ndim + axis slct0 = (slice(None),) * axis return [u[slct0 + (k,)] for k in range(u.shape[axis])]
Split an array into a list of arrays on the specified axis. The length of the list is the shape of the array on the specified axis, and the corresponding axis is removed from each entry in the list. This function does not have the same behaviour as :func:`numpy.split`. Parameters ---------- u :...
362,213
def _find_git_info(self, gitdir): res = {: None, : None, : None, : None} try: logger.debug(, gitdir) repo = Repo(path=gitdir, search_parent_directories=False) res[] = repo.head.commit.hexsha res[] = repo.is_dirty(untracked_files=True) ...
Find information about the git repository, if this file is in a clone. :param gitdir: path to the git repo's .git directory :type gitdir: str :returns: information about the git clone :rtype: dict
362,214
def end_scan(self): self._set_state(self._STATE_GAP_END) self.api.ble_cmd_gap_end_procedure() self._wait_for_state(self._STATE_GAP_END) logger.debug() return self.scan_responses
Ends an ongoing BLE scan started by :meth:`begin_scan`. Returns: a :class:`ScanResults` object containing the scan results.
362,215
def posnegtoggle(number): if bool(number > 0): return number - number * 2 elif bool(number < 0): return number + abs(number) * 2 elif bool(number == 0): return number
Toggle a number between positive and negative. The converter works as follows: - 1 > -1 - -1 > 1 - 0 > 0 :type number: number :param number: The number to toggle.
362,216
def sender(self, body, stamp, url, sig): if not timestamp(stamp): return False if self.url != url: if not signature_cert_chain_url(url): return False certs = retrieve(url) if not certs: return False i...
Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Signature of the Request: https://goo.gl/FDkjBN. Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ Args: body: str. HTTPS request body. s...
362,217
def opener(self): "A reusable connection manager" if self._opener is None: log.debug("Creating connection handler") opener = build_opener() if self._cookies: log.debug("Appending cookies") else: log.debug("No cookies to appe...
A reusable connection manager
362,218
def yule_walker_regression(dx, Y, deg, res=None): a=0 sig=0 if res is None : res=1.0 Y-=np.mean(Y) N=len(Y) gamma = np.zeros(N) lag = np.arange(N) for i,l in enumerate(lag) : gamma[i] = np.corrcoef(Y, np.roll(Y,l))[0][1...
:parameter X: time vector (disabled) :parameter Y: stationary time series :parameter deg: AR model degree :return: * a : Yule Walker parameters * sig : Standard deviation of the noise term * aicc : corrected Akaike Information Criterion * gamma : Autocorrelation function ...
362,219
def get(self, key): key = self._service_key(key) return self._service_ops[](key)
Return the object in `service` named by `key` or None. Args: key: Key naming the object to retrieve. Returns: object or None
362,220
def stack_patches( patch_list, nr_row, nr_col, border=None, pad=False, bgcolor=255, viz=False, lclick_cb=None): if pad: patch_list = _pad_patch_list(patch_list, bgcolor) patch_list = _preprocess_patch_list(patch_list) if lclick_cb is not None: viz = True ph, pw = pa...
Stacked patches into grid, to produce visualizations like the following: .. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.jpg Args: patch_list(list[ndarray] or ndarray): NHW or NHWC images in [0,255]. nr_row(int), nr_col(int): rows and cols ...
362,221
def parse_uptime(uptime_str): (years, weeks, days, hours, minutes) = (0, 0, 0, 0, 0) uptime_str = uptime_str.strip() time_list = uptime_str.split(",") for element in time_list: if re.search("year", element): years = int(element.split()[0]) ...
Extract the uptime string from the given Cisco IOS Device. Return the uptime in seconds as an integer
362,222
def by_col(cls, df, e, b, t=None, geom_col=, inplace=False, **kwargs): import pandas as pd if not inplace: new = df.copy() cls.by_col(new, e, b, t=t, geom_col=geom_col, inplace=True, **kwargs) return new import pandas as pd if isinsta...
Compute smoothing by columns in a dataframe. The bounding box and point information is computed from the geometry column. Parameters ----------- df : pandas.DataFrame a dataframe containing the data to be smoothed e : string or list of strings ...
362,223
def update(self, resource, id_or_uri=None, timeout=-1): uri = resource.pop(, None) if not uri: if not id_or_uri: raise ValueError("URI was not provided") uri = self._client.build_uri(id_or_uri) return self._client.update(resource=resource, uri=uri...
Updates the specified alert resource. Args: resource (dict): Object to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. Returns: d...
362,224
def next_event(self): if isinstance(self._arrivals[0], ResourceAgent): if self._departures[0]._time < self._arrivals[0]._time: return super(ResourceQueue, self).next_event() elif self._arrivals[0]._time < infty: if self._arrivals[0]._has_resource:...
Simulates the queue forward one event. This method behaves identically to a :class:`.LossQueue` if the arriving/departing agent is anything other than a :class:`.ResourceAgent`. The differences are; Arriving: * If the :class:`.ResourceAgent` has a resource then it deletes ...
362,225
def load_remote_dataset(self, ds_str): if opendap.is_opendap(ds_str): return Dataset(ds_str) else: response = requests.get(ds_str, allow_redirects=True) if in response.headers[]: return self.process_doc(response.content) ...
Returns a dataset instance for the remote resource, either OPeNDAP or SOS :param str ds_str: URL to the remote resource
362,226
def on_end_validation(self, event): self.Enable() self.Show() self.magic_gui_frame.Destroy()
Switch back from validation mode to main Pmag GUI mode. Hide validation frame and show main frame.
362,227
def get_dataset(self, key, info=None): if key in self.cache: return self.cache[key] logger.debug(.format(key.name)) variable = self.nc[ .format(key.name)] radiances = xr.DataArray(np.asarray(variable, np.float32)...
Load a dataset.
362,228
def Register(): parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register( "Dpkg", linux_cmd_parser.DpkgCmdParser) parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register( "Dmidecode", linux_cmd_parser.DmidecodeCmdParser) parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register( "Mount", config_file.MountCmdPars...
Adds all known parsers to the registry.
362,229
def match(self, path): m = self._regex.search(path) if not m: raise NotFoundException items = dict((key, unquote_plus(val)) for key, val in m.groupdict().items()) items = unpickle_dict(items) [items....
Attempts to match a url to the given path. If successful, a tuple is returned. The first item is the matchd function and the second item is a dictionary containing items to be passed to the function parsed from the provided path. If the provided path does not match this url rule then a ...
362,230
def add_fragment(self, fragment, as_last=True): if not isinstance(fragment, TextFragment): self.log_exc(u"fragment is not an instance of TextFragment", None, True, TypeError) self.fragments_tree.add_child(Tree(value=fragment), as_last=as_last)
Add the given text fragment as the first or last child of the root node of the text file tree. :param fragment: the text fragment to be added :type fragment: :class:`~aeneas.textfile.TextFragment` :param bool as_last: if ``True`` append fragment, otherwise prepend it
362,231
def get_module_classes(node): return [ child for child in ast.walk(node) if isinstance(child, ast.ClassDef) ]
Return classes associated with a given module
362,232
def create_xml_path(path, **kwargs): * try: with salt.utils.files.fopen(path, ) as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False
Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding...
362,233
def calculate_between_class_scatter_matrix(X, y): mean_vectors = calculate_mean_vectors(X, y) n_features = X.shape[1] Sb = np.zeros((n_features, n_features)) m = np.mean(X, axis=0).reshape(n_features, 1) for cl, m_i in zip(np.unique(y), mean_vectors): v = m_i.reshape(n_features, 1) - ...
Calculates the Between-Class Scatter matrix Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- between_class_scatter_matrix : array-like, shape (n, n)
362,234
def full_exec_request_actions(actions, func=None, render_func=None): response = None try: exec_before_request_actions(actions, catch_context_exit=False) exec_request_actions(actions, catch_context_exit=False) if func: response = func() except ContextExitException as ...
Full process to execute before, during and after actions. If func is specified, it will be called after exec_request_actions() unless a ContextExitException was raised. If render_func is specified, it will be called after exec_request_actions() only if there is no response. exec_after_request_actions() ...
362,235
def patch_request(self, uri, body, custom_headers=None, timeout=-1): logger.debug( % (uri, body)) if not custom_headers: custom_headers = {} if self._connection._apiVersion >= 300 and not in custom_headers: custom_headers[] = task, entity = self._con...
Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: body (list): Patch request body timeout (int): Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it jus...
362,236
def get_image_dimensions(request): if request.service_type is ServiceType.WCS or (isinstance(request.size_x, int) and isinstance(request.size_y, int)): return request.size_x, request.size_y if not isinstance(request.size_x, int)...
Verifies or calculates image dimensions. :param request: OGC-type request :type request: WmsRequest or WcsRequest :return: horizontal and vertical dimensions of requested image :rtype: (int or str, int or str)
362,237
def _to_java_object_rdd(self): rdd = self._pickled() return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, True)
Return a JavaRDD of Object by unpickling It will convert each Python object into Java object by Pyrolite, whenever the RDD is serialized in batch or not.
362,238
def _expand_base_distribution_mean(self): single_draw_shape = concat_vectors(self.batch_shape_tensor(), self.event_shape_tensor()) m = tf.reshape( self.distribution.mean(), shape=tf.ones_like(single_draw_shape, dtype=tf.int32)) m = tf.tile(m, mul...
Ensures `self.distribution.mean()` has `[batch, event]` shape.
362,239
def _node_add_without_peer_leaf(self, node_sum, child_other): e = deepcopy(child_other) node_sum.append(self._del_attrib(e))
_node_add_without_peer_leaf Low-level api: Apply delta child_other to node_sum when there is no peer of child_other can be found under node_sum. child_other is a leaf node. Element node_sum will be modified during the process. Parameters ---------- node_sum : `Element`...
362,240
def delete_stack(awsclient, conf, feedback=True): client_cf = awsclient.get_client() stack_name = _get_stack_name(conf) last_event = _get_stack_events_last_timestamp(awsclient, stack_name) request = {} dict_selective_merge(request, conf[], [, ]) response = client_cf.delete_stack(**request...
Delete the stack from AWS cloud. :param awsclient: :param conf: :param feedback: print out stack events (defaults to True)
362,241
def _get_entity(entity_id): entity_type = g.request_dict[] if entity_type == : return model.FileRecord.from_dict(g.request_dict[]) elif entity_type == : return model.ObservatoryMetadata.from_dict(g.request_dict[]) elif entity_type == : return ...
Uses the request context to retrieve a :class:`meteorpi_model.CameraStatus`, :class:`meteorpi_model.Event` or :class:`meteorpi_model.FileRecord` from the POSTed JSON string. :param string entity_id: The ID of a CameraStatus, Event or FileRecord contained within the request :return: ...
362,242
def _printAvailableCheckpoints(experimentDir): checkpointParentDir = getCheckpointParentDir(experimentDir) if not os.path.exists(checkpointParentDir): print "No available checkpoints." return checkpointDirs = [x for x in os.listdir(checkpointParentDir) if _isCheckpointDir(os.path....
List available checkpoints for the specified experiment.
362,243
def clean_username(self): user = None try: user = User.objects.get(username__iexact=self.\ cleaned_data[]) except User.DoesNotExist: return self.cleaned_data[] if user: if user.username == self.user.username: ...
Validate that the username is alphanumeric and is not already in use. Don't fail if users username is provided.
362,244
def qos_rcv_queue_multicast_threshold_traffic_class0(self, **kwargs): config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") rcv_queue = ET.SubElement(qos, "rcv-queue") multicast = ET.SubElement(rcv_queue, "multicast") ...
Auto Generated Code
362,245
def index_discovered_zonefiles(self, lastblock): all_queued_zfinfos = [] subdomain_zonefile_infos = {} name_blocks = {} offset = 0 while True: queued_zfinfos = queuedb_findall(self.subdomain_queue_path, "zonefiles", limit=100, of...
Go through the list of zone files we discovered via Atlas, grouped by name and ordered by block height. Find all subsequent zone files for this name, and process all subdomain operations contained within them.
362,246
def update_vrf_table(self, route_dist, prefix=None, next_hop=None, route_family=None, route_type=None, tunnel_type=None, is_withdraw=False, redundancy_mode=None, pmsi_tunnel_type=None, **kwargs): from ryu.services.protocols.bgp....
Update a BGP route in the VRF table identified by `route_dist` with the given `next_hop`. If `is_withdraw` is False, which is the default, add a BGP route to the VRF table identified by `route_dist` with the given `next_hop`. If `is_withdraw` is True, remove a BGP route from the...
362,247
def to_dataframe(self, columns=None): if not isinstance(self.measured_value, DimensionedMeasuredValue): raise TypeError( ) if columns is None: columns = [d.name for d in self.dimensions] columns += [self.units.name if self.units else ] dataframe = self.measured_value.to_data...
Convert a multi-dim to a pandas dataframe.
362,248
def get_default_drive(self, request_drive=False): if request_drive is False: return Drive(con=self.con, protocol=self.protocol, main_resource=self.main_resource, name=) url = self.build_url(self._endpoints.get()) response = self.con.get(url) ...
Returns a Drive instance :param request_drive: True will make an api call to retrieve the drive data :return: default One Drive :rtype: Drive
362,249
def compute_range(travel_data, attr, travel_time_attr, dist, agg=np.sum): travel_data = travel_data.reset_index(level=1) travel_data = travel_data[travel_data[travel_time_attr] < dist] travel_data["attr"] = attr[travel_data.to_zone_id].values return travel_data.groupby(level=0).attr.apply(agg)
Compute a zone-based accessibility query using the urbansim format travel data dataframe. Parameters ---------- travel_data : dataframe The dataframe of urbansim format travel data. Has from_zone_id as first index, to_zone_id as second index, and different impedances between zo...
362,250
def build_directory(): if os.path.exists(): pass else: os.mkdir() if os.path.exists(WHOOSH_DB_DIR): pass else: os.makedirs(WHOOSH_DB_DIR)
Build the directory for Whoosh database, and locale.
362,251
def timeout_request_rebinding(self): logger.debug("C6.2:T In %s, timeout receiving response to request.", self.current_state) if self.request_attempts >= MAX_ATTEMPTS_REQUEST: logger.debug( , MAX_ATTEMPTS_REQUEST...
Timeout of request rebinding on REBINDING state. Same comments as in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`.
362,252
def wait(self, timeout=None): if self.__event.wait(timeout): if self.exception is not None: raise self.exception return True return False
Wait for the request to finish, optionally timing out. Returns True if the request has finished or False if it is still pending. Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a network related problem.
362,253
def get(self, **queryparams): return self._mc_client._get(url=self._build_path(), **queryparams)
Get links to all other resources available in the API. :param queryparams: The query string parameters queryparams['fields'] = [] queryparams['exclude_fields'] = []
362,254
def dispose(self): for registration in self._registrations.values(): registration.dispose() self._registrations = {}
Disposes every performed registration; the container can then be used again
362,255
def is_magic(self): return (self.name.startswith() and self.name.endswith() and self.name not in VARIADIC_MAGIC_METHODS)
Return True iff this method is a magic method (e.g., `__str__`).
362,256
def add_resources(self, resources): new_resources = self._build_resource_dictionary(resources) for key in new_resources: self._resources[key] = new_resources[key] self._dirty_attributes.add(u)
Adds new resources to the event. *resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects.
362,257
def with_pattern(pattern, regex_group_count=None): def decorator(func): func.pattern = pattern func.regex_group_count = regex_group_count return func return decorator
Attach a regular expression pattern matcher to a custom type converter function. This annotates the type converter with the :attr:`pattern` attribute. EXAMPLE: >>> import parse >>> @parse.with_pattern(r"\d+") ... def parse_number(text): ... return int(text) is equi...
362,258
async def _pause(self, ctx): player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send() if player.paused: await player.set_pause(False) await ctx.send() else: await player.se...
Pauses/Resumes the current track.
362,259
def requestCheckRegularDocker(origAppliance, registryName, imageName, tag): ioURL = \ .format(webhost=registryName, pathName=imageName, tag=tag) response = requests.head(ioURL) if not response.ok: raise ApplianceImageNotFound(origAppliance, ioURL, response.status_code) else: ...
Checks to see if an image exists using the requests library. URL is based on the docker v2 schema described here: https://docs.docker.com/registry/spec/manifest-v2-2/ This has the following format: https://{websitehostname}.io/v2/{repo}/manifests/{tag} Does not work with the official (docker.io) ...
362,260
def parse_prefix(prefix, default_length=128): if in prefix: network, pfxlen = prefix.split() else: network = prefix pfxlen = default_length return network, int(pfxlen)
Splits the given IP prefix into a network address and a prefix length. If the prefix does not have a length (i.e., it is a simple IP address), it is presumed to have the given default length. :type prefix: string :param prefix: An IP mask. :type default_length: long :param default_length: The...
362,261
def create(self, stylename, **kwargs): if stylename == "default": self[stylename] = style(stylename, self._ctx, **kwargs) return self[stylename] k = kwargs.get("template", "default") s = self[stylename] = self[k].copy(stylename) for attr in kwargs: ...
Creates a new style which inherits from the default style, or any other style which name is supplied to the optional template parameter.
362,262
def email_verifier(self, email, raw=False): params = {: email, : self.api_key} endpoint = self.base_endpoint.format() return self._query_hunter(endpoint, params, raw=raw)
Verify the deliverability of a given email adress.abs :param email: The email adress to check. :param raw: Gives back the entire response instead of just the 'data'. :return: Full payload of the query as a dict.
362,263
def _WriteSerializedAttributeContainerList(self, container_type): if container_type == self._CONTAINER_TYPE_EVENT: if not self._serialized_event_heap.data_size: return number_of_attribute_containers = ( self._serialized_event_heap.number_of_events) else: container_list...
Writes a serialized attribute container list. Args: container_type (str): attribute container type.
362,264
def _send_response(self, http_code, message=None, headers=None): self.send_response(http_code, message) if headers: for header in headers: self.send_header(*header) self.end_headers()
Sends HTTP response code, message and headers.
362,265
def make_zoom_block(min,max,count,colorkeyfields,bounds,filter_file_dictionary): if min == and max == and not bounds == True: return if colorkeyfields == False and bounds == False: block = zoomend % (str(min),str(max),str(count)) elif bounds == True: if min == and max == : min,max = [0,20] if filte...
else: block = ''' map.on('zoomend', function(e) { if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){ if (map.hasLayer(dataLayer) != true) { map.addLayer(dataLayer) } } else { map.removeLayer( dataLayer ) } }) map.on('click',function(e) { var skillsSelect = document.getElementById("mapStyle")...
362,266
def splitroot(self, part, sep=sep): drv = root = base = get_global_base_url(part) if base and without_http_prefix(part).startswith(without_http_prefix(base)): mark = without_http_prefix(base).rstrip(sep) + sep parts = part.split(mark) else: ...
Splits path string into drive, root and relative path Uses '/artifactory/' as a splitting point in URI. Everything before it, including '/artifactory/' itself is treated as drive. The next folder is treated as root, and everything else is taken for relative path. If '/artifacto...
362,267
def remove(self, path): norm_path = self.absnormpath(path) if self.ends_with_path_separator(path): self._handle_broken_link_with_trailing_sep(norm_path) if self.exists(norm_path): obj = self.resolve(norm_path) if S_IFMT(obj.st_mode) == S_IFDIR: ...
Remove the FakeFile object at the specified file path. Args: path: Path to file to be removed. Raises: OSError: if path points to a directory. OSError: if path does not exist. OSError: if removal failed.
362,268
def setOverlayName(self, ulOverlayHandle, pchName): fn = self.function_table.setOverlayName result = fn(ulOverlayHandle, pchName) return result
set the name to use for this overlay
362,269
def rollback(using=None): if using is None: for using in tldap.backend.connections: connection = tldap.backend.connections[using] connection.rollback() return connection = tldap.backend.connections[using] connection.rollback()
This function does the rollback itself and resets the dirty flag.
362,270
def chunks(iterable, n): for i in np.arange(0, len(iterable), n): yield iterable[i:i+n]
A python generator that yields 100-length sub-list chunks. Input: - full_list: The input list that is to be separated in chunks of 100. - chunk_size: Should be set to 100, unless the Twitter API changes. Yields: - sub_list: List chunks of length 100.
362,271
def delete_fallbackserver(self, serverid, data): return self.api_call( ENDPOINTS[][], dict(serverid=serverid), body=data)
Delete Fallback server
362,272
def autodoc_process_docstring(app, what, name, obj, options, lines): _, symbol = name.rsplit(, 1) if symbol not in callee.__all__: raise SphinxError( "autodoc%ss docstring if what == and name in autoclass_content_exceptions: ctor_docstring_lines = prepare...
Handler for the event emitted when autodoc processes a docstring. See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring. The TL;DR is that we can modify ``lines`` in-place to influence the output.
362,273
def _update_physics(self): phase = self.project.phases()[self.settings[]] physics = self.project.find_physics(phase=phase) for item in self.settings[]: quantity = self.settings[] phase[quantity] = self[quantity] ...
r Update physics using the current value of 'quantity' Notes ----- The algorithm directly writes the value of 'quantity' into the phase. This method was implemented relaxing one of the OpenPNM rules of algorithms not being able to write into phases.
362,274
def _prepare_for_submission(self, tempfolder, inputdict): parameters, code, distance_matrix, symlink = \ self._validate_inputs(inputdict) calcinfo = CalcInfo() calcinfo.uuid = self.uuid calcinfo.remote_copy_list = [] calcinfo.retrieve_list = par...
Create input files. :param tempfolder: aiida.common.folders.Folder subclass where the plugin should put all its files. :param inputdict: dictionary of the input nodes as they would be returned by get_inputs_dict
362,275
def renders_impl(self, template_content, context, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): renderer = self._make_renderer(at_paths, at_encoding, **kwargs) ctxs = [] if context is None else [context] return renderer.ren...
Render given template string and return the result. :param template_content: Template content :param context: A dict or dict-like object to instantiate given template file :param at_paths: Template search paths :param at_encoding: Template encoding :param kwargs: Key...
362,276
def replace_launch_config(self, scaling_group, launch_config_type, server_name, image, flavor, disk_config=None, metadata=None, personality=None, networks=None, load_balancers=None, key_name=None, config_drive=False, user_data=None): group_id = utils.get_id(scaling_g...
Replace an existing launch configuration. All of the attributes must be specified. If you wish to delete any of the optional attributes, pass them in as None.
362,277
def as_tmpfile(self, tmpdir=None): import tempfile, shutil tmpdir = tempfile.mkdtemp() if tmpdir is None else tmpdir new_path = os.path.join(tmpdir, self.basename) shutil.copy(self.filepath, new_path) root, ext = os.path.splitext(self.filepath) djrepo =...
Copy the pseudopotential to a temporary a file and returns a new pseudopotential object. Useful for unit tests in which we have to change the content of the file. Args: tmpdir: If None, a new temporary directory is created and files are copied here else tmpdir is used.
362,278
def get_mainmarket_ip(ip, port): global best_ip if ip is None and port is None and best_ip[][] is None and best_ip[][] is None: best_ip = select_best_ip() ip = best_ip[][] port = best_ip[][] elif ip is None and port is None and best_ip[][] is not None and best_ip[][] is not Non...
[summary] Arguments: ip {[type]} -- [description] port {[type]} -- [description] Returns: [type] -- [description]
362,279
def spcol(knots, order, tau): m = knt2mlt(tau) B = bspline.Bspline(knots, order) dummy = B(0.) nbasis = len(dummy) A = np.empty( (tau.shape[0], nbasis), dtype=dummy.dtype ) for i,item in enumerate(zip(tau,m)): taui,mi = item f = B.diff(order=mi) A[i,:] = f...
Return collocation matrix. Minimal emulation of MATLAB's ``spcol``. Parameters: knots: rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`) order: int, >= 0, order of spline tau: rank-1 array, collocation sites Returns: rank-2 array A such ...
362,280
def _parse_document(self): self._reset() doc = self._profile_doc self._split_tokens_calculated = True self._split_tokens = None self._duration_calculated = True self._duration = doc[u] self._datetime_calculated = True self._datetime = doc[u] ...
Parse system.profile doc, copy all values to member variables.
362,281
def _filterCopy(self, dataFile, newStart, newEnd, newDataDir): import csv pathToData = os.path.split(dataFile) dataFileName = pathToData[1] dataDeviceName = os.path.split(pathToData[0])[1] os.makedirs(os.path.join(newDataDir, dataDeviceName), exist_ok=True) outpu...
Copies the data file to a new file in the tmp dir, filtering it according to newStart and newEnd and adjusting the times as appropriate so it starts from 0. :param dataFile: the input file. :param newStart: the new start time. :param newEnd: the new end time. :param newDataDir: ...
362,282
def _get_repo_path(pathname, levels=None): if os.path.isfile(pathname): current_dir = os.path.abspath(os.path.dirname(pathname)) elif os.path.isdir(pathname): current_dir = os.path.abspath(pathname) else: return None current_level = 0 while levels is None or current_l...
Given a file or directory name, determine the root of the git repository this path is under. If given, this won't look any higher than ``levels`` (that is, if ``levels=0`` then the given path must be the root of the git repository and is returned if so. Returns `None` if the given path could not be de...
362,283
def write_how_many(self, file): report = CaseReport(self.case) components = [("Bus", "n_buses"), ("Generator", "n_generators"), ("Committed Generator", "n_online_generators"), ("Load", "n_loads"), ("Fixed Load", "n_fixed_loads"), ("Despatchable Load...
Writes component numbers to a table.
362,284
def clone_to(self, target_catalog): def _clone(obj_id): package_name = obj_id.get_identifier_namespace().split()[0] obj_name = obj_id.get_identifier_namespace().split()[1].lower() catalogs = { : , : } my_cata...
need to clone both the enclosed object + the wrapping asset
362,285
def breadcrumb_safe(context, label, viewname, *args, **kwargs): append_breadcrumb(context, _(label), viewname, args, kwargs) return
Same as breadcrumb but label is not escaped.
362,286
def get_old_value(self, args, kwargs, default=None): if self.arg_pos is not None and len(args) > self.arg_pos: return args[self.arg_pos] else: return kwargs.get(self.name, default)
Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present.
362,287
def copy_object(self, container, obj, metadata=None, destination=None, **kwargs): try: LOG.debug(, self.driver) return self.driver.copy_object(container, obj, metadata=metadata, destination=destination, **kwargs) ...
Copy object :param container: container name (Container is equivalent to Bucket term in Amazon). :param obj: object name (Object is equivalent to Key term in Amazon). :param destination: The container and object name of the destination ...
362,288
def parse_entry(self, row): var_call = VCFEntry(self.individuals) var_call.parse_entry(row) return var_call
Parse an individual VCF entry and return a VCFEntry which contains information about the call (such as alternative allele, zygosity, etc.)
362,289
def _CreateZMQSocket(self): logger.debug(.format(self.name)) if not self._zmq_context: self._zmq_context = zmq.Context() if not self._terminate_event: self._terminate_event = threading.Event() if not self._closed_event: self._closed_event = threading.Event() ...
Creates a ZeroMQ socket.
362,290
def _from_dict(cls, _dict): args = {} if in _dict: args[] = [ TokenResult._from_dict(x) for x in (_dict.get()) ] if in _dict: args[] = [ SentenceResult._from_dict(x) for x in (_dict.get()) ] return...
Initialize a SyntaxResult object from a json dictionary.
362,291
def md5(self): hashes = [self.graph.md5()] for g in self.geometry.values(): if hasattr(g, ): hashes.append(g.md5()) elif hasattr(g, ): hashes.append(str(hash(g.tostring()))) else: ...
MD5 of scene which will change when meshes or transforms are changed Returns -------- hashed: str, MD5 hash of scene
362,292
async def read_data(self, stream_id: int) -> bytes: frames = [f async for f in self.stream_frames(stream_id)] return b.join(frames)
Read data from the specified stream until it is closed by the remote peer. If the stream is never ended, this never returns.
362,293
def view_package_path(self, package: str) -> _PATH: if package not in self.view_packgets_list(): raise NoSuchPackageException( f) output, _ = self._execute( , self.device_sn, , , , package) return output[8:-1]
Print the path to the APK of the given.
362,294
def _common(ret, name, service_name, kwargs): if not in kwargs and not in kwargs: kwargs[] = name service = __salt__[](name_or_id=service_name) if not service: ret[] = ret[] = False return (False, ret) filters = kwargs.copy() filters.pop(, None) filters....
Returns: tuple whose first element is a bool indicating success or failure and the second element is either a ret dict for salt or an object
362,295
def _ReadParserPresetsFromFile(self): self._presets_file = os.path.join( self._data_location, self._PRESETS_FILE_NAME) if not os.path.isfile(self._presets_file): raise errors.BadConfigOption( .format(self._presets_file)) try: parsers_manager.ParsersManager.ReadPresetsFrom...
Reads the parser presets from the presets.yaml file. Raises: BadConfigOption: if the parser presets file cannot be read.
362,296
def _list_gids(): output = __salt__[]( [, , ], output_loglevel=, python_shell=False ) ret = set() for line in salt.utils.itertools.split(output, ): if line.startswith(): ret.update(line.split()[1:]) return sorted(ret)
Return a list of gids in use
362,297
def list(self): try: return (yield from self._vmware_manager.list_vms()) except VMwareError as e: raise GNS3VMError("Could not list VMware VMs: {}".format(str(e)))
List all VMware VMs
362,298
def filter_oauth_params(params): is_oauth = lambda kv: kv[0].startswith("oauth_") if isinstance(params, dict): return list(filter(is_oauth, list(params.items()))) else: return list(filter(is_oauth, params))
Removes all non oauth parameters from a dict or a list of params.
362,299
def get_csv_next_event_start(location, event_buffer): start = -1 end = -1 event_start = event_buffer.find("\n", location + 1) event_end = event_buffer.find(, event_start + 1) while (event_end > 0): parts = event_buffer[event_start:event_end].split(",") try: ...
determin the event start and end of *any* valid event