code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def startup_config_file(self): """ Returns the startup-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'startup-config.cfg') if os.path.exists(path): return path els...
Returns the startup-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist
def parse_clusterflow_runfiles(self, f): """ Parse run files generated by Cluster Flow. Currently gets pipeline IDs and associated steps.""" data = dict() in_comment = False seen_pipeline = False cf_file = False for l in f['f']: l = l.rstrip() ...
Parse run files generated by Cluster Flow. Currently gets pipeline IDs and associated steps.
def getPrice(self, searches): """ Prices all quest items and returns result Searches the shop wizard x times (x being number given in searches) for each quest item and finds the lowest price for each item. Combines all item prices and sets KitchenQuest.npSpent to the final value...
Prices all quest items and returns result Searches the shop wizard x times (x being number given in searches) for each quest item and finds the lowest price for each item. Combines all item prices and sets KitchenQuest.npSpent to the final value. Returns whether or not this proc...
async def get_novel(self, term, hide_nsfw=False): """ If term is an ID will return that specific ID. If it's a string, it will return the details of the first search result for that term. Returned Dictionary Has the following structure: Please note, if it says list or dict, it means the ...
If term is an ID will return that specific ID. If it's a string, it will return the details of the first search result for that term. Returned Dictionary Has the following structure: Please note, if it says list or dict, it means the python types. Indentation indicates level. So English is ['Tit...
def id(self): """ Unique identifier of user object""" return sa.Column(sa.Integer, primary_key=True, autoincrement=True)
Unique identifier of user object
def load_weight(weight_file: str, weight_name: str, weight_file_cache: Dict[str, Dict]) -> mx.nd.NDArray: """ Load wight fron a file or the cache if it was loaded before. :param weight_file: Weight file. :param weight_name: Weight name. :param weight_file_cache: Cach...
Load wight fron a file or the cache if it was loaded before. :param weight_file: Weight file. :param weight_name: Weight name. :param weight_file_cache: Cache of loaded files. :return: Loaded weight.
def base_url(self): """Base URL for resolving resource URLs""" if self.doc.package_url: return self.doc.package_url return self.doc._ref
Base URL for resolving resource URLs
def tag_clause_annotations(self): """Tag clause annotations in ``words`` layer. Depends on morphological analysis. """ if not self.is_tagged(ANALYSIS): self.tag_analysis() if self.__clause_segmenter is None: self.__clause_segmenter = load_default_clauseseg...
Tag clause annotations in ``words`` layer. Depends on morphological analysis.
def set_differentiable_objective(self): """Function that constructs minimization objective from dual variables.""" # Checking if graphs are already created if self.vector_g is not None: return # Computing the scalar term bias_sum = 0 for i in range(0, self.nn_params.num_hidden_layers): ...
Function that constructs minimization objective from dual variables.
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pix1 = pixmapper(pt1) pix2 = pixmapper(pt2) (width, height) = image_shape(img) (ret, pix1, pix2) = cv2.clipLine((0, 0, width, height), pix1, pix2) if ret is False: ...
draw a line on the image
def DeserializeExclusiveData(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): Raises: Exception: If the transaction type is incorrect or if there are no claims. """ self.Type = TransactionType.StateTransaction ...
Deserialize full object. Args: reader (neo.IO.BinaryReader): Raises: Exception: If the transaction type is incorrect or if there are no claims.
def challenge(self, shutit, task_desc, expect=None, hints=None, congratulations='OK', failed='FAILED', expect_type='exact', challenge_type='command', timeout=None, check_...
Set the user a task to complete, success being determined by matching the output. Either pass in regexp(s) desired from the output as a string or a list, or an md5sum of the output wanted. @param follow_on_context On success, move to this context. A dict of information about that context. ...
async def FindActionTagsByPrefix(self, prefixes): ''' prefixes : typing.Sequence[str] Returns -> typing.Sequence[~Entity] ''' # map input types to rpc msg _params = dict() msg = dict(type='Action', request='FindActionTagsByPrefix', ...
prefixes : typing.Sequence[str] Returns -> typing.Sequence[~Entity]
def parse_response(fields, records): """Parse an API response into usable objects. Args: fields (list[str]): List of strings indicating the fields that are represented in the records, in the order presented in the records.:: [ ...
Parse an API response into usable objects. Args: fields (list[str]): List of strings indicating the fields that are represented in the records, in the order presented in the records.:: [ 'number1', 'number2', ...
def function(self,p): """ Return a square-wave grating (alternating black and white bars). """ return np.around( 0.5 + 0.5*np.sin(pi*(p.duty_cycle-0.5)) + 0.5*np.sin(p.frequency*2*pi*self.pattern_y + p.phase))
Return a square-wave grating (alternating black and white bars).
def is_repeated_suggestion(params, history): """ Parameters ---------- params : dict Trial param set history : list of 3-tuples History of past function evaluations. Each element in history should be a tuple `(params, score, status)`, where `pa...
Parameters ---------- params : dict Trial param set history : list of 3-tuples History of past function evaluations. Each element in history should be a tuple `(params, score, status)`, where `params` is a dict mapping parameter names to values ...
def get(cls): """ Use the masking function (``sigprocmask(2)`` or ``pthread_sigmask(3)``) to obtain the mask of blocked signals :returns: A fresh :class:`sigprocmask` object. The returned object behaves as it was constructed with the list of currently blocke...
Use the masking function (``sigprocmask(2)`` or ``pthread_sigmask(3)``) to obtain the mask of blocked signals :returns: A fresh :class:`sigprocmask` object. The returned object behaves as it was constructed with the list of currently blocked signals, ``setmask=False`` and a...
def get_series_by_name(self, series_name): """Perform lookup for series :param str series_name: series name found within filename :returns: instance of series :rtype: object """ try: return self.api.search_series(name=series_name), None except excepti...
Perform lookup for series :param str series_name: series name found within filename :returns: instance of series :rtype: object
def username(self, value): """gets/sets the username""" if isinstance(value, str): self._username = value self._handler = None
gets/sets the username
def read_time(self, content): """ Core function used to generate the read_time for content. Parameters: :param content: Instance of pelican.content.Content Returns: None """ if get_class_name(content) in self.content_type_supported: # Exit if...
Core function used to generate the read_time for content. Parameters: :param content: Instance of pelican.content.Content Returns: None
def _reference_rmvs(self, removes): """Prints all removed packages """ print("") self.msg.template(78) msg_pkg = "package" if len(removes) > 1: msg_pkg = "packages" print("| Total {0} {1} removed".format(len(removes), msg_pkg)) self.msg.templat...
Prints all removed packages
def get_delivery_stats(api_key=None, secure=None, test=None, **request_args): '''Get delivery stats for your Postmark account. :param api_key: Your Postmark API key. Required, if `test` is not `True`. :param secure: Use the https scheme for the Postmark API. Defaults to `True` :param test: Use ...
Get delivery stats for your Postmark account. :param api_key: Your Postmark API key. Required, if `test` is not `True`. :param secure: Use the https scheme for the Postmark API. Defaults to `True` :param test: Use the Postmark Test API. Defaults to `False`. :param \*\*request_args: Keyword argu...
def tasks_by_tag(self, registry_tag): """ Get tasks from registry by its tag :param registry_tag: any hash-able object :return: Return task (if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is not True) or \ list of tasks """ if registry_tag not in self.__registry.keys(): return None tasks ...
Get tasks from registry by its tag :param registry_tag: any hash-able object :return: Return task (if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is not True) or \ list of tasks
def unchanged(self): ''' Returns all keys that have been unchanged. If the keys are in child dictionaries they will be represented with . notation ''' def _unchanged(current_dict, diffs, prefix): keys = [] for key in current_dict.keys(): ...
Returns all keys that have been unchanged. If the keys are in child dictionaries they will be represented with . notation
def merge_svg_files(svg_file1, svg_file2, x_coord, y_coord, scale=1): """ Merge `svg_file2` in `svg_file1` in the given positions `x_coord`, `y_coord` and `scale`. Parameters ---------- svg_file1: str or svgutils svg document object Path to a '.svg' file. svg_file2: str or svgutils svg doc...
Merge `svg_file2` in `svg_file1` in the given positions `x_coord`, `y_coord` and `scale`. Parameters ---------- svg_file1: str or svgutils svg document object Path to a '.svg' file. svg_file2: str or svgutils svg document object Path to a '.svg' file. x_coord: float Horizo...
def update_object_from_dictionary_representation(dictionary, instance): """Given a dictionary and an object instance, will set all object attributes equal to the dictionary's keys and values. Assumes dictionary does not have any keys for which object does not have attributes @type dictionary: d...
Given a dictionary and an object instance, will set all object attributes equal to the dictionary's keys and values. Assumes dictionary does not have any keys for which object does not have attributes @type dictionary: dict @param dictionary: Dictionary representation of the object @par...
def switch_toggle(self, device): """Toggles the current state of the given device""" state = self.get_state(device) if(state == '1'): return self.switch_off(device) elif(state == '0'): return self.switch_on(device) else: return state
Toggles the current state of the given device
def requires_libsodium(func): """ Mark a function as requiring libsodium. If no libsodium support is detected, a `RuntimeError` is thrown. """ @wraps(func) def wrapper(*args, **kwargs): libsodium_check() return func(*args, **kwargs) return wrapper
Mark a function as requiring libsodium. If no libsodium support is detected, a `RuntimeError` is thrown.
def connect_head_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501 """connect_head_namespaced_pod_proxy_with_path # noqa: E501 connect HEAD requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asyn...
connect_head_namespaced_pod_proxy_with_path # noqa: E501 connect HEAD requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_head_namespaced_pod_proxy_with...
def _write_scalar(self, name:str, scalar_value, iteration:int)->None: "Writes single scalar value to Tensorboard." tag = self.metrics_root + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)
Writes single scalar value to Tensorboard.
def ip_between(ip, start, finish): """Checks to see if IP is between start and finish""" if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish): return IPAddress(ip) in IPRange(start, finish) else: return False
Checks to see if IP is between start and finish
def _get_npcap_config(param_key): """ Get a Npcap parameter matching key in the registry. List: AdminOnly, DefaultFilterSettings, DltNull, Dot11Adapters, Dot11Support LoopbackAdapter, LoopbackSupport, NdisImPlatformBindingOptions, VlanSupport WinPcapCompatible """ hkey = winreg.HKEY_LOC...
Get a Npcap parameter matching key in the registry. List: AdminOnly, DefaultFilterSettings, DltNull, Dot11Adapters, Dot11Support LoopbackAdapter, LoopbackSupport, NdisImPlatformBindingOptions, VlanSupport WinPcapCompatible
def sentiment(self): """Return a tuple of form (polarity, subjectivity ) where polarity is a float within the range [-1.0, 1.0] and subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. :rtype: named tuple of the form ``Senti...
Return a tuple of form (polarity, subjectivity ) where polarity is a float within the range [-1.0, 1.0] and subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. :rtype: named tuple of the form ``Sentiment(polarity=0.0, subjectivity=...
def process(inFile,force=False,newpath=None, inmemory=False, num_cores=None, headerlets=True, align_to_gaia=True): """ Run astrodrizzle on input file/ASN table using default values for astrodrizzle parameters. """ # We only need to import this package if a user run the task import dr...
Run astrodrizzle on input file/ASN table using default values for astrodrizzle parameters.
def _addSpecfile(self, specfile, path): """Adds a new specfile entry to MsrunContainer.info. See also :class:`MsrunContainer.addSpecfile()`. :param specfile: the name of an ms-run file :param path: filedirectory used for loading and saving ``mrc`` files """ datatypeStatu...
Adds a new specfile entry to MsrunContainer.info. See also :class:`MsrunContainer.addSpecfile()`. :param specfile: the name of an ms-run file :param path: filedirectory used for loading and saving ``mrc`` files
def policyChange(self, updateParams, func): """ update defaultPolicy dict """ for k,v in updateParams.items(): k = k.replace('-','_') c = globals()[k](v) try: self.defaultPolicies[k] = getattr(c,func)(self.defaultPolicies[k]) except Exception, e: raise
update defaultPolicy dict
def serialize_list(out, lst, delimiter=u'', max_length=20): """This method is used to serialize list of text pieces like ["some=u'Another'", "blah=124"] Depending on how many lines are in these items, they are concatenated in row or as a column. Concatenation result is appended to the `out` argum...
This method is used to serialize list of text pieces like ["some=u'Another'", "blah=124"] Depending on how many lines are in these items, they are concatenated in row or as a column. Concatenation result is appended to the `out` argument.
def toggle_state(self, state, active=TOGGLE): """ Toggle the given state for this conversation. The state will be set ``active`` is ``True``, otherwise the state will be removed. If ``active`` is not given, it will default to the inverse of the current state (i.e., ``False`` if...
Toggle the given state for this conversation. The state will be set ``active`` is ``True``, otherwise the state will be removed. If ``active`` is not given, it will default to the inverse of the current state (i.e., ``False`` if the state is currently set, ``True`` if it is not; essentially ...
def dragEnterEvent(self, event): """ Listens for query's being dragged and dropped onto this tree. :param event | <QDragEnterEvent> """ data = event.mimeData() if data.hasFormat('application/x-orb-table') and \ data.hasFormat('application/...
Listens for query's being dragged and dropped onto this tree. :param event | <QDragEnterEvent>
def parse_requirements_list(requirements_list): """ Take a list and return a list of dicts with {package, versions) based on the requirements specs :param requirements_list: string :return: string """ req_list = [] for requirement in requirements_list: requirement_no_comments = req...
Take a list and return a list of dicts with {package, versions) based on the requirements specs :param requirements_list: string :return: string
def get_length_task_loss(config: LossConfig) -> 'Loss': """ Returns a Loss instance. :param config: Loss configuration. :return: Instance implementing Loss. """ if config.length_task_link is not None: if config.length_task_link == C.LINK_NORMAL: return MSELoss(config, ...
Returns a Loss instance. :param config: Loss configuration. :return: Instance implementing Loss.
def listen(self): '''Listen for events as they come in''' try: self._pubsub.subscribe(self._channels) for message in self._pubsub.listen(): if message['type'] == 'message': yield message finally: self._channels = []
Listen for events as they come in
def random_string(length=8, charset=None): ''' Generates a string with random characters. If no charset is specified, only letters and digits are used. Args: length (int) length of the returned string charset (string) list of characters to choose from Returns: (str) with ran...
Generates a string with random characters. If no charset is specified, only letters and digits are used. Args: length (int) length of the returned string charset (string) list of characters to choose from Returns: (str) with random characters from charset Raises: -
def upload_predictions(self, file_path, tournament=1): """Upload predictions from file. Args: file_path (str): CSV file with predictions that will get uploaded tournament (int): ID of the tournament (optional, defaults to 1) Returns: str: submission_id ...
Upload predictions from file. Args: file_path (str): CSV file with predictions that will get uploaded tournament (int): ID of the tournament (optional, defaults to 1) Returns: str: submission_id Example: >>> api = NumerAPI(secret_key="..", publi...
def calculate_metrics(self, model, train_loader, valid_loader, metrics_dict): """Add standard and custom metrics to metrics_dict""" # Check whether or not it's time for validation as well self.log_count += 1 log_valid = ( valid_loader is not None and self.valid_ev...
Add standard and custom metrics to metrics_dict
def _new_from_cdata(cls, cdata: Any) -> "Color": """new in libtcod-cffi""" return cls(cdata.r, cdata.g, cdata.b)
new in libtcod-cffi
def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subproces...
Returns a bool whether or not this node is a bhyve hypervisor
def _ttm_me_compute(self, V, edims, sdims, transp): """ Assume Y = T x_i V_i for i = 1...n can fit into memory """ shapeY = np.copy(self.shape) # Determine size of Y for n in np.union1d(edims, sdims): shapeY[n] = V[n].shape[1] if transp else V[n].shape[0] ...
Assume Y = T x_i V_i for i = 1...n can fit into memory
def list_eids(self): """ Returns a list of all known eids """ entities = self.list() return sorted([int(eid) for eid in entities])
Returns a list of all known eids
def get_stranger_info(self, *, user_id, no_cache=False): """ 获取陌生人信息 ------------ :param int user_id: QQ 号(不可以是登录号) :param bool no_cache: 是否不使用缓存(使用缓存可能更新不及时,但响应更快) :return: { "user_id": (QQ 号: int), "nickname": (昵称: str), "sex": (性别: str in ['male', 'female', 'unknown'...
获取陌生人信息 ------------ :param int user_id: QQ 号(不可以是登录号) :param bool no_cache: 是否不使用缓存(使用缓存可能更新不及时,但响应更快) :return: { "user_id": (QQ 号: int), "nickname": (昵称: str), "sex": (性别: str in ['male', 'female', 'unknown']), "age": (年龄: int) } :rtype: dict[ str, int | str ] ------...
def set_file_type(self, doc, type_value): """ Raises OrderError if no package or file defined. Raises CardinalityError if more than one type set. Raises SPDXValueError if type is unknown. """ type_dict = { 'SOURCE': file.FileType.SOURCE, 'BINARY': ...
Raises OrderError if no package or file defined. Raises CardinalityError if more than one type set. Raises SPDXValueError if type is unknown.
def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None: """mouse_event from Win32.""" ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)
mouse_event from Win32.
def _sample(probability_vec): """Return random binary string, with given probabilities.""" return map(int, numpy.random.random(probability_vec.size) <= probability_vec)
Return random binary string, with given probabilities.
def cprint(message, status=None): """color printing based on status: None -> BRIGHT 'ok' -> GREEN 'err' -> RED 'warn' -> YELLOW """ # TODO use less obscure dict, probably "error", "warn", "success" as keys status = {'warn': Fore.YELLOW, 'err': Fore.RED, 'ok': Fore.GREEN, ...
color printing based on status: None -> BRIGHT 'ok' -> GREEN 'err' -> RED 'warn' -> YELLOW
def three_way_information_gain(W, X, Y, Z, base=2): """Calculates the three-way information gain between three variables, I(W;X;Y;Z), in the given base IG(W;X;Y;Z) indicates the information gained about variable Z by the joint variable W_X_Y, after removing the information that W, X, and Y have about Z ind...
Calculates the three-way information gain between three variables, I(W;X;Y;Z), in the given base IG(W;X;Y;Z) indicates the information gained about variable Z by the joint variable W_X_Y, after removing the information that W, X, and Y have about Z individually and jointly in pairs. Thus, 3-way information gai...
def do(self, params): """发起对 api 的请求并过滤返回结果 :param params: 交易所需的动态参数""" request_params = self.create_basic_params() request_params.update(params) response_data = self.request(request_params) try: format_json_data = self.format_response_data(response_data) ...
发起对 api 的请求并过滤返回结果 :param params: 交易所需的动态参数
async def on_isupport_maxlist(self, value): """ Limits on channel modes involving lists. """ self._list_limits = {} for entry in value.split(','): modes, limit = entry.split(':') # Assign limit to mode group and add lookup entry for mode. self._list_limits[f...
Limits on channel modes involving lists.
def bartlett(timeseries, segmentlength, noverlap=None, window=None, plan=None): # pylint: disable=unused-argument """Calculate an PSD of this `TimeSeries` using Bartlett's method Parameters ---------- timeseries : `~gwpy.timeseries.TimeSeries` input `TimeSeries` data. segmentlength : `...
Calculate an PSD of this `TimeSeries` using Bartlett's method Parameters ---------- timeseries : `~gwpy.timeseries.TimeSeries` input `TimeSeries` data. segmentlength : `int` number of samples in single average. noverlap : `int` number of samples to overlap between segments...
def fit_partial( self, interactions, user_features=None, item_features=None, sample_weight=None, epochs=1, num_threads=1, verbose=False, ): """ Fit the model. Fit the model. Unlike fit, repeated calls to this method will ...
Fit the model. Fit the model. Unlike fit, repeated calls to this method will cause training to resume from the current model state. For details on how to use feature matrices, see the documentation on the :class:`lightfm.LightFM` class. Arguments --------- int...
def table_create(self, remove_existing=False): """Creates all tables. """ for engine in self.engines(): tables = self._get_tables(engine, create_drop=True) logger.info('Create all tables for %s', engine) try: self.metadata.create_all(engine, ta...
Creates all tables.
def _to_rule(self, lark_rule): """Converts a lark rule, (lhs, rhs, callback, options), to a Rule.""" assert isinstance(lark_rule.origin, NT) assert all(isinstance(x, Symbol) for x in lark_rule.expansion) return Rule( lark_rule.origin, lark_rule.expansion, weight=l...
Converts a lark rule, (lhs, rhs, callback, options), to a Rule.
def import_libsvm_sparse(filename): """Imports dataset file in libsvm sparse format""" from sklearn.datasets import load_svmlight_file X, y = load_svmlight_file(filename) return Dataset(X.toarray().tolist(), y.tolist())
Imports dataset file in libsvm sparse format
def random_forest(self): """ Random Forest. This function runs random forest and stores the, 1. Model 2. Model name 3. Max score 4. Metrics """ model = RandomForestRegressor(random_state=42) scores = [] kfold = KFold(n_splits=self.cv, s...
Random Forest. This function runs random forest and stores the, 1. Model 2. Model name 3. Max score 4. Metrics
def emit(self, record, closed=False): '''Do nothing''' HierarchicalOutput.emit(self, record, closed)
Do nothing
def model_eval(sess, x, y, predictions, X_test=None, Y_test=None, feed=None, args=None): """ Compute the accuracy of a TF model on some data :param sess: TF session to use :param x: input placeholder :param y: output placeholder (for labels) :param predictions: model output predictions :par...
Compute the accuracy of a TF model on some data :param sess: TF session to use :param x: input placeholder :param y: output placeholder (for labels) :param predictions: model output predictions :param X_test: numpy array with training inputs :param Y_test: numpy array with training outputs :param feed: An...
def run_false_positive_experiment_dim( numActive = 128, dim = 500, numSamples = 1000, numDendrites = 500, synapses = 24, numTrials = 10000, ...
Run an experiment to test the false positive rate based on number of synapses per dendrite, dimension and sparsity. Uses two competing neurons, along the P&M model. Based on figure 5B in the original SDR paper.
def is_multidex(self): """ Test if the APK has multiple DEX files :return: True if multiple dex found, otherwise False """ dexre = re.compile("^classes(\d+)?.dex$") return len([instance for instance in self.get_files() if dexre.search(instance)]) > 1
Test if the APK has multiple DEX files :return: True if multiple dex found, otherwise False
def scrape(self, selector, cleaner=None, processor=None): """Scrape the value for this field from the selector.""" # Apply CSS or XPath expression to the selector selected = selector.xpath(self.selection) if self.xpath else selector.css(self.selection) # Extract the value and apply regul...
Scrape the value for this field from the selector.
def load_gettext_translations(directory: str, domain: str) -> None: """Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate...
Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Python --keyword=_:1,2...
def add_grad(left, right): """Recursively add the gradient of two objects. Args: left: The left value to add. Can be either an array, a number, list or dictionary. right: The right value. Must be of the same type (recursively) as the left. Returns: The sum of the two gradients, which will of...
Recursively add the gradient of two objects. Args: left: The left value to add. Can be either an array, a number, list or dictionary. right: The right value. Must be of the same type (recursively) as the left. Returns: The sum of the two gradients, which will of the same type.
def refine_cell(self, tilde_obj): ''' NB only used for perovskite_tilting app ''' try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance) except Exception as ex: self.error = 'Symmetr...
NB only used for perovskite_tilting app
def iresolve(self, *keys): ''' Iterates over resolved instances for given provider keys. :param keys: Provider keys :type keys: tuple :return: Iterator of resolved instances :rtype: generator ''' for key in keys: missing = self.get_missing_dep...
Iterates over resolved instances for given provider keys. :param keys: Provider keys :type keys: tuple :return: Iterator of resolved instances :rtype: generator
def _read_from_socket(self): """Read data from the socket. :rtype: bytes """ if not self.use_ssl: if not self.socket: raise socket.error('connection/socket error') return self.socket.recv(MAX_FRAME_SIZE) with self._rd_lock: if...
Read data from the socket. :rtype: bytes
def run(uri, user_entry_point, args, env_vars=None, wait=True, capture_error=False, runner=_runner.ProcessRunnerType, extra_opts=None): # type: (str, str, List[str], Dict[str, str], bool, bool, _runner.RunnerType, Dict[str, str]) -> None """Download, prepa...
Download, prepare and executes a compressed tar file from S3 or provided directory as an user entrypoint. Runs the user entry point, passing env_vars as environment variables and args as command arguments. If the entry point is: - A Python package: executes the packages as >>> env_vars python -m mo...
def load_json_from_string(string): """Load schema from JSON string""" try: json_data = json.loads(string) except ValueError as e: raise ValueError('Given string is not valid JSON: {}'.format(e)) else: return json_data
Load schema from JSON string
def disconnect_pools(self): """Disconnects all connections from the internal pools.""" with self._lock: for pool in self._pools.itervalues(): pool.disconnect() self._pools.clear()
Disconnects all connections from the internal pools.
def chmod(path, mode, recursive=False): """Emulates bash chmod command This method sets the file permissions to the specified mode. :param path: (str) Full path to the file or directory :param mode: (str) Mode to be set (e.g. 0755) :param recursive: (bool) Set True to make a recursive call :re...
Emulates bash chmod command This method sets the file permissions to the specified mode. :param path: (str) Full path to the file or directory :param mode: (str) Mode to be set (e.g. 0755) :param recursive: (bool) Set True to make a recursive call :return: int exit code of the chmod command :r...
def handle_get_passphrase(self, conn, _): """Allow simple GPG symmetric encryption (using a passphrase).""" p1 = self.client.device.ui.get_passphrase('Symmetric encryption:') p2 = self.client.device.ui.get_passphrase('Re-enter encryption:') if p1 == p2: result = b'D ' + util....
Allow simple GPG symmetric encryption (using a passphrase).
def _as_array(arr, dtype=None): """Convert an object to a numerical NumPy array. Avoid a copy if possible. """ if arr is None: return None if isinstance(arr, np.ndarray) and dtype is None: return arr if isinstance(arr, integer_types + (float,)): arr = [arr] out = np...
Convert an object to a numerical NumPy array. Avoid a copy if possible.
def _parse_req(requnit, reqval): ''' Parse a non-day fixed value ''' assert reqval[0] != '=' try: retn = [] for val in reqval.split(','): if requnit == 'month': if reqval[0].isdigit(): retn.append(int(reqval)) ...
Parse a non-day fixed value
def cp_als(X, rank, random_state=None, init='randn', **options): """Fits CP Decomposition using Alternating Least Squares (ALS). Parameters ---------- X : (I_1, ..., I_N) array_like A tensor with ``X.ndim >= 3``. rank : integer The `rank` sets the number of components to be compute...
Fits CP Decomposition using Alternating Least Squares (ALS). Parameters ---------- X : (I_1, ..., I_N) array_like A tensor with ``X.ndim >= 3``. rank : integer The `rank` sets the number of components to be computed. random_state : integer, ``RandomState``, or ``None``, optional (...
def execute(self, **minimize_options): """ Execute the fit. :param minimize_options: keyword arguments to be passed to the specified minimizer. :return: FitResults instance """ minimizer_ans = self.minimizer.execute(**minimize_options) try: # to build...
Execute the fit. :param minimize_options: keyword arguments to be passed to the specified minimizer. :return: FitResults instance
def web(port, debug=False, theme="modern", ssh_config=None): """Starts the web UI.""" from storm import web as _web _web.run(port, debug, theme, ssh_config)
Starts the web UI.
def get_url(pif, dataset, version=1, site="https://citrination.com"): """ Construct the URL of a PIF on a site :param pif: to construct URL for :param dataset: the pif will belong to :param version: of the PIF (default: 1) :param site: for the dataset (default: https://citrination.com) :retu...
Construct the URL of a PIF on a site :param pif: to construct URL for :param dataset: the pif will belong to :param version: of the PIF (default: 1) :param site: for the dataset (default: https://citrination.com) :return: the URL as a string
def _adapt_WSDateTime(dt): """Return unix timestamp of the datetime like input. If conversion overflows high, return sint64_max , if underflows, return 0 """ try: ts = int( (dt.replace(tzinfo=pytz.utc) - datetime(1970,1,1,tzinfo=pytz.utc) ).total_seconds()...
Return unix timestamp of the datetime like input. If conversion overflows high, return sint64_max , if underflows, return 0
def _build_tpm(tpm): """Validate the TPM passed by the user and convert to multidimensional form. """ tpm = np.array(tpm) validate.tpm(tpm) # Convert to multidimensional state-by-node form if is_state_by_state(tpm): tpm = convert.state_by_state2state...
Validate the TPM passed by the user and convert to multidimensional form.
def getWeights(self, fromName, toName): """ Gets the weights of the connection between two layers (argument strings). """ for connection in self.connections: if connection.fromLayer.name == fromName and \ connection.toLayer.name == toName: retur...
Gets the weights of the connection between two layers (argument strings).
def add_voice(self, voices, item): """ Adds a voice to the list """ voice = None if item.get('type') == 'title': voice = self.get_title_voice(item) elif item.get('type') == 'app': voice = self.get_app_voice(item) elif item.get('type') == 'model': ...
Adds a voice to the list
def print_png(o): """ A function to display sympy expression using inline style LaTeX in PNG. """ s = latex(o, mode='inline') # mathtext does not understand certain latex flags, so we try to replace # them with suitable subs. s = s.replace('\\operatorname','') s = s.replace('\\overline',...
A function to display sympy expression using inline style LaTeX in PNG.
def slice_orthogonal(dataset, x=None, y=None, z=None, generate_triangles=False, contour=False): """Creates three orthogonal slices through the dataset on the three caresian planes. Yields a MutliBlock dataset of the three slices Parameters ---------- x :...
Creates three orthogonal slices through the dataset on the three caresian planes. Yields a MutliBlock dataset of the three slices Parameters ---------- x : float The X location of the YZ slice y : float The Y location of the XZ slice z : float ...
def deregister_all(self, *events): """ Deregisters all handler functions, or those registered against the given event(s). """ if events: for event in events: self._handler_dict[event] = [] else: self._handler_dict = {}
Deregisters all handler functions, or those registered against the given event(s).
def update_vm_result(self, context, msg): """Update VM's result field in the DB. The result reflects the success of failure of operation when an agent processes the vm info. """ args = jsonutils.loads(msg) agent = context.get('agent') port_id = args.get('port_uui...
Update VM's result field in the DB. The result reflects the success of failure of operation when an agent processes the vm info.
def getCustomDict(cls): """ Returns a dict of all temporary values in custom configuration file """ if not os.path.exists(cls.getPath()): return dict() properties = Configuration._readConfigFile(os.path.basename( cls.getPath()), os.path.dirname(cls.getPath())) values = dict() for ...
Returns a dict of all temporary values in custom configuration file
def get_update(self, z=None): """ Computes the new estimate based on measurement `z` and returns it without altering the state of the filter. Parameters ---------- z : (dim_z, 1): array_like measurement for this update. z can be a scalar if dim_z is 1, ...
Computes the new estimate based on measurement `z` and returns it without altering the state of the filter. Parameters ---------- z : (dim_z, 1): array_like measurement for this update. z can be a scalar if dim_z is 1, otherwise it must be convertible to a colum...
def request(self, url, json="", data="", username="", password="", headers=None, timout=30): """This is overridden on module initialization. This function will make an HTTP POST to a given url. Either json/da...
This is overridden on module initialization. This function will make an HTTP POST to a given url. Either json/data will be what is posted to the end point. he HTTP request needs to be basicAuth when username and password are provided. a headers dict maybe provided, whatever the values ar...
def interlink_translated_content(generator): '''Make translations link to the native locations for generators that may contain translated content ''' inspector = GeneratorInspector(generator) for content in inspector.all_contents(): interlink_translations(content)
Make translations link to the native locations for generators that may contain translated content
def count_subgraph_sizes(graph: BELGraph, annotation: str = 'Subgraph') -> Counter[int]: """Count the number of nodes in each subgraph induced by an annotation. :param annotation: The annotation to group by and compare. Defaults to 'Subgraph' :return: A dictionary from {annotation value: number of nodes} ...
Count the number of nodes in each subgraph induced by an annotation. :param annotation: The annotation to group by and compare. Defaults to 'Subgraph' :return: A dictionary from {annotation value: number of nodes}
def start_engine(self): ''' Start the child processes (one per device OS) ''' if self.disable_security is True: log.warning('***Not starting the authenticator process due to disable_security being set to True***') else: log.debug('Generating the private ke...
Start the child processes (one per device OS)
def trigger_show_by_id(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/triggers#getting-triggers" api_path = "/api/v2/triggers/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/triggers#getting-triggers
def save_screenshot(driver, name, folder=None): """ Saves a screenshot to the current directory (or to a subfolder if provided) If the folder provided doesn't exist, it will get created. The screenshot will be in PNG format. """ if "." not in name: name = name + ".png" if folder: ...
Saves a screenshot to the current directory (or to a subfolder if provided) If the folder provided doesn't exist, it will get created. The screenshot will be in PNG format.