code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def is_valid_python(code, reraise=True, ipy_magic_workaround=False): """ References: http://stackoverflow.com/questions/23576681/python-check-syntax """ import ast try: if ipy_magic_workaround: code = '\n'.join(['pass' if re.match(r'\s*%[a-z]*', line) else line for line i...
References: http://stackoverflow.com/questions/23576681/python-check-syntax
def stream_replicate(): """Monitor changes in approximately real-time and replicate them""" stream = primary.stream(SomeDataBlob, "trim_horizon") next_heartbeat = pendulum.now() while True: now = pendulum.now() if now >= next_heartbeat: stream.heartbeat() next_hea...
Monitor changes in approximately real-time and replicate them
def set_polling_override(self, override): """Set the sensor polling timer override value in milliseconds. Due to the time it takes to poll all the sensors on up to 5 IMUs, it's not possible for the SK8 firmware to define a single fixed rate for reading new samples without it being ar...
Set the sensor polling timer override value in milliseconds. Due to the time it takes to poll all the sensors on up to 5 IMUs, it's not possible for the SK8 firmware to define a single fixed rate for reading new samples without it being artificially low for most configurations. ...
def bls_stats_singleperiod(times, mags, errs, period, magsarefluxes=False, sigclip=10.0, perioddeltapercent=10, nphasebins=200, mintransitduration=0.01, maxtr...
This calculates the SNR, depth, duration, a refit period, and time of center-transit for a single period. The equation used for SNR is:: SNR = (transit model depth / RMS of LC with transit model subtracted) * sqrt(number of points in transit) NOTE: you should set the kwargs `sigclip...
def cluster_coincs_multiifo(stat, time_coincs, timeslide_id, slide, window, argmax=numpy.argmax): """Cluster coincident events for each timeslide separately, across templates, based on the ranking statistic Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize t...
Cluster coincident events for each timeslide separately, across templates, based on the ranking statistic Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time_coincs: tuple of numpy.ndarrays trigger times for each ifo, or -1 if an ifo does not particip...
def pemp(stat, stat0): """ Computes empirical values identically to bioconductor/qvalue empPvals """ assert len(stat0) > 0 assert len(stat) > 0 stat = np.array(stat) stat0 = np.array(stat0) m = len(stat) m0 = len(stat0) statc = np.concatenate((stat, stat0)) v = np.array([True] * ...
Computes empirical values identically to bioconductor/qvalue empPvals
def c2ln(c,l1,l2,n): "char[n] to two unsigned long???" c = c + n l1, l2 = U32(0), U32(0) f = 0 if n == 8: l2 = l2 | (U32(c[7]) << 24) f = 1 if f or (n == 7): l2 = l2 | (U32(c[6]) << 16) f = 1 if f or (n == 6): l2 = l2 | (U32(c[5]) << 8) f = 1 ...
char[n] to two unsigned long???
def get_datasets_list(self, project_id=None): """ Method returns full list of BigQuery datasets in the current project .. seealso:: For more information, see: https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list :param project_id: Google Cloud ...
Method returns full list of BigQuery datasets in the current project .. seealso:: For more information, see: https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list :param project_id: Google Cloud Project for which you try to get all datasets ...
def files_to_pif(files, verbose=0, quality_report=True, inline=True): '''Given a directory that contains output from a DFT calculation, parse the data and return a pif object Input: files - [str] list of files from which the parser is allowed to read. verbose - int, How much status mess...
Given a directory that contains output from a DFT calculation, parse the data and return a pif object Input: files - [str] list of files from which the parser is allowed to read. verbose - int, How much status messages to print Output: pif - ChemicalSystem, Results and settings...
def transform(function): """Return a processor for a style's "transform" function. """ def transform_fn(_, result): if isinstance(result, Nothing): return result lgr.debug("Transforming %r with %r", result, function) try: retur...
Return a processor for a style's "transform" function.
def vb_get_network_addresses(machine_name=None, machine=None, wait_for_pattern=None): ''' TODO distinguish between private and public addresses A valid machine_name or a machine is needed to make this work! !!! Guest prerequisite: GuestAddition !!! Thanks to Shrikant Havale for the StackO...
TODO distinguish between private and public addresses A valid machine_name or a machine is needed to make this work! !!! Guest prerequisite: GuestAddition !!! Thanks to Shrikant Havale for the StackOverflow answer http://stackoverflow.com/a/29335390 More information on guest properties: http...
def seq_2_StdStringVector(seq, vec=None): """Converts a python sequence<str> object to a :class:`tango.StdStringVector` :param seq: the sequence of strings :type seq: sequence<:py:obj:`str`> :param vec: (optional, default is None) an :class:`tango.StdStringVector` to be ...
Converts a python sequence<str> object to a :class:`tango.StdStringVector` :param seq: the sequence of strings :type seq: sequence<:py:obj:`str`> :param vec: (optional, default is None) an :class:`tango.StdStringVector` to be filled. If None is given, a new :class:`tango.Std...
def get_molo_comments(parser, token): """ Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. Set the amount of comments to usage: {% get_molo_comments for object as variable_name %} {% get_molo_comments for object ...
Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. Set the amount of comments to usage: {% get_molo_comments for object as variable_name %} {% get_molo_comments for object as variable_name limit amount %} {% get_mo...
def user(self, login=None): """Returns a User object for the specified login name if provided. If no login name is provided, this will return a User object for the authenticated user. :param str login: (optional) :returns: :class:`User <github3.users.User>` """ i...
Returns a User object for the specified login name if provided. If no login name is provided, this will return a User object for the authenticated user. :param str login: (optional) :returns: :class:`User <github3.users.User>`
def dump(self): """ Dump (return) a dict representation of the GameObject. This is a Python dict and is NOT serialized. NB: the answer (a DigitWord object) and the mode (a GameMode object) are converted to python objects of a list and dict respectively. :return: python <...
Dump (return) a dict representation of the GameObject. This is a Python dict and is NOT serialized. NB: the answer (a DigitWord object) and the mode (a GameMode object) are converted to python objects of a list and dict respectively. :return: python <dict> of the GameObject as detailed ...
def get_surface_as_bytes(self, order=None): """Returns the surface area as a bytes encoded RGB image buffer. Subclass should override if there is a more efficient conversion than from generating a numpy array first. """ arr8 = self.get_surface_as_array(order=order) return...
Returns the surface area as a bytes encoded RGB image buffer. Subclass should override if there is a more efficient conversion than from generating a numpy array first.
def keyword(self) -> Tuple[Optional[str], str]: """Parse a YANG statement keyword. Raises: EndOfInput: If past the end of input. UnexpectedInput: If no syntactically correct keyword is found. """ i1 = self.yang_identifier() if self.peek() == ":": ...
Parse a YANG statement keyword. Raises: EndOfInput: If past the end of input. UnexpectedInput: If no syntactically correct keyword is found.
def get_episodes(self, series_id, **kwargs): """All episodes for a given series. Paginated with 100 results per page. .. warning:: authorization token required The following search arguments currently supported: * airedSeason * airedEpisode ...
All episodes for a given series. Paginated with 100 results per page. .. warning:: authorization token required The following search arguments currently supported: * airedSeason * airedEpisode * imdbId * dvdSeason * dvd...
def _fourier(self): """ 1 side Fourier transform and scale by dt all waveforms in catalog """ freq_bin_upper = 2000 freq_bin_lower = 40 fs = self._metadata['fs'] Y_transformed = {} for key in self.Y_dict.keys(): # normalize by fs, bins have units strain/Hz ...
1 side Fourier transform and scale by dt all waveforms in catalog
def callback(self, request, **kwargs): """ Called from the Service when the user accept to activate it """ try: client = self.get_evernote_client() # finally we save the user auth token # As we already stored the object ServicesActivated ...
Called from the Service when the user accept to activate it
def bresenham(x1, y1, x2, y2): """ Return a list of points in a bresenham line. Implementation hastily copied from RogueBasin. Returns: List[Tuple[int, int]]: A list of (x, y) points, including both the start and end-points. """ points = [] issteep = abs(y2-y1) > abs(x2...
Return a list of points in a bresenham line. Implementation hastily copied from RogueBasin. Returns: List[Tuple[int, int]]: A list of (x, y) points, including both the start and end-points.
def upload_file(self, path=None, stream=None, name=None, **kwargs): """ Uploads file to WeedFS I takes either path or stream and name and upload it to WeedFS server. Returns fid of the uploaded file. :param string path: :param string stream: :param stri...
Uploads file to WeedFS I takes either path or stream and name and upload it to WeedFS server. Returns fid of the uploaded file. :param string path: :param string stream: :param string name: :rtype: string or None
def _lemmatise_roman_numerals(self, form, pos=False, get_lemma_object=False): """ Lemmatise un mot f si c'est un nombre romain :param form: Mot à lemmatiser :param pos: Récupère la POS :param get_lemma_object: Retrieve Lemma object instead of string representation of lemma """ ...
Lemmatise un mot f si c'est un nombre romain :param form: Mot à lemmatiser :param pos: Récupère la POS :param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
def configs_in(src_dir): """Enumerate all configs in src_dir""" for filename in files_in_dir(src_dir, 'json'): with open(os.path.join(src_dir, filename), 'rb') as in_f: yield json.load(in_f)
Enumerate all configs in src_dir
def compute_bbox_with_margins(margin, x, y): 'Helper function to compute bounding box for the plot' # set margins pos = np.asarray((x, y)) minxy, maxxy = pos.min(axis=1), pos.max(axis=1) xy1 = minxy - margin*(maxxy - minxy) xy2 = maxxy + margin*(maxxy - minxy) return tuple(xy1), tuple(xy2)
Helper function to compute bounding box for the plot
def solve(self, assumptions=[]): """ Solve internal formula. """ if self.minicard: if self.use_timer: start_time = time.clock() # saving default SIGINT handler def_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_DFL) ...
Solve internal formula.
def supported_tags(self, interpreter=None, force_manylinux=True): """Returns a list of supported PEP425 tags for the current platform.""" if interpreter and not self.is_extended: # N.B. If we don't get an extended platform specifier, we generate # all possible ABI permutations to mimic earlier pex v...
Returns a list of supported PEP425 tags for the current platform.
def unqueue(self, timeout=10, should_wait=False): """Unqueue all the received ensime responses for a given file.""" start, now = time.time(), time.time() wait = self.queue.empty() and should_wait while (not self.queue.empty() or wait) and (now - start) < timeout: if wait and...
Unqueue all the received ensime responses for a given file.
def _check_all_devices_in_sync(self): '''Wait until all devices have failover status of 'In Sync'. :raises: UnexpectedClusterState ''' if len(self._get_devices_by_failover_status('In Sync')) != \ len(self.devices): msg = "Expected all devices in group to hav...
Wait until all devices have failover status of 'In Sync'. :raises: UnexpectedClusterState
def get_top_sentences(self): ''' getter ''' if isinstance(self.__top_sentences, int) is False: raise TypeError("The type of __top_sentences must be int.") return self.__top_sentences
getter
def create_fork(self, repo): """ :calls: `POST /repos/:owner/:repo/forks <http://developer.github.com/v3/repos/forks>`_ :param repo: :class:`github.Repository.Repository` :rtype: :class:`github.Repository.Repository` """ assert isinstance(repo, github.Repository.Repositor...
:calls: `POST /repos/:owner/:repo/forks <http://developer.github.com/v3/repos/forks>`_ :param repo: :class:`github.Repository.Repository` :rtype: :class:`github.Repository.Repository`
def thresholdBlocks(self, blocks, recall_weight=1.5): # pragma: nocover """ Returns the threshold that maximizes the expected F score, a weighted average of precision and recall for a sample of blocked data. Arguments: blocks -- Sequence of tuples of records, where eac...
Returns the threshold that maximizes the expected F score, a weighted average of precision and recall for a sample of blocked data. Arguments: blocks -- Sequence of tuples of records, where each tuple is a set of records covered by a blocking predicate recall...
def aggregate(self, query: Optional[dict] = None, group: Optional[dict] = None, order_by: Optional[tuple] = None) -> List[IModel]: """Get aggregated results : param query: Rulez based query : param group: Grouping structure : param order_by: Tuple of ...
Get aggregated results : param query: Rulez based query : param group: Grouping structure : param order_by: Tuple of ``(field, order)`` where ``order`` is ``'asc'`` or ``'desc'`` : todo: Grouping structure need to be documented
def get_season_stats(self, season_key): """ Calling Season Stats API. Arg: season_key: key of the season Return: json data """ season_stats_url = self.api_path + "season/" + season_key + "/stats/" response = self.get_response(season_stats_u...
Calling Season Stats API. Arg: season_key: key of the season Return: json data
def import_generators(self, session, debug=False): """ Imports renewable (res) and conventional (conv) generators Args: session : sqlalchemy.orm.session.Session Database session debug: If True, information is printed during process Notes: ...
Imports renewable (res) and conventional (conv) generators Args: session : sqlalchemy.orm.session.Session Database session debug: If True, information is printed during process Notes: Connection of generators is done later on in NetworkDing0's method ...
def plot_mixture(mixture, i=0, j=1, center_style=dict(s=0.15), cmap='nipy_spectral', cutoff=0.0, ellipse_style=dict(alpha=0.3), solid_edge=True, visualize_weights=False): '''Plot the (Gaussian) components of the ``mixture`` density as one-sigma ellipses in the ``(i,j)`` plane. ...
Plot the (Gaussian) components of the ``mixture`` density as one-sigma ellipses in the ``(i,j)`` plane. :param center_style: If a non-empty ``dict``, plot mean value with the style passed to ``scatter``. :param cmap: The color map to which components are mapped in order to choose ...
def addToLayout(self, analysis, position=None): """ Adds the analysis passed in to the worksheet's layout """ # TODO Redux layout = self.getLayout() container_uid = self.get_container_for(analysis) if IRequestAnalysis.providedBy(analysis) and \ not IDuplic...
Adds the analysis passed in to the worksheet's layout
def reset(name, soft=False, call=None): ''' To reset a VM using its name .. note:: If ``soft=True`` then issues a command to the guest operating system asking it to perform a reboot. Otherwise hypervisor will terminate VM and start it again. Default is soft=False For ``sof...
To reset a VM using its name .. note:: If ``soft=True`` then issues a command to the guest operating system asking it to perform a reboot. Otherwise hypervisor will terminate VM and start it again. Default is soft=False For ``soft=True`` vmtools should be installed on guest system...
def stopped(name, connection=None, username=None, password=None): ''' Stops a VM by shutting it down nicely. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults ...
Stops a VM by shutting it down nicely. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect w...
def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ # in order to expose the Figure constructor to the pylab # interface we need to create the figure here DEBUG_MSG("new_figure_manager()", 3, None) _create_wx_app() FigureClass = kwargs.pop('FigureC...
Create a new figure manager instance
def on_service_arrival(self, svc_ref): """ Called when a service has been registered in the framework :param svc_ref: A service reference """ with self._lock: new_ranking = svc_ref.get_property(SERVICE_RANKING) if self._current_ranking is not None: ...
Called when a service has been registered in the framework :param svc_ref: A service reference
def sg_expand_dims(tensor, opt): r"""Inserts a new axis. See tf.expand_dims() in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : Dimension to expand. Default is -1. name: If provided, it replaces current tensor's name. Returns: ...
r"""Inserts a new axis. See tf.expand_dims() in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : Dimension to expand. Default is -1. name: If provided, it replaces current tensor's name. Returns: A `Tensor`.
async def purgeQueues(self, *args, **kwargs): """ Purge the SQS queues This method is only for debugging the ec2-manager This method is ``experimental`` """ return await self._makeApiCall(self.funcinfo["purgeQueues"], *args, **kwargs)
Purge the SQS queues This method is only for debugging the ec2-manager This method is ``experimental``
def updateVersions(region="us-east-1", table="credential-store"): ''' do a full-table scan of the credential-store, and update the version format of every credential if it is an integer ''' dynamodb = boto3.resource('dynamodb', region_name=region) secrets = dynamodb.Table(table) response = ...
do a full-table scan of the credential-store, and update the version format of every credential if it is an integer
def extract_params(raw): """Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of ...
Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of None.
def get_ticket_results(mgr, ticket_id, update_count=1): """Get output about a ticket. :param integer id: the ticket ID :param integer update_count: number of entries to retrieve from ticket :returns: a KeyValue table containing the details of the ticket """ ticket = mgr.get_ticket(ticket_id) ...
Get output about a ticket. :param integer id: the ticket ID :param integer update_count: number of entries to retrieve from ticket :returns: a KeyValue table containing the details of the ticket
def parse_methodcall(self, tup_tree): """ :: <!ELEMENT METHODCALL ((LOCALCLASSPATH | LOCALINSTANCEPATH), PARAMVALUE*)> <!ATTLIST METHODCALL %CIMName;> """ self.check_node(tup_tree, 'METHODCALL', ('NAME',), (), ...
:: <!ELEMENT METHODCALL ((LOCALCLASSPATH | LOCALINSTANCEPATH), PARAMVALUE*)> <!ATTLIST METHODCALL %CIMName;>
def change_password(self, id_user, user_current_password, password): """Change password of User from by the identifier. :param id_user: Identifier of the User. Integer value and greater than zero. :param user_current_password: Senha atual do usuário. :param password: Nova Senha do usuár...
Change password of User from by the identifier. :param id_user: Identifier of the User. Integer value and greater than zero. :param user_current_password: Senha atual do usuário. :param password: Nova Senha do usuário. :return: None :raise UsuarioNaoExisteError: User not regis...
def text(self): """ String formed by concatenating the text of each run in the paragraph. Tabs and line breaks in the XML are mapped to ``\\t`` and ``\\n`` characters respectively. Assigning text to this property causes all existing paragraph content to be replaced with ...
String formed by concatenating the text of each run in the paragraph. Tabs and line breaks in the XML are mapped to ``\\t`` and ``\\n`` characters respectively. Assigning text to this property causes all existing paragraph content to be replaced with a single run containing the assigned...
def draw_tiling(coord_generator, filename): """Given a coordinate generator and a filename, render those coordinates in a new image and save them to the file.""" im = Image.new('L', size=(CANVAS_WIDTH, CANVAS_HEIGHT)) for shape in coord_generator(CANVAS_WIDTH, CANVAS_HEIGHT): ImageDraw.Draw(im)....
Given a coordinate generator and a filename, render those coordinates in a new image and save them to the file.
def pumper(html_generator): """ Pulls HTML from source generator, feeds it to the parser and yields DOM elements. """ source = html_generator() parser = etree.HTMLPullParser( events=('start', 'end'), remove_comments=True ) while True: for element in parser.rea...
Pulls HTML from source generator, feeds it to the parser and yields DOM elements.
def get_aggregations(metrics_dict, saved_metrics, adhoc_metrics=[]): """ Returns a dictionary of aggregation metric names to aggregation json objects :param metrics_dict: dictionary of all the metrics :param saved_metrics: list of saved metric names :param adhoc_...
Returns a dictionary of aggregation metric names to aggregation json objects :param metrics_dict: dictionary of all the metrics :param saved_metrics: list of saved metric names :param adhoc_metrics: list of adhoc metric names :raise SupersetException: if one or more metr...
def replace(self, **kw): """Return datetime with new specified fields given as arguments. For example, dt.replace(days=4) would return a new datetime_tz object with exactly the same as dt but with the days attribute equal to 4. Any attribute can be replaced, but tzinfo can not be set to None. Arg...
Return datetime with new specified fields given as arguments. For example, dt.replace(days=4) would return a new datetime_tz object with exactly the same as dt but with the days attribute equal to 4. Any attribute can be replaced, but tzinfo can not be set to None. Args: Any datetime_tz attribu...
def get_agent(self, agent_id): """Fetches the agent for the given agent ID""" url = 'agents/%s' % agent_id return Agent(**self._api._get(url))
Fetches the agent for the given agent ID
def handle(data_type, data, data_id=None, caller=None): """ execute all data handlers on the specified data according to data type Args: data_type (str): data type handle data (dict or list): data Kwargs: data_id (str): can be used to differentiate between different data ...
execute all data handlers on the specified data according to data type Args: data_type (str): data type handle data (dict or list): data Kwargs: data_id (str): can be used to differentiate between different data sets of the same data type. If not specified will default to ...
def listen(self, timeout=10): """ Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds """ self._socket.settimeout(float(timeout)) while not self.stopped.isSet(): try: ...
Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds
def feedforward(self): """ Soon to be depriciated. Needed to make the SP implementation compatible with some older code. """ m = self._numInputs n = self._numColumns W = np.zeros((n, m)) for i in range(self._numColumns): self.getPermanence(i, W[i, :]) return W
Soon to be depriciated. Needed to make the SP implementation compatible with some older code.
def _search_for_user_dn(self): """ Searches the directory for a user matching AUTH_LDAP_USER_SEARCH. Populates self._user_dn and self._user_attrs. """ search = self.settings.USER_SEARCH if search is None: raise ImproperlyConfigured( "AUTH_LDAP_...
Searches the directory for a user matching AUTH_LDAP_USER_SEARCH. Populates self._user_dn and self._user_attrs.
def allow(self, comment, content_object, request): """ Determine whether a given comment is allowed to be posted on a given object. Return ``True`` if the comment should be allowed, ``False otherwise. """ if self.enable_field: if not getattr(content_...
Determine whether a given comment is allowed to be posted on a given object. Return ``True`` if the comment should be allowed, ``False otherwise.
def _locate_index(self, index): """ given index, find out sub-db and sub-index Parameters ---------- index : int index of a specific image Returns ---------- a tuple (sub-db, sub-index) """ assert index >= 0 and index < self.n...
given index, find out sub-db and sub-index Parameters ---------- index : int index of a specific image Returns ---------- a tuple (sub-db, sub-index)
def nlerp_quat(from_quat, to_quat, percent): """Return normalized linear interpolation of two quaternions. Less computationally expensive than slerp (which not implemented in this lib yet), but does not maintain a constant velocity like slerp. """ result = lerp_quat(from_quat, to_quat, percent) ...
Return normalized linear interpolation of two quaternions. Less computationally expensive than slerp (which not implemented in this lib yet), but does not maintain a constant velocity like slerp.
def factor_kkt(S_LU, R, d): """ Factor the U22 block that we can only do after we know D. """ nBatch, nineq = d.size() neq = S_LU[1].size(1) - nineq # TODO: There's probably a better way to add a batched diagonal. global factor_kkt_eye if factor_kkt_eye is None or factor_kkt_eye.size() != d.size...
Factor the U22 block that we can only do after we know D.
def send_request(self, request, callback=None, timeout=None, no_response=False): # pragma: no cover """ Send a request to the remote server. :param request: the request to send :param callback: the callback function to invoke upon response :param timeout: the timeout of the req...
Send a request to the remote server. :param request: the request to send :param callback: the callback function to invoke upon response :param timeout: the timeout of the request :return: the response
def to_serializable(self, use_bytes=False, bias_dtype=np.float32, bytes_type=bytes): """Convert the binary quadratic model to a serializable object. Args: use_bytes (bool, optional, default=False): If True, a compact representation representing the bi...
Convert the binary quadratic model to a serializable object. Args: use_bytes (bool, optional, default=False): If True, a compact representation representing the biases as bytes is used. bias_dtype (numpy.dtype, optional, default=numpy.float32): If `use_b...
def _formatters_default(self): """Activate the default formatters.""" formatter_classes = [ PlainTextFormatter, HTMLFormatter, SVGFormatter, PNGFormatter, JPEGFormatter, LatexFormatter, JSONFormatter, Javascr...
Activate the default formatters.
def localize_field(self, value): """ Method that must transform the value from object to localized string """ if self.default is not None: if value is None or value == '': value = self.default return value or ''
Method that must transform the value from object to localized string
def list_events(self, source=None, severity=None, text_filter=None, start=None, stop=None, page_size=500, descending=False): """ Reads events between the specified start and stop time. Events are sorted by generation time, source, then sequence number. :param str so...
Reads events between the specified start and stop time. Events are sorted by generation time, source, then sequence number. :param str source: The source of the returned events. :param str severity: The minimum severity level of the returned events. One of ``INFO``...
def add_textop_iter(func): """Decorator to declare custom *ITER* function as a new textops op An *ITER* function is a function that will receive the input text as a *LIST* of lines. One have to iterate over this list and generate a result (it can be a list, a generator, a dict, a string, an int ...) ...
Decorator to declare custom *ITER* function as a new textops op An *ITER* function is a function that will receive the input text as a *LIST* of lines. One have to iterate over this list and generate a result (it can be a list, a generator, a dict, a string, an int ...) Examples: >>> @add_tex...
def get_member_brief(self, member_id=0): ''' a method to retrieve member profile info :param member_id: [optional] integer with member id from member profile :return: dictionary with member profile inside [json] key member_profile = self.objects.profile_brief.schema ''...
a method to retrieve member profile info :param member_id: [optional] integer with member id from member profile :return: dictionary with member profile inside [json] key member_profile = self.objects.profile_brief.schema
def write(self, message, delay_seconds=None): """ Add a single message to the queue. :type message: Message :param message: The message to be written to the queue :rtype: :class:`boto.sqs.message.Message` :return: The :class:`boto.sqs.message.Message` object that was wr...
Add a single message to the queue. :type message: Message :param message: The message to be written to the queue :rtype: :class:`boto.sqs.message.Message` :return: The :class:`boto.sqs.message.Message` object that was written.
def confd_state_internal_cdb_client_lock(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") internal = ET.SubElement(confd_state, "internal") cdb = E...
Auto Generated Code
def _set_gaussian_expected_stats(self, smoothed_mus, smoothed_sigmas, E_xtp1_xtT): """ Both meanfield and VBEM require expected statistics of the continuous latent states, x. This is a helper function to take E[x_t], E[x_t x_t^T] and E[x_{t+1}, x_t^T] and compute the expected sufficient...
Both meanfield and VBEM require expected statistics of the continuous latent states, x. This is a helper function to take E[x_t], E[x_t x_t^T] and E[x_{t+1}, x_t^T] and compute the expected sufficient statistics for the initial distribution, dynamics distribution, and Gaussian observation distr...
def vclose(L, V): """ gets the closest vector """ lam, X = 0, [] for k in range(3): lam = lam + V[k] * L[k] beta = np.sqrt(1. - lam**2) for k in range(3): X.append((old_div((V[k] - lam * L[k]), beta))) return X
gets the closest vector
def removeItem( self ): """ Removes the item from the menu. """ item = self.uiMenuTREE.currentItem() if ( not item ): return opts = QMessageBox.Yes | QMessageBox.No answer = QMessageBox.question( self, 'R...
Removes the item from the menu.
def setup_logging(): """Logging config.""" logging.basicConfig(format=("[%(levelname)s\033[0m] " "\033[1;31m%(module)s\033[0m: " "%(message)s"), level=logging.INFO, stream=sys.stdout) logging.addL...
Logging config.
def _validate_format(req): ''' Validate jsonrpc compliance of a jsonrpc-dict. req - the request as a jsonrpc-dict raises SLOJSONRPCError on validation error ''' #check for all required keys for key in SLOJSONRPC._min_keys: if not key in req: ...
Validate jsonrpc compliance of a jsonrpc-dict. req - the request as a jsonrpc-dict raises SLOJSONRPCError on validation error
def serial_assimilate(self, rootpath): """ Assimilate the entire subdirectory structure in rootpath serially. """ valid_paths = [] for (parent, subdirs, files) in os.walk(rootpath): valid_paths.extend(self._drone.get_valid_paths((parent, subdirs, ...
Assimilate the entire subdirectory structure in rootpath serially.
def encipher_shift(plaintext, plain_vocab, shift): """Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is...
Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is positive. Returns: ciphertext (list of Strings): ...
def set_shuffle(self, shuffle): """stub""" if not self.my_osid_object_form._is_valid_boolean( shuffle): raise InvalidArgument('shuffle') self.my_osid_object_form._my_map['shuffle'] = shuffle
stub
def _evaluate_model_single_file(target_folder, test_file): """ Evaluate a model for a single recording. Parameters ---------- target_folder : string Folder where the model is test_file : string The test file (.hdf5) """ logging.info("Create running model...") model_s...
Evaluate a model for a single recording. Parameters ---------- target_folder : string Folder where the model is test_file : string The test file (.hdf5)
def _parse(self, msg_dict): ''' Parse a syslog message and check what OpenConfig object should be generated. ''' error_present = False # log.debug('Matching the message:') # log.debug(msg_dict) for message in self.compiled_messages: # log.debug...
Parse a syslog message and check what OpenConfig object should be generated.
def parse_color(self, color): ''' color : string, eg: '#rrggbb' or 'none' (where rr, gg, bb are hex digits from 00 to ff) returns a triple of unsigned bytes, eg: (0, 128, 255) ''' if color == 'none': return None return ( int(color[1:3], 16)...
color : string, eg: '#rrggbb' or 'none' (where rr, gg, bb are hex digits from 00 to ff) returns a triple of unsigned bytes, eg: (0, 128, 255)
def calculateLocalElasticity(self, bp, frames=None, helical=False, unit='kT'): r"""Calculate local elastic matrix or stiffness matrix for local DNA segment .. note:: Here local DNA segment referred to less than 5 base-pair long. In case of :ref:`base-step-image`: Shift (:math:`Dx`), Slide (:ma...
r"""Calculate local elastic matrix or stiffness matrix for local DNA segment .. note:: Here local DNA segment referred to less than 5 base-pair long. In case of :ref:`base-step-image`: Shift (:math:`Dx`), Slide (:math:`Dy`), Rise (:math:`Dz`), Tilt (:math:`\tau`), Roll (:math:`\rho`) and Twist...
def _retrieveRemoteCertificate(self, From, port=port): """ The entire conversation, starting with TCP handshake and ending at disconnect, to retrieve a foreign domain's certificate for the first time. """ CS = self.service.certificateStorage host = str(From.domain...
The entire conversation, starting with TCP handshake and ending at disconnect, to retrieve a foreign domain's certificate for the first time.
def remove_labels(self, labels, relabel=False): """ Remove one or more labels. Removed labels are assigned a value of zero (i.e., background). Parameters ---------- labels : int, array-like (1D, int) The label number(s) to remove. relabel : bool, op...
Remove one or more labels. Removed labels are assigned a value of zero (i.e., background). Parameters ---------- labels : int, array-like (1D, int) The label number(s) to remove. relabel : bool, optional If `True`, then the segmentation image will be re...
def will_set(self, topic, payload=None, qos=0, retain=False): """Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message...
Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message to send as a will. If not given, or set to None a zero length me...
def netconf_state_statistics_in_bad_rpcs(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring") statistics = ET.SubElement(netconf_state, "statis...
Auto Generated Code
def scale(self, x, y=None, z=None): "Uniform scale, if only sx argument is specified" if y is None: y = x if z is None: z = x m = self for col in range(4): # Only the top three rows m[0,col] *= x m[1,col] *= y ...
Uniform scale, if only sx argument is specified
def venv_bin(name=None): # pylint: disable=inconsistent-return-statements """ Get the directory for virtualenv stubs, or a full executable path if C{name} is provided. """ if not hasattr(sys, "real_prefix"): easy.error("ERROR: '%s' is not a virtualenv" % (sys.executable,)) sys.exit(...
Get the directory for virtualenv stubs, or a full executable path if C{name} is provided.
def currentPage(self): """ Return a sequence of mappings of attribute IDs to column values, to display to the user. nextPage/prevPage will strive never to skip items whose column values have not been returned by this method. This is best explained by a demonstration. L...
Return a sequence of mappings of attribute IDs to column values, to display to the user. nextPage/prevPage will strive never to skip items whose column values have not been returned by this method. This is best explained by a demonstration. Let's say you have a table viewing a...
def repartition(self, npartitions): """ Repartition data (Spark only). Parameters ---------- npartitions : int Number of partitions after repartitions. """ if self.mode == 'spark': return self._constructor(self.values.repartition(npartitio...
Repartition data (Spark only). Parameters ---------- npartitions : int Number of partitions after repartitions.
def minimize_metric(field, metric_func, nm, res, ival, roi=None, coarse_acc=1, fine_acc=.005, return_gradient=True, padding=True): """Find the focus by minimizing the `metric` of an image Parameters ---------- field : 2d array electric field metric_fu...
Find the focus by minimizing the `metric` of an image Parameters ---------- field : 2d array electric field metric_func : callable some metric to be minimized ival : tuple of floats (minimum, maximum) of interval to search in pixels nm : float RI of medium re...
def register(scheme): """ Registers a new scheme to the urlparser. :param schema | <str> """ scheme = nstr(scheme) urlparse.uses_fragment.append(scheme) urlparse.uses_netloc.append(scheme) urlparse.uses_params.append(scheme) urlparse.uses_query.append(scheme) urlparse.u...
Registers a new scheme to the urlparser. :param schema | <str>
def user_fields(self, user): """ Retrieve the user fields for this user. :param user: User object or id """ return self._query_zendesk(self.endpoint.user_fields, 'user_field', id=user)
Retrieve the user fields for this user. :param user: User object or id
def nlargest(self, n=5, keep='first'): """ Return the largest `n` elements. Parameters ---------- n : int, default 5 Return this many descending sorted values. keep : {'first', 'last', 'all'}, default 'first' When there are duplicate values that c...
Return the largest `n` elements. Parameters ---------- n : int, default 5 Return this many descending sorted values. keep : {'first', 'last', 'all'}, default 'first' When there are duplicate values that cannot all fit in a Series of `n` elements: ...
def down(self, path, link, repo): """Download files """ filename = link.split("/")[-1] if not os.path.isfile(path + filename): Download(path, link.split(), repo).start()
Download files
def start_polling(self, interval): """ Start polling for term updates and streaming. """ interval = float(interval) self.polling = True # clear the stored list of terms - we aren't tracking any self.term_checker.reset() logger.info("Starting polling for...
Start polling for term updates and streaming.
def listen(self, timeout=10): """ Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds """ self._socket.settimeout(float(timeout)) while not self.stopped.isSet(): try: ...
Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds
def isel_points(self, dim='points', **indexers): # type: (...) -> Dataset """Returns a new dataset with each array indexed pointwise along the specified dimension(s). This method selects pointwise values from each array and is akin to the NumPy indexing behavior of `arr[[0, 1], ...
Returns a new dataset with each array indexed pointwise along the specified dimension(s). This method selects pointwise values from each array and is akin to the NumPy indexing behavior of `arr[[0, 1], [0, 1]]`, except this method does not require knowing the order of each array's dimen...
def __coord_mel_hz(n, fmin=0, fmax=11025.0, **_kwargs): '''Get the frequencies for Mel bins''' if fmin is None: fmin = 0 if fmax is None: fmax = 11025.0 basis = core.mel_frequencies(n, fmin=fmin, fmax=fmax) basis[1:] -= 0.5 * np.diff(basis) basis = np.append(np.maximum(0, basis...
Get the frequencies for Mel bins