code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def update(self, response, **kwargs): ''' If a record matching the instance already exists in the database, update it, else create a new record. ''' response_cls = self._get_instance(**kwargs) if response_cls: setattr(response_cls, self.column, self.accessor(r...
If a record matching the instance already exists in the database, update it, else create a new record.
def preferences_view(request): """View and process updates to the preferences page.""" user = request.user if request.method == "POST": logger.debug(dict(request.POST)) phone_formset, email_formset, website_formset, errors = save_personal_info(request, user) if user.is_student: ...
View and process updates to the preferences page.
def split_gtf(gtf, sample_size=None, out_dir=None): """ split a GTF file into two equal parts, randomly selecting genes. sample_size will select up to sample_size genes in total """ if out_dir: part1_fn = os.path.basename(os.path.splitext(gtf)[0]) + ".part1.gtf" part2_fn = os.path.ba...
split a GTF file into two equal parts, randomly selecting genes. sample_size will select up to sample_size genes in total
def discretize(value, factor=100): """Discretize the given value, pre-multiplying by the given factor""" if not isinstance(value, Iterable): return int(value * factor) int_value = list(deepcopy(value)) for i in range(len(int_value)): int_value[i] = int(int_value[i] * factor) return i...
Discretize the given value, pre-multiplying by the given factor
def build_ricecooker_json_tree(args, options, metadata_provider, json_tree_path): """ Download all categories, subpages, modules, and resources from open.edu. """ LOGGER.info('Starting to build the ricecooker_json_tree') channeldir = args['channeldir'] if channeldir.endswith(os.path.sep): ...
Download all categories, subpages, modules, and resources from open.edu.
def sample(self): """ Draws a trajectory length, first coordinates, lengths, angles and length-angle-difference pairs according to the empirical distribution. Each call creates one complete trajectory. """ lenghts = [] angles = [] coordinates = [] ...
Draws a trajectory length, first coordinates, lengths, angles and length-angle-difference pairs according to the empirical distribution. Each call creates one complete trajectory.
def generate(self): ''' Draws samples from the `true` distribution. Returns: `np.ndarray` of samples. ''' observed_arr = None for result_tuple in self.__feature_generator.generate(): observed_arr = result_tuple[0] bre...
Draws samples from the `true` distribution. Returns: `np.ndarray` of samples.
def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]): """Add roles to a member This method takes a list of **role ids** that you want to give to the user, on top of whatever roles they may already have. This method will fetch the user's current roles, and add to t...
Add roles to a member This method takes a list of **role ids** that you want to give to the user, on top of whatever roles they may already have. This method will fetch the user's current roles, and add to that list the roles passed in. The user's resulting list of roles will not contai...
def ConsultarCortes(self, sep="||"): "Retorna listado de cortes -carnes- (código, descripción)" ret = self.client.consultarCortes( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, ...
Retorna listado de cortes -carnes- (código, descripción)
def _realsize(self): ''' Get the struct size without padding (or the "real size") :returns: the "real size" in bytes ''' current = self size= 0 while current is not None: size += current._parser.sizeof(current) last = curr...
Get the struct size without padding (or the "real size") :returns: the "real size" in bytes
def update_wallet(self, wallet_name, limit): """Update a wallet with a new limit. @param the name of the wallet. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request. """ request = { 'u...
Update a wallet with a new limit. @param the name of the wallet. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request.
def _build_archive(self, dir_path): """ Creates a zip archive from files in path. """ zip_path = os.path.join(dir_path, "import.zip") archive = zipfile.ZipFile(zip_path, "w") for filename in CSV_FILES: filepath = os.path.join(dir_path, filename) ...
Creates a zip archive from files in path.
def index_spacing(self, value): """Validate and set the index_spacing flag.""" if not isinstance(value, bool): raise TypeError('index_spacing attribute must be a logical type.') self._index_spacing = value
Validate and set the index_spacing flag.
def get_categories(self): """ Get all categories and post count of each category. :return dict_item(category_name, Pair(count_all, count_published)) """ posts = self.get_posts(include_draft=True) result = {} for post in posts: for category_name in set...
Get all categories and post count of each category. :return dict_item(category_name, Pair(count_all, count_published))
def get_parallel_value_for_key(self, key): """ Get the value for a key. If there is no value for the key then empty string is returned. """ if self._remotelib: return self._remotelib.run_keyword('get_parallel_value_for_key', ...
Get the value for a key. If there is no value for the key then empty string is returned.
def delete_namespaced_cron_job(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_cron_job # noqa: E501 delete a CronJob # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>>...
delete_namespaced_cron_job # noqa: E501 delete a CronJob # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_cron_job(name, namespace, async_req=True) >>> resu...
def write_contents_to_file(self, entities, path_patterns=None, contents=None, link_to=None, content_mode='text', conflicts='fail', strict=False, domains=None, index=False, index_domains=None): ...
Write arbitrary data to a file defined by the passed entities and path patterns. Args: entities (dict): A dictionary of entities, with Entity names in keys and values for the desired file in values. path_patterns (list): Optional path patterns to use when buildin...
def _complete_batch_send(self, resp): """Complete the processing of our batch send operation Clear the deferred tracking our current batch processing and reset our retry count and retry interval Return none to eat any errors coming from up the deferred chain """ self._ba...
Complete the processing of our batch send operation Clear the deferred tracking our current batch processing and reset our retry count and retry interval Return none to eat any errors coming from up the deferred chain
def dict_of_numpyarray_to_dict_of_list(d): ''' Convert dictionary containing numpy arrays to dictionary containing lists Parameters ---------- d : dict sli parameter name and value as dictionary key and value pairs Returns ------- d : dict modified dictionary ...
Convert dictionary containing numpy arrays to dictionary containing lists Parameters ---------- d : dict sli parameter name and value as dictionary key and value pairs Returns ------- d : dict modified dictionary
def evaluate_accuracy(data_iterator, net): """Function to evaluate accuracy of any data iterator passed to it as an argument""" acc = mx.metric.Accuracy() for data, label in data_iterator: output = net(data) predictions = nd.argmax(output, axis=1) predictions = predictions.reshape((-...
Function to evaluate accuracy of any data iterator passed to it as an argument
def start(self) -> None: """Connect websocket to deCONZ.""" if self.config: self.websocket = self.ws_client( self.loop, self.session, self.host, self.config.websocketport, self.async_session_handler) self.websocket.start() else: ...
Connect websocket to deCONZ.
def PhyDMSComprehensiveParser(): """Returns *argparse.ArgumentParser* for ``phdyms_comprehensive`` script.""" parser = ArgumentParserNoArgHelp(description=("Comprehensive phylogenetic " "model comparison and detection of selection informed by deep " "mutational scanning data. This progra...
Returns *argparse.ArgumentParser* for ``phdyms_comprehensive`` script.
def next(self): """Move to the next valid locus. Will only return valid loci or exit via StopIteration exception """ while True: self.cur_idx += 1 if self.__datasource.populate_iteration(self): return self raise StopIteration
Move to the next valid locus. Will only return valid loci or exit via StopIteration exception
def _fix_typo(s): """M:.-O:.-'M:.-wa.e.-'t.x.-s.y.-', => M:.-O:.-'M:.-wa.e.-'t.-x.-s.y.-',""" subst, attr, mode = s return m(subst, attr, script("t.-x.-s.y.-'"))
M:.-O:.-'M:.-wa.e.-'t.x.-s.y.-', => M:.-O:.-'M:.-wa.e.-'t.-x.-s.y.-',
def exit_and_fail(self, msg=None, out=None): """Exits the runtime with a nonzero exit code, indicating failure. :param msg: A string message to print to stderr or another custom file desciptor before exiting. (Optional) :param out: The file descriptor to emit `msg` to. (Optional) """ ...
Exits the runtime with a nonzero exit code, indicating failure. :param msg: A string message to print to stderr or another custom file desciptor before exiting. (Optional) :param out: The file descriptor to emit `msg` to. (Optional)
def host_members(self): '''Return the members of the host committee. ''' host = self.host() if host is None: return for member, full_member in host.members_objects: yield full_member
Return the members of the host committee.
def xpathNextPreceding(self, cur): """Traversal function for the "preceding" direction the preceding axis contains all nodes in the same document as the context node that are before the context node in document order, excluding any ancestors and excluding attribute nodes ...
Traversal function for the "preceding" direction the preceding axis contains all nodes in the same document as the context node that are before the context node in document order, excluding any ancestors and excluding attribute nodes and namespace nodes; the nodes are ordered ...
def get_resource_group(access_token, subscription_id, rgname): '''Get details about the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP r...
Get details about the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body.
def auth(self): """ Auth is used to call the AUTH API of CricketAPI. Access token required for every request call to CricketAPI. Auth functional will post user Cricket API app details to server and return the access token. Return: Access token ...
Auth is used to call the AUTH API of CricketAPI. Access token required for every request call to CricketAPI. Auth functional will post user Cricket API app details to server and return the access token. Return: Access token
def fcm_send_single_device_data_message( registration_id, condition=None, collapse_key=None, delay_while_idle=False, time_to_live=None, restricted_package_name=None, low_priority=False, dry_run=False, data_message=None, content_available=No...
Send push message to a single device All arguments correspond to that defined in pyfcm/fcm.py. Args: registration_id (str): FCM device registration IDs. data_message (dict): Data message payload to send alone or with the notification message Keyword Args: collapse_key (...
def nltk_tree_to_logical_form(tree: Tree) -> str: """ Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted into the correct number of parentheses. This is used in t...
Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted into the correct number of parentheses. This is used in the logic that converts action sequences back into logical form...
def as_lwp_str(self, ignore_discard=True, ignore_expires=True): """Return cookies as a string of "\\n"-separated "Set-Cookie3" headers. ignore_discard and ignore_expires: see docstring for FileCookieJar.save """ now = time.time() r = [] for cookie in self: i...
Return cookies as a string of "\\n"-separated "Set-Cookie3" headers. ignore_discard and ignore_expires: see docstring for FileCookieJar.save
def cmd_tracker_mode(self, args): '''set arbitrary mode''' connection = self.find_connection() if not connection: print("No antenna tracker found") return mode_mapping = connection.mode_mapping() if mode_mapping is None: print('No mode mapping ...
set arbitrary mode
def setnx(self, key, value): """Set the value of a key, only if the key does not exist.""" fut = self.execute(b'SETNX', key, value) return wait_convert(fut, bool)
Set the value of a key, only if the key does not exist.
def set_check(self, name, state): '''set a status value''' if self.child.is_alive(): self.parent_pipe.send(CheckItem(name, state))
set a status value
def convert_to_unicode( tscii_input ): """ convert a byte-ASCII encoded string into equivalent Unicode string in the UTF-8 notation.""" output = list() prev = None prev2x = None # need a look ahead of 2 tokens atleast for char in tscii_input: ## print "%2x"%ord(char) # debugging ...
convert a byte-ASCII encoded string into equivalent Unicode string in the UTF-8 notation.
def banner(*lines, **kwargs): """prints a banner sep -- string -- the character that will be on the line on the top and bottom and before any of the lines, defaults to * count -- integer -- the line width, defaults to 80 """ sep = kwargs.get("sep", "*") count = kwargs.get("width", globa...
prints a banner sep -- string -- the character that will be on the line on the top and bottom and before any of the lines, defaults to * count -- integer -- the line width, defaults to 80
def is_subdir(a, b): """ Return true if a is a subdirectory of b """ a, b = map(os.path.abspath, [a, b]) return os.path.commonpath([a, b]) == b
Return true if a is a subdirectory of b
def _sanitize_parameters(self): """ Perform a sanity check on parameters passed in to CFG.__init__(). An AngrCFGError is raised if any parameter fails the sanity check. :return: None """ # Check additional_edges if isinstance(self._additional_edges, (list, set, ...
Perform a sanity check on parameters passed in to CFG.__init__(). An AngrCFGError is raised if any parameter fails the sanity check. :return: None
def mk_subsuper_association(m, r_subsup): ''' Create pyxtuml associations from a sub/super association in BridgePoint. ''' r_rel = one(r_subsup).R_REL[206]() r_rto = one(r_subsup).R_SUPER[212].R_RTO[204]() target_o_obj = one(r_rto).R_OIR[203].O_OBJ[201]() for r_sub in many(r_subsup).R_S...
Create pyxtuml associations from a sub/super association in BridgePoint.
def get_template_data(template_file): """ Read the template file, parse it as JSON/YAML and return the template as a dictionary. Parameters ---------- template_file : string Path to the template to read Returns ------- Template data as a dictionary """ if not pathlib.P...
Read the template file, parse it as JSON/YAML and return the template as a dictionary. Parameters ---------- template_file : string Path to the template to read Returns ------- Template data as a dictionary
def _parse_request(self, schema, req, locations): """Return a parsed arguments dictionary for the current request.""" if schema.many: assert ( "json" in locations ), "schema.many=True is only supported for JSON location" # The ad hoc Nested field is mo...
Return a parsed arguments dictionary for the current request.
def get_normal_draws(num_mixers, num_draws, num_vars, seed=None): """ Parameters ---------- num_mixers : int. Should be greater than zero. Denotes the number of observations for which we are making draws from a normal distrib...
Parameters ---------- num_mixers : int. Should be greater than zero. Denotes the number of observations for which we are making draws from a normal distribution for. I.e. the number of observations with randomly distributed coefficients. num_draws : int. Should be greater tha...
def create_and_register_access97_db(filename: str, dsn: str, description: str) -> bool: """ (Windows only.) Creates a Microsoft Access 97 database and registers it with ODBC. Args: filename: filename of the database to crea...
(Windows only.) Creates a Microsoft Access 97 database and registers it with ODBC. Args: filename: filename of the database to create dsn: ODBC data source name to create description: description of the database Returns: bool: was the DSN created?
def domain_create(auth=None, **kwargs): ''' Create a domain CLI Example: .. code-block:: bash salt '*' keystoneng.domain_create name=domain1 ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(keep_name=True, **kwargs) return cloud.create_domain(**kwargs)
Create a domain CLI Example: .. code-block:: bash salt '*' keystoneng.domain_create name=domain1
def Softmax(x, params, axis=-1, **kwargs): """Apply softmax to x: exponentiate and normalize along the given axis.""" del params, kwargs return np.exp(x - backend.logsumexp(x, axis, keepdims=True))
Apply softmax to x: exponentiate and normalize along the given axis.
def ParseRow(self, parser_mediator, row_offset, row): """Parses a line of the log file and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. row_offset (int): line number of the row. row (d...
Parses a line of the log file and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. row_offset (int): line number of the row. row (dict[str, str]): fields of a single row, as specified in COLUM...
def _create_cell(args, cell_body): """Implements the pipeline cell create magic used to create Pipeline objects. The supported syntax is: %%pipeline create <args> [<inline YAML>] Args: args: the arguments following '%%pipeline create'. cell_body: the contents of the cell """ name = args.ge...
Implements the pipeline cell create magic used to create Pipeline objects. The supported syntax is: %%pipeline create <args> [<inline YAML>] Args: args: the arguments following '%%pipeline create'. cell_body: the contents of the cell
def remove_attr(self, attr): """Removes an attribute.""" self._stable = False self.attrs.pop(attr, None) return self
Removes an attribute.
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidChronometer, self).init_widget() w = self.widget w.setOnChronometerTickListener(w.getId()) w.onChronometerTick.connect(self.on_chronometer_tick)
Initialize the underlying widget.
def getlist(self, section, option): """Read a list of strings. The value of `section` and `option` is treated as a comma- and newline- separated list of strings. Each value is stripped of whitespace. Returns the list of strings. """ value_list = self.get(section, opti...
Read a list of strings. The value of `section` and `option` is treated as a comma- and newline- separated list of strings. Each value is stripped of whitespace. Returns the list of strings.
def yn_prompt(text): ''' Takes the text prompt, and presents it, takes only "y" or "n" for answers, and returns True or False. Repeats itself on bad input. ''' text = "\n"+ text + "\n('y' or 'n'): " while True: answer = input(text).strip() if answer != 'y' and answer !...
Takes the text prompt, and presents it, takes only "y" or "n" for answers, and returns True or False. Repeats itself on bad input.
def find_declaration(self): """ Find the most likely function declaration from the embedded collection of prototypes, set it to self.prototype, and update self.calling_convention with the declaration. :return: None """ # determine the library name if not self.i...
Find the most likely function declaration from the embedded collection of prototypes, set it to self.prototype, and update self.calling_convention with the declaration. :return: None
def _reset_problem_type(self): """Reset problem type to whatever is appropriate.""" # Only need to reset the type after the first solve. This also works # around a bug in Cplex where get_num_binary() is some rare cases # causes a segfault. if self._solve_count > 0: i...
Reset problem type to whatever is appropriate.
def dict_contents(self, use_dict=None, as_class=None): """Return the contents of an object as a dict.""" if _debug: _log.debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class) # exception to the rule of returning a dict return str(self)
Return the contents of an object as a dict.
def rdf_source(self, aformat="turtle"): """ Serialize graph using the format required """ if aformat and aformat not in self.SUPPORTED_FORMATS: return "Sorry. Allowed formats are %s" % str(self.SUPPORTED_FORMATS) if aformat == "dot": return self.__serializedDot() else: # use stardard rdf serializat...
Serialize graph using the format required
def find_xml_all(cls, url, markup, tag, pattern): """ find xml(list) :param url: contents url :param markup: markup provider :param tag: find tag :param pattern: xml file pattern :return: BeautifulSoup object list """ body = cls.find_xml(url, marku...
find xml(list) :param url: contents url :param markup: markup provider :param tag: find tag :param pattern: xml file pattern :return: BeautifulSoup object list
def seq_minibatches(inputs, targets, batch_size, seq_length, stride=1): """Generate a generator that return a batch of sequence inputs and targets. If `batch_size=100` and `seq_length=5`, one return will have 500 rows (examples). Parameters ---------- inputs : numpy.array The input features...
Generate a generator that return a batch of sequence inputs and targets. If `batch_size=100` and `seq_length=5`, one return will have 500 rows (examples). Parameters ---------- inputs : numpy.array The input features, every row is a example. targets : numpy.array The labels of input...
def filter_for_ignored_ext(result, ignored_ext, ignore_copying): """ Will filter if instructed to do so the result to remove matching criteria :param result: list of dicts returned by Snakebite ls :type result: list[dict] :param ignored_ext: list of ignored extensions :t...
Will filter if instructed to do so the result to remove matching criteria :param result: list of dicts returned by Snakebite ls :type result: list[dict] :param ignored_ext: list of ignored extensions :type ignored_ext: list :param ignore_copying: shall we ignore ? :type ...
def save(self, ts): """ Save timestamp to file. """ with open(self, 'w') as f: Timestamp.wrap(ts).dump(f)
Save timestamp to file.
def _cur_band_filled(self): """Checks if the current band is filled. The size of the current band should be equal to s_max_1""" cur_band = self._hyperbands[self._state["band_idx"]] return len(cur_band) == self._s_max_1
Checks if the current band is filled. The size of the current band should be equal to s_max_1
def extract(cls, padded): """ Removes the surrounding "@{...}" from the name. :param padded: the padded string :type padded: str :return: the extracted name :rtype: str """ if padded.startswith("@{") and padded.endswith("}"): return padded[2:l...
Removes the surrounding "@{...}" from the name. :param padded: the padded string :type padded: str :return: the extracted name :rtype: str
def remove(self, data): """ Removes a data node from the list. If the list contains more than one node having the same data that shall be removed, then the node having the first occurrency of the data is removed. :param data: the data to be removed in the new list node :...
Removes a data node from the list. If the list contains more than one node having the same data that shall be removed, then the node having the first occurrency of the data is removed. :param data: the data to be removed in the new list node :type data: object
def enqueue(self, item_type, item): """Queue a new data item, make item iterable""" with self.enlock: self.queue[item_type].append(item)
Queue a new data item, make item iterable
def astra_projector(vol_interp, astra_vol_geom, astra_proj_geom, ndim, impl): """Create an ASTRA projector configuration dictionary. Parameters ---------- vol_interp : {'nearest', 'linear'} Interpolation type of the volume discretization. This determines the projection model that is cho...
Create an ASTRA projector configuration dictionary. Parameters ---------- vol_interp : {'nearest', 'linear'} Interpolation type of the volume discretization. This determines the projection model that is chosen. astra_vol_geom : dict ASTRA volume geometry. astra_proj_geom : d...
def capture_output(self, with_hook=True): """Steal stream output, return them in string, restore them""" self.hooked = '' def display_hook(obj): # That's some dirty hack self.hooked += self.safe_better_repr(obj) self.last_obj = obj stdout, stderr = s...
Steal stream output, return them in string, restore them
def process_placeholder_image(self): """ Process the field's placeholder image. Ensures the placeholder image has been saved to the same storage class as the field in a top level folder with a name specified by settings.VERSATILEIMAGEFIELD_SETTINGS['placeholder_directory_name'] ...
Process the field's placeholder image. Ensures the placeholder image has been saved to the same storage class as the field in a top level folder with a name specified by settings.VERSATILEIMAGEFIELD_SETTINGS['placeholder_directory_name'] This should be called by the VersatileImageFileD...
def search_related(self, request): logger.debug("Cache Search Request") if self.cache.is_empty() is True: logger.debug("Empty Cache") return None """ extracting everything from the cache """ result = [] items = list(self.cache.cache.items(...
extracting everything from the cache
def random_string(length=6, alphabet=string.ascii_letters+string.digits): """ Return a random string of given length and alphabet. Default alphabet is url-friendly (base62). """ return ''.join([random.choice(alphabet) for i in xrange(length)])
Return a random string of given length and alphabet. Default alphabet is url-friendly (base62).
def authenticate_server(self, response): """ Uses GSSAPI to authenticate the server. Returns True on success, False on failure. """ log.debug("authenticate_server(): Authenticate header: {0}".format( _negotiate_value(response))) host = urlparse(response.url...
Uses GSSAPI to authenticate the server. Returns True on success, False on failure.
def get_jobs_from_argument(self, raw_job_string): """ return a list of jobs corresponding to the raw_job_string """ jobs = [] if raw_job_string.startswith(":"): job_keys = raw_job_string.strip(" :") jobs.extend([job for job in self.jobs(job_keys)]) # we assume a j...
return a list of jobs corresponding to the raw_job_string
def get_all_events(self): """Gather all event IDs in the REACH output by type. These IDs are stored in the self.all_events dict. """ self.all_events = {} events = self.tree.execute("$.events.frames") if events is None: return for e in events: ...
Gather all event IDs in the REACH output by type. These IDs are stored in the self.all_events dict.
def chisquare(n_ij, weighted): """ Calculates the chisquare for a matrix of ind_v x dep_v for the unweighted and SPSS weighted case """ if weighted: m_ij = n_ij / n_ij nan_mask = np.isnan(m_ij) m_ij[nan_mask] = 0.000001 # otherwise it breaks the chi-squared test w_...
Calculates the chisquare for a matrix of ind_v x dep_v for the unweighted and SPSS weighted case
def Cp(self, T): """ Calculate the heat capacity of the compound phase. :param T: [K] temperature :returns: [J/mol/K] Heat capacity. """ result = 0.0 for c, e in zip(self._coefficients, self._exponents): result += c*T**e return result
Calculate the heat capacity of the compound phase. :param T: [K] temperature :returns: [J/mol/K] Heat capacity.
def url_join(base, *args): """ Helper function to join an arbitrary number of url segments together. """ scheme, netloc, path, query, fragment = urlsplit(base) path = path if len(path) else "/" path = posixpath.join(path, *[('%s' % x) for x in args]) return urlunsplit([scheme, netloc, path, ...
Helper function to join an arbitrary number of url segments together.
def startGraph(self): """Starts RDF graph and bing namespaces""" g = r.Graph() g.namespace_manager.bind("rdf", r.namespace.RDF) g.namespace_manager.bind("foaf", r.namespace.FOAF) g.namespace_manager.bind("xsd", r.namespace.XSD) g.namespace_manager.bind("opa", ...
Starts RDF graph and bing namespaces
def GetDirections(self, origin, destination, sensor = False, mode = None, waypoints = None, alternatives = None, avoid = None, language = None, units = None, region = None, departure_time = None, arrival_time = None): '''Get Directions Service Pls refer to the Google Maps Web ...
Get Directions Service Pls refer to the Google Maps Web API for the details of the remained parameters
def ToLatLng(self): """ Returns that latitude and longitude that this point represents under a spherical Earth model. """ rad_lat = math.atan2(self.z, math.sqrt(self.x * self.x + self.y * self.y)) rad_lng = math.atan2(self.y, self.x) return (rad_lat * 180.0 / math.pi, rad_lng * 180.0 / math....
Returns that latitude and longitude that this point represents under a spherical Earth model.
def bind(self, prefix, namespace, *args, **kwargs): """ Extends the function to add an attribute to the class for each added namespace to allow for use of dot notation. All prefixes are converted to lowercase Args: prefix: string of namespace name namespace: rdfl...
Extends the function to add an attribute to the class for each added namespace to allow for use of dot notation. All prefixes are converted to lowercase Args: prefix: string of namespace name namespace: rdflib.namespace instance kwargs: calc: whether...
def xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spin2x, spin2y): """Returns the effective precession spin argument for the smaller mass. This function assumes it's given spins of the secondary mass. """ q = q_from_mass1_mass2(mass1, mass2) a1 = 2 + 3 * q / 2 a2 = 2 + 3 / (2 * q) return ...
Returns the effective precession spin argument for the smaller mass. This function assumes it's given spins of the secondary mass.
def log(self, branch, remote): """ Call a log-command, if set by git-up.fetch.all. """ log_hook = self.settings['rebase.log-hook'] if log_hook: if ON_WINDOWS: # pragma: no cover # Running a string in CMD from Python is not that easy on # Windo...
Call a log-command, if set by git-up.fetch.all.
def _prefetch_items(self,change): """ When the current_row in the model changes (whether from scrolling) or set by the application. Make sure the results are loaded! """ if self.is_initialized: view = self.item_view upper_limit = view.iterabl...
When the current_row in the model changes (whether from scrolling) or set by the application. Make sure the results are loaded!
def snap_to_nearest_config(x, tune_params): """helper func that for each param selects the closest actual value""" params = [] for i, k in enumerate(tune_params.keys()): values = numpy.array(tune_params[k]) idx = numpy.abs(values-x[i]).argmin() params.append(int(values[idx])) ret...
helper func that for each param selects the closest actual value
def merge_parameters(parameters, date_time, macros, types_and_values): """ Merge Return a mapping from airflow macro names (prefixed with '_') to values Args: date_time: The timestamp at which the macro values need to be evaluated. This is only applicable when types_and_values = True macr...
Merge Return a mapping from airflow macro names (prefixed with '_') to values Args: date_time: The timestamp at which the macro values need to be evaluated. This is only applicable when types_and_values = True macros: If true, the values in the returned dict are the macro strings (like '{{ ds...
def load_modules_alignak_configuration(self): # pragma: no cover, not yet with unit tests. """Load Alignak configuration from the arbiter modules If module implements get_alignak_configuration, call this function :param raw_objects: raw objects we got from reading config files :type ra...
Load Alignak configuration from the arbiter modules If module implements get_alignak_configuration, call this function :param raw_objects: raw objects we got from reading config files :type raw_objects: dict :return: None
def surface_of_section(orbit, plane_ix, interpolate=False): """ Generate and return a surface of section from the given orbit. .. warning:: This is an experimental function and the API may change. Parameters ---------- orbit : `~gala.dynamics.Orbit` plane_ix : int Integer ...
Generate and return a surface of section from the given orbit. .. warning:: This is an experimental function and the API may change. Parameters ---------- orbit : `~gala.dynamics.Orbit` plane_ix : int Integer that represents the coordinate to record crossings in. For examp...
def getinfo(self, member): """Return RarInfo for filename """ if isinstance(member, RarInfo): fname = member.filename else: fname = member # accept both ways here if PATH_SEP == '/': fname2 = fname.replace("\\", "/") else: ...
Return RarInfo for filename
def vlan_classifier_rule_class_type_proto_proto_proto_val(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan") classifier = ET.SubElement(vlan, "classifier") rule = ET.Sub...
Auto Generated Code
def on_nick(self, connection, event): """ Someone changed their nickname - send the nicknames list to the WebSocket. """ old_nickname = self.get_nickname(event) old_color = self.nicknames.pop(old_nickname) new_nickname = event.target() message = "is now kn...
Someone changed their nickname - send the nicknames list to the WebSocket.
def _check_available_data(archive, arc_type, day): """ Function to check what stations are available in the archive for a given \ day. :type archive: str :param archive: The archive source :type arc_type: str :param arc_type: The type of archive, can be: :type day: datetime.date :pa...
Function to check what stations are available in the archive for a given \ day. :type archive: str :param archive: The archive source :type arc_type: str :param arc_type: The type of archive, can be: :type day: datetime.date :param day: Date to retrieve data for :returns: list of tuple...
def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.style...
Convert a reST file to HTML.
def remove_config_to_machine_group(self, project_name, config_name, group_name): """ remove a logtail config to a machine group Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_name: string ...
remove a logtail config to a machine group Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_name: string :param config_name: the logtail config name to apply :type group_n...
def build_values(name, values_mods): """Update name/values.yaml with modifications""" values_file = os.path.join(name, 'values.yaml') with open(values_file) as f: values = yaml.load(f) for key, value in values_mods.items(): parts = key.split('.') mod_obj = values for p ...
Update name/values.yaml with modifications
def create_in_cluster(self): """ call Kubernetes API and create this Service in cluster, raise ConuExeption if the API call fails :return: None """ try: self.api.create_namespaced_service(self.namespace, self.body) except ApiException as e: ...
call Kubernetes API and create this Service in cluster, raise ConuExeption if the API call fails :return: None
def intercept_(self): """ Intercept (bias) property .. note:: Intercept is defined only for linear learners Intercept (bias) is only defined when the linear model is chosen as base learner (`booster=gblinear`). It is not defined for other base learner types, such ...
Intercept (bias) property .. note:: Intercept is defined only for linear learners Intercept (bias) is only defined when the linear model is chosen as base learner (`booster=gblinear`). It is not defined for other base learner types, such as tree learners (`booster=gbtree`)....
def delete_vmss(access_token, subscription_id, resource_group, vmss_name): '''Delete a virtual machine scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_nam...
Delete a virtual machine scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP respons...
def csoftmax_for_slice(input): """ It is a implementation of the constrained softmax (csoftmax) for slice. Based on the paper: https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers" (page 4) Args: input: A list of [...
It is a implementation of the constrained softmax (csoftmax) for slice. Based on the paper: https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers" (page 4) Args: input: A list of [input tensor, cumulative attention]. ...
def classify(self, n_jobs=-1, configure=None): """ Returns input-output behaviors for the list of logical networks in the attribute :attr:`networks` Example:: >>> from caspo import core, classify >>> networks = core.LogicalNetworkList.from_csv('networks.csv') ...
Returns input-output behaviors for the list of logical networks in the attribute :attr:`networks` Example:: >>> from caspo import core, classify >>> networks = core.LogicalNetworkList.from_csv('networks.csv') >>> setup = core.Setup.from_json('setup.json') >>> ...
def highlight(self, *args): """ Highlights the region with a colored frame. Accepts the following parameters: highlight([toEnable], [seconds], [color]) * toEnable (boolean): Enables or disables the overlay * seconds (number): Seconds to show overlay * color (string): He...
Highlights the region with a colored frame. Accepts the following parameters: highlight([toEnable], [seconds], [color]) * toEnable (boolean): Enables or disables the overlay * seconds (number): Seconds to show overlay * color (string): Hex code ("#XXXXXX") or color name ("black...
def run(self): """ Run consumer """ if KSER_METRICS_ENABLED == "yes": from prometheus_client import start_http_server logger.info("Metric.Starting...") start_http_server( os.getenv("KSER_METRICS_PORT", 8888), os.getenv("KSER_MET...
Run consumer